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
//! The teardown of a [`Child`] handle: what [`Drop`] does, and what the run-to-completion helpers do
//! to a child that failed after its spawn. One policy, whichever way it waits: it splits at its one
//! wait, as [`OwnedChild::begin_tear_down`] does. The first half ([`Child::begin_tear_down`]) never
//! blocks, and answers the teardown's [`Remains`] or the pending [`DropWait`]. The second half
//! reports and, with the policy's warn, blocks ([`DropWait::settle`]) or, for the async `Child`,
//! awaits ([`Child::tear_down_awaiting`]).

use crate::child::owned::teardown::{BeginOutcome, Disposition, Kill, Remains, TeardownOutcome, TeardownWait};
#[cfg(unix)]
use crate::child::owned::teardown::{FrontLook, FrontWait};
use crate::child::owned::unreaped::Unreaped;
use crate::child::Child;
use crate::containment::dispatch::{TeardownCaller, TreeKillOutcome};
#[cfg(unix)]
use crate::containment::mechanism::{FrontReach, Release};
#[cfg(unix)]
use crate::elevation::front::{AloneStep, KillRootOutcome, RootStep};

/// What a failed spawn's or run's teardown left of its child: its fate, the child itself if it could
/// not be ended, and the teardown's failures (the error's `cleanup`).
pub(crate) struct Torn {
    pub(crate) fate: crate::error::ChildFate,
    pub(crate) unreaped: Option<Unreaped>,
    pub(crate) cleanup: Option<crate::error::Failures>,
}

impl Torn {
    /// A child the teardown left alone (it was disarmed): nothing ran, so nothing failed.
    pub(crate) fn left(fate: crate::error::ChildFate) -> Torn {
        Torn {
            fate,
            unreaped: None,
            cleanup: None,
        }
    }
}

impl Child {
    /// What [`Drop`] does, now, for a caller that owns the child and fails after its spawn: it says
    /// what became of the child. With [`Disposition::HandBack`], a child whose teardown could not
    /// end it, a refused kill or an elevation front (which is sent none), is given back too if it
    /// still runs.
    ///
    /// Only a `kill_on_drop(false)` child is left whatever `disposition` says. The containment is
    /// torn down as `self` drops, before this returns. On Windows a refused root kill gets the
    /// single look.
    pub(crate) fn tear_down_or_hand_back(mut self, disposition: Disposition) -> Torn {
        if !self.kill_on_drop {
            return Torn::left(self.fate_of_a_disarmed_child());
        }
        self.kill_on_drop = false;
        let torn = self.tear_down(TeardownCaller::FailedRun, disposition);
        let unreaped = disposition.hands_back(&torn).then(|| self.into_unreaped());
        Torn {
            fate: torn.fate,
            unreaped,
            cleanup: torn.failures,
        }
    }

    /// [`tear_down_or_hand_back`](Self::tear_down_or_hand_back) for an `async fn`: the root's wait
    /// and the leaf's drain are awaited, with no warn (the warn is about a blocked thread).
    /// Dropped mid-teardown, the future settles as the drop does.
    #[cfg(feature = "tokio")]
    pub(crate) async fn tear_down_or_hand_back_awaiting(mut self, disposition: Disposition) -> Torn {
        if !self.kill_on_drop {
            return Torn::left(self.fate_of_a_disarmed_child());
        }
        // Before the waits, so the handle's own drop does nothing more if this future is dropped.
        self.kill_on_drop = false;
        let torn = self.tear_down_awaiting(TeardownCaller::FailedRun, disposition).await;
        let unreaped = disposition.hands_back(&torn).then(|| self.into_unreaped());
        Torn {
            fate: torn.fate,
            unreaped,
            cleanup: torn.failures,
        }
    }

    /// What became of a child whose teardown a `kill_on_drop(false)` leaves, from a peek at the root:
    /// an exit is the handle's to consume at its drop (`Reaped`), but where that drop consumes only
    /// an exit its own wait saw, an exit it did not see stays a zombie, dead and uncollected
    /// (`Killed`). Another's reap is `Gone`; a root that shows no exit may still run, and so may
    /// one whose peek failed (the failure is logged at debug): the child is left alone either way,
    /// so `Running { id }` hands the caller its identity where `Unknown` would not.
    fn fate_of_a_disarmed_child(&self) -> crate::error::ChildFate {
        use crate::error::ChildFate;
        use crate::os_process::child::PeekOutcome;
        match self.proc.peek() {
            Ok(PeekOutcome::Exit(_)) if self.proc.consumes_at_drop() => ChildFate::Reaped,
            Ok(PeekOutcome::Exit(_)) => ChildFate::Killed,
            Ok(PeekOutcome::Foreign(_)) => ChildFate::Gone,
            Ok(PeekOutcome::Running) => ChildFate::Running { id: self.id },
            Err(e) => {
                log::debug!(
                    "a disarmed child's teardown could not look at it, so it may still run: {}",
                    crate::error::Report(&e)
                );
                ChildFate::Running { id: self.id }
            }
        }
    }

    /// The root, as an [`Unreaped`]. `self` has already torn its containment down by dropping.
    pub(super) fn into_unreaped(mut self) -> Unreaped {
        debug_assert!(!self.kill_on_drop, "a handed-back child is no longer killed on drop");
        let root = self.proc.take().expect("a child handed back still holds its root");
        Unreaped::new(root, self.id, self.policy.unreaped_drop)
    }

    /// The kill-on-drop teardown, answering what became of the child. `caller` prefixes the event's
    /// warn, and `disposition` words it for a child that still runs after a refused kill, and for an
    /// elevation front left running. The clause has been said: the warn, or a debug line, has said
    /// it, so what is left is the [`Remains`].
    pub(crate) fn tear_down(&mut self, caller: TeardownCaller, disposition: Disposition) -> Remains {
        match self.begin_tear_down(caller, disposition) {
            BeginOutcome::Done(remains) => remains,
            BeginOutcome::Wait(wait) => wait.settle(self),
        }
    }

    /// [`tear_down`](Self::tear_down) awaited, as [`tear_down_or_hand_back_awaiting`] has it.
    ///
    /// [`tear_down_or_hand_back_awaiting`]: Self::tear_down_or_hand_back_awaiting
    #[cfg(feature = "tokio")]
    pub(crate) async fn tear_down_awaiting(&mut self, caller: TeardownCaller, disposition: Disposition) -> Remains {
        let remains = match self.begin_tear_down(caller, disposition) {
            BeginOutcome::Done(remains) => remains,
            BeginOutcome::Wait(wait) => {
                let mut settling = Settling {
                    child: self,
                    wait: Some(wait),
                };
                // The wait stays in `settling` while it is awaited, for the drop of this future to
                // settle.
                let torn = settling
                    .wait
                    .as_mut()
                    .expect("held until it is settled")
                    .settle_async(&mut *settling.child)
                    .await;
                let wait = settling.wait.take().expect("held until it is settled");
                let remains = wait.parts.finish(settling.child, torn);
                drop(settling);
                remains
            }
        };
        // The root is reaped and the event reported: what is left is the leaf's drain, which its kill
        // bounds. The awaited steps are taken here, and the leaf then drops with the handle in place,
        // which finds nothing left to wait for. Every other mechanism drops with the handle.
        #[cfg(target_os = "linux")]
        self.tree.await_release_steps(self.pid()).await;
        remains
    }

    /// The first half of [`tear_down`](Self::tear_down), which never blocks: the signals, and what
    /// can be settled without waiting. Nothing that names the tree by the root's number runs once
    /// the root is reaped, or when its handle cannot say: the handle's own answer (`RootState`), or
    /// the number no longer reading as this root. Each send by the group's number checks the root
    /// again, as for [`kill_tree`](Child::kill_tree): the drop's tree kill is the mechanism's own,
    /// the same answer as a tree call's ([`Tree::kill`](crate::containment::Tree::kill)).
    /// An unreaped root stays a zombie, pinning its number, until its teardown settles.
    pub(crate) fn begin_tear_down(
        &mut self,
        caller: TeardownCaller,
        disposition: Disposition,
    ) -> BeginOutcome<Remains, DropWait> {
        // Hard-kill the contained tree (if any) — on Linux cgroup.kill reaches an elevated
        // subtree — then tear the direct child down. The dispatcher preserves the Unix
        // kill-before-wait order and NEVER blocks on an unkillable elevated child.
        #[cfg(unix)]
        {
            self.begin_drop_unix(caller, disposition)
        }
        #[cfg(not(unix))]
        {
            // The drop sends only: what it killed is waited for by the root's reap and the tree's drain.
            let tree = self.tree.send_kill(Some(&self.proc.hold(self.pid())));
            let parts = DropParts {
                caller,
                tree: Some(tree),
            };
            let begun = self.proc.begin_tear_down(
                self.id,
                Kill {
                    disposition,
                    tree: None,
                },
                self.policy.teardown_warn_after,
            );
            self.begun(parts, begun)
        }
    }

    /// What `begun`, the first half of a root's teardown, comes to: the teardown's end, or its wait.
    fn begun(
        &mut self,
        parts: DropParts,
        begun: BeginOutcome<TeardownOutcome, TeardownWait>,
    ) -> BeginOutcome<Remains, DropWait> {
        match begun {
            BeginOutcome::Done(torn) => BeginOutcome::Done(parts.finish(self, torn)),
            BeginOutcome::Wait(wait) => BeginOutcome::Wait(DropWait {
                parts,
                wait: RootWait::Root(wait),
            }),
        }
    }
}

#[cfg(unix)]
impl Child {
    /// [`begin_tear_down`](Self::begin_tear_down) on Unix, with one report of the event.
    fn begin_drop_unix(&mut self, caller: TeardownCaller, disposition: Disposition) -> BeginOutcome<Remains, DropWait> {
        use crate::child::owned::teardown::Reach;
        use crate::error::ChildFate;

        // A live elevation front gets no signal of its own: outside a cgroup it is sent nothing and
        // stays running and unreaped, named by the warn; a `HandBack` caller then takes it. The
        // rule reads first, so the look at the root is right before the kill it decides. The drop's
        // own root kill is `begin_tear_down`'s, so the step never asks the rule for it.
        let kill_tree = || {
            let view = crate::containment::DropView::read(caller, self.pid(), self.id, &self.proc, &self.tree);
            // The root handle names the root's group.
            let root_handle = self.proc.hold(self.pid());
            // The kill decides on the view's look, the one its report is worded from.
            // The drop sends alone: the wait for what it killed is the root's reap and the leaf's drain.
            let kill = {
                let seen = crate::containment::Seen::new(&root_handle, view.look());
                self.tree.send_kill(Some(&seen))
            };
            kill.log_skip(&view);
            // A live member refused, or couldn't be confirmed — visible, not silently discarded. A
            // mechanism failure (e.g. `EACCES`/`EIO` on `cgroup.kill`) is a real OS outcome, so it is
            // reported, never asserted on.
            let skipped = kill.left_undone(&view);
            (view, kill, skipped)
        };
        let killed = self.proc.kill_root(
            Some(&self.tree),
            |_| {
                let torn = kill_tree();
                if torn.1.completed() {
                    AloneStep::Killed {
                        result: Ok(()),
                        carry: torn,
                    }
                } else {
                    AloneStep::NotKilled(torn)
                }
            },
            |_| RootStep::<std::convert::Infallible, _>::Answered(kill_tree()),
        );
        // `reached`: the rule's answer for a front its cgroup kill is the only kill of.
        let (reached, (view, kill, skipped)) = match killed {
            KillRootOutcome::Refused(unkillable) => {
                // The leaf stays armed: its teardown kills what it holds, a front among it if it is
                // in it. Run now, not at field drop, so the look at the front comes after it.
                let view = crate::containment::DropView::read(caller, self.pid(), self.id, &self.proc, &self.tree);
                let parts = DropParts {
                    view,
                    skipped: None,
                    tree: None,
                    disposition,
                };
                return self.begin_leaf_and_front(NotKilled::by(unkillable), parts);
            }
            KillRootOutcome::Contained { reached, carry } => (Some(reached), carry),
            KillRootOutcome::Answered(torn) => (None, torn),
            KillRootOutcome::Root { carry, .. } => match carry {},
        };
        // A reaped root is neither killed nor waited for: its number may name another child by now.
        // Neither is a root this process does not pin (macOS: launchd holds its zombie). The view says
        // the root is another's to have reaped, never this handle's (it consumes at its drop), and
        // nothing was signalled, so its fate is `Gone`, as the classifier has it.
        if view.leaves_root_alone() {
            let torn = TeardownOutcome::collected(ChildFate::Gone);
            let parts = DropParts {
                view,
                skipped,
                tree: Some(kill),
                disposition,
            };
            return BeginOutcome::Done(parts.finish(self, torn));
        }
        if let Some(reached) = reached {
            // The tree kill's failure is the tree's, settled in `DropParts::finish`.
            let not_reached = match reached {
                Ok(()) => None,
                Err(unreached) => Some(match kill.incomplete() {
                    Some(failure) => NotKilled::in_words(failure),
                    None => NotKilled::by(unreached),
                }),
            };
            let parts = DropParts {
                view,
                skipped,
                tree: Some(kill),
                disposition,
            };
            return match not_reached {
                // The cgroup kill ended it: reap it, sending nothing. The reap is the front's.
                None => {
                    let wait = self.proc.begin_reap_after_tree_kill(
                        None,
                        crate::elevation::front::front_named(Some(self.pid())),
                        disposition,
                        self.policy.teardown_warn_after,
                    );
                    BeginOutcome::Wait(DropWait {
                        parts,
                        wait: RootWait::Root(wait),
                    })
                }
                // Never waited for. A kill that failed is final: the armed leaf writes no
                // other. The front is looked at once the leaf is torn down.
                Some(why) => self.begin_leaf_and_front(why, parts),
            };
        }
        // The tree kill above may have reached the root: if the root's own kill is refused,
        // that kill is what ends it.
        let begun = {
            let reach = kill.completed().then_some(&self.tree as &dyn Reach);
            self.proc.begin_tear_down(
                self.id,
                Kill {
                    disposition,
                    tree: reach,
                },
                self.policy.teardown_warn_after,
            )
        };
        let parts = DropParts {
            view,
            skipped,
            tree: Some(kill),
            disposition,
        };
        self.begun(parts, begun)
    }

    /// A drop's end for an elevation front it cannot be sure its cgroup kill reached: its leaf is
    /// torn down (killed through unless a kill was made, whose failure is final; drained; removed),
    /// and then the front is looked at. The leaf's drain is the first of the teardown's waits, so
    /// the first half only names it ([`RootWait::Leaf`]) and blocks on nothing. `why` is why the
    /// front is not killed.
    fn begin_leaf_and_front(&mut self, why: NotKilled, parts: DropParts) -> BeginOutcome<Remains, DropWait> {
        BeginOutcome::Wait(DropWait {
            parts,
            wait: RootWait::Leaf { why },
        })
    }

    /// The tree's resource released, with the reach that places the front once it is gone, read before
    /// any step of the release, which may remove the leaf. What the kills settled stays the handle's.
    fn release_tree_for_front(&mut self) -> (Release, FrontReach) {
        let release = self.tree.release();
        let reach = release.front_reach();
        (release, reach)
    }

    /// The second half of [`begin_leaf_and_front`](Self::begin_leaf_and_front): the tree's resource is
    /// released, so a leaf is killed through, drained and removed, and then the front is looked at
    /// ([`look_at_front_after_leaf`](Self::look_at_front_after_leaf)), and worded as `why` says it
    /// was not killed. The reach is the release's, read before its first step, which may remove the
    /// leaf.
    fn look_at_front_after_releasing(
        &mut self,
        (release, reach): (Release, FrontReach),
        why: &NotKilled,
        disposition: Disposition,
    ) -> TeardownOutcome {
        release.wait();
        match self.look_at_front_after_leaf(reach) {
            BeginOutcome::Done(look) => why.word_front(self.proc.pid(), disposition, look),
            BeginOutcome::Wait(wait) => why.word_front(self.proc.pid(), disposition, wait.settle(&self.proc)),
        }
    }

    /// The look at the front, once the leaf is gone, through
    /// [`begin_look_at_front`](OwnedChild::begin_look_at_front), which waits for it only if its place
    /// says the kill reached it. A front is never killed through [`tear_down`](OwnedChild::tear_down):
    /// that would orphan its program. How the look went is worded by [`word_front`].
    #[cfg_attr(
        not(target_os = "linux"),
        allow(unused_variables, reason = "only a Linux cgroup leaf has a subtree")
    )]
    fn look_at_front_after_leaf(&mut self, reach: FrontReach) -> BeginOutcome<FrontLook, FrontWait> {
        use crate::child::owned::teardown::Reach;

        #[cfg(target_os = "linux")]
        let subtree;
        #[cfg(target_os = "linux")]
        let reach = match reach.0 {
            Ok(read) => {
                subtree = read;
                Ok(subtree.as_ref().map(|subtree| subtree as &dyn Reach))
            }
            Err(e) => Err(e),
        };
        #[cfg(not(target_os = "linux"))]
        let reach: Result<Option<&dyn Reach>, crate::error::Error> = Ok(None);
        self.proc
            .begin_look_at_front(self.id, reach, self.policy.teardown_warn_after)
    }
}

/// What a teardown's report needs once its wait is over: the kill's outcome and the root's view.
struct DropParts {
    /// The look at the root.
    #[cfg(unix)]
    view: crate::containment::DropView,
    /// What the tree kill skipped ([`TreeKillOutcome::left_undone`]).
    #[cfg(unix)]
    skipped: Option<String>,
    /// Who tore the child down: it names itself in the report. On Unix the root view holds it.
    #[cfg(not(unix))]
    caller: TeardownCaller,
    /// What the tree kill did, settled for the report only once the root's kill is known
    /// ([`Tree::settle_for_drop`](crate::containment::Tree::settle_for_drop)). `None`: no tree
    /// kill ran (a closed front's gate), so there is nothing to settle and nothing to mark.
    tree: Option<TreeKillOutcome>,
    /// How the look at an elevation front words a child that still runs.
    #[cfg(unix)]
    disposition: Disposition,
}

impl DropParts {
    /// The teardown's one report, once the root's `torn` is known: what became of the child.
    #[cfg(unix)]
    fn finish(self, child: &mut Child, torn: TeardownOutcome) -> Remains {
        let DropParts {
            view,
            skipped,
            tree,
            disposition: _,
        } = self;
        let mut report = crate::child::drop_report::DropReport::new(&view);
        report.skipped = skipped;
        let mut remains = report.fold_clause(torn);
        if let Some(kill) = tree {
            if let Some(left) = child.tree.settle_for_drop(kill, remains.fate.not_running()) {
                report.tree = Some(left.text);
                remains = remains.after_tree_kill(left.failure);
            }
        }
        report.emit(&child.reported);
        remains
    }

    /// The teardown's one report, once the root's `torn` is known: what became of the child.
    #[cfg(not(unix))]
    fn finish(self, child: &mut Child, torn: TeardownOutcome) -> Remains {
        let (warn, mut remains) = torn.take_warn(self.caller.label());
        let mut left = Vec::new();
        if let Some(tree) = self.tree {
            if let Some(tree_left) = child.tree.settle_for_drop(tree, remains.fate.not_running()) {
                left.push(tree_left.text);
                remains = remains.after_tree_kill(tree_left.failure);
            }
        }
        left.extend(warn);
        if !left.is_empty() {
            log::warn!("{}: {}", self.caller.label(), left.join("; "));
        }
        remains
    }
}

/// The one wait of a handle's teardown, with what its second half needs: the root's reap, or the
/// leaf's teardown and the look at an elevation front that a kill sent elsewhere is ending.
#[must_use = "a pending wait that is dropped leaves the child unreaped"]
pub(crate) struct DropWait {
    parts: DropParts,
    wait: RootWait,
}

enum RootWait {
    Root(TeardownWait),
    /// The leaf is still held: its teardown, then the look at the front, are to come. `why` is why
    /// the front was not killed.
    #[cfg(unix)]
    Leaf {
        why: NotKilled,
    },
    /// The tree's resource is being released, as an awaited teardown does it: held here until its wait
    /// completes, so a future dropped mid-await leaves it to the blocking settle, with the reach it
    /// read before its first step. `why` is why the front was not killed.
    #[cfg(all(unix, feature = "tokio"))]
    Releasing {
        released: Option<Box<(Release, FrontReach)>>,
        why: NotKilled,
    },
    /// The look at the front is under way, as an awaited teardown leaves it; `why` is why the front
    /// was not killed.
    #[cfg(all(unix, feature = "tokio"))]
    Front {
        wait: FrontWait,
        why: NotKilled,
    },
}

/// Why an elevation front was not killed: the words of the teardown's warn and, when an error says
/// it, that error (the refusal of its kill), which is a failure of the teardown ahead of the look's.
#[cfg(unix)]
#[derive(Clone, Default)]
struct NotKilled {
    text: String,
    failure: Option<std::sync::Arc<crate::error::Error>>,
}

#[cfg(unix)]
impl NotKilled {
    /// Not killed as `refusal` says.
    fn by(refusal: crate::error::Error) -> NotKilled {
        NotKilled {
            text: crate::error::Report(&refusal).to_string(),
            failure: Some(std::sync::Arc::new(refusal)),
        }
    }

    /// Not killed for a reason that is words alone.
    fn in_words(text: String) -> NotKilled {
        NotKilled { text, failure: None }
    }

    /// [`word_front`], with the refusal, if there is one, ahead of the look's failures.
    fn word_front(&self, pid: Option<u32>, disposition: Disposition, look: FrontLook) -> TeardownOutcome {
        word_front(pid, &self.text, disposition, look).failing_first(self.failure.clone())
    }
}

impl DropWait {
    /// Blocks until the root has exited and been reaped, warning once past the policy's threshold,
    /// then reports and says what became of the child.
    pub(crate) fn settle(self, child: &mut Child) -> Remains {
        let DropWait { parts, wait } = self;
        let torn = match wait {
            RootWait::Root(wait) => wait.settle(&child.proc),
            #[cfg(unix)]
            RootWait::Leaf { why } => {
                let released = child.release_tree_for_front();
                child.look_at_front_after_releasing(released, &why, parts.disposition)
            }
            #[cfg(all(unix, feature = "tokio"))]
            RootWait::Releasing { released, why } => {
                let released = *released.expect("held until its wait completes");
                child.look_at_front_after_releasing(released, &why, parts.disposition)
            }
            #[cfg(all(unix, feature = "tokio"))]
            RootWait::Front { wait, why } => {
                why.word_front(child.proc.pid(), parts.disposition, wait.settle(&child.proc))
            }
        };
        parts.finish(child, torn)
    }
}

impl DropWait {
    /// [`settle`](Self::settle)'s wait, awaited, with no warn: the caller still holds the wait if
    /// its future is dropped, and then settles it blocking. The wait moves on as it is awaited
    /// (the leaf's teardown over, the look at the front under way), so a drop settles what is left.
    #[cfg(feature = "tokio")]
    async fn settle_async(&mut self, child: &mut Child) -> TeardownOutcome {
        #[cfg(unix)]
        if let RootWait::Leaf { why } = &self.wait {
            // Held in the wait before the first await: the reach is read before the leaf's first step,
            // which may remove it, and the leaf is kept until its wait completes.
            self.wait = RootWait::Releasing {
                why: why.clone(),
                released: Some(Box::new(child.release_tree_for_front())),
            };
        }
        #[cfg(unix)]
        if let RootWait::Releasing { released, why } = &mut self.wait {
            // The leaf is killed through and its drain awaited, so dropping it waits for nothing.
            let release = &released.as_ref().expect("held until its wait completes").0;
            release.wait_async(child.pid()).await;
            let why = std::mem::take(why);
            let (release, reach) = *released.take().expect("held until its wait completes");
            release.wait();
            match child.look_at_front_after_leaf(reach) {
                BeginOutcome::Done(look) => return why.word_front(child.proc.pid(), self.parts.disposition, look),
                BeginOutcome::Wait(wait) => self.wait = RootWait::Front { wait, why },
            }
        }
        match &self.wait {
            RootWait::Root(wait) => wait.settle_async(&mut child.proc).await,
            #[cfg(unix)]
            RootWait::Leaf { .. } | RootWait::Releasing { .. } => unreachable!("the leaf's teardown is over"),
            #[cfg(unix)]
            RootWait::Front { wait, why } => {
                let look = wait.settle_async(&mut child.proc).await;
                why.word_front(child.proc.pid(), self.parts.disposition, look)
            }
        }
    }
}

/// A teardown whose wait is being awaited. Dropped with the wait unfinished (its future was), it
/// settles it as the drop would, blocking, with the policy's warn. While unwinding it gives the
/// child up unreaped and warns with its pid, as an [`Unreaped`]'s drop does.
#[cfg(feature = "tokio")]
struct Settling<'a> {
    child: &'a mut Child,
    wait: Option<DropWait>,
}

#[cfg(feature = "tokio")]
impl Drop for Settling<'_> {
    fn drop(&mut self) {
        if let Some(wait) = self.wait.take() {
            if std::thread::panicking() {
                log::warn!(
                    "{} was given up unreaped: its teardown was dropped while the thread is panicking",
                    crate::os_process::child_named(self.child.proc.pid())
                );
            } else {
                _ = wait.settle(self.child);
            }
        }
    }
}

/// Words how a look at the elevation front `pid` (`None`: not known) went, as the outcome of its
/// teardown: the front's [`Settlement`](crate::child::lifecycle::Settlement) words one it looked at,
/// and a warn the others. `why` is why the caller did not kill the front. A front seen running (left
/// running, or with its place or its leaf's subtree unreadable) is worded as handed back if
/// `disposition` says the caller hands it back, and as left otherwise; no other look depends on it.
#[cfg(unix)]
pub(super) fn word_front(
    pid: impl Into<Option<u32>>,
    why: &dyn std::fmt::Display,
    disposition: Disposition,
    look: FrontLook,
) -> TeardownOutcome {
    use crate::child::owned::teardown::LookOutcome;

    let front = crate::elevation::front::front_named(pid.into());
    let FrontLook { fate, look } = look;
    // A front seen running whose reach cannot be read: it is not known whether the cgroup kill ended it.
    let unreadable = |cause: String| match disposition {
        Disposition::Leave => {
            format!("{front} is left unreaped: {cause}, so it is not known whether the cgroup kill ended it")
        }
        Disposition::HandBack => format!(
            "{front} is running and unreaped: {cause}, so it is not known whether the cgroup kill \
             ended it{}",
            Disposition::HandBack.suffix(true)
        ),
    };
    // A front seen running is still this process's.
    let left = |warn: String| TeardownOutcome::left_uncollected(fate, warn);
    match look {
        LookOutcome::Ended(settlement) => {
            TeardownOutcome::new(fate, settlement.wording(&front, None, Some(disposition)))
                .failing(settlement.failure())
        }
        LookOutcome::LeftRunning => left(match disposition {
            Disposition::Leave => format!(
                "{front} is left running and unreaped: {why}, and a kill of the front would orphan \
                 the elevated program"
            ),
            Disposition::HandBack => format!(
                "{front} is running and unreaped: {why}, and a kill of the front would orphan \
                 the elevated program{}",
                Disposition::HandBack.suffix(true)
            ),
        }),
        LookOutcome::PlaceUnreadable(e) => left(unreadable(format!(
            "where it is cannot be read ({})",
            crate::error::Report(&e)
        )))
        .failing([std::sync::Arc::new(
            e.with_note(&format!("where {front} is cannot be read")),
        )]),
        LookOutcome::SubtreeUnreadable(e) => left(unreadable(format!(
            "its leaf's subtree cannot be read ({})",
            crate::error::Report(&e)
        )))
        .failing([std::sync::Arc::new(
            e.with_note(&format!("the subtree of {front}'s leaf cannot be read")),
        )]),
    }
}