shep-daemon 0.18.2

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

use std::path::{Path, PathBuf};

use shep_core::paths::ShepPaths;
use shep_core::transport::Listener;

use super::BootError;
use super::pidfile::PidfileLock;
use crate::supervisor::SupervisorHandle;

/// The apps a successor records in its own registry, which is what the muster
/// roll on disk is written from.
///
/// Every carried sheep's, and no dog's: the roll outlives the daemon, so a dog
/// in it would come back on a later cold boot as an unmarked sheep, ahead of
/// `spawn_enabled_dogs`, and `shep disable metrics` could not take it out.
/// Filtered here because `record_config` takes bare
/// [`AppConfig`](shep_core::config::AppConfig)s with no marker to filter on.
pub(super) fn apps_for_the_roll(
    flock: &[crate::handover::adopt::AdoptedSheep],
) -> Vec<shep_core::config::AppConfig> {
    flock
        .iter()
        .filter(|sheep| sheep.carried.dog().is_none())
        .map(|sheep| sheep.carried.app().clone())
        .collect()
}

/// The handover blob this process was handed, if it is a successor.
///
/// A successor is a shep image an outgoing daemon `execve`d in its own place.
/// There are two markers. `SHEP_PROCESS_HANDOVER` is what this build leaves,
/// and `shep-handover` reads it. `SHEP_HANDOVER`, naming a blob on disk, is
/// what the release before it left, and it is read here so a reload from that
/// release onto this one still hands over. The first wins.
///
/// An unusable legacy blob logs at `error` and boots as if fresh: the
/// predecessor has already replaced itself, so refusing leaves the operator no
/// shepherd. That is self-limiting, since a real successor also inherited the
/// locked pidfile descriptor and the fresh boot stops at
/// [`BootError::AlreadyRunning`] before restoring anything.
///
/// One `shep-handover` refused is not, and boots nothing. It has closed the
/// descriptors it carried, the pidfile among them, so a fresh boot would take
/// the lock, restore the roll and run every sheep a second time beside the
/// originals. The boot is refused instead, as a failed adoption is.
///
/// Also answers a predecessor's probe, and exits.
///
/// # Errors
///
/// - [`BootError::Adopt`] if `shep-handover` found the blob unreadable, in a
///   format this build does not read, or naming a descriptor that was not
///   inherited.
///
/// Unix only: Windows has no `execve`, so no image can be a successor.
pub(crate) fn successor_handover() -> Result<Option<Successor>, BootError> {
    match crate::handover::arrive() {
        Ok(Some(arrival)) => return Ok(Some(Successor::Arrived(arrival))),
        Ok(None) => {}
        Err(error) => return Err(BootError::Adopt(Box::new(error))),
    }
    let Some(path) = std::env::var_os(crate::handover::HANDOVER_ENV).map(PathBuf::from) else {
        return Ok(None);
    };
    Ok(successor_handover_at(&path).map(|blob| Successor::Written { path, blob }))
}

/// Rebuild everything a successor was handed: the lock, the listener, and
/// every sheep's plumbing.
///
/// A legacy blob is removed once its descriptors are adopted, and only then:
/// one left after a refusal is evidence, one left after a success would be
/// adopted again by the next boot. No partial success, since the predecessor
/// has already `execve`d itself away.
///
/// # Errors
///
/// - [`BootError::Adopt`] if a descriptor the blob names is not open in this
///   process, or is not the kind of object it was named as.
pub(super) fn rehydrate(carried: Successor) -> Result<Rehydrated, BootError> {
    let (blob, written) = match carried {
        Successor::Arrived(arrival) => {
            let blob = crate::handover::claim(arrival)
                .map_err(|source| BootError::Adopt(Box::new(source)))?;
            (blob, None)
        }
        Successor::Written { path, blob } => (blob, Some(path)),
    };
    let counters = blob.counters();
    let adopted = crate::handover::adopt::adopt(&blob)
        .map_err(|source| BootError::Adopt(Box::new(source)))?;
    if let Some(path) = written {
        crate::handover::adopt::discard_blob(&path);
    }
    let reloads = blob.reloads().to_vec();
    Ok(Rehydrated {
        lock: PidfileLock::from_locked(adopted.pidfile),
        listener: Listener::from_unix_listener(adopted.listener),
        flock: adopted.sheep,
        counters,
        reloads,
    })
}

/// A handover this process was handed, and how it reached it.
#[derive(Debug)]
pub(crate) enum Successor {
    /// Through `shep-handover`, which has read and removed the blob and holds
    /// the descriptors it named until [`rehydrate`] claims them.
    Arrived(shep_handover::Arrival<crate::handover::Handover>),
    /// By a release before it: the blob is a file [`rehydrate`] unlinks once
    /// adopted, and its descriptors were inherited under their own numbers.
    Written {
        /// Where the blob was read from.
        path: PathBuf,
        /// What it said.
        blob: crate::handover::Handover,
    },
}

/// [`successor_handover`]'s legacy arm, against a caller-named path.
///
/// Split out so a test can drive every refusal without writing the
/// environment, which is process-global and `unsafe` in edition 2024.
fn successor_handover_at(path: &Path) -> Option<crate::handover::Handover> {
    match crate::handover::Handover::read(path) {
        Ok(blob) => Some(blob),
        Err(error) => {
            tracing::error!(
                path = %path.display(),
                %error,
                "this process was handed a handover blob it cannot use, and is booting as if \
                 it were fresh; if a flock was running, it is no longer supervised"
            );
            None
        }
    }
}

/// How long a handover waits for each dog connection to reach a frame
/// boundary before leaving it behind.
const DOG_LINK_PARK: core::time::Duration = core::time::Duration::from_secs(1);

/// What [`rehydrate`] rebuilds from a blob: the home's lock, the control
/// listener, and the flock to install with the counters and the in-flight
/// reloads it ran under.
///
/// No `Debug`: `flock` carries each sheep's environment.
pub(super) struct Rehydrated {
    /// The home's pidfile lock, still held by the predecessor's `execve`.
    pub(super) lock: PidfileLock,
    /// The control listener, still bound by the predecessor's `execve`.
    pub(super) listener: Listener,
    /// Every sheep the predecessor carried, descriptors adopted into this
    /// process.
    pub(super) flock: Vec<crate::handover::adopt::AdoptedSheep>,
    /// The id, deadline and stamp counters the predecessor ran under.
    pub(super) counters: crate::handover::Counters,
    /// The reloads in flight when the predecessor handed over.
    pub(super) reloads: Vec<crate::supervisor::CarriedReload>,
}

/// Everything the SIGHUP task needs to replace this daemon's image.
///
/// Handed over a channel rather than as arguments, because none of it exists
/// when [`install_signals`](super::install_signals) runs. `Debug` carries nothing sensitive: two
/// descriptor numbers, a mailbox and the home's paths. The blob they end up in
/// does carry each sheep's environment; see [`crate::handover::Handover`].
#[derive(Debug)]
pub(crate) struct HandoverSeam {
    /// The flock to carry.
    pub(super) supervisor: SupervisorHandle,
    /// The daemon's own two descriptors, which the actor never sees.
    pub(super) fds: crate::handover::DaemonFds,
    /// The home, for the blob's path.
    pub(super) paths: ShepPaths,
    /// The connections the dogs hold to this shepherd, which the actor never
    /// sees: the server tasks serving them own their descriptors.
    pub(super) dog_links: crate::server::DogLinks,
}

/// Replace this process with a successor holding `seam`'s flock.
///
/// The gate runs here as well as in the client that asked before signalling:
/// anyone can send a signal, and the flock can change between the question and
/// the signal.
///
/// # Errors
///
/// The sentence to log, when the flock cannot be carried, when the actor is
/// gone, or when the exec failed. Each leaves this process still itself with
/// no blob on disk, and the caller falls back to a graceful stop.
pub(super) async fn hand_over_now(
    seam: &HandoverSeam,
) -> Result<core::convert::Infallible, String> {
    let (candidates, mut blob, parked) = seam
        .supervisor
        .handover_snapshot(seam.fds)
        .await
        .map_err(|err| format!("the supervisor could not describe its flock: {err}"))?;
    // Held until this function returns, which is only ever on a refusal: the
    // numbers written into the blob stay live sockets for as long as these
    // duplicates are open. A dog that connected after the snapshot above is
    // not in the blob and so not carried; it falls back to the control socket.
    // The freeze parks the tasks serving the dogs on a frame boundary, so the
    // blob neither changes nor splits a frame until the exec, or until a
    // refusal thaws them below.
    let dog_links = seam.dog_links.freeze(DOG_LINK_PARK).await;
    blob.carry_dog_links(&dog_links);
    let refusal = match hand_over_carrying(&candidates, &blob, seam) {
        Ok(never) => match never {},
        Err(refusal) => refusal,
    };
    // Taking the snapshot stopped every pump it reached and nothing else ever
    // sends a resume, so without this the flock logs nothing through the
    // graceful stop the caller falls back to. Here rather than in
    // `exec_into`'s error path: this is where every way out meets.
    seam.dog_links.thaw();
    parked.resume().await;
    Err(refusal)
}

/// [`hand_over_now`]'s body, split out so a single resume can cover every
/// way it refuses.
///
/// Two gates, in order: whether this flock is a shape a handover carries, then
/// whether the blob describing it is one a successor could adopt, run against
/// duplicates while this image still exists to fall back to.
///
/// # Errors
///
/// The flock cannot be carried, a successor could not have adopted the blob,
/// or the exec failed. All three leave this process still itself, with no blob
/// on disk.
fn hand_over_carrying(
    candidates: &[crate::handover::OwnedCandidate],
    blob: &crate::handover::Handover,
    seam: &HandoverSeam,
) -> Result<core::convert::Infallible, String> {
    let borrowed: Vec<crate::handover::Candidate<'_>> = candidates
        .iter()
        .map(crate::handover::OwnedCandidate::as_candidate)
        .collect();
    if let crate::handover::Fitness::Refused(reason) = crate::handover::fitness(&borrowed) {
        return Err(reason.to_string());
    }
    // The gate with no way back if it is skipped: past the `execve` there is
    // no image to refuse to, and the flock runs on unsupervised. Not inside
    // `handover::hand_over`, because the rehearsal registers objects with the
    // tokio reactor and that fn's own self-test runs from a plain `#[test]`.
    // The target's side of it, whether it reads this blob at all, is
    // `hand_over`'s probe.
    crate::handover::adopt::dry_run(blob).map_err(|err| {
        format!(
            "a successor could not have adopted this flock, so none was started: {err}. This is \
             a shep bug worth reporting: the descriptors are ones this shepherd opened itself, \
             and the check that refused them is the successor's own. The flock is stopped and \
             started instead, which is the reload an operator had before handovers existed"
        )
    })?;
    crate::handover::hand_over(blob, &seam.paths).map_err(|err| err.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::boot::{BootOptions, SIGNAL_TEST_LOCK, boot_with_idle_sweep, init_dirs};
    use crate::fake::{ProcScript, ScriptedRunner};
    use crate::testing::{SharedRunner, app_with, capture_logs, plain_entry, test_paths};
    use shep_core::config::{AppConfig, normalize};
    use shep_core::protocol::DogSource;
    use std::sync::Arc;
    use std::time::Duration;

    /// The daemon-side gate: anyone can send a signal, and the flock can
    /// change between a client's question and the delivery, so the SIGHUP path
    /// runs [`crate::handover::fitness`] again and refuses on its own.
    ///
    /// The descriptors are invalid on purpose: if the gate stopped refusing,
    /// `hand_over` would meet `EBADF` and return rather than exec this test
    /// binary into a re-run of the suite. The assertion on the message is what
    /// tells the two failures apart.
    #[tokio::test(start_paused = true)]
    async fn a_sighup_over_a_flock_it_cannot_carry_refuses_before_it_execs() {
        // A successful `boot()` installs signal listeners for this test's
        // whole duration, and a `raise()` elsewhere reaches them, hence the
        // lock. The paused clock is separate: it keeps the refusal this needs,
        // a pump missing `REPORT_DEADLINE`, from costing two real seconds.
        let _guard = SIGNAL_TEST_LOCK.lock().await;
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        init_dirs(&paths).unwrap();
        // A wedged log pump: the one thing the gate still refuses. The case is
        // about the gate firing at all, not about what fires it.
        let daemon = boot_with_idle_sweep(
            ScriptedRunner::new(vec![ProcScript::never_exits()])
                .with_a_pump_that_never_reports(&["wedged"]),
            paths.clone(),
            BootOptions::default(),
        )
        .await
        .unwrap();
        let ctx = daemon.context();
        ctx.supervisor
            .start(vec![
                normalize(AppConfig::minimal("wedged", "./srv")).unwrap(),
            ])
            .await
            .unwrap();

        let seam = HandoverSeam {
            supervisor: ctx.supervisor.clone(),
            fds: crate::handover::DaemonFds {
                listener: -1,
                pidfile: -1,
            },
            paths: paths.clone(),
            dog_links: crate::server::DogLinks::default(),
        };
        let refusal = hand_over_now(&seam)
            .await
            .expect_err("a flock with a wedged log pump cannot be carried");
        assert!(
            refusal.contains("did not report its descriptors in time"),
            "the gate must refuse before anything is exec'd: {refusal}"
        );
        assert!(
            refusal.contains("wedged"),
            "the refusal must name the sheep that held the flock back: {refusal}"
        );

        ctx.shutdown();
        // Bounded: the lock is held across this await, so a hung teardown
        // would stop every other signal test rather than failing this one.
        tokio::time::timeout(Duration::from_secs(5), daemon.run())
            .await
            .unwrap()
            .unwrap();
    }

    /// The second gate: a flock the fitness check passes, described by a blob
    /// no successor could have adopted, refuses here rather than after the
    /// `execve`. Past the exec there is no predecessor to refuse to, so
    /// `rehydrate` returns [`BootError::Adopt`], the successor exits without
    /// serving, and the flock runs on unsupervised.
    ///
    /// The assertion is on which refusal, not on there being one: the
    /// exec's own descriptor check meeting `EBADF` refused these descriptors
    /// before the gate existed. They stay invalid on purpose, since a blob past both
    /// gates would exec this test binary into a re-run of the suite.
    #[tokio::test]
    async fn a_sighup_over_a_blob_no_successor_could_adopt_refuses_before_it_execs() {
        // A successful `boot()` installs real signal listeners for this
        // test's whole duration.
        let _guard = SIGNAL_TEST_LOCK.lock().await;
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        init_dirs(&paths).unwrap();
        // No dog and no sheep, so the first gate passes: an empty flock is
        // carryable, and this case is about the second gate.
        let daemon = boot_with_idle_sweep(
            ScriptedRunner::new(Vec::new()),
            paths.clone(),
            BootOptions::default(),
        )
        .await
        .unwrap();
        let ctx = daemon.context();

        let seam = HandoverSeam {
            supervisor: ctx.supervisor.clone(),
            fds: crate::handover::DaemonFds {
                listener: -1,
                pidfile: -2,
            },
            paths: paths.clone(),
            dog_links: crate::server::DogLinks::default(),
        };
        let refusal = hand_over_now(&seam)
            .await
            .expect_err("a blob naming no real listener cannot be adopted");
        assert!(
            refusal.contains("a successor could not have adopted this flock"),
            "the rehearsal must be what refuses, not the exec's descriptor check further on: \
             {refusal}"
        );
        assert!(
            refusal.contains("-1"),
            "the refusal must name the descriptor it refused: {refusal}"
        );
        assert!(
            !crate::handover::Handover::path(&paths).exists(),
            "a refusal before the exec must leave no blob on disk"
        );

        ctx.shutdown();
        tokio::time::timeout(Duration::from_secs(5), daemon.run())
            .await
            .unwrap()
            .unwrap();
    }

    /// A handover that reports and then refuses has to leave every pump
    /// reading again.
    ///
    /// Taking the snapshot stops each pump where it stands, and nothing else
    /// in the daemon ever sends a resume, so a missing one is a flock that
    /// logs nothing more for the rest of the daemon's life.
    ///
    /// Two sheep, since the resume has to reach every pump that was reported
    /// to rather than the one the refusal named.
    #[tokio::test(start_paused = true)]
    async fn an_abandoned_handover_starts_every_pump_reading_again() {
        // A successful `boot()` installs real signal listeners for this test's
        // whole duration, and the paused clock keeps the missed
        // `REPORT_DEADLINE` this refusal needs from costing real seconds.
        let _guard = SIGNAL_TEST_LOCK.lock().await;
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        init_dirs(&paths).unwrap();
        let runner = Arc::new(
            ScriptedRunner::new(vec![ProcScript::never_exits(); 3])
                .with_a_pump_that_never_reports(&["wedged"]),
        );
        // The refusal: a wedged log pump, read after every pump that answered
        // has been reported to and parked, which is what makes a resume owed.
        let daemon = boot_with_idle_sweep(
            SharedRunner(Arc::clone(&runner)),
            paths.clone(),
            BootOptions::default(),
        )
        .await
        .unwrap();
        let ctx = daemon.context();
        ctx.supervisor
            .start(vec![
                normalize(AppConfig::minimal("quiet", "./srv")).unwrap(),
                normalize(AppConfig::minimal("chatty", "./srv")).unwrap(),
                normalize(AppConfig::minimal("wedged", "./srv")).unwrap(),
            ])
            .await
            .unwrap();
        for sheep in 0..3 {
            assert!(
                runner.log_ctl_live(sheep),
                "sheep {sheep} must have a live log pump before the report, or this case                  proves nothing"
            );
        }

        let seam = HandoverSeam {
            supervisor: ctx.supervisor.clone(),
            fds: crate::handover::DaemonFds {
                listener: -1,
                pidfile: -1,
            },
            paths: paths.clone(),
            dog_links: crate::server::DogLinks::default(),
        };
        let refusal = hand_over_now(&seam)
            .await
            .expect_err("a flock with a wedged log pump cannot be carried");
        assert!(
            refusal.contains("did not report its descriptors in time"),
            "the gate must refuse before anything is exec'd: {refusal}"
        );

        let answered: Vec<usize> = ["quiet", "chatty"]
            .iter()
            .map(|name| runner.spawn_index_of(name).expect("started above"))
            .collect();
        let wedged = runner.spawn_index_of("wedged").expect("started above");
        // Polled: `LogCtl::Resume` carries no acknowledgement, so a send that
        // returned was queued rather than served. Bounded, so a pump that is
        // never told fails here instead of hanging.
        let all_resumed = async {
            while answered.iter().any(|sheep| runner.resumes(*sheep) == 0) {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        };
        tokio::time::timeout(Duration::from_secs(10), all_resumed)
            .await
            .expect("every pump a refused handover reported to must be reading again");
        for sheep in &answered {
            assert_eq!(
                runner.resumes(*sheep),
                1,
                "sheep {sheep} must be resumed once rather than repeatedly"
            );
        }
        // A resume that reached only the first sheep reported to would satisfy
        // the single-pump sibling and fail here.
        assert_eq!(answered.len(), 2, "two pumps must have answered the report");
        assert_eq!(
            runner.resumes(wedged),
            0,
            "a pump that never answered never parked, so nothing may resume it"
        );

        ctx.shutdown();
        tokio::time::timeout(Duration::from_secs(5), daemon.run())
            .await
            .unwrap()
            .unwrap();
    }

    /// A snapshot abandoned because a pump went quiet still owes a resume to
    /// every pump that answered. A missed deadline is a different way into the
    /// refusal than the sibling's config gate, and it arrives with one pump
    /// parked and one that never was.
    ///
    /// No `boot()` and no signal: this is about what `hand_over_now` does with
    /// a snapshot, and building the supervisor directly is what lets the clock
    /// be paused so the deadline costs nothing to wait out.
    #[tokio::test(start_paused = true)]
    async fn a_handover_abandoned_on_a_wedged_pump_resumes_the_pumps_that_parked() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        init_dirs(&paths).unwrap();
        let (events, _rx) = crate::bus::test_bus(64);
        let runner = Arc::new(
            ScriptedRunner::new(vec![ProcScript::never_exits(); 2])
                .with_a_pump_that_never_reports(&["wedged"]),
        );
        let supervisor = crate::supervisor::spawn_supervisor(
            SharedRunner(Arc::clone(&runner)),
            paths.clone(),
            events,
        );
        supervisor
            .start(vec![
                normalize(AppConfig::minimal("answering", "./srv")).unwrap(),
                normalize(AppConfig::minimal("wedged", "./srv")).unwrap(),
            ])
            .await
            .unwrap();

        // Invalid on purpose: if the gate stopped refusing, `hand_over` would
        // meet `EBADF` and return rather than exec this test binary into a
        // re-run of the suite.
        let seam = HandoverSeam {
            supervisor: supervisor.clone(),
            fds: crate::handover::DaemonFds {
                listener: -1,
                pidfile: -1,
            },
            paths: paths.clone(),
            dog_links: crate::server::DogLinks::default(),
        };
        let refusal = hand_over_now(&seam)
            .await
            .expect_err("a flock with a pump that never reported cannot be carried");
        assert!(
            refusal.contains("did not report its descriptors in time"),
            "the refusal must say the pump went quiet, not something else: {refusal}"
        );
        assert!(
            refusal.contains("wedged"),
            "the refusal must name the sheep whose pump went quiet: {refusal}"
        );

        let answering = runner.spawn_index_of("answering").expect("started above");
        let wedged = runner.spawn_index_of("wedged").expect("started above");
        // Polled: `LogCtl::Resume` carries no acknowledgement, so a send that
        // returned was queued rather than served. Bounded, so a pump that is
        // never told fails here instead of hanging.
        let delivered = async {
            while runner.resumes(answering) == 0 {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        };
        tokio::time::timeout(Duration::from_secs(10), delivered)
            .await
            .expect("the pump that answered was parked, and a refusal owes it a resume");
        assert_eq!(
            runner.resumes(wedged),
            0,
            "a pump that never answered never parked, so nothing may resume it"
        );
    }

    /// One carried sheep, named, with `dog` set or not.
    fn carried_for_the_roll(
        name: &str,
        dog: Option<DogSource>,
    ) -> crate::handover::adopt::AdoptedSheep {
        let entry = crate::entry::ProcessEntry {
            pid: Some(4242),
            dog,
            ..plain_entry(1, app_with(name, |_| {}))
        };
        crate::handover::adopt::AdoptedSheep {
            carried: crate::handover::CarriedSheep::from_entry(
                &entry,
                0,
                crate::handover::CarriedFds::none(),
                false,
                None,
                false,
                None,
            ),
            out_pipe: None,
            err_pipe: None,
            out_log: None,
            err_log: None,
            stdin_pipe: None,
            channel: None,
            dog_link: None,
        }
    }

    /// A successor rebuilds its registry from the blob, and the roll on disk
    /// is written from that registry within seconds. `spawn_enabled_dogs`
    /// never touches `FlockRegistry`, so a successor that recorded a dog would
    /// put one in the roll permanently: a later cold boot restores `metrics`
    /// as an unmarked sheep ahead of `spawn_enabled_dogs`, and `shep disable
    /// metrics` cannot take it out.
    ///
    /// Both rows are asserted, since a filter that dropped everything would
    /// satisfy the negative half and overwrite a good roll with an empty one.
    #[test]
    fn a_carried_dog_does_not_reach_the_muster_roll() {
        let flock = vec![
            carried_for_the_roll("web", None),
            carried_for_the_roll("metrics", Some(DogSource::BuiltIn { grants: None })),
            carried_for_the_roll(
                "log-rotate",
                Some(DogSource::Adopted {
                    grants: None,
                    path: "/opt/bin/shep-log-rotate".to_string(),
                    channel: false,
                }),
            ),
        ];

        let names: Vec<String> = apps_for_the_roll(&flock)
            .into_iter()
            .map(|app| app.name)
            .collect();

        assert_eq!(
            names,
            vec!["web".to_string()],
            "the roll is the operator's flock; a dog belongs to `shep.toml`"
        );
    }

    /// A blob written by hand rather than by `Handover::write`, so this
    /// module's tests pin the on-disk shape a successor has to read rather
    /// than round-tripping whatever the writer happens to emit.
    fn write_blob(path: &Path, version: u32) {
        std::fs::write(
            path,
            format!(
                r#"{{"version":{version},"sheep":[],"listener_fd":3,"pidfile_fd":4,"next_id":0,"next_deadline":0,"next_action_stamp":0}}"#
            ),
        )
        .unwrap();
    }

    #[test]
    fn a_blob_on_disk_makes_this_process_a_successor() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("handover.json");
        write_blob(&path, 1);

        assert!(successor_handover_at(&path).is_some());
    }

    #[test]
    fn a_missing_blob_is_refused_out_loud_rather_than_silently() {
        // A stale inherited variable and a lost blob look the same from
        // here, and neither may pass for a fresh boot without a word.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("never-written.json");

        let logs = capture_logs(|| assert!(successor_handover_at(&path).is_none()));

        assert!(logs.contains("never-written.json"), "{logs}");
    }

    #[test]
    fn a_blob_of_an_unknown_version_is_refused_out_loud() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("handover.json");
        write_blob(&path, u32::MAX);

        let logs = capture_logs(|| assert!(successor_handover_at(&path).is_none()));

        assert!(logs.contains("version"), "{logs}");
    }

    #[test]
    fn a_refused_blob_is_left_on_disk_for_an_operator_to_read() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("handover.json");
        write_blob(&path, u32::MAX);

        capture_logs(|| assert!(successor_handover_at(&path).is_none()));

        assert!(path.exists(), "a refused blob is evidence, not litter");
    }

    /// The environment variable that tells the child of
    /// [`a_release_before_the_envelope_hands_over_to_this_one`] to be the
    /// successor stage.
    const LEGACY_STAGE: &str = "SHEP_HANDOVER_LEGACY_STAGE";

    /// The full path of that test, as libtest's `--exact` wants it.
    const LEGACY_NAME: &str =
        "boot::handover::tests::a_release_before_the_envelope_hands_over_to_this_one";

    /// The number the carried pipe has in the successor, and the one the blob
    /// names it by.
    const LEGACY_FD: i32 = 11;

    /// A reload from the release before the envelope onto this build.
    ///
    /// That release wrote the blob where `SHEP_HANDOVER` points, set nothing
    /// else, and `execve`d with the descriptors it named left open under their
    /// own numbers. Here the parent plays it: a hand-written blob in that
    /// release's layout, a pipe at the number the blob names, and a child of
    /// this test binary started with `SHEP_HANDOVER` alone. The child is the
    /// successor, and finds the flock through [`successor_handover`] itself.
    #[test]
    fn a_release_before_the_envelope_hands_over_to_this_one() {
        use command_fds::{CommandFdExt as _, FdMapping};
        use std::io::Write as _;

        if std::env::var_os(LEGACY_STAGE).is_some() {
            legacy_successor_stage();
        }

        let dir = tempfile::tempdir().unwrap();
        let blob = dir.path().join("handover.json");
        std::fs::write(
            &blob,
            format!(
                r#"{{"version":1,"sheep":[],"listener_fd":10,"pidfile_fd":{LEGACY_FD},"next_id":17,"next_deadline":3,"next_action_stamp":4}}"#
            ),
        )
        .unwrap();
        let (reader, mut writer) = std::io::pipe().unwrap();
        writer.write_all(b"from the old shepherd").unwrap();
        drop(writer);

        let out = std::process::Command::new(std::env::current_exe().unwrap())
            .arg(LEGACY_NAME)
            .arg("--exact")
            .arg("--nocapture")
            .env(LEGACY_STAGE, "1")
            .env(crate::handover::HANDOVER_ENV, &blob)
            .env_remove(shep_handover::HANDOVER_ENV)
            // The old release cleared `FD_CLOEXEC` itself; `command_fds` does
            // the same for the descriptors it maps.
            .fd_mappings(vec![FdMapping {
                parent_fd: reader.try_clone().unwrap().into(),
                child_fd: LEGACY_FD,
            }])
            .unwrap()
            .output()
            .unwrap();

        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            out.status.success(),
            "{stdout}{}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(
            stdout.contains("running 1 test"),
            "the child ran no test, so `{LEGACY_NAME}` is not where this test lives any more: \
             {stdout}"
        );
        assert!(
            stdout.contains("a legacy successor: next id 17, read: from the old shepherd"),
            "{stdout}"
        );
    }

    /// The environment variable that tells the child of
    /// [`a_refused_envelope_refuses_the_boot_rather_than_booting_fresh`] to be
    /// the successor stage.
    const REFUSED_STAGE: &str = "SHEP_HANDOVER_REFUSED_STAGE";

    /// The full path of that test, as libtest's `--exact` wants it.
    const REFUSED_NAME: &str =
        "boot::handover::tests::a_refused_envelope_refuses_the_boot_rather_than_booting_fresh";

    /// A successor whose envelope names a blob that is gone.
    ///
    /// `shep-handover` closes every descriptor it carried when it refuses, the
    /// pidfile among them, so a fresh boot would take the lock and run the
    /// flock a second time. The boot is refused instead.
    #[test]
    fn a_refused_envelope_refuses_the_boot_rather_than_booting_fresh() {
        if std::env::var_os(REFUSED_STAGE).is_some() {
            let refused = successor_handover();
            println!("refused: {}", matches!(refused, Err(BootError::Adopt(_))));
            std::process::exit(0);
        }

        let dir = tempfile::tempdir().unwrap();
        // The marker names its reader's pid, and a shell that `exec`s keeps
        // its own: `$$` is the successor's.
        let out = std::process::Command::new("/bin/sh")
            .arg("-c")
            .arg(format!(
                "{}=$$:\"$1\" exec \"$2\" \"$3\" --exact --nocapture",
                shep_handover::HANDOVER_ENV
            ))
            .arg("sh")
            .arg(dir.path().join("lost.json"))
            .arg(std::env::current_exe().unwrap())
            .arg(REFUSED_NAME)
            .env(REFUSED_STAGE, "1")
            .env_remove(crate::handover::HANDOVER_ENV)
            .output()
            .unwrap();

        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("running 1 test"),
            "the child ran no test, so `{REFUSED_NAME}` is not where this test lives any more: \
             {stdout}"
        );
        assert!(stdout.contains("refused: true"), "{stdout}");
    }

    /// The successor stage: take the flock the way `boot` does, and read what
    /// the predecessor left in the pipe the blob names.
    fn legacy_successor_stage() -> ! {
        let Ok(Some(Successor::Written { blob, .. })) = successor_handover() else {
            panic!("a blob where SHEP_HANDOVER points is a legacy successor");
        };
        let mut buf = [0_u8; 64];
        let read = nix::unistd::read(LEGACY_FD, &mut buf).expect("the carried descriptor is open");
        println!(
            "a legacy successor: next id {}, read: {}",
            blob.counters().next_id,
            String::from_utf8_lossy(&buf[..read])
        );
        std::process::exit(0);
    }
}