Skip to main content

subc_daemon/
supervise.rs

1use std::{
2    collections::{HashMap, VecDeque},
3    error::Error,
4    fmt, io,
5    path::PathBuf,
6    process::{ExitStatus, Stdio},
7    sync::{Arc, Mutex, OnceLock},
8    time::{Duration, SystemTime, UNIX_EPOCH},
9};
10
11use cortexkit_log::Retention;
12use serde_json::Value;
13use subc_control::{
14    ClientControlPush, LiveSpawn, ModuleProtocol, RouteCloseReason, SpawnCursor, SpawnEvent,
15    SpawnEventKind, SpawnSnapshot, SupervisorHealthStatus, TerminalDisposition, TerminalExitKind,
16};
17use subc_protocol::{
18    manifest::{SelfSignalKind, SignalAnchor},
19    session::{
20        HealthReport, HealthStatus, ModuleControlCommand, ModuleControlRequest,
21        MODULE_CONTROL_OP_HEALTH_CHECK,
22    },
23    Flags, FrameType, Priority, SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV,
24};
25use tokio::{
26    process::{Child, Command},
27    sync::{mpsc, oneshot, watch, Mutex as AsyncMutex},
28    task::JoinHandle,
29    time::{sleep, sleep_until, timeout, timeout_at, Instant},
30};
31use tracing::{debug, error, info, warn};
32
33use crate::{
34    child_roster::ChildRoster,
35    daemon_config::{
36        CAPTURE_KEEP_ENV, CAPTURE_MAX_AGE_DAYS_ENV, CAPTURE_MAX_FILE_MB_ENV, CK_LOG_ENV,
37    },
38    forwarding::{
39        CloseReason, ForwardingError, ForwardingTable, GoodbyeTarget, ModuleControlRpcOutcome,
40        ModuleDrainTarget, PendingModuleControlRpc,
41    },
42    provenance::{spawned_file_identity, ExecutableIdentityProbe, SpawnedFileIdentity},
43    registry::{ConnectionId, RegistryError},
44    stderr_tail::{
45        pump_stderr_to, pump_stdout_to, ChildOutputSink, StderrRing, StderrTailConfig,
46        StderrTailSnapshot,
47    },
48    terminal_ring::{TerminalHistorySnapshot, TerminalRecord, TerminalRing, TerminalRingConfig},
49    Frame, FrameSink, Registry,
50};
51
52#[path = "supervise_swap.rs"]
53mod swap;
54
55/// Command-line flag used by supervised modules to find subc.
56///
57/// subc launches module-mode children as `<module> --subc <connection-file-path>`.
58/// The path points at the TCP+key connection file; it is not an ambient signal and
59/// is never inherited by standalone children.
60pub const SUBC_ARG: &str = "--subc";
61
62const DEFAULT_MAX_RESTARTS: u32 = 3;
63const DEFAULT_BACKOFF: Duration = Duration::from_millis(100);
64const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
65/// The span `DEFAULT_MAX_RESTARTS` is counted over. Ten minutes is long enough
66/// to contain a real crash loop (which respawns in seconds) and short enough
67/// that unrelated crashes hours apart never accumulate into a permanent stop.
68const DEFAULT_RESTART_WINDOW: Duration = Duration::from_secs(600);
69/// How long a drain waits for already-dispatched requests to finalize before
70/// the child is torn down. Sized for TOOL-SCALE work (bash, inspect, builds),
71/// not RPC-scale: the original 2s value silently cut nearly every real tool
72/// call at the fence, making the wait-for-finalize design decorative for the
73/// workloads it existed for. Quiescence short-circuits, so an idle module
74/// restarts immediately regardless of this value; the budget is spent only
75/// when a genuine in-flight request is worth finishing. Per-module override:
76/// `drain_timeout_ms` in subc.jsonc; per-restart override: the operator's
77/// `supervisor.restart{drain_timeout_ms}` (0 = cut now, for wedge bounces
78/// where a stuck request will never settle).
79pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
80const REGISTRY_RELEASE_TIMEOUT: Duration = Duration::from_secs(1);
81const REGISTRY_RELEASE_POLL: Duration = Duration::from_millis(10);
82/// How long a restart waits for the exited process's output readers.
83///
84/// The restart does not depend on the stderr reader finishing. A reader still
85/// running at this bound is left running, and whatever it delivers later goes
86/// into the exited process's own section of the stderr ring (see
87/// `StderrRing::push_line_from`), ending naturally at EOF on its pipe. So the
88/// bound no longer decides whether a crash's last lines are kept: under load
89/// the reader may simply not have been scheduled yet, and cutting it there
90/// discarded exactly the lines that explained the crash.
91///
92/// What the bound still decides is when the tail starts reporting
93/// `Incomplete`: a pipe open past it usually means a descendant of the exited
94/// process still holds it, and the tail cannot claim to be whole until that
95/// pipe closes. That is also the only case in which the wait costs the restart
96/// anything, because a pipe with no other holder reaches EOF when the process
97/// exits. Under load a slow reader can show `Incomplete` briefly; it returns to
98/// `Captured` at EOF with nothing lost.
99///
100/// The stdout reader carries no ring, only the capture file, and is still
101/// stopped at this bound so an old process's stdout cannot trail into the file
102/// after its successor starts.
103const STDERR_PUMP_DRAIN_TIMEOUT: Duration = Duration::from_millis(250);
104/// Maximum number of supervised process spawn/exit facts retained per daemon incarnation.
105pub const SPAWN_EVENT_RING_CAPACITY: usize = 4096;
106const SPAWN_SUBSCRIBER_BUFFER: usize = SPAWN_EVENT_RING_CAPACITY + 1;
107/// Terminal Error code for a `supervisor.spawn_subscribe` stream the daemon
108/// dropped because the subscriber stopped draining its frames. The detail's
109/// `first_undelivered_cursor` names the first event it did not receive; the
110/// client resubscribes from the last cursor it did receive.
111pub(crate) const SPAWN_SUBSCRIBER_LAGGED_CODE: &str = "spawn_subscriber_lagged";
112
113struct SupervisedChild {
114    child: Child,
115    /// The name of this process's cgroup: the module id, or for a swap
116    /// candidate the alternate name (see `swap::cgroup_name`).
117    #[cfg(target_os = "linux")]
118    module_id: String,
119    #[cfg(target_os = "linux")]
120    cgroup_placement: Option<subc_cgroup::Placement>,
121    /// The job that contains this child and every process it spawns (issue #109).
122    ///
123    /// Dropping this handle is what reaps a surviving tree when no supervisor
124    /// code runs — a daemon crash — because the job carries
125    /// `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`.
126    ///
127    /// That limit is not crash-only, and the difference is worth knowing: a
128    /// Windows daemon *stop* is `taskkill` or the scheduler's `/End` — the
129    /// SIGTERM handler is `#[cfg(unix)]` — so the daemon dies with no stop
130    /// notice and the kernel closes the job handle, `TerminateProcess`ing every
131    /// module at once. Before this change they survived that, saw EOF on the
132    /// control socket, and ran their own teardown; Unix keeps that path
133    /// deliberately, so a module can seal a WAL or close a capture rather than
134    /// be killed mid-write. So this trades graceful teardown on every Windows
135    /// daemon stop for containment on a crash, which is the right way round
136    /// today: orphaned GPU workers are a reported, recurring problem, and the
137    /// modules that write most heavily do not run on Windows.
138    ///
139    /// The fix is a real Windows stop path — the daemon draining before it
140    /// exits, the twin of the Unix SIGTERM handler. Once it exists, this limit
141    /// reaches only what the drain left behind, which is what it should reach.
142    #[cfg(windows)]
143    job: Option<subc_jobobject::JobObject>,
144    stdout_pump: Option<JoinHandle<()>>,
145    stderr_pump: Option<StderrPump>,
146    stderr_ring: Arc<Mutex<StderrRing>>,
147    spawned_at_ms: u64,
148    spawned_from: PathBuf,
149    spawned_file_identity: Option<SpawnedFileIdentity>,
150    process_start_time: Option<u64>,
151    process_identity: Option<ProcessIdentity>,
152    pid: u32,
153    /// This process's entry in the daemon's child roster, released when the
154    /// process is reaped or this handle is dropped.
155    roster_guard: Option<crate::child_roster::RosterGuard>,
156}
157
158impl SupervisedChild {
159    fn id(&self) -> Option<u32> {
160        Some(self.pid)
161    }
162
163    fn process_identity(&self) -> Option<ProcessIdentity> {
164        self.process_identity
165    }
166
167    async fn wait(&mut self) -> io::Result<ExitStatus> {
168        // The roster entry is NOT released here. A daemon shutdown waits for the
169        // roster to empty and then exits the process, so releasing at the reap
170        // let it exit before the exit handler wrote this child's terminal record
171        // (the stderr drain and snapshot update sit in between), and the
172        // shutdown's own `daemon_shutdown` record was intermittently lost. The
173        // caller releases it after recording the exit (`release_roster`), and
174        // dropping the handle releases it too.
175        let result = self.child.wait().await;
176        #[cfg(target_os = "linux")]
177        if result.is_ok() {
178            if let Some(placement) = self.cgroup_placement.take() {
179                remove_module_cgroup(&placement, &self.module_id);
180            }
181        }
182        result
183    }
184
185    /// Releases this child's daemon-shutdown roster entry once its exit has
186    /// been recorded. The pid is already reaped and free for reuse, so the
187    /// entry must not outlive the record any longer than that.
188    fn release_roster(&mut self) {
189        self.roster_guard = None;
190    }
191
192    /// Kill the child, and on Windows the whole tree it spawned (issue #109).
193    ///
194    /// `Child::kill` is `TerminateProcess` scoped to one pid, so a module with a
195    /// helper process leaked the helper — the Synapse embedding module's CUDA
196    /// worker holds the GPU allocation, so the leak cost VRAM until the next
197    /// restart of something else. Terminating the job reaches grandchildren that
198    /// a tree walk cannot, including one whose parent has already exited and
199    /// been reparented away.
200    ///
201    /// Best-effort like `request_graceful_stop`: a job failure is logged and the
202    /// direct-child kill still decides the outcome, so containment can never
203    /// change whether a module is reported as stopped.
204    fn start_kill(&mut self) -> io::Result<()> {
205        #[cfg(windows)]
206        if let Some(job) = &self.job {
207            if let Err(error) = job.terminate() {
208                debug!(
209                    error = %error,
210                    "job termination failed; the direct-child kill still owns the outcome"
211                );
212            }
213        }
214        self.child.start_kill()
215    }
216
217    async fn drain_stderr(&mut self, module_id: &str) {
218        if let Some(mut pump) = self.stdout_pump.take() {
219            match timeout(STDERR_PUMP_DRAIN_TIMEOUT, &mut pump).await {
220                Ok(Ok(())) => {}
221                Ok(Err(error)) => {
222                    warn!(module_id, error = %error, "stdout pump ended unexpectedly");
223                }
224                Err(_) => {
225                    pump.abort();
226                    warn!(
227                        module_id,
228                        waited = ?STDERR_PUMP_DRAIN_TIMEOUT,
229                        "stdout pump did not drain before restart; stopped it before the next process"
230                    );
231                }
232            }
233        }
234
235        let Some(pump) = self.stderr_pump.take() else {
236            return;
237        };
238        settle_stderr_pump(
239            module_id,
240            &self.stderr_ring,
241            pump,
242            STDERR_PUMP_DRAIN_TIMEOUT,
243        )
244        .await;
245    }
246}
247
248/// The reader task for one process's stderr, with the ring generation its
249/// lines are attributed to.
250struct StderrPump {
251    task: JoinHandle<()>,
252    generation: u64,
253}
254
255/// Retire an exited process's stderr reader and wait up to `bound` for it to
256/// reach EOF. A reader still running at the bound is detached, not stopped: it
257/// keeps filling the exited process's section of the ring until its pipe
258/// closes, and the tail reads `Incomplete` until then. See
259/// [`STDERR_PUMP_DRAIN_TIMEOUT`] for why.
260async fn settle_stderr_pump(
261    module_id: &str,
262    ring: &Arc<Mutex<StderrRing>>,
263    pump: StderrPump,
264    bound: Duration,
265) {
266    let lock = || ring.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
267    let StderrPump {
268        mut task,
269        generation,
270    } = pump;
271    lock().retire_pump(generation);
272    match timeout(bound, &mut task).await {
273        Ok(Ok(())) => {}
274        Ok(Err(err)) => {
275            let mut ring = lock();
276            ring.mark_incomplete(format!("stderr pump ended unexpectedly: {err}"));
277            ring.finish_pump(generation);
278            warn!(module_id, error = %err, "stderr pump ended before clean EOF");
279        }
280        Err(_) => {
281            // Dropping the handle detaches the task; it ends at EOF on its pipe.
282            drop(task);
283            lock().mark_pump_late(
284                generation,
285                format!(
286                    "stderr of the exited process had not reached EOF {bound:?} after it was \
287                     retired (a descendant may still hold the pipe open); lines it still \
288                     writes are kept in that process's section"
289                ),
290            );
291            warn!(
292                module_id,
293                waited = ?bound,
294                "stderr pipe of the exited process is still open; its reader keeps running without delaying the restart"
295            );
296        }
297    }
298}
299
300fn registration_release_events() -> &'static watch::Sender<u64> {
301    static EVENTS: OnceLock<watch::Sender<u64>> = OnceLock::new();
302    EVENTS.get_or_init(|| {
303        let (sender, _receiver) = watch::channel(0);
304        sender
305    })
306}
307
308pub(crate) fn notify_registration_release() {
309    let events = registration_release_events();
310    let next_generation = (*events.borrow()).wrapping_add(1);
311    events.send_replace(next_generation);
312}
313
314/// How to launch one singleton module process.
315#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct ModuleSpec {
317    pub module_id: String,
318    pub program: PathBuf,
319    pub args: Vec<String>,
320    pub env: Vec<(String, String)>,
321    /// When true this is a reserved module: each spawn gets a fresh one-time launch
322    /// nonce that the child must echo in its HELLO, so only the daemon-spawned
323    /// process can register this module_id (a security-boundary module like the
324    /// credential vault must not be impersonable while it is down/restarting).
325    pub reserved: bool,
326    /// Module-id prefixes this supervised module owns for reserved HELLO checks.
327    /// Prefixes come from daemon config and must end in `:` before they reach the
328    /// supervisor; the owner module's current spawn nonce authorizes claims under
329    /// each prefix.
330    pub reserved_prefixes: Vec<String>,
331    /// The wire protocol this module speaks, as DECLARED in daemon config.
332    ///
333    /// [`ModuleProtocol::None`] changes four things and nothing else: health
334    /// probing is suppressed, teardown sends SIGTERM before waiting,
335    /// `route.open` is refused, and the spawn passes NO `--subc <path>` argument
336    /// and NO launch nonce. `SUBC_MODULE_ID` still goes into the environment,
337    /// because a process ignores an environment variable it does not read.
338    ///
339    /// The argument is the part that cannot be "harmless to a process that
340    /// ignores it": a stock binary exits on an unknown flag before it listens
341    /// (`nats-server`: "flag provided but not defined: -subc"), which is how the
342    /// first conformance run against this mode found it. The nonce is withheld
343    /// because a process that will never present it gains nothing from holding
344    /// it, and a secret in the environment of a process that does not need it is
345    /// a leak surface for no benefit.
346    pub protocol: ModuleProtocol,
347    /// Whether two processes of this module may run at once, which is what a
348    /// blue/green swap does for the length of its overlap. Declared in daemon
349    /// config because the daemon must be able to answer it while the module is
350    /// down, and so a module cannot talk itself into it after registering.
351    pub overlap: ModuleOverlap,
352}
353
354/// Whether a module tolerates a second process of itself running alongside.
355///
356/// Most modules are single-writer on their store (a WAL, a capture log, a
357/// resident index behind a writer barrier), and two processes on one store
358/// corrupt it. So a swap, which overlaps the old and new process by design,
359/// is refused unless the module's config opts in with `overlap: "safe"`.
360#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
361pub enum ModuleOverlap {
362    /// Never run two processes of this module at once. The default.
363    #[default]
364    Exclusive,
365    /// The module has said a second process of itself is harmless for the
366    /// length of a swap.
367    ///
368    /// Declare it only if a second instance can run for a few seconds without
369    /// touching ANY single-writer store: every database, WAL, index, projector
370    /// and scheduled job the module owns. A lease on part of that state is not
371    /// enough. broca's session lease guards WAL appends while its run index, its
372    /// store projector and its archive fold timer (which unlinks live WAL files)
373    /// stay single-writer, so broca is exclusive despite holding a lease. The
374    /// refusal only fires after this has been decided, so the decision is the
375    /// check.
376    Safe,
377}
378
379impl ModuleOverlap {
380    pub fn as_str(self) -> &'static str {
381        match self {
382            Self::Exclusive => "exclusive",
383            Self::Safe => "safe",
384        }
385    }
386}
387
388/// Environment variable telling a spawned module which case it was started
389/// for, before it sends HELLO. Only a swap candidate carries it, as
390/// [`SPAWN_ROLE_SWAP_CANDIDATE`]; every other spawn has it removed.
391///
392/// It chooses a warm-up budget, nothing else: a swap candidate can warm for
393/// longer because nobody waits on it, while a plain restart must flip ready
394/// quickly because callers see `module_warming` until it does. Absence means
395/// plain restart, the safe reading. The daemon trusts nothing about it; the
396/// candidate is proven by its launch nonce at HELLO.
397pub const SUBC_SPAWN_ROLE_ENV: &str = "SUBC_SPAWN_ROLE";
398/// The one value of [`SUBC_SPAWN_ROLE_ENV`] the daemon sets.
399pub const SPAWN_ROLE_SWAP_CANDIDATE: &str = "swap_candidate";
400/// How long a swap waits for its candidate to register and declare itself
401/// ready when the operator does not say. A module warming as a swap candidate
402/// may take up to 90 s (aft's ceiling, the largest in the fleet), so the
403/// daemon allows that plus time to start the process and send HELLO.
404pub const DEFAULT_SWAP_READY_TIMEOUT: Duration = Duration::from_secs(100);
405
406/// Bounded restart policy for crash exits.
407///
408/// `max_restarts` is the number of replacement processes allowed after the
409/// initial spawn WITHIN `window`. After that many crash restarts inside one
410/// window the module enters [`ModuleState::Failed`] and the supervisor stops
411/// the crash loop.
412///
413/// The budget is a RATE, not a lifetime total. It used to be a lifetime total,
414/// and that only survived because crashes were rare: a module that crashed
415/// three times across a week was disabled forever by crashes that had nothing
416/// to do with each other. That stopped being survivable once modules began
417/// exiting non-zero whenever the daemon's connection to them drops, because
418/// then every daemon-side connection drop spends a unit of the same budget and
419/// one flappy hour permanently stops a healthy module. Restarts older than
420/// `window` release their slot, so a module that crashed twice yesterday has a
421/// full budget today, while a genuine crash loop -- which is fast by
422/// definition -- still reaches the cap and stops.
423#[derive(Debug, Clone, Copy, PartialEq, Eq)]
424pub struct RestartPolicy {
425    pub max_restarts: u32,
426    /// Base delay before a crash replacement. The actual delay escalates with
427    /// the number of recent crash replacements and is capped by `max_backoff`.
428    pub backoff: Duration,
429    /// Maximum delay before a crash replacement.
430    pub max_backoff: Duration,
431    /// The span `max_restarts` is counted over. `Duration::ZERO` makes the
432    /// budget effectively infinite (nothing is ever in-window), which is why
433    /// daemon config refuses `window_secs: 0` rather than quietly accepting it.
434    pub window: Duration,
435}
436
437impl RestartPolicy {
438    /// A policy with the default crash window. Callers that care about the
439    /// window say so with [`Self::with_window`]; the ones that do not are
440    /// asking for the standard rate limit, not for no limit.
441    pub fn new(max_restarts: u32, backoff: Duration) -> Self {
442        Self {
443            max_restarts,
444            backoff,
445            max_backoff: DEFAULT_MAX_BACKOFF,
446            window: DEFAULT_RESTART_WINDOW,
447        }
448    }
449
450    pub fn with_max_backoff(mut self, max_backoff: Duration) -> Self {
451        self.max_backoff = max_backoff;
452        self
453    }
454
455    pub fn with_window(mut self, window: Duration) -> Self {
456        self.window = window;
457        self
458    }
459
460    /// Calculate the capped exponential delay for the next crash replacement.
461    /// `restart_in_window` is zero for the first replacement after an operator
462    /// action (restart, reload, re-enable) cleared the crash ring, or after all
463    /// older crash replacements have aged out of the window.
464    fn delay_for_restart(&self, restart_in_window: u32) -> Duration {
465        if self.backoff.is_zero() || self.max_backoff.is_zero() {
466            return Duration::ZERO;
467        }
468
469        let mut delay = self.backoff;
470        for _ in 0..restart_in_window {
471            if delay >= self.max_backoff {
472                return self.max_backoff;
473            }
474            delay = delay
475                .checked_mul(10)
476                .unwrap_or(self.max_backoff)
477                .min(self.max_backoff);
478        }
479        delay.min(self.max_backoff)
480    }
481
482    /// The one sentence that explains a budget-exhausted stop, used for both the
483    /// log line and the terminal record so the two cannot drift. It names the
484    /// window because `max_restarts=3` alone reads as a lifetime cap, which is
485    /// exactly what this budget is not.
486    fn budget_exhausted_detail(&self) -> String {
487        format!(
488            "crash budget exhausted: max_restarts={} within window_secs={}",
489            self.max_restarts,
490            self.window.as_secs()
491        )
492    }
493}
494
495impl Default for RestartPolicy {
496    fn default() -> Self {
497        Self {
498            max_restarts: DEFAULT_MAX_RESTARTS,
499            backoff: DEFAULT_BACKOFF,
500            max_backoff: DEFAULT_MAX_BACKOFF,
501            window: DEFAULT_RESTART_WINDOW,
502        }
503    }
504}
505
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
507struct CrashRestartSchedule {
508    restart_in_window: u32,
509    delay: Duration,
510}
511
512/// Whether the daemon itself will bring this module back after the exit being
513/// handled: it is enabled AND its in-window crash restarts are below the cap.
514///
515/// Takes `&mut` because reading the budget prunes it. Instants that fell out of
516/// the window are dropped here rather than by a timer, so the count is right
517/// the moment somebody asks and no bookkeeping runs for idle modules.
518fn daemon_will_restart(
519    state: &mut SupervisorSnapshot,
520    policy: &RestartPolicy,
521    now: Instant,
522) -> bool {
523    state.enabled && state.crash_restarts_in_window(policy.window, now) < policy.max_restarts
524}
525
526const DEFAULT_HEALTH_CADENCE: Duration = Duration::from_secs(30);
527const DEFAULT_HEALTH_DEADLINE: Duration = Duration::from_secs(5);
528const DEFAULT_HEALTH_FAILURE_THRESHOLD: u32 = 3;
529const MAX_HEALTH_METRICS_BYTES: usize = 16 * 1024;
530
531#[derive(Debug, Clone, Copy, PartialEq, Eq)]
532pub enum HealthAction {
533    Report,
534    Restart,
535    Alert,
536}
537
538impl fmt::Display for HealthAction {
539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540        f.write_str(match self {
541            Self::Report => "report",
542            Self::Restart => "restart",
543            Self::Alert => "alert",
544        })
545    }
546}
547
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549pub struct HealthConfig {
550    pub cadence: Duration,
551    pub deadline: Duration,
552    pub failure_threshold: u32,
553    pub on_degraded: HealthAction,
554    pub on_failing: HealthAction,
555    pub critical: bool,
556}
557
558impl Default for HealthConfig {
559    fn default() -> Self {
560        Self {
561            cadence: DEFAULT_HEALTH_CADENCE,
562            deadline: DEFAULT_HEALTH_DEADLINE,
563            failure_threshold: DEFAULT_HEALTH_FAILURE_THRESHOLD,
564            on_degraded: HealthAction::Report,
565            on_failing: HealthAction::Report,
566            critical: false,
567        }
568    }
569}
570
571/// The supervisor's view of one module's health, relayed to clients over
572/// channel-0 and rendered by `ck health`.
573///
574/// THIS TYPE IS WHERE THE ABSENCE MEANINGS ARE CREATED, which is why they are
575/// stated here rather than only at the wire type a consumer reads. A reader can
576/// look up what `None` means; only a writer can silently change it, and the
577/// writer has no reason to go looking at a downstream contract before editing.
578///
579/// `last_probe_ms: None` MEANS NEVER PROBED, not probed-long-ago. It is cleared
580/// back to `None` on re-registration precisely so a respawned module does not
581/// carry its predecessor's timestamp — so an old value and an absent one call for
582/// opposite readings, and anything that defaulted this to a number would make a
583/// never-probed module indistinguishable from one probed at the epoch.
584///
585/// `detail` and `metrics` are `None` when the module published none on this
586/// probe, which does not mean it reported nothing wrong — it is also the shape
587/// when the probe never reached it. `last_probe_ms` is what separates those.
588#[derive(Debug, Clone, PartialEq)]
589pub struct ModuleHealthStatus {
590    pub status: SupervisorHealthStatus,
591    pub last_probe_ms: Option<u64>,
592    pub detail: Option<String>,
593    pub metrics: Option<Value>,
594    pub consecutive_failures: u32,
595    /// Number of replies received after a recurring health probe's deadline.
596    /// Unlike a timeout, every increment proves the module was alive.
597    pub late_answer_count: u64,
598    /// End-to-end latency of the newest late reply, measured from probe start.
599    pub last_late_answer_latency_ms: Option<u64>,
600    pub last_action: Option<String>,
601    /// Set together with `last_action`; the pair moves as one, and both being
602    /// absent means no escalation has ever been taken rather than that the last
603    /// one succeeded.
604    pub last_action_ms: Option<u64>,
605}
606
607impl Default for ModuleHealthStatus {
608    fn default() -> Self {
609        Self {
610            status: SupervisorHealthStatus::Unknown,
611            last_probe_ms: None,
612            detail: None,
613            metrics: None,
614            consecutive_failures: 0,
615            late_answer_count: 0,
616            last_late_answer_latency_ms: None,
617            last_action: None,
618            last_action_ms: None,
619        }
620    }
621}
622
623/// Typed lifecycle state for a supervised module.
624#[derive(Debug, Clone, Copy, PartialEq, Eq)]
625pub enum ModuleState {
626    Starting,
627    Running,
628    Unresponsive,
629    Restarting,
630    Draining,
631    Stopped,
632    Failed,
633    Disabled,
634}
635
636impl fmt::Display for ModuleState {
637    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638        f.write_str(match self {
639            Self::Starting => "starting",
640            Self::Running => "running",
641            Self::Unresponsive => "unresponsive",
642            Self::Restarting => "restarting",
643            Self::Draining => "draining",
644            Self::Stopped => "stopped",
645            Self::Failed => "failed",
646            Self::Disabled => "disabled",
647        })
648    }
649}
650
651/// Supervisor classification of a child-process exit.
652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
653pub enum ExitKind {
654    Clean,
655    Crash,
656    DeliberateSeverance,
657}
658
659impl From<ExitKind> for TerminalExitKind {
660    fn from(kind: ExitKind) -> Self {
661        match kind {
662            ExitKind::Clean => Self::Clean,
663            ExitKind::Crash => Self::Crash,
664            ExitKind::DeliberateSeverance => Self::DeliberateSeverance,
665        }
666    }
667}
668
669/// Exact process identity retained when a supervised module registers its
670/// connection. PID reuse makes a PID alone insufficient evidence of ownership.
671#[derive(Debug, Clone, Copy, PartialEq, Eq)]
672pub(crate) struct ProcessIdentity {
673    pub(crate) pid: u32,
674    pub(crate) start_time: u64,
675}
676
677/// Last observed child exit, if any.
678#[derive(Debug, Clone, PartialEq, Eq)]
679pub struct ExitReport {
680    pub kind: ExitKind,
681    pub code: Option<i32>,
682    pub signal: Option<i32>,
683    pub at_ms: u64,
684}
685
686/// Point-in-time module status answerable by subc without forwarding to the
687/// module process.
688#[derive(Debug, Clone, PartialEq)]
689pub struct ModuleStatus {
690    pub module_id: String,
691    pub state: ModuleState,
692    pub enabled: bool,
693    pub process_alive: bool,
694    pub registration_active: bool,
695    /// The module's declared wire protocol, carried beside `live` because it is
696    /// what makes `live` readable: the two fields answer one question together.
697    pub protocol: ModuleProtocol,
698    /// Whether the module is serving, under the strongest definition the daemon
699    /// can assert for its protocol.
700    ///
701    /// A subc module must also be REGISTERED: its process being alive says
702    /// nothing about whether it can take a request. A `protocol: "none"` module
703    /// never registers, so that term is dropped and this falls back to "enabled,
704    /// running, and the process the daemon launched is alive" -- which is all
705    /// the daemon observes about a process that speaks no subc wire. It stays a
706    /// `bool` on the wire for compatibility; renderers pair it with `protocol`
707    /// rather than printing it bare.
708    pub live: bool,
709    /// Crash restarts spent INSIDE `restart_window` as of this read. Older
710    /// restarts have already released their slot, so this count can go down
711    /// without anybody touching the module.
712    pub restart_count: u32,
713    /// Replacement processes spawned over this module's entire supervisor lifetime;
714    /// unlike `restart_count`, this value is never reset by an operator action
715    /// and never falls out of a window.
716    pub lifetime_restarts: u32,
717    pub spawn_generation: u64,
718    /// The budget `restart_count` is spent against. Carried alongside the count
719    /// because the count alone does not say how close the module is to being
720    /// disabled, and reporting one without the other is what makes an
721    /// about-to-be-retired module look ordinary.
722    pub max_restarts: u32,
723    /// The span `restart_count` is counted over. Carried with the pair above for
724    /// the same reason they are carried together: "2 of 3" means one thing for a
725    /// ten-minute window and something else entirely for a lifetime.
726    pub restart_window: Duration,
727    /// Effective drain and restart timing policy used by this running module.
728    /// These values are carried together with the restart budget so status
729    /// readers can compare configured intent with what the supervisor applied.
730    pub drain_timeout: Duration,
731    pub restart_backoff: Duration,
732    pub restart_max_backoff: Duration,
733    pub pid: Option<u32>,
734    pub spawned_at_ms: Option<u64>,
735    pub spawned_from: Option<PathBuf>,
736    pub process_start_time: Option<u64>,
737    pub last_exit: Option<ExitReport>,
738    pub health: ModuleHealthStatus,
739}
740
741#[derive(Debug, Clone, PartialEq)]
742struct SupervisorSnapshot {
743    state: ModuleState,
744    enabled: bool,
745    process_alive: bool,
746    /// When each crash restart was spent, oldest first. This IS the crash
747    /// budget: its in-window length is the count an operator sees and the count
748    /// the restart decision is made against, so there is no second counter that
749    /// can disagree with it. Bounded by `max_restarts`, and cleared by the same
750    /// operator actions that used to zero the old lifetime counter.
751    crash_restarts: VecDeque<Instant>,
752    lifetime_restarts: u32,
753    /// Successful child spawns in this daemon incarnation.
754    ///
755    /// `lifetime_restarts` was considered and rejected: it starts at zero
756    /// (line 640), successful initial/operator spawns in `set_running` do not
757    /// increment it (lines 5264-5274), and crash/deliberate retry bookkeeping
758    /// increments before a successful replacement exists (lines 604, 3846,
759    /// and 3921), so a failed spawn can consume it. This counter moves only
760    /// when a live PID is accepted below.
761    spawn_generation: u64,
762    pid: Option<u32>,
763    spawned_at_ms: Option<u64>,
764    spawned_from: Option<PathBuf>,
765    spawned_file_identity: Option<SpawnedFileIdentity>,
766    process_start_time: Option<u64>,
767    deliberate_severance: Option<ProcessIdentity>,
768    last_exit: Option<ExitReport>,
769    health: ModuleHealthStatus,
770    /// Whether the current process was started as a swap candidate and so
771    /// lives in the module's alternate cgroup. The next swap's candidate takes
772    /// the other one, so the two processes of a swap never share a cgroup. A
773    /// plain spawn always uses the primary cgroup.
774    in_alternate_slot: bool,
775    /// Whether the current `Draining` state ends in a replacement process
776    /// (restart, reload, health restart) rather than a stop. Only meaningful
777    /// while `state` is `Draining`; every entry into that state rewrites it.
778    /// It is what lets route.open answer the retryable `module_reloading` to a
779    /// consumer that reaches a still-registered process mid-restart, instead of
780    /// the `supervisor_not_live` a stop or disable deserves.
781    draining_to_replace: bool,
782    /// Whether a configuration update has been applied since the current
783    /// process was spawned, so that process runs an older spec than the one
784    /// the supervisor now holds. A queued restart is only coalesced into a
785    /// fresher process when this is false: a restart requested to pick up a
786    /// new configuration must not be satisfied by a process that predates it.
787    configuration_updated_since_spawn: bool,
788}
789
790impl SupervisorSnapshot {
791    fn starting() -> Self {
792        Self::new(ModuleState::Starting, true)
793    }
794
795    fn disabled() -> Self {
796        Self::new(ModuleState::Disabled, false)
797    }
798
799    fn failed() -> Self {
800        Self::new(ModuleState::Failed, true)
801    }
802
803    /// Crash restarts still inside `window`, having dropped the ones that are
804    /// not. Pruning on read is what makes the budget a rate: an instant older
805    /// than the window stops holding a slot the moment anybody counts.
806    fn crash_restarts_in_window(&mut self, window: Duration, now: Instant) -> u32 {
807        while let Some(oldest) = self.crash_restarts.front() {
808            if now.duration_since(*oldest) > window {
809                self.crash_restarts.pop_front();
810            } else {
811                break;
812            }
813        }
814        u32::try_from(self.crash_restarts.len()).unwrap_or(u32::MAX)
815    }
816
817    /// Spend one unit of the crash budget and record the restart in the ledger.
818    ///
819    /// The ring is bounded by the cap because more than `max_restarts` in-window
820    /// instants can never be reached (the caller refuses the restart first), so
821    /// anything beyond that is an unbounded queue waiting to happen.
822    fn record_crash_restart(&mut self, policy: &RestartPolicy, now: Instant) {
823        self.crash_restarts.push_back(now);
824        while self.crash_restarts.len() > policy.max_restarts as usize {
825            self.crash_restarts.pop_front();
826        }
827        self.lifetime_restarts += 1;
828    }
829
830    /// Reserve one crash-restart slot and calculate the delay before respawning.
831    /// The count is captured before recording this restart, so the first retry
832    /// uses the base delay and each later in-window retry escalates once.
833    fn next_crash_restart(
834        &mut self,
835        policy: &RestartPolicy,
836        now: Instant,
837    ) -> Option<CrashRestartSchedule> {
838        let restart_in_window = self.crash_restarts_in_window(policy.window, now);
839        if restart_in_window >= policy.max_restarts {
840            return None;
841        }
842        self.record_crash_restart(policy, now);
843        Some(CrashRestartSchedule {
844            restart_in_window,
845            delay: policy.delay_for_restart(restart_in_window),
846        })
847    }
848
849    /// Give the module its full budget back, as an operator restart, reload, or
850    /// re-enable does. `lifetime_restarts` deliberately does not move: it is the
851    /// ledger of what actually happened, and an operator action does not unmake
852    /// the crashes.
853    fn clear_crash_restarts(&mut self) {
854        self.crash_restarts.clear();
855    }
856
857    fn new(state: ModuleState, enabled: bool) -> Self {
858        Self {
859            state,
860            enabled,
861            process_alive: false,
862            crash_restarts: VecDeque::new(),
863            lifetime_restarts: 0,
864            spawn_generation: 0,
865            pid: None,
866            spawned_at_ms: None,
867            spawned_from: None,
868            spawned_file_identity: None,
869            process_start_time: None,
870            deliberate_severance: None,
871            last_exit: None,
872            health: ModuleHealthStatus::default(),
873            in_alternate_slot: false,
874            draining_to_replace: false,
875            configuration_updated_since_spawn: false,
876        }
877    }
878}
879
880type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
881
882type SpawnSubscriberKey = (ConnectionId, u64);
883
884#[derive(Debug)]
885struct SpawnSubscriber {
886    version: u8,
887    frames: mpsc::Sender<Frame>,
888    /// Tells this subscriber's forwarder that it was dropped for lagging, and
889    /// from which event. The full frame channel cannot carry that news, so it
890    /// travels beside it; see `SpawnEventFeed::subscribe`.
891    lagged: Option<oneshot::Sender<SpawnCursor>>,
892}
893
894#[derive(Debug)]
895struct SpawnEventState {
896    daemon_incarnation: String,
897    seq: u64,
898    capacity: usize,
899    live: HashMap<String, LiveSpawn>,
900    generations: HashMap<String, u64>,
901    events: VecDeque<SpawnEvent>,
902    subscribers: HashMap<SpawnSubscriberKey, SpawnSubscriber>,
903}
904
905impl Default for SpawnEventState {
906    fn default() -> Self {
907        Self {
908            daemon_incarnation: "unconfigured".to_string(),
909            seq: 0,
910            capacity: SPAWN_EVENT_RING_CAPACITY,
911            live: HashMap::new(),
912            generations: HashMap::new(),
913            events: VecDeque::new(),
914            subscribers: HashMap::new(),
915        }
916    }
917}
918
919#[derive(Debug, Clone, Default)]
920struct SpawnEventFeed(Arc<Mutex<SpawnEventState>>);
921
922#[derive(Debug, Clone, PartialEq, Eq)]
923pub(crate) enum SpawnSubscribeRefusal {
924    ForeignIncarnation { current: String },
925    TooOld { oldest: SpawnCursor },
926    Frame(String),
927}
928
929impl SpawnEventFeed {
930    fn configure_incarnation(&self, daemon_incarnation: String) {
931        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
932        state.daemon_incarnation = daemon_incarnation;
933        state.seq = 0;
934        state.live.clear();
935        state.generations.clear();
936        state.events.clear();
937        state.subscribers.clear();
938    }
939
940    fn cursor(state: &SpawnEventState) -> SpawnCursor {
941        SpawnCursor {
942            daemon_incarnation: state.daemon_incarnation.clone(),
943            seq: state.seq,
944        }
945    }
946
947    fn snapshot(&self) -> SpawnSnapshot {
948        let state = self.0.lock().unwrap_or_else(|p| p.into_inner());
949        let mut live = state.live.values().cloned().collect::<Vec<_>>();
950        live.sort_by(|left, right| left.module_id.cmp(&right.module_id));
951        SpawnSnapshot {
952            cursor: Self::cursor(&state),
953            ring_bound: state.capacity as u64,
954            live,
955        }
956    }
957
958    fn emit_spawned(&self, module_id: &str, pid: u32, spawned_at_ms: u64) -> u64 {
959        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
960        let generation = state
961            .generations
962            .get(module_id)
963            .copied()
964            .unwrap_or(0)
965            .checked_add(1)
966            .expect("spawn generation exhausted");
967        state.generations.insert(module_id.to_string(), generation);
968        let live = LiveSpawn {
969            module_id: module_id.to_string(),
970            spawn_generation: generation,
971            pid,
972            spawned_at_ms,
973        };
974        state.live.insert(module_id.to_string(), live);
975        Self::emit_locked(
976            &mut state,
977            SpawnEventKind::Spawned,
978            module_id.to_string(),
979            generation,
980            pid,
981            None,
982            None,
983        );
984        generation
985    }
986
987    fn emit_exited(&self, module_id: &str, exit_code: Option<i32>, exit_signal: Option<i32>) {
988        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
989        let Some(live) = state.live.remove(module_id) else {
990            warn!(
991                module_id,
992                "terminal record had no live spawn event identity"
993            );
994            return;
995        };
996        Self::emit_locked(
997            &mut state,
998            SpawnEventKind::Exited,
999            module_id.to_string(),
1000            live.spawn_generation,
1001            live.pid,
1002            exit_code,
1003            exit_signal,
1004        );
1005    }
1006
1007    /// Report the exit of a process that a swap has already replaced.
1008    ///
1009    /// `emit_exited` removes the module's live entry, which after a swap's
1010    /// cutover describes the promoted candidate, not the old process now
1011    /// exiting. This emits the old generation's exit and leaves the live entry
1012    /// alone unless it still names that generation.
1013    fn emit_superseded_exited(
1014        &self,
1015        module_id: &str,
1016        spawn_generation: u64,
1017        pid: u32,
1018        exit_code: Option<i32>,
1019        exit_signal: Option<i32>,
1020    ) {
1021        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1022        if state
1023            .live
1024            .get(module_id)
1025            .is_some_and(|live| live.spawn_generation == spawn_generation)
1026        {
1027            state.live.remove(module_id);
1028        }
1029        Self::emit_locked(
1030            &mut state,
1031            SpawnEventKind::Exited,
1032            module_id.to_string(),
1033            spawn_generation,
1034            pid,
1035            exit_code,
1036            exit_signal,
1037        );
1038    }
1039
1040    #[allow(clippy::too_many_arguments)]
1041    fn emit_locked(
1042        state: &mut SpawnEventState,
1043        kind: SpawnEventKind,
1044        module_id: String,
1045        spawn_generation: u64,
1046        pid: u32,
1047        exit_code: Option<i32>,
1048        exit_signal: Option<i32>,
1049    ) {
1050        state.seq = state
1051            .seq
1052            .checked_add(1)
1053            .expect("spawn event sequence exhausted");
1054        let event = SpawnEvent {
1055            cursor: Self::cursor(state),
1056            kind,
1057            module_id,
1058            spawn_generation,
1059            pid,
1060            exit_code,
1061            exit_signal,
1062        };
1063        state.events.push_back(event.clone());
1064        while state.events.len() > state.capacity {
1065            state.events.pop_front();
1066        }
1067        let body = match serde_json::to_vec(&event) {
1068            Ok(body) => body,
1069            Err(error) => {
1070                error!(%error, "failed to serialize supervisor spawn event");
1071                return;
1072            }
1073        };
1074        state.subscribers.retain(|(connection_id, corr), subscriber| {
1075            let frame = Frame::build_with_version(
1076                subscriber.version,
1077                FrameType::StreamData,
1078                control_flags(),
1079                0,
1080                0,
1081                *corr,
1082                body.clone(),
1083            );
1084            match frame {
1085                Ok(frame) => {
1086                    if subscriber.frames.try_send(frame).is_ok() {
1087                        true
1088                    } else {
1089                        warn!(connection_id = connection_id.get(), corr, "dropping lagged supervisor spawn subscriber");
1090                        if let Some(lagged) = subscriber.lagged.take() {
1091                            let _ = lagged.send(event.cursor.clone());
1092                        }
1093                        false
1094                    }
1095                }
1096                Err(error) => {
1097                    warn!(connection_id = connection_id.get(), corr, %error, "dropping supervisor spawn subscriber after frame build failure");
1098                    false
1099                }
1100            }
1101        });
1102    }
1103
1104    fn subscribe(
1105        &self,
1106        connection_id: ConnectionId,
1107        corr: u64,
1108        version: u8,
1109        since: Option<SpawnCursor>,
1110        sink: FrameSink,
1111    ) -> Result<(), SpawnSubscribeRefusal> {
1112        let (frames, mut receiver) = mpsc::channel(SPAWN_SUBSCRIBER_BUFFER);
1113        let (lagged, mut lagged_rx) = oneshot::channel::<SpawnCursor>();
1114        {
1115            let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1116            let replay = if let Some(since) = since {
1117                if since.daemon_incarnation != state.daemon_incarnation {
1118                    return Err(SpawnSubscribeRefusal::ForeignIncarnation {
1119                        current: state.daemon_incarnation.clone(),
1120                    });
1121                }
1122                if let Some(oldest) = state.events.front().map(|event| event.cursor.clone()) {
1123                    if since.seq < oldest.seq.saturating_sub(1) {
1124                        return Err(SpawnSubscribeRefusal::TooOld { oldest });
1125                    }
1126                }
1127                state
1128                    .events
1129                    .iter()
1130                    .filter(|event| event.cursor.seq > since.seq)
1131                    .cloned()
1132                    .collect::<Vec<_>>()
1133            } else {
1134                Vec::new()
1135            };
1136            for event in replay {
1137                let body = serde_json::to_vec(&event)
1138                    .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
1139                let frame = Frame::build_with_version(
1140                    version,
1141                    FrameType::StreamData,
1142                    control_flags(),
1143                    0,
1144                    0,
1145                    corr,
1146                    body,
1147                )
1148                .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
1149                frames
1150                    .try_send(frame)
1151                    .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
1152            }
1153            state.subscribers.insert(
1154                (connection_id, corr),
1155                SpawnSubscriber {
1156                    version,
1157                    frames,
1158                    lagged: Some(lagged),
1159                },
1160            );
1161        }
1162        // The lagged terminal is sent here, by the forwarder, rather than by
1163        // the emitter: at the moment of the drop the subscriber's own channel
1164        // is full, and writing to the connection sink directly from the emitter
1165        // would put the Error AHEAD of the events still queued in that channel
1166        // (and the emitter holds the feed lock, so it cannot await the sink).
1167        // Dropping the subscriber drops the only sender, so `recv` drains every
1168        // queued event and then returns `None`; only then is the Error sent, so
1169        // the client sees each event it can keep, then the reason it was cut.
1170        // Cancel and connection removal drop the oneshot unsent, so they end
1171        // the stream with no Error.
1172        tokio::spawn(async move {
1173            while let Some(frame) = receiver.recv().await {
1174                if sink.send(frame).await.is_err() {
1175                    return;
1176                }
1177            }
1178            let Ok(first_undelivered) = lagged_rx.try_recv() else {
1179                return;
1180            };
1181            match spawn_subscriber_lagged_frame(version, corr, first_undelivered) {
1182                Ok(frame) => {
1183                    let _ = sink.send(frame).await;
1184                }
1185                Err(error) => {
1186                    error!(%error, corr, "failed to build lagged spawn subscriber terminal frame");
1187                }
1188            }
1189        });
1190        Ok(())
1191    }
1192
1193    fn cancel(&self, connection_id: ConnectionId, corr: u64) -> bool {
1194        let Some(subscriber) = self
1195            .0
1196            .lock()
1197            .unwrap_or_else(|p| p.into_inner())
1198            .subscribers
1199            .remove(&(connection_id, corr))
1200        else {
1201            return false;
1202        };
1203        if let Ok(frame) = Frame::build_with_version(
1204            subscriber.version,
1205            FrameType::StreamEnd,
1206            control_flags(),
1207            0,
1208            0,
1209            corr,
1210            Vec::new(),
1211        ) {
1212            tokio::spawn(async move {
1213                let _ = subscriber.frames.send(frame).await;
1214            });
1215        }
1216        true
1217    }
1218
1219    fn remove_connection(&self, connection_id: ConnectionId) {
1220        self.0
1221            .lock()
1222            .unwrap_or_else(|p| p.into_inner())
1223            .subscribers
1224            .retain(|(subscriber_connection, _), _| *subscriber_connection != connection_id);
1225    }
1226
1227    #[cfg(any(test, feature = "test-support"))]
1228    fn set_capacity(&self, capacity: usize) {
1229        self.0.lock().unwrap_or_else(|p| p.into_inner()).capacity = capacity;
1230    }
1231
1232    #[cfg(any(test, feature = "test-support"))]
1233    fn subscriber_count(&self) -> usize {
1234        self.0
1235            .lock()
1236            .unwrap_or_else(|p| p.into_inner())
1237            .subscribers
1238            .len()
1239    }
1240}
1241
1242/// Narrow process-liveness signal published by supervisors and consumed by passive liveness polls.
1243/// The terminal Error a lagged spawn subscriber receives after its queued events.
1244fn spawn_subscriber_lagged_frame(
1245    version: u8,
1246    corr: u64,
1247    first_undelivered: SpawnCursor,
1248) -> Result<Frame, String> {
1249    let body = serde_json::to_vec(&subc_protocol::ErrorBody {
1250        code: SPAWN_SUBSCRIBER_LAGGED_CODE.to_string(),
1251        message: "spawn subscriber fell behind and was dropped; resubscribe from the last cursor received"
1252            .to_string(),
1253        detail: Some(serde_json::json!({
1254            "first_undelivered_cursor": first_undelivered
1255        })),
1256    })
1257    .map_err(|error| error.to_string())?;
1258    Frame::build_with_version(version, FrameType::Error, control_flags(), 0, 0, corr, body)
1259        .map_err(|error| error.to_string())
1260}
1261
1262pub trait ModuleProcessLiveness: Send + Sync {
1263    fn process_live(&self, module_id: &str) -> Option<bool>;
1264
1265    /// Whether the supervisor is replacing this module's process right now: an
1266    /// operator restart or reload, a health restart, or a crash respawn whose
1267    /// backoff is running. A module in that state is not live, but a consumer
1268    /// refused now should retry shortly rather than treat the target as gone.
1269    /// Stopped, failed, and disabled modules are not replacing.
1270    fn process_replacing(&self, _module_id: &str) -> bool {
1271        false
1272    }
1273}
1274
1275/// Shared process-liveness registry keyed by supervised `module_id`.
1276#[derive(Debug, Clone, Default)]
1277pub struct SupervisorProcessLiveness {
1278    snapshots: Arc<Mutex<HashMap<String, SharedSnapshot>>>,
1279}
1280
1281impl SupervisorProcessLiveness {
1282    pub fn new() -> Self {
1283        Self::default()
1284    }
1285
1286    fn track(&self, module_id: String, snapshot: SharedSnapshot) {
1287        let mut snapshots = self
1288            .snapshots
1289            .lock()
1290            .unwrap_or_else(|poisoned| poisoned.into_inner());
1291        snapshots.insert(module_id, snapshot);
1292    }
1293
1294    fn untrack_if_current(&self, module_id: &str, snapshot: &SharedSnapshot) {
1295        let mut snapshots = self
1296            .snapshots
1297            .lock()
1298            .unwrap_or_else(|poisoned| poisoned.into_inner());
1299        let is_current = snapshots
1300            .get(module_id)
1301            .map(|tracked| Arc::ptr_eq(tracked, snapshot))
1302            .unwrap_or(false);
1303        if is_current {
1304            snapshots.remove(module_id);
1305        }
1306    }
1307}
1308
1309impl ModuleProcessLiveness for SupervisorProcessLiveness {
1310    fn process_live(&self, module_id: &str) -> Option<bool> {
1311        let snapshot = {
1312            let snapshots = self
1313                .snapshots
1314                .lock()
1315                .unwrap_or_else(|poisoned| poisoned.into_inner());
1316            snapshots.get(module_id).cloned()
1317        }?;
1318        let snapshot = snapshot
1319            .lock()
1320            .unwrap_or_else(|poisoned| poisoned.into_inner());
1321        Some(snapshot.state == ModuleState::Running && snapshot.process_alive)
1322    }
1323
1324    fn process_replacing(&self, module_id: &str) -> bool {
1325        let Some(snapshot) = self
1326            .snapshots
1327            .lock()
1328            .unwrap_or_else(|poisoned| poisoned.into_inner())
1329            .get(module_id)
1330            .cloned()
1331        else {
1332            return false;
1333        };
1334        let snapshot = snapshot
1335            .lock()
1336            .unwrap_or_else(|poisoned| poisoned.into_inner());
1337        snapshot.enabled
1338            && match snapshot.state {
1339                ModuleState::Restarting => true,
1340                ModuleState::Draining => snapshot.draining_to_replace,
1341                ModuleState::Starting
1342                | ModuleState::Running
1343                | ModuleState::Unresponsive
1344                | ModuleState::Stopped
1345                | ModuleState::Failed
1346                | ModuleState::Disabled => false,
1347            }
1348    }
1349}
1350
1351#[derive(Debug, Clone)]
1352struct SupervisorRuntimeConfig {
1353    restart_policy: RestartPolicy,
1354    /// This module's RESOLVED drain budget: per-module config when present,
1355    /// else `default_drain_timeout`.
1356    drain_timeout: Duration,
1357    /// Shared with the status handle so the attested value changes atomically
1358    /// when a rescan updates the running drain policy.
1359    effective_drain_timeout: Arc<Mutex<Duration>>,
1360    /// The supervisor-wide fallback, kept so a configuration update that
1361    /// REMOVES the per-module override can re-resolve to it.
1362    default_drain_timeout: Duration,
1363    health: HealthConfig,
1364    connection_file_path: Option<PathBuf>,
1365    capture_logs_dir: Option<PathBuf>,
1366    forwarding: Option<Arc<ForwardingTable>>,
1367    /// The shared handle, so every spawn path (initial, restart, reload) records the
1368    /// reserved-module launch nonce the HELLO verifier checks against.
1369    supervisor_handle: Option<SupervisorHandle>,
1370    /// This module's stderr tail, shared with the [`SupervisedModule`] that answers
1371    /// status queries.
1372    ///
1373    /// One ring per module, held across every respawn. The lines explaining an exit
1374    /// are written BEFORE that exit, so a ring recreated per process would be empty
1375    /// exactly when it is asked for.
1376    stderr_ring: Arc<Mutex<StderrRing>>,
1377    terminal_ring: Arc<Mutex<TerminalRing>>,
1378    spawn_events: SpawnEventFeed,
1379    child_roster: ChildRoster,
1380    #[cfg(target_os = "linux")]
1381    cgroup_placement: Option<subc_cgroup::Placement>,
1382    #[cfg(test)]
1383    test_seed_stale_facts_before_enable_spawn: bool,
1384}
1385
1386#[derive(Debug, Clone, PartialEq, Eq)]
1387struct SupervisedConfiguration {
1388    spec: ModuleSpec,
1389    health: HealthConfig,
1390}
1391
1392/// Shared daemon lookup table for supervised module handles.
1393///
1394/// Shared by clone between the [`Supervisor`] (which spawns processes) and the
1395/// channel-0 control handler (which verifies HELLOs and consumer route opens), so
1396/// launch nonces recorded at spawn are checked by the same daemon instance.
1397#[derive(Debug, Clone, Default)]
1398pub struct SupervisorHandle {
1399    modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
1400    spawn_events: SpawnEventFeed,
1401    /// The current expected launch nonce for each reserved module_id. Set when the
1402    /// supervisor spawns the reserved module; checked when a HELLO claims that id. A
1403    /// non-reserved module never has an entry here and is never nonce-checked.
1404    /// Reserved module ids and the nonce that authorizes their next HELLO.
1405    /// `None` means RESERVED WITH NO LEGITIMATE HOLDER — a reserved module that
1406    /// has never been spawned (e.g. configured `enabled: false`) — and refuses
1407    /// every HELLO. Before this was expressible, a reserved-but-never-spawned id
1408    /// had NO entry and admitted anyone: the reservation protected the nonce
1409    /// holder, not the NAME (found live by CKCRED's canary probe registering
1410    /// against a reserved scratch id).
1411    reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
1412    /// Module ids removed by an executed rescan and the unix-millisecond removal time.
1413    ///
1414    /// This is deliberately in-memory only: subc is state-free across daemon
1415    /// restarts, and the tombstone only explains the hours-after-removal window
1416    /// while this executing daemon is still alive. Do not persist it in a store.
1417    removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
1418    /// The current launch nonce for every supervised spawn. This is separate from
1419    /// reserved_nonces because consumer route.open attestation applies to all spawned
1420    /// modules, while HELLO id-squatting protection remains opt-in via `reserved`.
1421    spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
1422    /// Reserved namespace prefixes mapped to the supervised owner module whose
1423    /// current spawn nonce authorizes HELLO claims below the prefix.
1424    ///
1425    /// Per §2.6 this is not a same-user security barrier: a same-user process can
1426    /// read the key file and launch nonce env. Like exact reserved ids, it prevents
1427    /// accidental collisions and lower-trust processes from squatting protected
1428    /// namespaces.
1429    reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
1430    /// Blue/green swaps in progress, by module id. An entry exists from just
1431    /// before the candidate process is spawned until the swap has failed, or
1432    /// has cut over and the old process is gone. While it exists, HELLO for the
1433    /// id is gated on the swap token (see [`Self::swap_hello_admission`]) and
1434    /// consumer attestation accepts both processes' nonces.
1435    swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
1436    /// Told when a swap promotes its candidate; see [`SwapPromotionObserver`].
1437    promotion_observer: PromotionObserverSlot,
1438    /// Serializes module-set reconciliation with operator lifecycle commands. Without
1439    /// this daemon-wide ordering, a rescan could retire or update a module while a
1440    /// concurrent reload still held its old handle and launch specification.
1441    operation_lock: Arc<AsyncMutex<()>>,
1442}
1443
1444/// Told when a swap has promoted its candidate to be the module's active
1445/// registration.
1446///
1447/// An ordinary HELLO runs the control plane's registration side effects (the
1448/// capability cache, the deny census, the requirement recompute) as it
1449/// registers. A swap candidate's HELLO does not, because it is not routable;
1450/// promotion is when those must run instead, and promotion happens in the
1451/// supervisor, which has no other way into the control handler.
1452pub(crate) trait SwapPromotionObserver: Send + Sync {
1453    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration);
1454}
1455
1456/// The installed [`SwapPromotionObserver`], held weakly: the observer (the
1457/// control handler) owns this handle, so a strong reference back would be a
1458/// cycle that keeps both alive.
1459#[derive(Clone, Default)]
1460struct PromotionObserverSlot(Arc<Mutex<Option<std::sync::Weak<dyn SwapPromotionObserver>>>>);
1461
1462impl fmt::Debug for PromotionObserverSlot {
1463    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1464        f.write_str("PromotionObserverSlot")
1465    }
1466}
1467
1468/// The nonces of one open swap.
1469#[derive(Debug, Clone)]
1470struct OpenSwap {
1471    /// The launch nonce minted for the candidate process. It is the swap
1472    /// token: the only thing that admits a HELLO into the candidate slot.
1473    candidate_nonce: String,
1474    /// The incumbent's launch nonce, captured when the swap opened. It is kept
1475    /// here because cutover moves the module's recorded spawn nonce to the
1476    /// candidate while the incumbent is still draining and its consumers are
1477    /// still attesting with this one.
1478    incumbent_nonce: Option<String>,
1479    /// Set once a HELLO has been admitted with the swap token, so the token
1480    /// admits one registration and cannot be replayed after cutover empties
1481    /// the candidate slot.
1482    candidate_admitted: bool,
1483}
1484
1485/// What the swap gate says about a HELLO. See
1486/// [`SupervisorHandle::swap_hello_admission`].
1487#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1488pub(crate) enum SwapHelloAdmission {
1489    /// No swap is open for the id (or the HELLO carries the incumbent's own
1490    /// nonce); the ordinary gates decide.
1491    NotSwapping,
1492    /// The HELLO carries the swap token: register it into the candidate slot.
1493    Candidate,
1494    /// A swap is open and the HELLO carries a nonce the supervisor did not
1495    /// mint for this id, no nonce, or a token already used.
1496    Refused,
1497}
1498
1499#[derive(Debug, Clone, PartialEq, Eq)]
1500pub(crate) enum ReservedHelloRejection {
1501    Exact {
1502        module_id: String,
1503    },
1504    Prefix {
1505        prefix: String,
1506        owner_module_id: String,
1507    },
1508}
1509
1510impl SupervisorHandle {
1511    pub fn new() -> Self {
1512        Self::default()
1513    }
1514
1515    pub(crate) fn spawn_snapshot(&self) -> SpawnSnapshot {
1516        self.spawn_events.snapshot()
1517    }
1518
1519    pub(crate) fn subscribe_spawns(
1520        &self,
1521        connection_id: ConnectionId,
1522        corr: u64,
1523        version: u8,
1524        since: Option<SpawnCursor>,
1525        sink: FrameSink,
1526    ) -> Result<(), SpawnSubscribeRefusal> {
1527        self.spawn_events
1528            .subscribe(connection_id, corr, version, since, sink)
1529    }
1530
1531    pub(crate) fn cancel_spawn_subscription(&self, connection_id: ConnectionId, corr: u64) -> bool {
1532        self.spawn_events.cancel(connection_id, corr)
1533    }
1534
1535    pub(crate) fn remove_spawn_subscribers(&self, connection_id: ConnectionId) {
1536        self.spawn_events.remove_connection(connection_id);
1537    }
1538
1539    #[cfg(any(test, feature = "test-support"))]
1540    pub fn set_spawn_event_capacity_for_test(&self, capacity: usize) {
1541        assert!(capacity > 0, "spawn event capacity must be non-zero");
1542        self.spawn_events.set_capacity(capacity);
1543    }
1544
1545    #[cfg(any(test, feature = "test-support"))]
1546    pub fn spawn_subscriber_count_for_test(&self) -> usize {
1547        self.spawn_events.subscriber_count()
1548    }
1549
1550    /// Record the launch nonce from a supervised spawn, replacing any prior nonce so
1551    /// a respawn invalidates stale consumer identities.
1552    pub fn set_spawn_nonce(&self, module_id: &str, nonce: String) {
1553        self.spawn_nonces
1554            .lock()
1555            .unwrap_or_else(|poisoned| poisoned.into_inner())
1556            .insert(module_id.to_string(), nonce);
1557    }
1558
1559    /// Record the launch nonce expected from the next HELLO for a reserved module,
1560    /// replacing any prior nonce (a respawn invalidates the previous one).
1561    pub fn set_reserved_nonce(&self, module_id: &str, nonce: String) {
1562        self.reserved_nonces
1563            .lock()
1564            .unwrap_or_else(|poisoned| poisoned.into_inner())
1565            .insert(module_id.to_string(), Some(nonce));
1566    }
1567
1568    /// Record namespace prefixes owned by a supervised module.
1569    pub fn set_reserved_prefixes(&self, owner_module_id: &str, prefixes: &[String]) {
1570        let mut owners = self
1571            .reserved_prefix_owners
1572            .lock()
1573            .unwrap_or_else(|poisoned| poisoned.into_inner());
1574        owners.retain(|_, owner| owner != owner_module_id);
1575        for prefix in prefixes {
1576            owners.insert(prefix.clone(), owner_module_id.to_string());
1577        }
1578    }
1579
1580    /// The launch nonce most recently minted for a module's spawn, if any.
1581    #[cfg(test)]
1582    pub(crate) fn spawn_nonce(&self, module_id: &str) -> Option<String> {
1583        self.spawn_nonces
1584            .lock()
1585            .unwrap_or_else(|poisoned| poisoned.into_inner())
1586            .get(module_id)
1587            .cloned()
1588    }
1589
1590    fn apply_identity_configuration(&self, spec: &ModuleSpec) {
1591        self.set_reserved_prefixes(&spec.module_id, &spec.reserved_prefixes);
1592        let spawn_nonce = self
1593            .spawn_nonces
1594            .lock()
1595            .unwrap_or_else(|poisoned| poisoned.into_inner())
1596            .get(&spec.module_id)
1597            .cloned();
1598        let mut reserved_nonces = self
1599            .reserved_nonces
1600            .lock()
1601            .unwrap_or_else(|poisoned| poisoned.into_inner());
1602        if spec.reserved {
1603            // `None` (no spawn nonce minted) is INSERTED, not skipped: a
1604            // reserved name whose module has never spawned has no legitimate
1605            // holder, and the entry's absence is what used to leave the name
1606            // open to the first claimant.
1607            reserved_nonces.insert(spec.module_id.clone(), spawn_nonce);
1608        }
1609        drop(reserved_nonces);
1610        // A later unreserved declaration must not silently unreserve an id that
1611        // was retained after its reserved configuration was removed. The explicit
1612        // release ceremony is the only operation that retires that gate.
1613        self.removal_tombstones
1614            .lock()
1615            .unwrap_or_else(|poisoned| poisoned.into_inner())
1616            .remove(&spec.module_id);
1617    }
1618
1619    /// Whether a HELLO claiming `module_id` is authorized. An exact reserved id is
1620    /// authorized only by its expected nonce; otherwise a matching reserved prefix
1621    /// is authorized by the owner module's current spawn nonce. Non-reserved ids
1622    /// with no matching prefix are always authorized.
1623    pub fn reserved_hello_authorized(&self, module_id: &str, presented: Option<&str>) -> bool {
1624        self.reserved_hello_rejection(module_id, presented)
1625            .is_none()
1626    }
1627
1628    pub(crate) fn reserved_hello_rejection(
1629        &self,
1630        module_id: &str,
1631        presented: Option<&str>,
1632    ) -> Option<ReservedHelloRejection> {
1633        let nonces = self
1634            .reserved_nonces
1635            .lock()
1636            .unwrap_or_else(|poisoned| poisoned.into_inner());
1637        if let Some(expected) = nonces.get(module_id) {
1638            // `None` = reserved with no legitimate holder: refuse every
1639            // presentation, because no process can hold a nonce that was never
1640            // minted. Only a real minted nonce admits, in constant time.
1641            let authorized = match expected {
1642                Some(expected) => {
1643                    presented.is_some_and(|p| constant_time_eq(expected.as_bytes(), p.as_bytes()))
1644                }
1645                None => false,
1646            };
1647            if authorized {
1648                return None;
1649            }
1650            return Some(ReservedHelloRejection::Exact {
1651                module_id: module_id.to_string(),
1652            });
1653        }
1654        drop(nonces);
1655
1656        let matched_prefix = self
1657            .reserved_prefix_owners
1658            .lock()
1659            .unwrap_or_else(|poisoned| poisoned.into_inner())
1660            .iter()
1661            .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
1662            .max_by_key(|(prefix, _)| prefix.len())
1663            .map(|(prefix, owner)| (prefix.clone(), owner.clone()));
1664        let (prefix, owner_module_id) = matched_prefix?;
1665
1666        let authorized = presented.is_some_and(|presented| {
1667            self.spawn_nonces
1668                .lock()
1669                .unwrap_or_else(|poisoned| poisoned.into_inner())
1670                .get(&owner_module_id)
1671                .is_some_and(|expected| constant_time_eq(expected.as_bytes(), presented.as_bytes()))
1672                // While the owner is being swapped, children started by
1673                // either of its two processes hold that process's nonce.
1674                || self.swap_nonce_matches(&owner_module_id, presented)
1675        });
1676        if authorized {
1677            None
1678        } else {
1679            Some(ReservedHelloRejection::Prefix {
1680                prefix,
1681                owner_module_id,
1682            })
1683        }
1684    }
1685
1686    /// Whether a consumer connection proved it came from a daemon-spawned module.
1687    ///
1688    /// Absence of an expected spawn nonce is a hard failure: consumer_identity is
1689    /// accepted only for module ids the supervisor has spawned.
1690    pub fn spawned_consumer_authorized(&self, module_id: &str, presented: &str) -> bool {
1691        if presented.is_empty() {
1692            return false;
1693        }
1694        let nonces = self
1695            .spawn_nonces
1696            .lock()
1697            .unwrap_or_else(|poisoned| poisoned.into_inner());
1698        let current = nonces
1699            .get(module_id)
1700            .is_some_and(|expected| constant_time_eq(expected.as_bytes(), presented.as_bytes()));
1701        drop(nonces);
1702        // During a swap two processes of the module are alive, and a consumer
1703        // started by either one presents that process's nonce. Accepting only
1704        // the recorded one would fail the incumbent's consumers for the whole
1705        // overlap once cutover moves the record to the candidate.
1706        current || self.swap_nonce_matches(module_id, presented)
1707    }
1708
1709    /// Whether `presented` is either nonce of an open swap for `module_id`.
1710    fn swap_nonce_matches(&self, module_id: &str, presented: &str) -> bool {
1711        let swaps = self
1712            .swaps
1713            .lock()
1714            .unwrap_or_else(|poisoned| poisoned.into_inner());
1715        swaps.get(module_id).is_some_and(|swap| {
1716            constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes())
1717                || swap.incumbent_nonce.as_deref().is_some_and(|incumbent| {
1718                    constant_time_eq(incumbent.as_bytes(), presented.as_bytes())
1719                })
1720        })
1721    }
1722
1723    /// Open a swap for `module_id` with the candidate's freshly minted nonce.
1724    /// Called before the candidate process exists.
1725    pub(crate) fn open_swap(&self, module_id: &str, candidate_nonce: String) {
1726        let incumbent_nonce = self
1727            .spawn_nonces
1728            .lock()
1729            .unwrap_or_else(|poisoned| poisoned.into_inner())
1730            .get(module_id)
1731            .cloned();
1732        self.swaps
1733            .lock()
1734            .unwrap_or_else(|poisoned| poisoned.into_inner())
1735            .insert(
1736                module_id.to_string(),
1737                OpenSwap {
1738                    candidate_nonce,
1739                    incumbent_nonce,
1740                    candidate_admitted: false,
1741                },
1742            );
1743    }
1744
1745    /// Close the swap for `module_id`, releasing whichever nonce is no longer
1746    /// the module's recorded one.
1747    pub(crate) fn close_swap(&self, module_id: &str) {
1748        self.swaps
1749            .lock()
1750            .unwrap_or_else(|poisoned| poisoned.into_inner())
1751            .remove(module_id);
1752    }
1753
1754    /// Install the observer told about swap promotions, replacing any earlier
1755    /// one.
1756    pub(crate) fn set_swap_promotion_observer(
1757        &self,
1758        observer: std::sync::Weak<dyn SwapPromotionObserver>,
1759    ) {
1760        *self
1761            .promotion_observer
1762            .0
1763            .lock()
1764            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer);
1765    }
1766
1767    /// Tell the installed observer, if it is still alive, that a swap promoted
1768    /// `registration`.
1769    fn notify_swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
1770        let observer = self
1771            .promotion_observer
1772            .0
1773            .lock()
1774            .unwrap_or_else(|poisoned| poisoned.into_inner())
1775            .as_ref()
1776            .and_then(std::sync::Weak::upgrade);
1777        if let Some(observer) = observer {
1778            observer.swap_promoted(registration);
1779        }
1780    }
1781
1782    /// Whether a swap is open for `module_id`.
1783    pub(crate) fn swap_open(&self, module_id: &str) -> bool {
1784        self.swaps
1785            .lock()
1786            .unwrap_or_else(|poisoned| poisoned.into_inner())
1787            .contains_key(module_id)
1788    }
1789
1790    /// Make the candidate's nonce the module's recorded spawn nonce, as a plain
1791    /// respawn would, once cutover has made the candidate the module's process.
1792    /// The swap stays open so the incumbent's nonce keeps attesting until the
1793    /// incumbent has drained and exited.
1794    fn promote_swap_nonce(&self, module_id: &str, reserved: bool) {
1795        let candidate_nonce = self
1796            .swaps
1797            .lock()
1798            .unwrap_or_else(|poisoned| poisoned.into_inner())
1799            .get(module_id)
1800            .map(|swap| swap.candidate_nonce.clone());
1801        let Some(nonce) = candidate_nonce else {
1802            return;
1803        };
1804        self.set_spawn_nonce(module_id, nonce.clone());
1805        if reserved {
1806            self.set_reserved_nonce(module_id, nonce);
1807        }
1808    }
1809
1810    /// The swap gate for a HELLO claiming `module_id`.
1811    ///
1812    /// This runs BEFORE the reserved-module gate. A reserved module's candidate
1813    /// presents the candidate nonce, which the reserved gate (holding the
1814    /// incumbent's nonce) would refuse as `reserved_module` before swap
1815    /// admission was ever reached. And it applies to unreserved ids too: for an
1816    /// unreserved id the only thing that ever stopped a second process claiming
1817    /// a live id was the `duplicate_module_id` refusal, which is exactly the
1818    /// refusal a swap lifts for its candidate.
1819    ///
1820    /// The incumbent's own nonce falls through to the ordinary gates, which
1821    /// treat it as they always have (a live incumbent is refused as a
1822    /// duplicate). Anything else while a swap is open is refused, including an
1823    /// absent nonce.
1824    pub(crate) fn swap_hello_admission(
1825        &self,
1826        module_id: &str,
1827        presented: Option<&str>,
1828    ) -> SwapHelloAdmission {
1829        let swaps = self
1830            .swaps
1831            .lock()
1832            .unwrap_or_else(|poisoned| poisoned.into_inner());
1833        let Some(swap) = swaps.get(module_id) else {
1834            return SwapHelloAdmission::NotSwapping;
1835        };
1836        let Some(presented) = presented else {
1837            return SwapHelloAdmission::Refused;
1838        };
1839        if constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes()) {
1840            return if swap.candidate_admitted {
1841                SwapHelloAdmission::Refused
1842            } else {
1843                SwapHelloAdmission::Candidate
1844            };
1845        }
1846        if swap
1847            .incumbent_nonce
1848            .as_deref()
1849            .is_some_and(|incumbent| constant_time_eq(incumbent.as_bytes(), presented.as_bytes()))
1850        {
1851            return SwapHelloAdmission::NotSwapping;
1852        }
1853        SwapHelloAdmission::Refused
1854    }
1855
1856    /// Record that the swap token has registered a candidate, so it admits no
1857    /// second HELLO.
1858    pub(crate) fn mark_swap_candidate_admitted(&self, module_id: &str) {
1859        if let Some(swap) = self
1860            .swaps
1861            .lock()
1862            .unwrap_or_else(|poisoned| poisoned.into_inner())
1863            .get_mut(module_id)
1864        {
1865            swap.candidate_admitted = true;
1866        }
1867    }
1868
1869    /// Test/support lookup for the current launch nonce of a supervised spawn.
1870    pub fn spawn_launch_nonce_for(&self, module_id: &str) -> Option<String> {
1871        self.spawn_nonces
1872            .lock()
1873            .unwrap_or_else(|poisoned| poisoned.into_inner())
1874            .get(module_id)
1875            .cloned()
1876    }
1877
1878    /// Test/support lookup for the HELLO-gating nonce of a reserved module.
1879    pub fn reserved_launch_nonce_for(&self, module_id: &str) -> Option<String> {
1880        self.reserved_nonces
1881            .lock()
1882            .unwrap_or_else(|poisoned| poisoned.into_inner())
1883            .get(module_id)
1884            .cloned()
1885            .flatten()
1886    }
1887
1888    pub fn insert(&self, module: SupervisedModule) -> Option<SupervisedModule> {
1889        let mut modules = self
1890            .modules
1891            .lock()
1892            .unwrap_or_else(|poisoned| poisoned.into_inner());
1893        modules.insert(module.module_id().to_string(), module)
1894    }
1895
1896    pub fn get(&self, module_id: &str) -> Option<SupervisedModule> {
1897        let modules = self
1898            .modules
1899            .lock()
1900            .unwrap_or_else(|poisoned| poisoned.into_inner());
1901        modules.get(module_id).cloned()
1902    }
1903
1904    pub(crate) fn record_late_health_answer(
1905        &self,
1906        module_id: &str,
1907        latency_ms: u64,
1908    ) -> Result<bool, SuperviseError> {
1909        let Some(module) = self.get(module_id) else {
1910            return Ok(false);
1911        };
1912        update_snapshot(&module.inner.snapshot, Some(module_id), |state| {
1913            state.health.late_answer_count = state.health.late_answer_count.saturating_add(1);
1914            state.health.last_late_answer_latency_ms = Some(latency_ms);
1915            // A late answer is an answer: the module served the probe, just past
1916            // the deadline. Leaving the miss streak in place while logging
1917            // "proves the module is alive" is how a CPU-starved module that
1918            // answers every probe a few seconds late still marches to the
1919            // threshold and gets killed — the exact kill class `NoAnswer` is
1920            // excluded from `is_proof_of_death` to prevent. Slow-but-answering
1921            // is degradation, and degradation reports; it does not restart.
1922            state.health.consecutive_failures = 0;
1923        })?;
1924        Ok(true)
1925    }
1926
1927    /// Arm the one-shot marker for the module process that this caller
1928    /// deliberately initiated severance against. Generic connection teardown
1929    /// must not call this:
1930    /// a surviving process would otherwise retain an exemption for a later
1931    /// genuine crash.
1932    pub fn record_deliberate_severance(&self, module_id: &str) -> Result<bool, SuperviseError> {
1933        let Some(module) = self.get(module_id) else {
1934            return Ok(false);
1935        };
1936        let status = module.status()?;
1937        let Some((pid, start_time)) = status.pid.zip(status.process_start_time) else {
1938            return Ok(false);
1939        };
1940        module.record_deliberate_severance(ProcessIdentity { pid, start_time })
1941    }
1942
1943    pub fn list(&self) -> Vec<SupervisedModule> {
1944        let modules = self
1945            .modules
1946            .lock()
1947            .unwrap_or_else(|poisoned| poisoned.into_inner());
1948        let mut modules = modules.values().cloned().collect::<Vec<_>>();
1949        modules.sort_by(|left, right| left.module_id().cmp(right.module_id()));
1950        modules
1951    }
1952
1953    pub(crate) fn retire(&self, module_id: &str) -> Option<SupervisedModule> {
1954        self.spawn_nonces
1955            .lock()
1956            .unwrap_or_else(|poisoned| poisoned.into_inner())
1957            .remove(module_id);
1958        self.close_swap(module_id);
1959        let mut reserved_nonces = self
1960            .reserved_nonces
1961            .lock()
1962            .unwrap_or_else(|poisoned| poisoned.into_inner());
1963        if reserved_nonces.contains_key(module_id) {
1964            // The old nonce must die with the removed process, but the exact-id
1965            // gate remains until an operator explicitly releases it.
1966            reserved_nonces.insert(module_id.to_string(), None);
1967        }
1968        drop(reserved_nonces);
1969        self.reserved_prefix_owners
1970            .lock()
1971            .unwrap_or_else(|poisoned| poisoned.into_inner())
1972            .retain(|_, owner| owner != module_id);
1973        self.modules
1974            .lock()
1975            .unwrap_or_else(|poisoned| poisoned.into_inner())
1976            .remove(module_id)
1977    }
1978
1979    /// Remember a module removed by a non-preview rescan so route.open can
1980    /// distinguish that intentional removal from an unknown id.
1981    pub(crate) fn record_rescan_removal(&self, module_id: &str) {
1982        self.removal_tombstones
1983            .lock()
1984            .unwrap_or_else(|poisoned| poisoned.into_inner())
1985            .insert(module_id.to_string(), unix_ms_now());
1986    }
1987
1988    /// Return how long ago a rescan removed this module in milliseconds.
1989    pub(crate) fn removal_tombstone_age_ms(&self, module_id: &str) -> Option<u64> {
1990        self.removal_tombstones
1991            .lock()
1992            .unwrap_or_else(|poisoned| poisoned.into_inner())
1993            .get(module_id)
1994            .copied()
1995            .map(|removed_at_ms| unix_ms_now().saturating_sub(removed_at_ms))
1996    }
1997
1998    /// Retire a reserved-id gate only after its module has left supervision.
1999    ///
2000    /// A retained gate has no live nonce (`None`), so releasing any other entry
2001    /// would weaken a currently configured or otherwise active reservation.
2002    pub(crate) fn release_retained_reserved_gate(&self, module_id: &str) -> bool {
2003        if self.get(module_id).is_some() {
2004            return false;
2005        }
2006        let mut reserved_nonces = self
2007            .reserved_nonces
2008            .lock()
2009            .unwrap_or_else(|poisoned| poisoned.into_inner());
2010        if !matches!(reserved_nonces.get(module_id), Some(None)) {
2011            return false;
2012        }
2013        reserved_nonces.remove(module_id);
2014        true
2015    }
2016
2017    pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
2018        Arc::clone(&self.operation_lock)
2019    }
2020}
2021
2022/// Process supervisor for subc-owned singleton modules.
2023#[derive(Debug, Clone)]
2024pub struct Supervisor {
2025    registry: Arc<Registry>,
2026    restart_policy: RestartPolicy,
2027    drain_timeout: Duration,
2028    connection_file_path: Option<PathBuf>,
2029    capture_logs_dir: Option<PathBuf>,
2030    forwarding: Option<Arc<ForwardingTable>>,
2031    process_liveness: Arc<SupervisorProcessLiveness>,
2032    supervisor_handle: Option<SupervisorHandle>,
2033    health: HealthConfig,
2034    daemon_start_clock: crate::clock::StartClock,
2035    terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
2036    spawn_events: SpawnEventFeed,
2037    provenance_probe: ExecutableIdentityProbe,
2038    /// Every process spawned through this supervisor (and its clones) and not
2039    /// yet reaped, so daemon shutdown can end them.
2040    child_roster: ChildRoster,
2041    #[cfg(target_os = "linux")]
2042    cgroup_placement: Option<subc_cgroup::Placement>,
2043}
2044
2045impl Supervisor {
2046    /// The first step of an announced daemon shutdown, before the notice and
2047    /// before any connection is closed.
2048    ///
2049    /// Sets the daemon-shutdown flag first: from here on no module is
2050    /// respawned (crash restart, operator restart, or swap), and every child
2051    /// exit is recorded as `daemon_shutdown` rather than as a crash, whether
2052    /// the module exits on the EOF this shutdown gives it or is signalled by a
2053    /// service manager that kills the whole cgroup. Then writes the journal's
2054    /// shutdown marker, which records the instant and closes this daemon
2055    /// incarnation's stretch of the journal.
2056    #[cfg(unix)]
2057    pub(crate) fn begin_daemon_shutdown(&self) {
2058        self.child_roster.close();
2059        if let Some(journal) = &self.terminal_journal {
2060            journal.stamp_shutdown();
2061        }
2062    }
2063
2064    /// Announce a cut while established connections can still carry replies.
2065    /// These budgets promise notice and a bounded wait, not child completion;
2066    /// they are local policy, not an estimate of launchd's unknown kill ceiling.
2067    #[cfg(unix)]
2068    pub(crate) async fn drain_for_daemon_shutdown(&self) -> Result<(), SuperviseError> {
2069        const NOTICE_BUDGET: Duration = Duration::from_millis(500);
2070        const DRAIN_BUDGET: Duration = Duration::from_secs(2);
2071        let Some(forwarding) = &self.forwarding else {
2072            return Ok(());
2073        };
2074        let module_ids = forwarding
2075            .begin_daemon_drain()
2076            .map_err(SuperviseError::Forwarding)?;
2077        let deadline_ms =
2078            unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
2079        let mut notices = tokio::task::JoinSet::new();
2080        let mut drains = Vec::new();
2081        for module_id in module_ids {
2082            let Some(target) = forwarding
2083                .begin_module_drain(&module_id, RouteCloseReason::Restart)
2084                .map_err(SuperviseError::Forwarding)?
2085            else {
2086                continue;
2087            };
2088            let routes = forwarding
2089                .endpoint_routes(target.endpoint)
2090                .map_err(SuperviseError::Forwarding)?;
2091            // Restart allows deployed consumers to reopen after the new daemon
2092            // appears. The wire reason stays `restart`; what tells a daemon cut
2093            // apart from a module restart afterwards is the terminal record
2094            // itself, whose disposition is `daemon_shutdown` for every exit
2095            // observed once `begin_daemon_shutdown` has run.
2096            let command = serde_json::to_vec(&ModuleControlCommand::Draining {
2097                reason: RouteCloseReason::Restart,
2098                deadline_ms,
2099            })
2100            .expect("module draining serializes");
2101            let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
2102                module_id: module_id.clone(),
2103                reason: RouteCloseReason::Restart,
2104            })
2105            .expect("route closing serializes");
2106            let mut recipients = vec![(target.sink.clone(), target.negotiated_ver, command)];
2107            let mut seen = std::collections::HashSet::new();
2108            for route in routes {
2109                let client = route.goodbye_target;
2110                if seen.insert(client.connection_id) {
2111                    recipients.push((client.sink, client.negotiated_ver, closing.clone()));
2112                }
2113            }
2114            for (sink, version, body) in recipients {
2115                notices.spawn(async move {
2116                    let frame = Frame::build_with_version(
2117                        version,
2118                        FrameType::Push,
2119                        control_flags(),
2120                        0,
2121                        0,
2122                        0,
2123                        body,
2124                    )
2125                    .expect("bounded lifecycle notice frame builds");
2126                    sink.send_flushed(frame).await
2127                });
2128            }
2129            let gauges = declared_busy_gauges(&self.registry, &module_id)?;
2130            drains.push((module_id, target.endpoint, gauges));
2131        }
2132        // A quiet forwarding table is not proof that queued notices reached the
2133        // socket. Wait for writer flush acknowledgements before testing quiescence.
2134        let notice_deadline = Instant::now() + NOTICE_BUDGET;
2135        while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
2136            if !matches!(result, Ok(Ok(()))) {
2137                warn!(?result, "daemon shutdown notice delivery failed");
2138            }
2139        }
2140        notices.abort_all();
2141        let deadline = Instant::now() + DRAIN_BUDGET;
2142        let mut waits = tokio::task::JoinSet::new();
2143        for (module_id, endpoint, gauges) in drains {
2144            let forwarding = Arc::clone(forwarding);
2145            let mut runtime = self.runtime_config();
2146            runtime.health.cadence = Duration::from_millis(100);
2147            waits.spawn(async move {
2148                wait_for_forwarding_quiescence(
2149                    &forwarding,
2150                    &module_id,
2151                    &runtime,
2152                    endpoint,
2153                    deadline,
2154                    &gauges,
2155                    DrainScope::Active,
2156                )
2157                .await
2158            });
2159        }
2160        while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
2161            if !matches!(result, Ok(Ok(true))) {
2162                warn!(?result, "daemon shutdown drain did not reach quiescence");
2163            }
2164        }
2165        Ok(())
2166    }
2167
2168    /// The last step of an announced daemon shutdown, after the notice and the
2169    /// drain: close every connection so each subc module sees EOF and starts
2170    /// its own teardown, then end every supervised child that has not exited
2171    /// by its own deadline (its drain budget, capped). Modules lead their own
2172    /// process groups, so a
2173    /// service manager's group kill no longer reaches them; without this a
2174    /// child that does not stop on EOF (every `protocol: "none"` child, which
2175    /// has no connection) would outlive the daemon. Every wait is bounded (see
2176    /// `child_roster`), and `escalate` resolving (a second SIGTERM) cuts them.
2177    #[cfg(unix)]
2178    pub(crate) async fn end_children_for_daemon_shutdown(
2179        &self,
2180        already_escalated: bool,
2181        escalate: impl std::future::Future<Output = ()>,
2182    ) {
2183        if let Some(forwarding) = &self.forwarding {
2184            let closed = forwarding.close_all_connections(&CloseReason::new(
2185                "daemon_shutdown",
2186                "the daemon is exiting after its shutdown notice and drain",
2187            ));
2188            debug!(closed, "closed established connections for daemon shutdown");
2189        }
2190        crate::child_roster::end_children_for_daemon_shutdown(
2191            &self.child_roster,
2192            already_escalated,
2193            escalate,
2194        )
2195        .await;
2196    }
2197
2198    pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
2199        Self {
2200            registry,
2201            restart_policy,
2202            drain_timeout: DEFAULT_DRAIN_TIMEOUT,
2203            connection_file_path: None,
2204            capture_logs_dir: None,
2205            forwarding: None,
2206            process_liveness: Arc::new(SupervisorProcessLiveness::default()),
2207            supervisor_handle: None,
2208            health: HealthConfig::default(),
2209            daemon_start_clock: crate::clock::StartClock::capture(),
2210            terminal_journal: None,
2211            spawn_events: SpawnEventFeed::default(),
2212            provenance_probe: ExecutableIdentityProbe::default(),
2213            child_roster: ChildRoster::default(),
2214            #[cfg(target_os = "linux")]
2215            cgroup_placement: None,
2216        }
2217    }
2218
2219    pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
2220        self.drain_timeout = drain_timeout;
2221        self
2222    }
2223
2224    pub fn with_process_liveness(
2225        mut self,
2226        process_liveness: Arc<SupervisorProcessLiveness>,
2227    ) -> Self {
2228        self.process_liveness = process_liveness;
2229        self
2230    }
2231
2232    pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
2233        self.connection_file_path = Some(connection_file_path.into());
2234        self
2235    }
2236
2237    /// Enables daemon-owned capture files for supervised stdout and stderr.
2238    pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
2239        self.capture_logs_dir = Some(logs_dir.into());
2240        self
2241    }
2242
2243    /// Names this daemon lifetime in spawn events, independently of whether a
2244    /// terminal journal is configured.
2245    pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
2246        // A millisecond start stamp can repeat after clock rollback or a rapid
2247        // restart. Use the connection file's random daemon_id instead: it already
2248        // identifies this daemon lifetime independently of the wall clock.
2249        self.spawn_events.configure_incarnation(daemon_incarnation);
2250        self
2251    }
2252
2253    /// Enables best-effort history shared by every supervised module. Without
2254    /// it, terminal history is kept only in each module's in-memory ring.
2255    pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
2256        let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
2257        this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
2258            path,
2259            daemon_incarnation,
2260        )));
2261        this
2262    }
2263
2264    pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
2265        self.forwarding = Some(forwarding);
2266        self
2267    }
2268
2269    pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
2270        self.spawn_events = supervisor_handle.spawn_events.clone();
2271        self.supervisor_handle = Some(supervisor_handle);
2272        self
2273    }
2274
2275    pub fn with_health_config(mut self, health: HealthConfig) -> Self {
2276        self.health = health;
2277        self
2278    }
2279
2280    /// Keeps a record of every live child at `path`, rewritten on each spawn and
2281    /// reap, for the orphan sweep a later daemon runs at boot. Without it no
2282    /// record is kept.
2283    pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
2284        self.child_roster.record_to(path.into());
2285        self
2286    }
2287
2288    #[cfg(target_os = "linux")]
2289    pub fn with_cgroup_placement(
2290        mut self,
2291        cgroup_placement: Option<subc_cgroup::Placement>,
2292    ) -> Self {
2293        self.cgroup_placement = cgroup_placement;
2294        self
2295    }
2296
2297    /// Spawn `spec.program` and start monitoring it.
2298    ///
2299    /// The child is expected to parse `--subc <connection-file-path>`, read the
2300    /// TCP+key connection file, authenticate to the already-running listener, and
2301    /// register with channel-0 `HELLO` using `spec.module_id` as its manifest id.
2302    pub fn spawn(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
2303        validate_spec(&spec)?;
2304
2305        let runtime = self.runtime_config();
2306        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
2307        let child = spawn_child(
2308            &spec,
2309            runtime.connection_file_path.as_deref(),
2310            self.supervisor_handle.as_ref(),
2311            &runtime.stderr_ring,
2312            runtime.capture_logs_dir.as_deref(),
2313            &runtime.child_roster,
2314            #[cfg(target_os = "linux")]
2315            runtime.cgroup_placement.as_ref(),
2316        )?;
2317        set_running(&snapshot, &child, &spec.module_id, &runtime.spawn_events)?;
2318        self.process_liveness
2319            .track(spec.module_id.clone(), Arc::clone(&snapshot));
2320
2321        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
2322    }
2323
2324    /// Start supervising a module declared in daemon configuration.
2325    ///
2326    /// Unlike [`Self::spawn`], this records disabled modules and immediate spawn
2327    /// failures in the supervisor handle so operator-facing `supervisor.list`
2328    /// reflects every configured module while daemon startup continues.
2329    pub fn supervise_configured(
2330        &self,
2331        spec: ModuleSpec,
2332        enabled: bool,
2333    ) -> Result<SupervisedModule, SuperviseError> {
2334        validate_spec(&spec)?;
2335
2336        let runtime = self.runtime_config();
2337        if !enabled {
2338            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::disabled()));
2339            return Ok(self.supervised_module(spec, runtime, snapshot, None));
2340        }
2341
2342        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
2343        match spawn_child(
2344            &spec,
2345            runtime.connection_file_path.as_deref(),
2346            self.supervisor_handle.as_ref(),
2347            &runtime.stderr_ring,
2348            runtime.capture_logs_dir.as_deref(),
2349            &runtime.child_roster,
2350            #[cfg(target_os = "linux")]
2351            runtime.cgroup_placement.as_ref(),
2352        ) {
2353            Ok(child) => {
2354                set_running(&snapshot, &child, &spec.module_id, &runtime.spawn_events)?;
2355                self.process_liveness
2356                    .track(spec.module_id.clone(), Arc::clone(&snapshot));
2357                Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
2358            }
2359            Err(err) => {
2360                error!(
2361                    module_id = %spec.module_id,
2362                    program = %spec.program.display(),
2363                    error = %err,
2364                    "configured module failed to spawn; marking failed and continuing"
2365                );
2366                let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::failed()));
2367                Ok(self.supervised_module(spec, runtime, snapshot, None))
2368            }
2369        }
2370    }
2371
2372    /// Supervise a configured module with its own health, drain, and crash
2373    /// budget. The restart policy is per-module because the config file is:
2374    /// `modules.<id>.restart` resolves to a full policy at parse time, and a
2375    /// module that is expensive to restart should not be forced onto the same
2376    /// budget as one that is cheap.
2377    pub fn supervise_configured_with_health(
2378        &self,
2379        spec: ModuleSpec,
2380        enabled: bool,
2381        health: HealthConfig,
2382        drain_timeout_ms: Option<u64>,
2383        restart_policy: RestartPolicy,
2384    ) -> Result<SupervisedModule, SuperviseError> {
2385        validate_spec(&spec)?;
2386
2387        let mut runtime = self.runtime_config();
2388        runtime.health = health;
2389        runtime.restart_policy = restart_policy;
2390        if let Some(ms) = drain_timeout_ms {
2391            runtime.drain_timeout = Duration::from_millis(ms);
2392            *runtime
2393                .effective_drain_timeout
2394                .lock()
2395                .unwrap_or_else(|poisoned| poisoned.into_inner()) = runtime.drain_timeout;
2396        }
2397        if !enabled {
2398            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::disabled()));
2399            return Ok(self.supervised_module(spec, runtime, snapshot, None));
2400        }
2401
2402        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
2403        match spawn_child(
2404            &spec,
2405            runtime.connection_file_path.as_deref(),
2406            self.supervisor_handle.as_ref(),
2407            &runtime.stderr_ring,
2408            runtime.capture_logs_dir.as_deref(),
2409            &runtime.child_roster,
2410            #[cfg(target_os = "linux")]
2411            runtime.cgroup_placement.as_ref(),
2412        ) {
2413            Ok(child) => {
2414                set_running(&snapshot, &child, &spec.module_id, &runtime.spawn_events)?;
2415                self.process_liveness
2416                    .track(spec.module_id.clone(), Arc::clone(&snapshot));
2417                Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
2418            }
2419            Err(err) => {
2420                if health.critical {
2421                    error!(
2422                        module_id = %spec.module_id,
2423                        program = %spec.program.display(),
2424                        error = %err,
2425                        "critical configured module failed to spawn; marking failed and alerting"
2426                    );
2427                } else {
2428                    error!(
2429                        module_id = %spec.module_id,
2430                        program = %spec.program.display(),
2431                        error = %err,
2432                        "configured module failed to spawn; marking failed and continuing"
2433                    );
2434                }
2435                let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::failed()));
2436                Ok(self.supervised_module(spec, runtime, snapshot, None))
2437            }
2438        }
2439    }
2440
2441    fn runtime_config(&self) -> SupervisorRuntimeConfig {
2442        let effective_drain_timeout = Arc::new(Mutex::new(self.drain_timeout));
2443        SupervisorRuntimeConfig {
2444            restart_policy: self.restart_policy,
2445            drain_timeout: self.drain_timeout,
2446            // Shared with this module's roster copy: daemon shutdown waits on
2447            // each child for the module's own drain budget, as resolved now.
2448            child_roster: self
2449                .child_roster
2450                .for_module(Arc::clone(&effective_drain_timeout)),
2451            effective_drain_timeout,
2452            default_drain_timeout: self.drain_timeout,
2453            health: self.health,
2454            connection_file_path: self.connection_file_path.clone(),
2455            capture_logs_dir: self.capture_logs_dir.clone(),
2456            forwarding: self.forwarding.clone(),
2457            supervisor_handle: self.supervisor_handle.clone(),
2458            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
2459            terminal_ring: Arc::new(Mutex::new(
2460                TerminalRing::new(
2461                    TerminalRingConfig::default(),
2462                    self.daemon_start_clock.started_at_ms(),
2463                )
2464                .with_start_clock(self.daemon_start_clock)
2465                .with_journal(self.terminal_journal.clone())
2466                .with_daemon_shutdown(self.child_roster.shutdown_flag()),
2467            )),
2468            spawn_events: self.spawn_events.clone(),
2469            #[cfg(target_os = "linux")]
2470            cgroup_placement: self.cgroup_placement.clone(),
2471            #[cfg(test)]
2472            test_seed_stale_facts_before_enable_spawn: false,
2473        }
2474    }
2475
2476    fn supervised_module(
2477        &self,
2478        spec: ModuleSpec,
2479        runtime: SupervisorRuntimeConfig,
2480        snapshot: SharedSnapshot,
2481        child: Option<SupervisedChild>,
2482    ) -> SupervisedModule {
2483        let configuration = Arc::new(Mutex::new(SupervisedConfiguration {
2484            spec: spec.clone(),
2485            health: runtime.health,
2486        }));
2487        let stderr_ring = Arc::clone(&runtime.stderr_ring);
2488        let terminal_ring = Arc::clone(&runtime.terminal_ring);
2489        // The module's OWN policy, which may be its per-module config rather than
2490        // the supervisor-wide one; status must report the budget the supervise
2491        // loop actually enforces.
2492        let restart_policy = runtime.restart_policy;
2493        let effective_drain_timeout = Arc::clone(&runtime.effective_drain_timeout);
2494        let (tx, rx) = mpsc::channel(4);
2495        let monitor = tokio::spawn(supervise_loop(
2496            spec.clone(),
2497            runtime,
2498            Arc::clone(&self.registry),
2499            Arc::clone(&self.process_liveness),
2500            Arc::clone(&snapshot),
2501            child,
2502            rx,
2503        ));
2504
2505        let module_id = spec.module_id.clone();
2506        let module = SupervisedModule {
2507            inner: Arc::new(SupervisedModuleInner {
2508                module_id: module_id.clone(),
2509                registry: Arc::clone(&self.registry),
2510                snapshot,
2511                configuration,
2512                stderr_ring,
2513                terminal_ring,
2514                commands: tx,
2515                monitor: Mutex::new(Some(monitor)),
2516                restart_policy,
2517                effective_drain_timeout,
2518                provenance_probe: self.provenance_probe.clone(),
2519            }),
2520        };
2521        if let Some(supervisor_handle) = &self.supervisor_handle {
2522            supervisor_handle.apply_identity_configuration(&spec);
2523            supervisor_handle.insert(module.clone());
2524        }
2525        module
2526    }
2527}
2528
2529impl Default for Supervisor {
2530    fn default() -> Self {
2531        Self::new(Arc::new(Registry::default()), RestartPolicy::default())
2532    }
2533}
2534
2535/// Handle to one supervised child process.
2536#[derive(Clone)]
2537pub struct SupervisedModule {
2538    inner: Arc<SupervisedModuleInner>,
2539}
2540
2541struct SupervisedModuleInner {
2542    module_id: String,
2543    registry: Arc<Registry>,
2544    snapshot: SharedSnapshot,
2545    configuration: Arc<Mutex<SupervisedConfiguration>>,
2546    stderr_ring: Arc<Mutex<StderrRing>>,
2547    terminal_ring: Arc<Mutex<TerminalRing>>,
2548    commands: mpsc::Sender<SupervisorCommand>,
2549    monitor: Mutex<Option<JoinHandle<()>>>,
2550    /// Copied from the supervisor's runtime config at spawn so `status()` can
2551    /// report the restart budget without reaching back into the supervisor. The
2552    /// policy is fixed for the process's lifetime, so a copy cannot drift.
2553    restart_policy: RestartPolicy,
2554    effective_drain_timeout: Arc<Mutex<Duration>>,
2555    provenance_probe: ExecutableIdentityProbe,
2556}
2557
2558impl fmt::Debug for SupervisedModule {
2559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2560        f.debug_struct("SupervisedModule")
2561            .field("module_id", &self.inner.module_id)
2562            .field("status", &self.status())
2563            .finish_non_exhaustive()
2564    }
2565}
2566
2567impl SupervisedModule {
2568    pub fn module_id(&self) -> &str {
2569        &self.inner.module_id
2570    }
2571
2572    /// Test-only: put one probe miss on the streak, the way
2573    /// `handle_health_probe_failure` does, so tests can assert what a later
2574    /// event does to the streak without driving the whole probe loop.
2575    #[cfg(test)]
2576    pub(crate) fn record_health_probe_failure_for_test(
2577        &self,
2578        detail: &str,
2579    ) -> Result<(), SuperviseError> {
2580        update_snapshot(&self.inner.snapshot, Some(&self.inner.module_id), |state| {
2581            state.health.consecutive_failures = state.health.consecutive_failures.saturating_add(1);
2582            state.health.detail = Some(detail.to_string());
2583        })
2584    }
2585
2586    pub fn state(&self) -> Result<ModuleState, SuperviseError> {
2587        Ok(lock_snapshot(&self.inner.snapshot)?.state)
2588    }
2589
2590    /// The module's retained stderr, newest lines last.
2591    ///
2592    /// Deliberately NOT on [`Self::status`]: a bounded tail is kilobytes per
2593    /// module, `supervisor.list` renders every module, and putting it in the
2594    /// shared snapshot would make each status read carry a payload almost nobody
2595    /// asked for. Callers that want the text ask for it.
2596    pub fn stderr_tail(
2597        &self,
2598        max_lines: Option<usize>,
2599        max_bytes: Option<usize>,
2600    ) -> StderrTailSnapshot {
2601        self.inner
2602            .stderr_ring
2603            .lock()
2604            .unwrap_or_else(|poisoned| poisoned.into_inner())
2605            .snapshot(max_lines, max_bytes)
2606    }
2607
2608    /// The module's bounded terminal history, oldest retained exit first.
2609    ///
2610    /// The daemon-start stamp distinguishes a quiet supervisor from a replacement
2611    /// daemon whose in-memory history was necessarily reset.
2612    pub fn terminal_history(&self) -> TerminalHistorySnapshot {
2613        self.inner
2614            .terminal_ring
2615            .lock()
2616            .unwrap_or_else(|poisoned| poisoned.into_inner())
2617            .snapshot()
2618    }
2619
2620    /// Retained observations from the current ring and all journal generations.
2621    ///
2622    /// Blocking: this reads the journal files. Async callers use
2623    /// [`Self::read_durable_terminal_history`].
2624    pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
2625        durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
2626    }
2627
2628    /// [`Self::durable_terminal_history`] on a blocking thread, so the journal
2629    /// read (up to every retained generation) never occupies a runtime worker.
2630    /// Fails only if the blocking task could not finish (runtime shutdown or a
2631    /// panic in the read).
2632    pub(crate) async fn read_durable_terminal_history(
2633        &self,
2634    ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
2635        let terminal_ring = Arc::clone(&self.inner.terminal_ring);
2636        let module_id = self.inner.module_id.clone();
2637        tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
2638            .await
2639    }
2640
2641    pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
2642        self.status_with_snapshot_lock(&self.inner.snapshot, None)
2643    }
2644
2645    pub(crate) fn record_deliberate_severance(
2646        &self,
2647        identity: ProcessIdentity,
2648    ) -> Result<bool, SuperviseError> {
2649        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
2650        if snapshot.pid != Some(identity.pid)
2651            || snapshot.process_start_time != Some(identity.start_time)
2652        {
2653            return Ok(false);
2654        }
2655        snapshot.deliberate_severance = Some(identity);
2656        Ok(true)
2657    }
2658
2659    /// Read status for a channel-0 renderer and report a contended snapshot lock.
2660    ///
2661    /// Internal supervision callers use [`Self::status`] so writer-side machinery
2662    /// does not produce reader-observability logs.
2663    pub(crate) fn status_for_control(
2664        &self,
2665        caller: &'static str,
2666    ) -> Result<ModuleStatus, SuperviseError> {
2667        self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
2668    }
2669
2670    fn status_with_snapshot_lock(
2671        &self,
2672        snapshot: &SharedSnapshot,
2673        caller: Option<&'static str>,
2674    ) -> Result<ModuleStatus, SuperviseError> {
2675        let mut guard = match caller {
2676            Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
2677            None => lock_snapshot(snapshot)?,
2678        };
2679        // Read the budget through the pruning path so a reader sees the same
2680        // in-window count the restart decision would use, not a stale total.
2681        let restart_count =
2682            guard.crash_restarts_in_window(self.inner.restart_policy.window, Instant::now());
2683        let snapshot = guard.clone();
2684        drop(guard);
2685        let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
2686            SuperviseError::StatePoisoned {
2687                module_id: Some(self.inner.module_id.clone()),
2688            }
2689        })?;
2690        let registration_active = self
2691            .inner
2692            .registry
2693            .get_module(&self.inner.module_id)
2694            .map_err(SuperviseError::Registry)?
2695            .is_some();
2696        let protocol = self.declared_protocol()?;
2697        let running_process =
2698            snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
2699        // Registration is the difference between the two protocols and the only
2700        // one: a subc module that has not registered cannot serve a request even
2701        // though its process is up, and a `none` module never registers at all,
2702        // so requiring it there would pin `live` to false for the whole life of
2703        // a perfectly healthy process.
2704        let live = match protocol {
2705            ModuleProtocol::Subc => running_process && registration_active,
2706            ModuleProtocol::None => running_process,
2707        };
2708
2709        Ok(ModuleStatus {
2710            module_id: self.inner.module_id.clone(),
2711            state: snapshot.state,
2712            enabled: snapshot.enabled,
2713            process_alive: snapshot.process_alive,
2714            registration_active,
2715            protocol,
2716            live,
2717            restart_count,
2718            lifetime_restarts: snapshot.lifetime_restarts,
2719            spawn_generation: snapshot.spawn_generation,
2720            max_restarts: self.inner.restart_policy.max_restarts,
2721            restart_window: self.inner.restart_policy.window,
2722            drain_timeout,
2723            restart_backoff: self.inner.restart_policy.backoff,
2724            restart_max_backoff: self.inner.restart_policy.max_backoff,
2725            pid: snapshot.pid,
2726            spawned_at_ms: snapshot.spawned_at_ms,
2727            spawned_from: snapshot.spawned_from,
2728            process_start_time: snapshot.process_start_time,
2729            last_exit: snapshot.last_exit,
2730            health: snapshot.health,
2731        })
2732    }
2733
2734    #[cfg(test)]
2735    pub(crate) fn hold_snapshot_for_test(
2736        &self,
2737        acquired: std::sync::mpsc::Sender<()>,
2738        hold: Duration,
2739    ) -> std::thread::JoinHandle<()> {
2740        let snapshot = Arc::clone(&self.inner.snapshot);
2741        std::thread::spawn(move || {
2742            let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
2743            acquired
2744                .send(())
2745                .expect("test receiver waits for snapshot lock");
2746            std::thread::sleep(hold);
2747        })
2748    }
2749
2750    pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
2751        let snapshot = match lock_snapshot(&self.inner.snapshot) {
2752            Ok(snapshot) => snapshot.clone(),
2753            Err(_) => {
2754                return subc_control::RunningImageAgreement::Unavailable {
2755                    reason: subc_control::RunningImageUnavailableReason::NotRunning,
2756                };
2757            }
2758        };
2759        self.inner
2760            .provenance_probe
2761            .observe(
2762                snapshot.pid,
2763                snapshot.spawned_from.as_deref(),
2764                snapshot.spawned_file_identity,
2765                snapshot.process_start_time,
2766            )
2767            .await
2768    }
2769
2770    /// Memory and CPU time of the module's current process, read now. Only the
2771    /// process the supervisor spawned is read, not processes it has started.
2772    pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
2773        let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
2774            Ok(snapshot) => (snapshot.pid, snapshot.process_start_time),
2775            Err(_) => {
2776                return subc_control::ChildResourceUsage::Unavailable {
2777                    reason: subc_control::ChildResourceUnavailableReason::Unreadable,
2778                }
2779            }
2780        };
2781        crate::child_resources::read(pid, start_time)
2782    }
2783
2784    pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
2785        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
2786        Ok(match snapshot.state {
2787            ModuleState::Restarting => true,
2788            ModuleState::Failed | ModuleState::Disabled => false,
2789            _ => daemon_will_restart(&mut snapshot, &self.inner.restart_policy, Instant::now()),
2790        })
2791    }
2792
2793    #[cfg(test)]
2794    pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
2795        self.is_warming_with_snapshot_lock(None)
2796    }
2797
2798    pub(crate) fn is_warming_for_control(
2799        &self,
2800        caller: &'static str,
2801    ) -> Result<bool, SuperviseError> {
2802        self.is_warming_with_snapshot_lock(Some(caller))
2803    }
2804
2805    fn is_warming_with_snapshot_lock(
2806        &self,
2807        caller: Option<&'static str>,
2808    ) -> Result<bool, SuperviseError> {
2809        let snapshot = match caller {
2810            Some(caller) => {
2811                lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
2812            }
2813            None => lock_snapshot(&self.inner.snapshot)?,
2814        }
2815        .clone();
2816        Ok(matches!(
2817            snapshot.state,
2818            ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
2819        ))
2820    }
2821
2822    /// Drain the module and stop monitoring it.
2823    pub async fn drain(&self) -> Result<(), SuperviseError> {
2824        self.stop().await
2825    }
2826
2827    pub(crate) async fn retire(&self) -> Result<(), SuperviseError> {
2828        match self.state()? {
2829            ModuleState::Stopped | ModuleState::Failed => return Ok(()),
2830            ModuleState::Starting
2831            | ModuleState::Running
2832            | ModuleState::Unresponsive
2833            | ModuleState::Restarting
2834            | ModuleState::Draining
2835            | ModuleState::Disabled => {}
2836        }
2837
2838        let (reply_tx, reply_rx) = oneshot::channel();
2839        self.inner
2840            .commands
2841            .send(SupervisorCommand::Retire { reply: reply_tx })
2842            .await
2843            .map_err(|_| SuperviseError::CommandClosed {
2844                module_id: self.inner.module_id.clone(),
2845            })?;
2846        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
2847            module_id: self.inner.module_id.clone(),
2848        })?
2849    }
2850
2851    pub async fn stop(&self) -> Result<(), SuperviseError> {
2852        match self.state()? {
2853            ModuleState::Stopped | ModuleState::Failed => return Ok(()),
2854            ModuleState::Starting
2855            | ModuleState::Running
2856            | ModuleState::Unresponsive
2857            | ModuleState::Restarting
2858            | ModuleState::Draining
2859            | ModuleState::Disabled => {}
2860        }
2861
2862        let (reply_tx, reply_rx) = oneshot::channel();
2863        self.inner
2864            .commands
2865            .send(SupervisorCommand::Drain { reply: reply_tx })
2866            .await
2867            .map_err(|_| SuperviseError::CommandClosed {
2868                module_id: self.inner.module_id.clone(),
2869            })?;
2870        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
2871            module_id: self.inner.module_id.clone(),
2872        })?
2873    }
2874
2875    pub async fn restart(&self, drain_timeout_ms: Option<u64>) -> Result<(), SuperviseError> {
2876        let received_at_generation = lock_snapshot(&self.inner.snapshot)?.spawn_generation;
2877        let (reply_tx, reply_rx) = oneshot::channel();
2878        self.inner
2879            .commands
2880            .send(SupervisorCommand::Restart {
2881                drain_timeout_ms,
2882                received_at_generation,
2883                queued_at: Instant::now(),
2884                reply: reply_tx,
2885            })
2886            .await
2887            .map_err(|_| SuperviseError::CommandClosed {
2888                module_id: self.inner.module_id.clone(),
2889            })?;
2890        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
2891            module_id: self.inner.module_id.clone(),
2892        })?
2893    }
2894
2895    /// Blue/green restart: see [`SupervisorCommand::Swap`] and the
2896    /// `supervisor_swap` module. Returns once the swap has cut over (the old
2897    /// process then drains in the background of the supervise loop) or has
2898    /// failed, leaving the old process serving.
2899    pub async fn swap(&self, ready_timeout: Option<Duration>) -> Result<(), SuperviseError> {
2900        let (reply_tx, reply_rx) = oneshot::channel();
2901        self.inner
2902            .commands
2903            .send(SupervisorCommand::Swap {
2904                ready_timeout,
2905                reply: reply_tx,
2906            })
2907            .await
2908            .map_err(|_| SuperviseError::CommandClosed {
2909                module_id: self.inner.module_id.clone(),
2910            })?;
2911        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
2912            module_id: self.inner.module_id.clone(),
2913        })?
2914    }
2915
2916    pub async fn reload(&self) -> Result<(), SuperviseError> {
2917        let (reply_tx, reply_rx) = oneshot::channel();
2918        self.inner
2919            .commands
2920            .send(SupervisorCommand::Reload { reply: reply_tx })
2921            .await
2922            .map_err(|_| SuperviseError::CommandClosed {
2923                module_id: self.inner.module_id.clone(),
2924            })?;
2925        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
2926            module_id: self.inner.module_id.clone(),
2927        })?
2928    }
2929
2930    pub async fn set_enabled(&self, enabled: bool) -> Result<bool, SuperviseError> {
2931        let (reply_tx, reply_rx) = oneshot::channel();
2932        self.inner
2933            .commands
2934            .send(SupervisorCommand::SetEnabled {
2935                enabled,
2936                reply: reply_tx,
2937            })
2938            .await
2939            .map_err(|_| SuperviseError::CommandClosed {
2940                module_id: self.inner.module_id.clone(),
2941            })?;
2942        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
2943            module_id: self.inner.module_id.clone(),
2944        })?
2945    }
2946
2947    /// This module's declared protocol, read from the same stored configuration
2948    /// the rescan diff compares and `update_configuration` rewrites, so a status
2949    /// read and the supervise loop can never disagree about which protocol is in
2950    /// force.
2951    pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
2952        Ok(self
2953            .inner
2954            .configuration
2955            .lock()
2956            .map_err(|_| SuperviseError::StatePoisoned {
2957                module_id: Some(self.inner.module_id.clone()),
2958            })?
2959            .spec
2960            .protocol)
2961    }
2962
2963    pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
2964        let configuration =
2965            self.inner
2966                .configuration
2967                .lock()
2968                .map_err(|_| SuperviseError::StatePoisoned {
2969                    module_id: Some(self.inner.module_id.clone()),
2970                })?;
2971        Ok((configuration.spec.clone(), configuration.health))
2972    }
2973
2974    /// Replace this module's launch spec, keeping its health and drain policy,
2975    /// the way a rescan does for a changed config entry. The running process is
2976    /// untouched; the next spawn (a restart, or a swap's candidate) uses it.
2977    #[cfg(any(test, feature = "test-support"))]
2978    pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
2979        let (_, health) = self.configuration()?;
2980        let drain_timeout_ms = u64::try_from(
2981            self.inner
2982                .effective_drain_timeout
2983                .lock()
2984                .unwrap_or_else(|poisoned| poisoned.into_inner())
2985                .as_millis(),
2986        )
2987        .ok();
2988        self.update_configuration(spec, health, drain_timeout_ms)
2989            .await
2990    }
2991
2992    pub(crate) async fn update_configuration(
2993        &self,
2994        spec: ModuleSpec,
2995        health: HealthConfig,
2996        drain_timeout_ms: Option<u64>,
2997    ) -> Result<(), SuperviseError> {
2998        if spec.module_id != self.inner.module_id {
2999            return Err(SuperviseError::InvalidSpec {
3000                reason: "a supervised module's module_id cannot be changed".to_string(),
3001            });
3002        }
3003        validate_spec(&spec)?;
3004        let (reply_tx, reply_rx) = oneshot::channel();
3005        self.inner
3006            .commands
3007            .send(SupervisorCommand::UpdateConfiguration {
3008                spec: spec.clone(),
3009                health,
3010                drain_timeout_ms,
3011                reply: reply_tx,
3012            })
3013            .await
3014            .map_err(|_| SuperviseError::CommandClosed {
3015                module_id: self.inner.module_id.clone(),
3016            })?;
3017        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
3018            module_id: self.inner.module_id.clone(),
3019        })?;
3020        let mut configuration =
3021            self.inner
3022                .configuration
3023                .lock()
3024                .map_err(|_| SuperviseError::StatePoisoned {
3025                    module_id: Some(self.inner.module_id.clone()),
3026                })?;
3027        configuration.spec = spec;
3028        configuration.health = health;
3029        Ok(())
3030    }
3031}
3032
3033impl Drop for SupervisedModuleInner {
3034    fn drop(&mut self) {
3035        let Ok(mut monitor) = self.monitor.lock() else {
3036            return;
3037        };
3038        if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
3039            let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
3040                state.state = ModuleState::Stopped;
3041                clear_current_process_facts(state);
3042            });
3043            monitor.abort();
3044        }
3045        let _ = monitor.take();
3046    }
3047}
3048
3049#[derive(Debug)]
3050enum SupervisorCommand {
3051    Drain {
3052        reply: oneshot::Sender<Result<(), SuperviseError>>,
3053    },
3054    Retire {
3055        reply: oneshot::Sender<Result<(), SuperviseError>>,
3056    },
3057    Restart {
3058        /// Operator override for this one restart's drain budget, in ms. `None`
3059        /// uses the module's configured/default budget; `Some(0)` cuts
3060        /// immediately (wedge bounce: a stuck request never settles, so
3061        /// waiting only delays recovery).
3062        drain_timeout_ms: Option<u64>,
3063        /// The module's `spawn_generation` when the request was received, before
3064        /// it waited in the command queue. A queued restart whose module has
3065        /// since spawned a newer process is already satisfied (see the handler).
3066        received_at_generation: u64,
3067        /// When the request entered the command queue, so the handler can log
3068        /// how long it waited behind the loop's other work.
3069        queued_at: Instant,
3070        reply: oneshot::Sender<Result<(), SuperviseError>>,
3071    },
3072    Reload {
3073        reply: oneshot::Sender<Result<(), SuperviseError>>,
3074    },
3075    SetEnabled {
3076        enabled: bool,
3077        reply: oneshot::Sender<Result<bool, SuperviseError>>,
3078    },
3079    UpdateConfiguration {
3080        spec: ModuleSpec,
3081        health: HealthConfig,
3082        /// Per-module drain override from the new config; `None` re-resolves to
3083        /// the supervisor-wide default.
3084        drain_timeout_ms: Option<u64>,
3085        reply: oneshot::Sender<()>,
3086    },
3087    Swap {
3088        /// How long the candidate may take to register and declare itself
3089        /// ready. `None` uses [`DEFAULT_SWAP_READY_TIMEOUT`].
3090        ready_timeout: Option<Duration>,
3091        /// Answered at cutover or failure; the incumbent's drain follows.
3092        reply: oneshot::Sender<Result<(), SuperviseError>>,
3093    },
3094}
3095
3096#[derive(Debug)]
3097pub enum SuperviseError {
3098    InvalidSpec {
3099        reason: String,
3100    },
3101    Spawn {
3102        program: PathBuf,
3103        source: io::Error,
3104        cgroup_path: Option<PathBuf>,
3105    },
3106    Cgroup {
3107        module_id: String,
3108        source: io::Error,
3109    },
3110    /// CSPRNG failure generating a reserved module's launch nonce. Fail loud rather
3111    /// than spawn a reserved module without its identity binding.
3112    LaunchNonce {
3113        reason: String,
3114    },
3115    Wait {
3116        module_id: String,
3117        source: io::Error,
3118    },
3119    Kill {
3120        module_id: String,
3121        source: io::Error,
3122    },
3123    Forwarding(ForwardingError),
3124    Registry(RegistryError),
3125    ReloadUnavailable {
3126        module_id: String,
3127        reason: String,
3128    },
3129    /// An operator restart/reload was requested for a module that is currently
3130    /// disabled. Restart/reload cycle a *running* module; a disabled module must
3131    /// be explicitly re-enabled (set_enabled(true)) rather than silently started
3132    /// by a restart, so these commands are rejected instead of re-enabling it.
3133    Disabled {
3134        module_id: String,
3135    },
3136    ReloadFailed {
3137        module_id: String,
3138        reason: String,
3139    },
3140    RegistrationStillActive {
3141        module_id: String,
3142        waited: Duration,
3143    },
3144    StatePoisoned {
3145        module_id: Option<String>,
3146    },
3147    CommandClosed {
3148        module_id: String,
3149    },
3150    /// A restart or reload arrived while a swap's candidate was warming. The
3151    /// swap owns the module until it cuts over or fails; a stop or disable
3152    /// would have aborted it instead.
3153    SwapInProgress {
3154        module_id: String,
3155    },
3156    /// A swap was refused before anything was spawned.
3157    SwapRefused {
3158        module_id: String,
3159        reason: SwapRefusal,
3160    },
3161    /// A swap spawned a candidate and gave up on it. The candidate has been
3162    /// killed and its slot freed; the incumbent was left serving and was never
3163    /// drained, except in the one `CutoverLost` case described on that arm.
3164    SwapFailed {
3165        module_id: String,
3166        arm: SwapFailureArm,
3167        detail: String,
3168        /// How the candidate exited, when it exited on its own before the
3169        /// supervisor gave up on it.
3170        candidate_exit: Option<ExitReport>,
3171    },
3172}
3173
3174/// Why a swap was refused before a candidate was spawned.
3175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3176pub enum SwapRefusal {
3177    /// The module's config does not declare `overlap: "safe"`.
3178    OverlapExclusive,
3179    /// The module is not registered, so there is no incumbent to keep serving
3180    /// and nothing a swap would improve on; a plain restart is the tool.
3181    NotRegistered,
3182    /// The module does not speak the subc wire, so a candidate could never
3183    /// register or declare itself ready.
3184    ProtocolNone,
3185    /// The supervisor lacks the forwarding table (to cut routes over) or the
3186    /// shared handle (to admit the candidate's HELLO) that a swap needs.
3187    NotConfigured,
3188    /// A swap is already open for this module.
3189    AlreadySwapping,
3190}
3191
3192impl SwapRefusal {
3193    pub fn as_str(self) -> &'static str {
3194        match self {
3195            Self::OverlapExclusive => "overlap_exclusive",
3196            Self::NotRegistered => "not_registered",
3197            Self::ProtocolNone => "protocol_none",
3198            Self::NotConfigured => "not_configured",
3199            Self::AlreadySwapping => "already_swapping",
3200        }
3201    }
3202}
3203
3204/// Which failure arm ended a swap. Every arm but one leaves the incumbent
3205/// serving and undrained; see `CutoverLost`.
3206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3207pub enum SwapFailureArm {
3208    /// The candidate process could not be started.
3209    SpawnFailed,
3210    /// The candidate did not register within the readiness budget.
3211    NeverRegistered,
3212    /// The candidate registered but did not declare itself ready in time.
3213    NeverReady,
3214    /// The candidate exited before cutover.
3215    CandidateExited,
3216    /// The candidate declared itself ready but failed its health probe.
3217    CandidateUnhealthy,
3218    /// An operator stop, disable or retire arrived while the candidate warmed.
3219    /// The candidate was killed and the operator's command then carried out on
3220    /// the incumbent.
3221    Interrupted,
3222    /// The candidate's connection closed at the moment of cutover. If it
3223    /// closed before forwarding moved, the incumbent is untouched. If it closed
3224    /// between the forwarding and registry halves of cutover, forwarding can no
3225    /// longer route to the incumbent, so the module is restarted plainly.
3226    CutoverLost,
3227}
3228
3229impl SwapFailureArm {
3230    pub fn as_str(self) -> &'static str {
3231        match self {
3232            Self::SpawnFailed => "spawn_failed",
3233            Self::NeverRegistered => "never_registered",
3234            Self::NeverReady => "never_ready",
3235            Self::CandidateExited => "candidate_exited",
3236            Self::CandidateUnhealthy => "candidate_unhealthy",
3237            Self::Interrupted => "interrupted",
3238            Self::CutoverLost => "cutover_lost",
3239        }
3240    }
3241}
3242
3243impl fmt::Display for SuperviseError {
3244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3245        match self {
3246            Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
3247            Self::Spawn {
3248                program,
3249                source,
3250                cgroup_path: Some(cgroup_path),
3251            } => write!(
3252                f,
3253                "failed to place module in cgroup '{}' while spawning '{}': {source}",
3254                cgroup_path.display(),
3255                program.display()
3256            ),
3257            Self::Spawn {
3258                program,
3259                source,
3260                cgroup_path: None,
3261            } => write!(
3262                f,
3263                "failed to spawn module '{}': {source}",
3264                program.display()
3265            ),
3266            Self::Cgroup { module_id, source } => {
3267                write!(
3268                    f,
3269                    "failed to prepare cgroup for module '{module_id}': {source}"
3270                )
3271            }
3272            Self::LaunchNonce { reason } => {
3273                write!(
3274                    f,
3275                    "failed to generate reserved-module launch nonce: {reason}"
3276                )
3277            }
3278            Self::Wait { module_id, source } => {
3279                write!(f, "failed to wait for module '{module_id}': {source}")
3280            }
3281            Self::Kill { module_id, source } => {
3282                write!(f, "failed to kill module '{module_id}': {source}")
3283            }
3284            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
3285            Self::Registry(err) => write!(f, "registry error: {err}"),
3286            Self::ReloadUnavailable { module_id, reason } => {
3287                write!(f, "reload unavailable for module '{module_id}': {reason}")
3288            }
3289            Self::Disabled { module_id } => {
3290                write!(
3291                    f,
3292                    "module '{module_id}' is disabled; enable it before restart or reload"
3293                )
3294            }
3295            Self::ReloadFailed { module_id, reason } => {
3296                write!(f, "reload failed for module '{module_id}': {reason}")
3297            }
3298            Self::RegistrationStillActive { module_id, waited } => write!(
3299                f,
3300                "module '{module_id}' registration remained active after waiting {waited:?}"
3301            ),
3302            Self::StatePoisoned { module_id } => match module_id {
3303                Some(module_id) => {
3304                    write!(f, "supervisor state for module '{module_id}' was poisoned")
3305                }
3306                None => write!(f, "supervisor state was poisoned"),
3307            },
3308            Self::CommandClosed { module_id } => {
3309                write!(
3310                    f,
3311                    "supervisor command channel for module '{module_id}' is closed"
3312                )
3313            }
3314            Self::SwapInProgress { module_id } => write!(
3315                f,
3316                "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
3317            ),
3318            Self::SwapRefused { module_id, reason } => match reason {
3319                SwapRefusal::OverlapExclusive => write!(
3320                    f,
3321                    "module '{module_id}' is declared overlap: \"exclusive\" (the default): two processes of it must not run at once, so it cannot be swapped; use a plain restart, or declare overlap: \"safe\" in its config if it really tolerates a second process"
3322                ),
3323                SwapRefusal::NotRegistered => write!(
3324                    f,
3325                    "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
3326                ),
3327                SwapRefusal::ProtocolNone => write!(
3328                    f,
3329                    "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
3330                ),
3331                SwapRefusal::NotConfigured => write!(
3332                    f,
3333                    "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
3334                ),
3335                SwapRefusal::AlreadySwapping => {
3336                    write!(f, "module '{module_id}' is already being swapped")
3337                }
3338            },
3339            Self::SwapFailed {
3340                module_id,
3341                arm,
3342                detail,
3343                ..
3344            } => write!(
3345                f,
3346                "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
3347                arm.as_str()
3348            ),
3349        }
3350    }
3351}
3352
3353impl Error for SuperviseError {
3354    fn source(&self) -> Option<&(dyn Error + 'static)> {
3355        match self {
3356            Self::Spawn { source, .. }
3357            | Self::Cgroup { source, .. }
3358            | Self::Wait { source, .. }
3359            | Self::Kill { source, .. } => Some(source),
3360            Self::Forwarding(err) => Some(err),
3361            Self::Registry(err) => Some(err),
3362            Self::LaunchNonce { .. }
3363            | Self::InvalidSpec { .. }
3364            | Self::ReloadUnavailable { .. }
3365            | Self::Disabled { .. }
3366            | Self::ReloadFailed { .. }
3367            | Self::RegistrationStillActive { .. }
3368            | Self::StatePoisoned { .. }
3369            | Self::CommandClosed { .. }
3370            | Self::SwapInProgress { .. }
3371            | Self::SwapRefused { .. }
3372            | Self::SwapFailed { .. } => None,
3373        }
3374    }
3375}
3376
3377pub(crate) fn validate_spec(spec: &ModuleSpec) -> Result<(), SuperviseError> {
3378    if spec.module_id.trim().is_empty() {
3379        return Err(SuperviseError::InvalidSpec {
3380            reason: "module_id must not be empty".to_string(),
3381        });
3382    }
3383
3384    Ok(())
3385}
3386
3387#[derive(Debug, Default)]
3388struct HealthProbeRuntime {
3389    registered_connection: Option<crate::ConnectionId>,
3390    advertised: bool,
3391    next_probe_at: Option<Instant>,
3392    probe_index: u64,
3393}
3394
3395impl HealthProbeRuntime {
3396    fn refresh_registration(
3397        &mut self,
3398        spec: &ModuleSpec,
3399        runtime: &SupervisorRuntimeConfig,
3400        registry: &Registry,
3401        snapshot: &SharedSnapshot,
3402    ) {
3403        // THE PROBE GATE FOR A MODULE THAT SPEAKS NO SUBC WIRE, placed here
3404        // because this is the only place that ever arms a probe: leaving
3405        // `advertised` false and `next_probe_at` empty makes `due()` false
3406        // forever, so `run_health_probe_cycle` -- and with it every arm of
3407        // `probe_module_health`, including the one that reads an absent
3408        // registration as proof the module is gone and escalates to a restart --
3409        // is unreachable for this module.
3410        //
3411        // That arm is right for a subc module and is exactly wrong here: a
3412        // `protocol: "none"` module never registers by declaration, so the
3413        // absence it would classify is the module working as configured.
3414        if spec.protocol == ModuleProtocol::None {
3415            self.registered_connection = None;
3416            self.advertised = false;
3417            self.next_probe_at = None;
3418            return;
3419        }
3420
3421        let registration = match registry.get_module(&spec.module_id) {
3422            Ok(registration) => registration,
3423            Err(err) => {
3424                warn!(module_id = %spec.module_id, error = %err, "health prober could not read registry");
3425                self.advertised = false;
3426                self.next_probe_at = None;
3427                return;
3428            }
3429        };
3430
3431        let Some(registration) = registration else {
3432            self.registered_connection = None;
3433            self.advertised = false;
3434            self.next_probe_at = None;
3435            return;
3436        };
3437
3438        let advertised = registration
3439            .control_ops
3440            .iter()
3441            .any(|op| op == MODULE_CONTROL_OP_HEALTH_CHECK);
3442        if !advertised {
3443            self.registered_connection = Some(registration.connection_id);
3444            self.advertised = false;
3445            self.next_probe_at = None;
3446            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
3447                state.health.status = SupervisorHealthStatus::Unknown;
3448                state.health.consecutive_failures = 0;
3449                state.health.last_probe_ms = None;
3450                state.health.detail = None;
3451                state.health.metrics = None;
3452            });
3453            return;
3454        }
3455
3456        let reregistered = self.registered_connection != Some(registration.connection_id);
3457        self.registered_connection = Some(registration.connection_id);
3458        self.advertised = true;
3459        if reregistered || self.next_probe_at.is_none() {
3460            self.probe_index = 0;
3461            self.next_probe_at = Some(
3462                Instant::now() + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
3463            );
3464            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
3465                state.health.status = SupervisorHealthStatus::Unknown;
3466                state.health.consecutive_failures = 0;
3467                state.health.detail = None;
3468                state.health.metrics = None;
3469            });
3470        }
3471    }
3472
3473    fn wake_after(&self) -> Duration {
3474        if !self.advertised {
3475            return REGISTRY_RELEASE_POLL;
3476        }
3477        self.next_probe_at
3478            .map(|next| next.saturating_duration_since(Instant::now()))
3479            .unwrap_or(REGISTRY_RELEASE_POLL)
3480    }
3481
3482    fn due(&self) -> bool {
3483        self.advertised
3484            && self
3485                .next_probe_at
3486                .is_some_and(|next| Instant::now() >= next)
3487    }
3488
3489    fn schedule_next(&mut self, spec: &ModuleSpec, cadence: Duration) {
3490        self.probe_index = self.probe_index.wrapping_add(1);
3491        self.next_probe_at = Some(
3492            Instant::now() + jittered_health_delay(&spec.module_id, self.probe_index, cadence),
3493        );
3494    }
3495}
3496
3497/// What a failed health probe actually OBSERVED, kept apart from how it reads.
3498///
3499/// This was a struct with a single `message: String`, and every one of the
3500/// fifteen construction sites collapsed into it. Each site knows exactly what it
3501/// saw -- the lane is gone, the module did not answer in time, the module
3502/// answered with the wrong thing -- and `handle_health_probe_failure` then
3503/// treated all of them identically: increment a counter, compare to a threshold,
3504/// restart the module. THE DISTINCTION EXISTED AT EVERY CALL SITE AND WAS
3505/// DESTROYED BEFORE THE DECISION THAT NEEDED IT.
3506///
3507/// The distinction that matters is not severity, it is EVIDENTIAL WEIGHT:
3508///
3509/// * `LaneDead` is PROOF. The module's control connection is gone; nothing will
3510///   answer on it again.
3511/// * `NoAnswer` is ABSENCE OF EVIDENCE. It is consistent with a wedged module
3512///   AND with a perfectly healthy one that lost a CPU race -- which is what
3513///   happens under machine load, and is how this supervisor killed a healthy
3514///   module three times in one day.
3515/// * `BadAnswer` proves the module is ALIVE. It replied; the reply was wrong.
3516///   Restarting on it is defensible, but it is not the silence case and should
3517///   never be counted as one.
3518/// * `Misconfigured` is a daemon-side fault. The module has not been asked
3519///   anything, so it cannot be evidence about the module at all.
3520///
3521/// The asymmetry is the whole point: under saturation the WEAKEST signal is the
3522/// one that fires most often, and while every variant collapsed into one string
3523/// it carried the same weight as the strongest.
3524///
3525/// LIVE BEHAVIOUR TODAY, stated here because this doc block describes the
3526/// DESIGN and a reader stopping at it gets the build backwards: the restart
3527/// decision does NOT yet consult this classification -- consecutive `NoAnswer`
3528/// probes still increment the failure streak and drive escalation at the
3529/// threshold (see `is_proof_of_death` below for why that is deliberate and
3530/// what gates the change). Absence of evidence restarts modules today.
3531#[derive(Debug)]
3532enum HealthProbeEvidence {
3533    /// The module's control lane is gone. Proof of death.
3534    LaneDead,
3535    /// No reply within the deadline. Proves nothing about the module's state.
3536    NoAnswer,
3537    /// The module replied, but not with a usable health report. Proves it is alive.
3538    BadAnswer,
3539    /// The daemon could not ask. Says nothing about the module.
3540    Misconfigured,
3541}
3542
3543#[derive(Debug)]
3544struct HealthProbeError {
3545    evidence: HealthProbeEvidence,
3546    message: String,
3547}
3548
3549impl HealthProbeError {
3550    fn lane_dead(message: impl Into<String>) -> Self {
3551        Self::with(HealthProbeEvidence::LaneDead, message)
3552    }
3553
3554    fn no_answer(message: impl Into<String>) -> Self {
3555        Self::with(HealthProbeEvidence::NoAnswer, message)
3556    }
3557
3558    fn bad_answer(message: impl Into<String>) -> Self {
3559        Self::with(HealthProbeEvidence::BadAnswer, message)
3560    }
3561
3562    fn misconfigured(message: impl Into<String>) -> Self {
3563        Self::with(HealthProbeEvidence::Misconfigured, message)
3564    }
3565
3566    fn with(evidence: HealthProbeEvidence, message: impl Into<String>) -> Self {
3567        Self {
3568            evidence,
3569            message: message.into(),
3570        }
3571    }
3572
3573    /// Whether this observation is proof the module cannot serve.
3574    ///
3575    /// Only `LaneDead` qualifies. `NoAnswer` is deliberately excluded: it is the
3576    /// variant that fires under CPU starvation, and treating it as proof is the
3577    /// defect this enum exists to make impossible to reintroduce silently.
3578    ///
3579    /// NOT YET CONSULTED BY THE RESTART DECISION, deliberately. Requiring proof
3580    /// to restart also needs a bound for the case it excludes -- a genuinely
3581    /// wedged module, alive but never answering -- and that bound must come from
3582    /// the distribution of real late-answer latencies, which nothing measures
3583    /// yet. Landing the classification first makes the later change a one-line
3584    /// decision against evidence that already exists, rather than two unproven
3585    /// changes at once.
3586    #[allow(dead_code)]
3587    fn is_proof_of_death(&self) -> bool {
3588        matches!(self.evidence, HealthProbeEvidence::LaneDead)
3589    }
3590
3591    /// Short stable label for logs and the health snapshot.
3592    ///
3593    /// An operator reading `ck health` currently cannot tell "the module is gone"
3594    /// from "the module did not answer in five seconds", because both render as
3595    /// prose in the same field. These labels are what make the two
3596    /// distinguishable at a glance, and they are what a later restart-policy
3597    /// change will be argued from.
3598    fn label(&self) -> &'static str {
3599        match self.evidence {
3600            HealthProbeEvidence::LaneDead => "lane-dead",
3601            HealthProbeEvidence::NoAnswer => "no-answer",
3602            HealthProbeEvidence::BadAnswer => "bad-answer",
3603            HealthProbeEvidence::Misconfigured => "daemon-misconfigured",
3604        }
3605    }
3606}
3607
3608impl fmt::Display for HealthProbeError {
3609    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3610        f.write_str(&self.message)
3611    }
3612}
3613
3614async fn run_health_probe_cycle(
3615    spec: &ModuleSpec,
3616    runtime: &SupervisorRuntimeConfig,
3617    registry: &Registry,
3618    process_liveness: &SupervisorProcessLiveness,
3619    snapshot: &SharedSnapshot,
3620    child: &mut Option<SupervisedChild>,
3621) {
3622    let now_ms = unix_ms_now();
3623    match probe_module_health(&spec.module_id, runtime, None).await {
3624        Ok(report) => {
3625            handle_health_report(
3626                spec,
3627                runtime,
3628                registry,
3629                process_liveness,
3630                snapshot,
3631                child,
3632                report,
3633                now_ms,
3634            )
3635            .await;
3636        }
3637        Err(err) => {
3638            handle_health_probe_failure(
3639                spec,
3640                runtime,
3641                registry,
3642                process_liveness,
3643                snapshot,
3644                child,
3645                err,
3646                now_ms,
3647            )
3648            .await;
3649        }
3650    }
3651}
3652
3653async fn probe_module_health(
3654    module_id: &str,
3655    runtime: &SupervisorRuntimeConfig,
3656    drain_deadline: Option<Instant>,
3657) -> Result<HealthReport, HealthProbeError> {
3658    let Some(forwarding) = runtime.forwarding.as_ref() else {
3659        return Err(HealthProbeError::misconfigured(
3660            "supervisor was not configured with a forwarding table",
3661        ));
3662    };
3663    let probe_started_at = Instant::now();
3664    let mut deadline = probe_started_at + runtime.health.deadline;
3665    if let Some(drain_deadline) = drain_deadline {
3666        deadline = deadline.min(drain_deadline);
3667    }
3668    let pending = if drain_deadline.is_some() {
3669        forwarding.begin_drain_health_probe_rpc_for(
3670            module_id,
3671            MODULE_CONTROL_OP_HEALTH_CHECK,
3672            probe_started_at,
3673            deadline,
3674        )
3675    } else {
3676        forwarding.begin_health_probe_rpc_for(
3677            module_id,
3678            MODULE_CONTROL_OP_HEALTH_CHECK,
3679            probe_started_at,
3680            deadline,
3681        )
3682    }
3683    .map_err(|err| {
3684        // The endpoint is not registered, so there is no live control lane to
3685        // ask. That is the module being absent, not slow.
3686        HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
3687    })?;
3688    await_health_probe(forwarding, pending, deadline, runtime.health.deadline).await
3689}
3690
3691/// [`probe_module_health`] for one endpoint rather than the id's active one.
3692///
3693/// A swap probes two processes that no by-id lookup reaches: its candidate
3694/// before cutover, and its superseded incumbent (for busy gauges) while the
3695/// incumbent drains. `deadline_cap` bounds the probe the way a drain deadline
3696/// bounds the by-id drain probe.
3697async fn probe_endpoint_health(
3698    endpoint: crate::ModuleEndpointId,
3699    runtime: &SupervisorRuntimeConfig,
3700    deadline_cap: Option<Instant>,
3701) -> Result<HealthReport, HealthProbeError> {
3702    let Some(forwarding) = runtime.forwarding.as_ref() else {
3703        return Err(HealthProbeError::misconfigured(
3704            "supervisor was not configured with a forwarding table",
3705        ));
3706    };
3707    let probe_started_at = Instant::now();
3708    let mut deadline = probe_started_at + runtime.health.deadline;
3709    if let Some(cap) = deadline_cap {
3710        deadline = deadline.min(cap);
3711    }
3712    let pending = forwarding
3713        .begin_endpoint_health_probe_rpc_for(
3714            endpoint,
3715            MODULE_CONTROL_OP_HEALTH_CHECK,
3716            probe_started_at,
3717            deadline,
3718        )
3719        .map_err(|err| {
3720            HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
3721        })?;
3722    await_health_probe(forwarding, pending, deadline, runtime.health.deadline).await
3723}
3724
3725/// Send a begun health probe and classify its answer.
3726async fn await_health_probe(
3727    forwarding: &ForwardingTable,
3728    pending: PendingModuleControlRpc,
3729    deadline: Instant,
3730    probe_budget: Duration,
3731) -> Result<HealthReport, HealthProbeError> {
3732    let PendingModuleControlRpc {
3733        endpoint,
3734        module_sink,
3735        negotiated_ver,
3736        corr,
3737        receiver,
3738    } = pending;
3739    let body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).map_err(|err| {
3740        HealthProbeError::misconfigured(format!("failed to encode health.check: {err}"))
3741    })?;
3742    let frame = Frame::build_with_version(
3743        negotiated_ver,
3744        FrameType::Request,
3745        control_flags(),
3746        0,
3747        0,
3748        corr,
3749        body,
3750    )
3751    .map_err(|err| {
3752        HealthProbeError::misconfigured(format!("failed to build health.check frame: {err}"))
3753    })?;
3754
3755    // The enqueue itself must be bounded by the probe deadline: FrameSink.send
3756    // blocks waiting for capacity when the module's egress queue is full, and an
3757    // unbounded await here freezes the whole supervision actor (it stops polling
3758    // Child::wait and supervisor commands), making the module unrecoverable
3759    // in-band. On timeout the probe fails like any transport failure.
3760    match timeout_at(deadline, module_sink.send(frame)).await {
3761        Ok(Ok(())) => {}
3762        Ok(Err(err)) => {
3763            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
3764            // A closed sink means the module's egress channel is gone -- the
3765            // receiving half is dropped when its connection tears down. Proof.
3766            return Err(HealthProbeError::lane_dead(format!(
3767                "failed to send health.check: {err}"
3768            )));
3769        }
3770        Err(_elapsed) => {
3771            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
3772            // A full egress queue means the module is not draining its socket, which
3773            // is consistent with a wedged module AND with one whose reader is merely
3774            // starved. Silence, not proof.
3775            return Err(HealthProbeError::no_answer(
3776                "health.check send timed out before enqueue (module egress full)",
3777            ));
3778        }
3779    }
3780
3781    match timeout_at(deadline, receiver).await {
3782        // Each arm records WHAT WAS OBSERVED. Four of them are the module
3783        // demonstrably answering -- rejected, non-health, malformed, wrong op --
3784        // and those prove it is alive even though the probe failed.
3785        Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
3786            response.health_report().ok_or_else(|| {
3787                HealthProbeError::bad_answer("health.check RPC returned a non-health response")
3788            })
3789        }
3790        Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => Err(HealthProbeError::bad_answer(
3791            format!("health.check rejected: {}", body.message),
3792        )),
3793        Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
3794            Err(HealthProbeError::lane_dead(message))
3795        }
3796        Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
3797            Err(HealthProbeError::bad_answer(message))
3798        }
3799        Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
3800            Err(HealthProbeError::bad_answer(format!(
3801                "expected module-control op '{expected}', got '{actual}'"
3802            )))
3803        }
3804        // A reply that crosses the deadline before this waiter observes it is
3805        // still proof of life. The forwarding path records its end-to-end latency
3806        // before delivering this classification.
3807        Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => Err(HealthProbeError::bad_answer(
3808            "module answered health.check after its daemon deadline",
3809        )),
3810        Ok(Err(_)) => Err(HealthProbeError::misconfigured(
3811            "health.check waiter was canceled before the module responded",
3812        )),
3813        Err(_) => {
3814            let _ = forwarding.tombstone_health_probe_rpc(endpoint, corr);
3815            Err(HealthProbeError::no_answer(format!(
3816                "module did not answer health.check within {probe_budget:?}"
3817            )))
3818        }
3819    }
3820}
3821
3822#[allow(clippy::too_many_arguments)]
3823async fn handle_health_report(
3824    spec: &ModuleSpec,
3825    runtime: &SupervisorRuntimeConfig,
3826    registry: &Registry,
3827    process_liveness: &SupervisorProcessLiveness,
3828    snapshot: &SharedSnapshot,
3829    child: &mut Option<SupervisedChild>,
3830    report: HealthReport,
3831    now_ms: u64,
3832) {
3833    let status = supervisor_health_status(report.status);
3834    let detail = report.detail.clone();
3835    let metrics = truncate_health_metrics(report.metrics);
3836    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
3837        state.health.status = status;
3838        state.health.last_probe_ms = Some(now_ms);
3839        state.health.detail = detail.clone();
3840        state.health.metrics = metrics.clone();
3841        state.health.consecutive_failures = 0;
3842    });
3843
3844    let action = match report.status {
3845        HealthStatus::Ok => return,
3846        HealthStatus::Degraded => runtime.health.on_degraded,
3847        HealthStatus::Failing => runtime.health.on_failing,
3848    };
3849    apply_l3_health_action(
3850        spec,
3851        runtime,
3852        registry,
3853        process_liveness,
3854        snapshot,
3855        child,
3856        status,
3857        detail.as_deref(),
3858        action,
3859        now_ms,
3860    )
3861    .await;
3862}
3863
3864#[allow(clippy::too_many_arguments)]
3865async fn handle_health_probe_failure(
3866    spec: &ModuleSpec,
3867    runtime: &SupervisorRuntimeConfig,
3868    registry: &Registry,
3869    process_liveness: &SupervisorProcessLiveness,
3870    snapshot: &SharedSnapshot,
3871    child: &mut Option<SupervisedChild>,
3872    err: HealthProbeError,
3873    now_ms: u64,
3874) {
3875    let threshold = runtime.health.failure_threshold.max(1);
3876    let mut failures = 0;
3877    // Carry the evidence class into the operator-visible detail. Without it,
3878    // "module did not answer within 5s" and "the control lane is gone" are two
3879    // prose strings in the same field, and the reader has to know the codebase to
3880    // tell which one is proof of anything.
3881    let detail = format!("[{}] {err}", err.label());
3882    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
3883        state.health.last_probe_ms = Some(now_ms);
3884        state.health.consecutive_failures = state.health.consecutive_failures.saturating_add(1);
3885        state.health.detail = Some(detail.clone());
3886        state.health.metrics = None;
3887        failures = state.health.consecutive_failures;
3888    });
3889
3890    if failures < threshold {
3891        warn!(
3892            module_id = %spec.module_id,
3893            consecutive_failures = failures,
3894            threshold,
3895            evidence = err.label(),
3896            detail = %detail,
3897            "health.check probe failed"
3898        );
3899        return;
3900    }
3901
3902    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
3903        state.state = ModuleState::Unresponsive;
3904        state.health.status = SupervisorHealthStatus::Unresponsive;
3905    });
3906    // The evidence class is logged at the kill site because this is the line an
3907    // operator reads after an unexplained restart. A streak of `no-answer` under
3908    // machine load is the known false-positive shape; a `lane-dead` is not.
3909    if runtime.health.critical {
3910        error!(
3911            module_id = %spec.module_id,
3912            status = "unresponsive",
3913            evidence = err.label(),
3914            detail = %detail,
3915            "critical module health alert"
3916        );
3917    } else {
3918        warn!(
3919            module_id = %spec.module_id,
3920            status = "unresponsive",
3921            evidence = err.label(),
3922            detail = %detail,
3923            "module health threshold breached"
3924        );
3925    }
3926    if let Err(err) = health_restart_child(
3927        spec,
3928        runtime,
3929        registry,
3930        process_liveness,
3931        snapshot,
3932        child,
3933        SupervisorHealthStatus::Unresponsive,
3934        Some(&detail),
3935        now_ms,
3936    )
3937    .await
3938    {
3939        error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
3940    }
3941}
3942
3943#[allow(clippy::too_many_arguments)]
3944async fn apply_l3_health_action(
3945    spec: &ModuleSpec,
3946    runtime: &SupervisorRuntimeConfig,
3947    registry: &Registry,
3948    process_liveness: &SupervisorProcessLiveness,
3949    snapshot: &SharedSnapshot,
3950    child: &mut Option<SupervisedChild>,
3951    status: SupervisorHealthStatus,
3952    detail: Option<&str>,
3953    action: HealthAction,
3954    now_ms: u64,
3955) {
3956    record_health_action(snapshot, &spec.module_id, action.to_string(), now_ms);
3957    match action {
3958        HealthAction::Report => {
3959            info!(
3960                module_id = %spec.module_id,
3961                status = ?status,
3962                detail,
3963                "module reported non-ok health"
3964            );
3965        }
3966        HealthAction::Alert => {
3967            error!(
3968                module_id = %spec.module_id,
3969                status = ?status,
3970                detail,
3971                "module health alert"
3972            );
3973        }
3974        HealthAction::Restart => {
3975            if let Err(err) = health_restart_child(
3976                spec,
3977                runtime,
3978                registry,
3979                process_liveness,
3980                snapshot,
3981                child,
3982                status,
3983                detail,
3984                now_ms,
3985            )
3986            .await
3987            {
3988                error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
3989            }
3990        }
3991    }
3992}
3993
3994#[allow(clippy::too_many_arguments)]
3995async fn health_restart_child(
3996    spec: &ModuleSpec,
3997    runtime: &SupervisorRuntimeConfig,
3998    registry: &Registry,
3999    process_liveness: &SupervisorProcessLiveness,
4000    snapshot: &SharedSnapshot,
4001    child: &mut Option<SupervisedChild>,
4002    status: SupervisorHealthStatus,
4003    detail: Option<&str>,
4004    now_ms: u64,
4005) -> Result<(), SuperviseError> {
4006    let (enabled, schedule) = {
4007        let mut state = lock_snapshot(snapshot)?;
4008        let enabled = state.enabled;
4009        let schedule = if enabled {
4010            state.next_crash_restart(&runtime.restart_policy, Instant::now())
4011        } else {
4012            None
4013        };
4014        (enabled, schedule)
4015    };
4016
4017    if !enabled {
4018        return Err(SuperviseError::Disabled {
4019            module_id: spec.module_id.clone(),
4020        });
4021    }
4022
4023    if schedule.is_none() {
4024        record_health_action(snapshot, &spec.module_id, "disabled".to_string(), now_ms);
4025        error!(
4026            module_id = %spec.module_id,
4027            status = ?status,
4028            detail,
4029            max_restarts = runtime.restart_policy.max_restarts,
4030            window_secs = runtime.restart_policy.window.as_secs(),
4031            "health restart budget exhausted; disabling module"
4032        );
4033        let stop_notice = begin_forwarding_drain_if_configured(
4034            spec,
4035            runtime,
4036            registry,
4037            snapshot,
4038            Some(false),
4039            RouteCloseReason::Disable,
4040        )
4041        .await?;
4042        drain_optional_child(
4043            &spec.module_id,
4044            spec.protocol,
4045            stop_notice,
4046            registry,
4047            snapshot,
4048            &runtime.terminal_ring,
4049            &runtime.spawn_events,
4050            child,
4051            runtime.drain_timeout,
4052            ModuleState::Disabled,
4053            Some(false),
4054        )
4055        .await?;
4056        process_liveness.untrack_if_current(&spec.module_id, snapshot);
4057        return Ok(());
4058    }
4059
4060    let schedule = schedule.expect("a health restart must have a crash-restart schedule");
4061    let mut restart_count = 0;
4062    update_snapshot(snapshot, Some(&spec.module_id), |state| {
4063        restart_count = state.crash_restarts.len();
4064        state.state = ModuleState::Unresponsive;
4065        state.health.status = status;
4066        state.health.last_action = Some(HealthAction::Restart.to_string());
4067        state.health.last_action_ms = Some(now_ms);
4068    })?;
4069    warn!(
4070        module_id = %spec.module_id,
4071        status = ?status,
4072        detail,
4073        restart_count,
4074        restart_in_window = schedule.restart_in_window,
4075        delay_ms = schedule.delay.as_millis() as u64,
4076        "health-triggered module restart"
4077    );
4078
4079    let stop_notice = begin_forwarding_drain_if_configured(
4080        spec,
4081        runtime,
4082        registry,
4083        snapshot,
4084        Some(true),
4085        RouteCloseReason::Restart,
4086    )
4087    .await?;
4088    drain_optional_child(
4089        &spec.module_id,
4090        spec.protocol,
4091        stop_notice,
4092        registry,
4093        snapshot,
4094        &runtime.terminal_ring,
4095        &runtime.spawn_events,
4096        child,
4097        runtime.drain_timeout,
4098        ModuleState::Restarting,
4099        Some(true),
4100    )
4101    .await?;
4102    sleep(schedule.delay).await;
4103    // The backoff may have outlasted the restart it was counting down to: an
4104    // operator disable or drain in between moves the snapshot out of
4105    // `Restarting`, and that stop must win over this respawn.
4106    if !respawn_still_pending(snapshot) {
4107        process_liveness.untrack_if_current(&spec.module_id, snapshot);
4108        return Ok(());
4109    }
4110    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
4111    match spawn_and_mark_running(spec, runtime, snapshot) {
4112        Ok(next_child) => {
4113            *child = Some(next_child);
4114            Ok(())
4115        }
4116        Err(err) => {
4117            fail_snapshot(snapshot, Some(&spec.module_id), None);
4118            process_liveness.untrack_if_current(&spec.module_id, snapshot);
4119            *child = None;
4120            Err(err)
4121        }
4122    }
4123}
4124
4125fn record_health_action(snapshot: &SharedSnapshot, module_id: &str, action: String, now_ms: u64) {
4126    let _ = update_snapshot(snapshot, Some(module_id), |state| {
4127        state.health.last_action = Some(action);
4128        state.health.last_action_ms = Some(now_ms);
4129    });
4130}
4131
4132fn supervisor_health_status(status: HealthStatus) -> SupervisorHealthStatus {
4133    match status {
4134        HealthStatus::Ok => SupervisorHealthStatus::Ok,
4135        HealthStatus::Degraded => SupervisorHealthStatus::Degraded,
4136        HealthStatus::Failing => SupervisorHealthStatus::Failing,
4137    }
4138}
4139
4140/// Caps the metrics blob stored in the cached supervisor snapshot, which is
4141/// returned to every `supervisor.list` and `supervisor.health` caller.
4142///
4143/// This cap is deliberately NOT applied on the one-shot `supervisor.health_probe`
4144/// path: that request exists to return a module's complete metrics object, and
4145/// `ck health <module-id>` documents it as the way to see what the cached view
4146/// truncates. The asymmetry is the feature.
4147///
4148/// So a new caller must decide which side it is on rather than assume the cap is
4149/// universal. Reaching for it on a fresh-probe path would silently reintroduce
4150/// the truncation that path exists to avoid.
4151fn truncate_health_metrics(metrics: Option<Value>) -> Option<Value> {
4152    let metrics = metrics?;
4153    match serde_json::to_vec(&metrics) {
4154        Ok(encoded) if encoded.len() > MAX_HEALTH_METRICS_BYTES => Some(serde_json::json!({
4155            "truncated": true,
4156            "original_bytes": encoded.len(),
4157        })),
4158        Ok(_) | Err(_) => Some(metrics),
4159    }
4160}
4161
4162/// Spread health probes so a fleet-wide restart does not converge them.
4163///
4164/// The delay is derived from the module id and probe index rather than a random
4165/// source, so it is deterministic per module: a module keeps its own offset
4166/// across daemon restarts instead of re-rolling into a collision.
4167fn jittered_health_delay(module_id: &str, probe_index: u64, cadence: Duration) -> Duration {
4168    if cadence.is_zero() {
4169        return Duration::ZERO;
4170    }
4171    let cadence_ms = cadence.as_millis() as u64;
4172    // This early return is REDUNDANT, deliberately, and a mutation run will show
4173    // it surviving removal. Recording why here so the next person to notice does
4174    // not have to re-derive it:
4175    //
4176    // - It is unreachable in practice. `positive_millis` in daemon_config rejects
4177    //   a zero cadence and builds the Duration from whole milliseconds, so a
4178    //   sub-millisecond cadence cannot come from config.
4179    // - Even if reached it changes no answer. The `.max(1)` below makes the span
4180    //   1, and `hash % 1` is 0, so the fall-through returns `cadence` unchanged
4181    //   -- exactly what this returns.
4182    //
4183    // Kept as a guard against a future widening of the config parser (accepting
4184    // microseconds, say), which would make the sub-millisecond case reachable.
4185    // The `.max(1)` is the load-bearing half TODAY: remove it and the modulo
4186    // divides by zero. Remove this and nothing changes.
4187    if cadence_ms == 0 {
4188        return cadence;
4189    }
4190    // Note that this never returns less than one cadence, including for the FIRST
4191    // probe. So a freshly registered module reports health `unknown` for a full
4192    // cadence plus jitter -- 30-33s at the default -- no matter how quickly it is
4193    // ready to answer.
4194    //
4195    // That is a property of the supervisor's schedule, not of any module: an
4196    // operator watching a restart sees `unknown` and cannot tell it from a module
4197    // that is slow to warm. Measured on two unrelated modules, both flipping to
4198    // `ok` between 22s and 32s after restart.
4199    //
4200    // Left as-is because spreading the first probe is what keeps a fleet-wide
4201    // restart from firing fourteen simultaneous probes into a cold machine. The
4202    // alternative -- probe at t+0 and jitter only from the second onward -- trades
4203    // that thundering herd for a faster first reading.
4204    let jitter_span = (cadence_ms / 10).max(1);
4205    let hash = module_id.as_bytes().iter().fold(
4206        probe_index.wrapping_mul(0x9E37_79B9_7F4A_7C15),
4207        |acc, byte| {
4208            acc.wrapping_mul(1099511628211)
4209                .wrapping_add(u64::from(*byte))
4210        },
4211    );
4212    cadence + Duration::from_millis(hash % jitter_span)
4213}
4214
4215#[cfg(test)]
4216mod tests {
4217    use super::*;
4218
4219    #[test]
4220    fn readding_a_module_clears_its_rescan_removal_tombstone() {
4221        let handle = SupervisorHandle::new();
4222        let module_id = "readded-tombstone";
4223        handle.record_rescan_removal(module_id);
4224        assert!(handle.removal_tombstone_age_ms(module_id).is_some());
4225
4226        handle.apply_identity_configuration(&ModuleSpec {
4227            module_id: module_id.to_string(),
4228            program: PathBuf::from("/test/module"),
4229            args: Vec::new(),
4230            env: Vec::new(),
4231            reserved: false,
4232            reserved_prefixes: Vec::new(),
4233            protocol: ModuleProtocol::Subc,
4234            overlap: Default::default(),
4235        });
4236
4237        assert!(
4238            handle.removal_tombstone_age_ms(module_id).is_none(),
4239            "a re-added module must not retain a stale removal tombstone"
4240        );
4241    }
4242
4243    fn stale_process_snapshot(state: ModuleState, enabled: bool) -> SharedSnapshot {
4244        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(state, enabled)));
4245        update_snapshot(&snapshot, Some("stale-process-facts"), |snapshot| {
4246            snapshot.process_alive = true;
4247            snapshot.pid = Some(41);
4248            snapshot.spawned_at_ms = Some(42);
4249            snapshot.spawned_from = Some(PathBuf::from("/spawned/module"));
4250            snapshot.spawned_file_identity = Some(SpawnedFileIdentity {
4251                device: 43,
4252                inode: 44,
4253            });
4254        })
4255        .unwrap();
4256        snapshot
4257    }
4258
4259    fn assert_snapshot_process_facts_cleared(snapshot: &SharedSnapshot) {
4260        let snapshot = lock_snapshot(snapshot).unwrap();
4261        assert!(!snapshot.process_alive);
4262        assert_eq!(snapshot.pid, None);
4263        assert_eq!(snapshot.spawned_at_ms, None);
4264        assert_eq!(snapshot.spawned_from, None);
4265        assert_eq!(snapshot.spawned_file_identity, None);
4266    }
4267
4268    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4269    async fn failed_enable_spawn_clears_preexisting_current_process_facts() {
4270        let supervisor = Supervisor::default();
4271        let mut runtime = supervisor.runtime_config();
4272        runtime.test_seed_stale_facts_before_enable_spawn = true;
4273        let snapshot = stale_process_snapshot(ModuleState::Disabled, false);
4274        let mut child = None;
4275        let spec = ModuleSpec {
4276            module_id: "failed-enable-clears-facts".to_string(),
4277            program: PathBuf::from("/definitely/missing/failed-enable-module"),
4278            args: Vec::new(),
4279            env: Vec::new(),
4280            reserved: false,
4281            reserved_prefixes: Vec::new(),
4282            protocol: ModuleProtocol::Subc,
4283            overlap: Default::default(),
4284        };
4285
4286        let result = set_child_enabled(
4287            &spec,
4288            &runtime,
4289            &supervisor.registry,
4290            &supervisor.process_liveness,
4291            &snapshot,
4292            &mut child,
4293            true,
4294        )
4295        .await;
4296
4297        assert!(matches!(result, Err(SuperviseError::Spawn { .. })));
4298        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
4299        assert_snapshot_process_facts_cleared(&snapshot);
4300    }
4301
4302    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4303    async fn failed_reload_spawn_clears_current_process_facts() {
4304        let supervisor = Supervisor::default();
4305        let mut runtime = supervisor.runtime_config();
4306        runtime.restart_policy = RestartPolicy::new(0, Duration::ZERO);
4307        let snapshot = stale_process_snapshot(ModuleState::Running, true);
4308        let mut child = None;
4309        let spec = ModuleSpec {
4310            module_id: "failed-reload-clears-facts".to_string(),
4311            program: PathBuf::from("/unused/failed-reload-module"),
4312            args: Vec::new(),
4313            env: Vec::new(),
4314            reserved: false,
4315            reserved_prefixes: Vec::new(),
4316            protocol: ModuleProtocol::Subc,
4317            overlap: Default::default(),
4318        };
4319
4320        let result = handle_reload_spawn_failure(
4321            &spec,
4322            &runtime,
4323            &supervisor.process_liveness,
4324            &snapshot,
4325            &mut child,
4326            "forced reload spawn failure".to_string(),
4327        )
4328        .await;
4329
4330        assert!(matches!(result, Err(SuperviseError::ReloadFailed { .. })));
4331        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
4332        assert_snapshot_process_facts_cleared(&snapshot);
4333    }
4334
4335    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4336    async fn dropping_a_module_with_an_active_monitor_clears_current_process_facts() {
4337        let supervisor = Supervisor::default();
4338        let snapshot = stale_process_snapshot(ModuleState::Running, true);
4339        let module = supervisor.supervised_module(
4340            ModuleSpec {
4341                module_id: "drop-clears-facts".to_string(),
4342                program: PathBuf::from("/unused/drop-module"),
4343                args: Vec::new(),
4344                env: Vec::new(),
4345                reserved: false,
4346                reserved_prefixes: Vec::new(),
4347                protocol: ModuleProtocol::Subc,
4348                overlap: Default::default(),
4349            },
4350            supervisor.runtime_config(),
4351            Arc::clone(&snapshot),
4352            None,
4353        );
4354        assert!(!module
4355            .inner
4356            .monitor
4357            .lock()
4358            .unwrap()
4359            .as_ref()
4360            .unwrap()
4361            .is_finished());
4362
4363        drop(module);
4364
4365        assert_eq!(
4366            lock_snapshot(&snapshot).unwrap().state,
4367            ModuleState::Stopped
4368        );
4369        assert_snapshot_process_facts_cleared(&snapshot);
4370    }
4371
4372    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4373    async fn configuration_update_does_not_replace_captured_running_process_facts() {
4374        let supervisor = Supervisor::default();
4375        let snapshot = stale_process_snapshot(ModuleState::Running, true);
4376        let initial = ModuleSpec {
4377            module_id: "rescan-preserves-spawn-facts".to_string(),
4378            program: PathBuf::from("/spawned/module"),
4379            args: Vec::new(),
4380            env: Vec::new(),
4381            reserved: false,
4382            reserved_prefixes: Vec::new(),
4383            protocol: ModuleProtocol::Subc,
4384            overlap: Default::default(),
4385        };
4386        let module = supervisor.supervised_module(
4387            initial.clone(),
4388            supervisor.runtime_config(),
4389            snapshot,
4390            None,
4391        );
4392        let before = module.status().unwrap();
4393        let mut replacement = initial;
4394        replacement.program = PathBuf::from("/rescanned/replacement-module");
4395
4396        module
4397            .update_configuration(replacement, HealthConfig::default(), None)
4398            .await
4399            .unwrap();
4400
4401        let after = module.status().unwrap();
4402        assert_eq!(after.pid, before.pid);
4403        assert_eq!(after.spawned_at_ms, before.spawned_at_ms);
4404        assert_eq!(after.spawned_from, before.spawned_from);
4405        drop(module);
4406    }
4407}
4408
4409fn unix_ms_now() -> u64 {
4410    SystemTime::now()
4411        .duration_since(UNIX_EPOCH)
4412        .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
4413        .unwrap_or(0)
4414}
4415
4416async fn supervise_loop(
4417    mut spec: ModuleSpec,
4418    mut runtime: SupervisorRuntimeConfig,
4419    registry: Arc<Registry>,
4420    process_liveness: Arc<SupervisorProcessLiveness>,
4421    snapshot: SharedSnapshot,
4422    mut child: Option<SupervisedChild>,
4423    mut commands: mpsc::Receiver<SupervisorCommand>,
4424) {
4425    let mut health_probe = HealthProbeRuntime::default();
4426    // Deadline of the crash respawn whose backoff is currently elapsing. While
4427    // it is set the loop serves commands instead of sleeping inside the exit
4428    // arm, so a disable or drain lands immediately and cancels the respawn.
4429    let mut pending_respawn: Option<Instant> = None;
4430    // Commands a swap handed back to run next (see `swap::SwapEnd`). Served
4431    // before anything else so a stop that interrupted a swap runs at once.
4432    let mut requeued: VecDeque<SupervisorCommand> = VecDeque::new();
4433    loop {
4434        if let Some(command) = requeued.pop_front() {
4435            if !handle_supervisor_command(
4436                command,
4437                &mut spec,
4438                &mut runtime,
4439                &registry,
4440                &process_liveness,
4441                &snapshot,
4442                &mut child,
4443                &mut commands,
4444                &mut requeued,
4445            )
4446            .await
4447            {
4448                return;
4449            }
4450            if child.is_some() || !respawn_still_pending(&snapshot) {
4451                pending_respawn = None;
4452            }
4453            continue;
4454        }
4455        if child.is_some() {
4456            health_probe.refresh_registration(&spec, &runtime, &registry, &snapshot);
4457            let probe_sleep = sleep(health_probe.wake_after());
4458            tokio::pin!(probe_sleep);
4459            let active_child = child.as_mut().expect("child checked above");
4460            tokio::select! {
4461                wait_result = active_child.wait() => {
4462                    // Every arm below that gives up on the CHILD must keep the
4463                    // supervision task itself alive (child = None, loop
4464                    // continues into command-serving mode). Returning here
4465                    // closes the command channel, which makes the module
4466                    // permanently unrestartable in-band: a clean child exit
4467                    // of an enabled module once wedged the fleet this way
4468                    // ('supervisor command channel is closed') and required a
4469                    // full daemon restart to recover.
4470                    let exit_report = match wait_result {
4471                        Ok(status) => classify_reaped_child_exit(&snapshot, active_child, &status),
4472                        Err(err) => {
4473                            active_child.drain_stderr(&spec.module_id).await;
4474                            fail_snapshot(&snapshot, Some(&spec.module_id), None);
4475                            // Every other exit path (on_child_exit's Clean/Crash arms,
4476                            // the reload-registration-failure path) records a terminal
4477                            // before moving on. Without one here, a module whose wait()
4478                            // itself errored (e.g. already reaped) leaves no terminal
4479                            // record at all -- an empty ring reads as "nothing died".
4480                            record_wait_error_terminal(
4481                                &spec.module_id,
4482                                &runtime.terminal_ring,
4483                                &runtime.spawn_events,
4484                            );
4485                            untrack_if_registration_released(
4486                                &process_liveness,
4487                                &registry,
4488                                &spec.module_id,
4489                                &snapshot,
4490                            );
4491                            error!(module_id = %spec.module_id, error = %err, "failed to wait for supervised module");
4492                            child = None;
4493                            continue;
4494                        }
4495                    };
4496                    active_child.drain_stderr(&spec.module_id).await;
4497
4498                    let next = on_child_exit(
4499                        &spec,
4500                        runtime.restart_policy,
4501                        &registry,
4502                        &snapshot,
4503                        &runtime.terminal_ring,
4504                        &runtime.spawn_events,
4505                        &runtime.child_roster,
4506                        exit_report,
4507                    ).await;
4508                    // The exit is recorded, so a daemon shutdown may stop
4509                    // waiting for this child (see `SupervisedChild::wait`).
4510                    active_child.release_roster();
4511                    match next {
4512                        NextAction::Stop { registration_released } => {
4513                            if registration_released {
4514                                process_liveness.untrack_if_current(&spec.module_id, &snapshot);
4515                            }
4516                            child = None;
4517                        }
4518                        NextAction::Restart { schedule } => {
4519                            let delay = schedule.map_or(
4520                                runtime.restart_policy.delay_for_restart(0),
4521                                |schedule| schedule.delay,
4522                            );
4523                            if let Some(schedule) = schedule {
4524                                log_crash_respawn(&spec.module_id, schedule);
4525                            }
4526                            // The exited child is fully recorded at this point,
4527                            // so release it and count the backoff down in the
4528                            // command-serving branch below rather than sleeping
4529                            // here: commands cannot be received from inside this
4530                            // select arm, and an operator disable or drain that
4531                            // arrives during the backoff must cancel the pending
4532                            // respawn instead of waiting for it to spawn first.
4533                            child = None;
4534                            pending_respawn = Some(Instant::now() + delay);
4535                        }
4536                    }
4537                }
4538                command = commands.recv() => {
4539                    let Some(command) = command else {
4540                        return;
4541                    };
4542                    if !handle_supervisor_command(
4543                        command,
4544                        &mut spec,
4545                        &mut runtime,
4546                        &registry,
4547                        &process_liveness,
4548                        &snapshot,
4549                        &mut child,
4550                        &mut commands,
4551                        &mut requeued,
4552                    ).await {
4553                        return;
4554                    }
4555                }
4556                _ = &mut probe_sleep => {
4557                    if health_probe.due() {
4558                        run_health_probe_cycle(
4559                            &spec,
4560                            &runtime,
4561                            &registry,
4562                            &process_liveness,
4563                            &snapshot,
4564                            &mut child,
4565                        ).await;
4566                        if child.is_some() {
4567                            health_probe.schedule_next(&spec, runtime.health.cadence);
4568                        }
4569                    }
4570                }
4571            }
4572        } else if let Some(deadline) = pending_respawn {
4573            tokio::select! {
4574                _ = sleep_until(deadline) => {
4575                    pending_respawn = None;
4576                    // A command handled below while the backoff elapsed may
4577                    // have stopped the module; never respawn past an operator's
4578                    // disable or drain.
4579                    if !respawn_still_pending(&snapshot) {
4580                        continue;
4581                    }
4582                    // The daemon began shutting down during the backoff: the
4583                    // spawn would be refused anyway, and refusing it here
4584                    // leaves the module stopped instead of reporting a
4585                    // failed restart.
4586                    if runtime.child_roster.is_closed() {
4587                        let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
4588                            state.state = ModuleState::Stopped;
4589                        });
4590                        debug!(module_id = %spec.module_id, "crash respawn cancelled by daemon shutdown");
4591                        continue;
4592                    }
4593                    if let Err(err) = wait_for_registration_release(
4594                        &registry,
4595                        &spec.module_id,
4596                        REGISTRY_RELEASE_TIMEOUT,
4597                    ).await {
4598                        fail_snapshot(&snapshot, Some(&spec.module_id), None);
4599                        error!(module_id = %spec.module_id, error = %err, "registration did not release before restart");
4600                        continue;
4601                    }
4602
4603                    match spawn_and_mark_running(&spec, &runtime, &snapshot) {
4604                        Ok(next_child) => {
4605                            child = Some(next_child);
4606                            debug!(module_id = %spec.module_id, "supervised module restarted after crash");
4607                        }
4608                        Err(err) => {
4609                            fail_snapshot(&snapshot, Some(&spec.module_id), None);
4610                            process_liveness.untrack_if_current(&spec.module_id, &snapshot);
4611                            error!(module_id = %spec.module_id, error = %err, "failed to restart supervised module");
4612                        }
4613                    }
4614                }
4615                command = commands.recv() => {
4616                    let Some(command) = command else {
4617                        return;
4618                    };
4619                    if !handle_supervisor_command(
4620                        command,
4621                        &mut spec,
4622                        &mut runtime,
4623                        &registry,
4624                        &process_liveness,
4625                        &snapshot,
4626                        &mut child,
4627                        &mut commands,
4628                        &mut requeued,
4629                    ).await {
4630                        return;
4631                    }
4632                    // Reconcile the pending respawn with what the command did:
4633                    // a restart or reload has already spawned a fresh child,
4634                    // while a disable or drain moved the snapshot out of the
4635                    // state the respawn was counting down from.
4636                    if child.is_some() || !respawn_still_pending(&snapshot) {
4637                        pending_respawn = None;
4638                    }
4639                }
4640            }
4641        } else {
4642            let Some(command) = commands.recv().await else {
4643                return;
4644            };
4645            if !handle_supervisor_command(
4646                command,
4647                &mut spec,
4648                &mut runtime,
4649                &registry,
4650                &process_liveness,
4651                &snapshot,
4652                &mut child,
4653                &mut commands,
4654                &mut requeued,
4655            )
4656            .await
4657            {
4658                return;
4659            }
4660        }
4661    }
4662}
4663
4664fn log_crash_respawn(module_id: &str, schedule: CrashRestartSchedule) {
4665    info!(
4666        module_id,
4667        restart_in_window = schedule.restart_in_window,
4668        delay_ms = schedule.delay.as_millis() as u64,
4669        "respawning after crash"
4670    );
4671}
4672
4673/// Whether the respawn a backoff was counting down to is still wanted. A
4674/// disable or drain handled while the backoff elapsed moves the snapshot out
4675/// of `Restarting`, and the operator's stop must win over the pending respawn,
4676/// so every sleep-then-spawn path re-validates against the live snapshot
4677/// instead of assuming the state it left behind still holds.
4678fn respawn_still_pending(snapshot: &SharedSnapshot) -> bool {
4679    matches!(
4680        lock_snapshot(snapshot),
4681        Ok(state) if state.enabled && state.state == ModuleState::Restarting
4682    )
4683}
4684
4685enum NextAction {
4686    Stop {
4687        registration_released: bool,
4688    },
4689    Restart {
4690        schedule: Option<CrashRestartSchedule>,
4691    },
4692}
4693
4694#[allow(clippy::too_many_arguments)]
4695async fn handle_supervisor_command(
4696    command: SupervisorCommand,
4697    spec: &mut ModuleSpec,
4698    runtime: &mut SupervisorRuntimeConfig,
4699    registry: &Registry,
4700    process_liveness: &SupervisorProcessLiveness,
4701    snapshot: &SharedSnapshot,
4702    child: &mut Option<SupervisedChild>,
4703    commands: &mut mpsc::Receiver<SupervisorCommand>,
4704    requeued: &mut VecDeque<SupervisorCommand>,
4705) -> bool {
4706    match command {
4707        SupervisorCommand::Drain { reply } => {
4708            // A plain stop runs no forwarding drain, so nothing reaches the
4709            // module over its connection before the wait: ask by signal.
4710            let result = drain_optional_child(
4711                &spec.module_id,
4712                spec.protocol,
4713                StopNotice::NotSent,
4714                registry,
4715                snapshot,
4716                &runtime.terminal_ring,
4717                &runtime.spawn_events,
4718                child,
4719                runtime.drain_timeout,
4720                ModuleState::Stopped,
4721                None,
4722            )
4723            .await;
4724            let registration_released = result.is_ok();
4725            let _ = reply.send(result);
4726            if registration_released {
4727                process_liveness.untrack_if_current(&spec.module_id, snapshot);
4728            }
4729            false
4730        }
4731        SupervisorCommand::Retire { reply } => {
4732            let result = async {
4733                let stop_notice = begin_forwarding_drain_if_configured(
4734                    spec,
4735                    runtime,
4736                    registry,
4737                    snapshot,
4738                    None,
4739                    RouteCloseReason::Disable,
4740                )
4741                .await?;
4742                drain_optional_child(
4743                    &spec.module_id,
4744                    spec.protocol,
4745                    stop_notice,
4746                    registry,
4747                    snapshot,
4748                    &runtime.terminal_ring,
4749                    &runtime.spawn_events,
4750                    child,
4751                    runtime.drain_timeout,
4752                    ModuleState::Stopped,
4753                    None,
4754                )
4755                .await
4756            }
4757            .await;
4758            let registration_released = result.is_ok();
4759            let _ = reply.send(result);
4760            if registration_released {
4761                process_liveness.untrack_if_current(&spec.module_id, snapshot);
4762            }
4763            false
4764        }
4765        SupervisorCommand::Restart {
4766            drain_timeout_ms,
4767            received_at_generation,
4768            queued_at,
4769            reply,
4770        } => {
4771            // Without this line a restart that waited in the queue (behind a
4772            // health probe cycle or another command) was invisible: the log
4773            // showed only the drain timing out, minutes after the operator's call.
4774            info!(
4775                module_id = %spec.module_id,
4776                queued_ms = u64::try_from(queued_at.elapsed().as_millis()).unwrap_or(u64::MAX),
4777                "restart command dequeued"
4778            );
4779            // ACK AT INITIATION, not completion. The blocking form deadlocked any
4780            // caller whose own request lane rides the module being restarted: the
4781            // caller's in-flight request keeps the drain from quiescing, the drain
4782            // keeps the restart from completing, and the completion keeps the reply
4783            // from releasing the caller — so the drain always timed out and cut the
4784            // initiator with a GOODBYE, even on a healthy module. Replying once the
4785            // restart is validated lets a self-lane caller settle, which is exactly
4786            // what makes the drain succeed. Completion is observable via
4787            // supervisor.list / module status; a post-ack failure lands the module
4788            // in a visible terminal state below rather than in a reply nobody can
4789            // receive.
4790            let validation = match lock_snapshot(snapshot) {
4791                Ok(state) if !state.enabled => Err(SuperviseError::Disabled {
4792                    module_id: spec.module_id.clone(),
4793                }),
4794                Ok(_) => Ok(()),
4795                Err(err) => Err(err),
4796            };
4797            let initiated = validation.is_ok();
4798            let _ = reply.send(validation);
4799            // A restart asks for a fresh process. Commands run one at a time,
4800            // so a restart queued behind another restart (two operator calls
4801            // in quick succession) is dequeued the moment the first one has
4802            // spawned its replacement -- before that process has sent HELLO.
4803            // Running it would drain and kill the process the first restart
4804            // just produced, which is the opposite of what both callers asked
4805            // for. If a process spawned after this request was received is
4806            // still supervised, the request is already satisfied. Not when the
4807            // configuration changed since that spawn: then the newer process
4808            // predates the spec this restart may exist to apply.
4809            let satisfied_by_generation = if initiated && child.is_some() {
4810                lock_snapshot(snapshot).ok().and_then(|state| {
4811                    (state.spawn_generation > received_at_generation
4812                        && !state.configuration_updated_since_spawn)
4813                        .then_some(state.spawn_generation)
4814                })
4815            } else {
4816                None
4817            };
4818            if let Some(generation) = satisfied_by_generation {
4819                info!(
4820                    module_id = %spec.module_id,
4821                    received_at_generation,
4822                    "restart already satisfied by generation {generation}; not restarting again"
4823                );
4824            } else if initiated {
4825                // Precedence: this restart's operator override, else the module's
4826                // configured budget (already resolved into the runtime).
4827                let drain_timeout = drain_timeout_ms
4828                    .map(Duration::from_millis)
4829                    .unwrap_or(runtime.drain_timeout);
4830                if let Err(err) = restart_child(
4831                    spec,
4832                    runtime,
4833                    registry,
4834                    process_liveness,
4835                    snapshot,
4836                    child,
4837                    drain_timeout,
4838                )
4839                .await
4840                {
4841                    warn!(
4842                        module_id = %spec.module_id,
4843                        error = %err,
4844                        "operator restart failed after initiation ack; module state carries the outcome"
4845                    );
4846                    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
4847                        state.state = ModuleState::Failed;
4848                        clear_current_process_facts(state);
4849                    });
4850                }
4851            }
4852            true
4853        }
4854        SupervisorCommand::Reload { reply } => {
4855            let result =
4856                reload_child(spec, runtime, registry, process_liveness, snapshot, child).await;
4857            let _ = reply.send(result);
4858            true
4859        }
4860        SupervisorCommand::SetEnabled { enabled, reply } => {
4861            let result = set_child_enabled(
4862                spec,
4863                runtime,
4864                registry,
4865                process_liveness,
4866                snapshot,
4867                child,
4868                enabled,
4869            )
4870            .await;
4871            let _ = reply.send(result);
4872            true
4873        }
4874        SupervisorCommand::UpdateConfiguration {
4875            spec: next_spec,
4876            health,
4877            drain_timeout_ms,
4878            reply,
4879        } => {
4880            if let Some(handle) = &runtime.supervisor_handle {
4881                handle.apply_identity_configuration(&next_spec);
4882            }
4883            *spec = next_spec;
4884            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
4885                state.configuration_updated_since_spawn = true;
4886            });
4887            runtime.health = health;
4888            runtime.drain_timeout = drain_timeout_ms
4889                .map(Duration::from_millis)
4890                .unwrap_or(runtime.default_drain_timeout);
4891            *runtime
4892                .effective_drain_timeout
4893                .lock()
4894                .unwrap_or_else(|poisoned| poisoned.into_inner()) = runtime.drain_timeout;
4895            let _ = reply.send(());
4896            true
4897        }
4898        SupervisorCommand::Swap {
4899            ready_timeout,
4900            reply,
4901        } => {
4902            let end = swap::run_swap(
4903                spec,
4904                runtime,
4905                registry,
4906                process_liveness,
4907                snapshot,
4908                child,
4909                commands,
4910                ready_timeout.unwrap_or(DEFAULT_SWAP_READY_TIMEOUT),
4911                reply,
4912            )
4913            .await;
4914            requeued.extend(end.requeue);
4915            true
4916        }
4917    }
4918}
4919
4920async fn restart_child(
4921    spec: &ModuleSpec,
4922    runtime: &SupervisorRuntimeConfig,
4923    registry: &Registry,
4924    process_liveness: &SupervisorProcessLiveness,
4925    snapshot: &SharedSnapshot,
4926    child: &mut Option<SupervisedChild>,
4927    drain_timeout: Duration,
4928) -> Result<(), SuperviseError> {
4929    // Restart cycles a running module; it must not silently start a disabled one.
4930    if !lock_snapshot(snapshot)?.enabled {
4931        return Err(SuperviseError::Disabled {
4932            module_id: spec.module_id.clone(),
4933        });
4934    }
4935    let stop_notice = begin_forwarding_drain_with_timeout(
4936        spec,
4937        runtime,
4938        registry,
4939        snapshot,
4940        None,
4941        RouteCloseReason::Restart,
4942        drain_timeout,
4943    )
4944    .await?;
4945
4946    if child.is_some() {
4947        drain_optional_child(
4948            &spec.module_id,
4949            spec.protocol,
4950            stop_notice,
4951            registry,
4952            snapshot,
4953            &runtime.terminal_ring,
4954            &runtime.spawn_events,
4955            child,
4956            drain_timeout,
4957            ModuleState::Restarting,
4958            Some(true),
4959        )
4960        .await?;
4961    } else {
4962        update_snapshot(snapshot, Some(&spec.module_id), |state| {
4963            state.enabled = true;
4964            state.state = ModuleState::Restarting;
4965            clear_current_process_facts(state);
4966        })?;
4967        wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT).await?;
4968    }
4969
4970    reset_restart_count(snapshot, &spec.module_id)?;
4971    sleep(runtime.restart_policy.backoff).await;
4972    // A disable or drain that landed during the backoff cancels this respawn:
4973    // the operator's stop must win over the restart the sleep counted down to.
4974    if !respawn_still_pending(snapshot) {
4975        process_liveness.untrack_if_current(&spec.module_id, snapshot);
4976        return Ok(());
4977    }
4978    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
4979    // Mirror health_restart_child's spawn-failure handling: of the four
4980    // spawn-failure sites this was the only one that propagated with the
4981    // snapshot still reading `Restarting` -- neither running nor failed, and
4982    // unrevivable by `set_enabled(true)` (issue #34). `Failed` is the state the
4983    // operator can see and heal.
4984    match spawn_and_mark_running(spec, runtime, snapshot) {
4985        Ok(next_child) => {
4986            *child = Some(next_child);
4987            debug!(module_id = %spec.module_id, "supervised module restarted by operator request");
4988            Ok(())
4989        }
4990        Err(err) => {
4991            fail_snapshot(snapshot, Some(&spec.module_id), None);
4992            process_liveness.untrack_if_current(&spec.module_id, snapshot);
4993            *child = None;
4994            Err(err)
4995        }
4996    }
4997}
4998
4999async fn reload_child(
5000    spec: &ModuleSpec,
5001    runtime: &SupervisorRuntimeConfig,
5002    registry: &Registry,
5003    process_liveness: &SupervisorProcessLiveness,
5004    snapshot: &SharedSnapshot,
5005    child: &mut Option<SupervisedChild>,
5006) -> Result<(), SuperviseError> {
5007    // Reload cycles a running module; it must not silently start a disabled one.
5008    if !lock_snapshot(snapshot)?.enabled {
5009        return Err(SuperviseError::Disabled {
5010            module_id: spec.module_id.clone(),
5011        });
5012    }
5013    let stop_notice = begin_forwarding_drain(
5014        spec,
5015        runtime,
5016        registry,
5017        snapshot,
5018        Some(true),
5019        RouteCloseReason::Reload,
5020    )
5021    .await?;
5022
5023    if child.is_some() {
5024        drain_optional_child(
5025            &spec.module_id,
5026            spec.protocol,
5027            stop_notice,
5028            registry,
5029            snapshot,
5030            &runtime.terminal_ring,
5031            &runtime.spawn_events,
5032            child,
5033            runtime.drain_timeout,
5034            ModuleState::Restarting,
5035            Some(true),
5036        )
5037        .await?;
5038    } else {
5039        update_snapshot(snapshot, Some(&spec.module_id), |state| {
5040            state.enabled = true;
5041            state.state = ModuleState::Restarting;
5042            clear_current_process_facts(state);
5043        })?;
5044        wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT).await?;
5045    }
5046
5047    reset_restart_count(snapshot, &spec.module_id)?;
5048    sleep(runtime.restart_policy.backoff).await;
5049    // A disable or drain that landed during the backoff cancels this respawn:
5050    // the operator's stop must win over the restart the sleep counted down to.
5051    if !respawn_still_pending(snapshot) {
5052        process_liveness.untrack_if_current(&spec.module_id, snapshot);
5053        return Ok(());
5054    }
5055    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
5056    let next_child = match spawn_and_mark_running(spec, runtime, snapshot) {
5057        Ok(next_child) => next_child,
5058        Err(err) => {
5059            return handle_reload_spawn_failure(
5060                spec,
5061                runtime,
5062                process_liveness,
5063                snapshot,
5064                child,
5065                format!("new child failed to spawn: {err}"),
5066            )
5067            .await;
5068        }
5069    };
5070    *child = Some(next_child);
5071
5072    let wait_outcome = {
5073        let active_child = child.as_mut().expect("new reload child was just stored");
5074        wait_for_registration_after_reload(
5075            registry,
5076            &spec.module_id,
5077            snapshot,
5078            active_child,
5079            REGISTRY_RELEASE_TIMEOUT,
5080        )
5081        .await?
5082    };
5083
5084    match wait_outcome {
5085        RegistrationWaitOutcome::Registered => {
5086            debug!(module_id = %spec.module_id, "supervised module reloaded and registered");
5087            Ok(())
5088        }
5089        RegistrationWaitOutcome::Exited(exit_report) => {
5090            if let Some(active_child) = child.as_mut() {
5091                active_child.drain_stderr(&spec.module_id).await;
5092            }
5093            *child = None;
5094            handle_reload_child_registration_failure(
5095                spec,
5096                runtime,
5097                registry,
5098                process_liveness,
5099                snapshot,
5100                child,
5101                ReloadRegistrationFailure {
5102                    exit_report: registration_failure_exit_report(exit_report),
5103                    reason: "new child exited before registering".to_string(),
5104                },
5105            )
5106            .await
5107        }
5108        RegistrationWaitOutcome::TimedOut => {
5109            let mut timed_out_child = child
5110                .take()
5111                .expect("timed-out reload child is still running");
5112            timed_out_child
5113                .start_kill()
5114                .map_err(|source| SuperviseError::Kill {
5115                    module_id: spec.module_id.clone(),
5116                    source,
5117                })?;
5118            let status = timed_out_child
5119                .wait()
5120                .await
5121                .map_err(|source| SuperviseError::Wait {
5122                    module_id: spec.module_id.clone(),
5123                    source,
5124                })?;
5125            timed_out_child.drain_stderr(&spec.module_id).await;
5126            handle_reload_child_registration_failure(
5127                spec,
5128                runtime,
5129                registry,
5130                process_liveness,
5131                snapshot,
5132                child,
5133                ReloadRegistrationFailure {
5134                    exit_report: registration_failure_exit_report(classify_reaped_child_exit(
5135                        snapshot,
5136                        &timed_out_child,
5137                        &status,
5138                    )),
5139                    reason: format!(
5140                        "new child did not register within {:?}",
5141                        REGISTRY_RELEASE_TIMEOUT
5142                    ),
5143                },
5144            )
5145            .await
5146        }
5147    }
5148}
5149
5150async fn set_child_enabled(
5151    spec: &ModuleSpec,
5152    runtime: &SupervisorRuntimeConfig,
5153    registry: &Registry,
5154    process_liveness: &SupervisorProcessLiveness,
5155    snapshot: &SharedSnapshot,
5156    child: &mut Option<SupervisedChild>,
5157    enabled: bool,
5158) -> Result<bool, SuperviseError> {
5159    let (current_enabled, current_state) = {
5160        let state = lock_snapshot(snapshot)?;
5161        (state.enabled, state.state)
5162    };
5163    // `start` (enable on an already-enabled module) heals TERMINAL states instead
5164    // of no-op'ing: a module whose restart budget exhausted (Failed) or that exited
5165    // clean (Stopped) has no live process and no other in-band recovery — the
5166    // operator's start is the explicit recovery act and resets the budget. Without
5167    // this arm the only revival was subc-probe --supervisor-restart in a terminal,
5168    // which the 2026-07-14 aft outage proved is a trap when the failed module is
5169    // the one providing every agent's shell.
5170    let revive_terminal = enabled
5171        && current_enabled
5172        && child.is_none()
5173        && matches!(current_state, ModuleState::Failed | ModuleState::Stopped);
5174    if current_enabled == enabled && !revive_terminal {
5175        return Ok(false);
5176    }
5177
5178    if enabled {
5179        update_snapshot(snapshot, Some(&spec.module_id), |state| {
5180            state.enabled = true;
5181            state.state = ModuleState::Starting;
5182            clear_current_process_facts(state);
5183        })?;
5184        #[cfg(test)]
5185        if runtime.test_seed_stale_facts_before_enable_spawn {
5186            update_snapshot(snapshot, Some(&spec.module_id), |state| {
5187                state.process_alive = true;
5188                state.pid = Some(41);
5189                state.spawned_at_ms = Some(42);
5190                state.spawned_from = Some(PathBuf::from("/spawned/module"));
5191                state.spawned_file_identity = Some(SpawnedFileIdentity {
5192                    device: 43,
5193                    inode: 44,
5194                });
5195            })?;
5196        }
5197        wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT).await?;
5198        reset_restart_count(snapshot, &spec.module_id)?;
5199        process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
5200        let next_child = match spawn_and_mark_running(spec, runtime, snapshot) {
5201            Ok(next_child) => next_child,
5202            Err(err) => {
5203                if let Err(state_err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
5204                    state.state = ModuleState::Failed;
5205                    clear_current_process_facts(state);
5206                }) {
5207                    error!(module_id = %spec.module_id, error = %state_err, "failed to record enable spawn failure");
5208                }
5209                process_liveness.untrack_if_current(&spec.module_id, snapshot);
5210                return Err(err);
5211            }
5212        };
5213        *child = Some(next_child);
5214        debug!(module_id = %spec.module_id, "supervised module enabled");
5215        Ok(true)
5216    } else {
5217        let stop_notice = begin_forwarding_drain_if_configured(
5218            spec,
5219            runtime,
5220            registry,
5221            snapshot,
5222            Some(false),
5223            RouteCloseReason::Disable,
5224        )
5225        .await?;
5226        drain_optional_child(
5227            &spec.module_id,
5228            spec.protocol,
5229            stop_notice,
5230            registry,
5231            snapshot,
5232            &runtime.terminal_ring,
5233            &runtime.spawn_events,
5234            child,
5235            runtime.drain_timeout,
5236            ModuleState::Disabled,
5237            Some(false),
5238        )
5239        .await?;
5240        debug!(module_id = %spec.module_id, "supervised module disabled");
5241        Ok(true)
5242    }
5243}
5244
5245#[allow(clippy::too_many_arguments)]
5246async fn on_child_exit(
5247    spec: &ModuleSpec,
5248    policy: RestartPolicy,
5249    registry: &Registry,
5250    snapshot: &SharedSnapshot,
5251    terminal_ring: &Arc<Mutex<TerminalRing>>,
5252    spawn_events: &SpawnEventFeed,
5253    roster: &ChildRoster,
5254    exit_report: ExitReport,
5255) -> NextAction {
5256    // Once the daemon has begun shutting down, no exit is a crash to recover
5257    // from: the module is exiting because the daemon is going away (EOF on its
5258    // connection, or a service manager signalling the whole cgroup). Record it
5259    // as such and never schedule a respawn, which would only start a process
5260    // for the shutdown to end again.
5261    if roster.is_closed() {
5262        return on_child_exit_during_daemon_shutdown(
5263            spec,
5264            registry,
5265            snapshot,
5266            terminal_ring,
5267            spawn_events,
5268            exit_report,
5269        )
5270        .await;
5271    }
5272    match exit_report.kind {
5273        ExitKind::Clean => {
5274            info!(
5275                module_id = %spec.module_id,
5276                exit_code = ?exit_report.code,
5277                exit_signal = ?exit_report.signal,
5278                "supervised module exited cleanly"
5279            );
5280            if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
5281                state.state = ModuleState::Stopped;
5282                clear_current_process_facts(state);
5283                state.last_exit = Some(exit_report.clone());
5284            }) {
5285                error!(module_id = %spec.module_id, error = %err, "failed to record clean module exit");
5286            }
5287            record_terminal(
5288                &spec.module_id,
5289                terminal_ring,
5290                spawn_events,
5291                &exit_report,
5292                TerminalDisposition::Stopped,
5293            );
5294            let registration_released = match wait_for_registration_release(
5295                registry,
5296                &spec.module_id,
5297                REGISTRY_RELEASE_TIMEOUT,
5298            )
5299            .await
5300            {
5301                Ok(()) => true,
5302                Err(err) => {
5303                    warn!(module_id = %spec.module_id, error = %err, "registration still active after clean exit");
5304                    false
5305                }
5306            };
5307            NextAction::Stop {
5308                registration_released,
5309            }
5310        }
5311        ExitKind::Crash => {
5312            warn!(
5313                module_id = %spec.module_id,
5314                exit_code = ?exit_report.code,
5315                exit_signal = ?exit_report.signal,
5316                "supervised module exited abnormally (crash)"
5317            );
5318            let mut restart_schedule = None;
5319            let mut disposition = TerminalDisposition::Disabled;
5320            // Set only when the budget is what stopped the module, so the
5321            // terminal record says which limit was hit rather than leaving
5322            // `failed` to be read as "crashed once, badly".
5323            let mut disposition_detail = None;
5324            let now = Instant::now();
5325            if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
5326                clear_current_process_facts(state);
5327                state.last_exit = Some(exit_report.clone());
5328                if state.enabled {
5329                    if let Some(schedule) = state.next_crash_restart(&policy, now) {
5330                        state.state = ModuleState::Restarting;
5331                        restart_schedule = Some(schedule);
5332                        disposition = TerminalDisposition::Restarting;
5333                    } else {
5334                        state.state = ModuleState::Failed;
5335                        disposition = TerminalDisposition::Failed;
5336                        disposition_detail = Some(policy.budget_exhausted_detail());
5337                    }
5338                } else {
5339                    state.state = ModuleState::Disabled;
5340                    disposition = TerminalDisposition::Disabled;
5341                }
5342            }) {
5343                error!(module_id = %spec.module_id, error = %err, "failed to record crashed module exit");
5344                return NextAction::Stop {
5345                    registration_released: false,
5346                };
5347            }
5348            if disposition_detail.is_some() {
5349                // The window is in the message, not only in the fields: this line
5350                // is read in a scrollback where a bare `max_restarts=3` reads as a
5351                // lifetime cap and sends the operator looking for three crashes
5352                // that never happened together.
5353                error!(
5354                    module_id = %spec.module_id,
5355                    max_restarts = policy.max_restarts,
5356                    window_secs = policy.window.as_secs(),
5357                    "module stopped: {}",
5358                    policy.budget_exhausted_detail()
5359                );
5360            }
5361            record_terminal_with_detail(
5362                &spec.module_id,
5363                terminal_ring,
5364                spawn_events,
5365                &exit_report,
5366                disposition,
5367                disposition_detail,
5368            );
5369
5370            if let Some(schedule) = restart_schedule {
5371                NextAction::Restart {
5372                    schedule: Some(schedule),
5373                }
5374            } else {
5375                let registration_released = match wait_for_registration_release(
5376                    registry,
5377                    &spec.module_id,
5378                    REGISTRY_RELEASE_TIMEOUT,
5379                )
5380                .await
5381                {
5382                    Ok(()) => true,
5383                    Err(err) => {
5384                        warn!(module_id = %spec.module_id, error = %err, "registration still active after failed module");
5385                        false
5386                    }
5387                };
5388                NextAction::Stop {
5389                    registration_released,
5390                }
5391            }
5392        }
5393        ExitKind::DeliberateSeverance => {
5394            warn!(
5395                module_id = %spec.module_id,
5396                exit_code = ?exit_report.code,
5397                exit_signal = ?exit_report.signal,
5398                "supervised module exited after deliberate connection severance"
5399            );
5400            let mut should_restart = false;
5401            let mut disposition = TerminalDisposition::Disabled;
5402            if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
5403                clear_current_process_facts(state);
5404                state.last_exit = Some(exit_report.clone());
5405                state.lifetime_restarts += 1;
5406                if state.enabled {
5407                    state.state = ModuleState::Restarting;
5408                    should_restart = true;
5409                    disposition = TerminalDisposition::Restarting;
5410                } else {
5411                    state.state = ModuleState::Disabled;
5412                }
5413            }) {
5414                error!(module_id = %spec.module_id, error = %err, "failed to record deliberately severed module exit");
5415                return NextAction::Stop {
5416                    registration_released: false,
5417                };
5418            }
5419            record_terminal(
5420                &spec.module_id,
5421                terminal_ring,
5422                spawn_events,
5423                &exit_report,
5424                disposition,
5425            );
5426
5427            if should_restart {
5428                NextAction::Restart { schedule: None }
5429            } else {
5430                let registration_released = match wait_for_registration_release(
5431                    registry,
5432                    &spec.module_id,
5433                    REGISTRY_RELEASE_TIMEOUT,
5434                )
5435                .await
5436                {
5437                    Ok(()) => true,
5438                    Err(err) => {
5439                        warn!(module_id = %spec.module_id, error = %err, "registration still active after deliberately severed module exit");
5440                        false
5441                    }
5442                };
5443                NextAction::Stop {
5444                    registration_released,
5445                }
5446            }
5447        }
5448    }
5449}
5450
5451async fn on_child_exit_during_daemon_shutdown(
5452    spec: &ModuleSpec,
5453    registry: &Registry,
5454    snapshot: &SharedSnapshot,
5455    terminal_ring: &Arc<Mutex<TerminalRing>>,
5456    spawn_events: &SpawnEventFeed,
5457    exit_report: ExitReport,
5458) -> NextAction {
5459    info!(
5460        module_id = %spec.module_id,
5461        exit_code = ?exit_report.code,
5462        exit_signal = ?exit_report.signal,
5463        exit_kind = ?exit_report.kind,
5464        "supervised module exited during daemon shutdown; not restarting it"
5465    );
5466    if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
5467        state.state = ModuleState::Stopped;
5468        clear_current_process_facts(state);
5469        state.last_exit = Some(exit_report.clone());
5470    }) {
5471        error!(module_id = %spec.module_id, error = %err, "failed to record module exit during daemon shutdown");
5472    }
5473    record_terminal(
5474        &spec.module_id,
5475        terminal_ring,
5476        spawn_events,
5477        &exit_report,
5478        TerminalDisposition::DaemonShutdown,
5479    );
5480    let registration_released =
5481        wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT)
5482            .await
5483            .is_ok();
5484    NextAction::Stop {
5485        registration_released,
5486    }
5487}
5488
5489fn record_wait_error_terminal(
5490    module_id: &str,
5491    terminal_ring: &Arc<Mutex<TerminalRing>>,
5492    spawn_events: &SpawnEventFeed,
5493) {
5494    record_terminal(
5495        module_id,
5496        terminal_ring,
5497        spawn_events,
5498        &wait_error_exit_report(),
5499        TerminalDisposition::Failed,
5500    );
5501}
5502
5503fn record_terminal(
5504    module_id: &str,
5505    terminal_ring: &Arc<Mutex<TerminalRing>>,
5506    spawn_events: &SpawnEventFeed,
5507    exit_report: &ExitReport,
5508    disposition: TerminalDisposition,
5509) {
5510    record_terminal_with_detail(
5511        module_id,
5512        terminal_ring,
5513        spawn_events,
5514        exit_report,
5515        disposition,
5516        None,
5517    );
5518}
5519
5520/// The ring lock is held only to capture the read (see
5521/// `TerminalJournal::capture_read`), so this module's exits keep recording
5522/// while the journal files are read. Blocking: it reads files.
5523fn durable_terminal_history_of(
5524    terminal_ring: &Mutex<TerminalRing>,
5525    module_id: &str,
5526) -> subc_control::TerminalHistory {
5527    let read = terminal_ring
5528        .lock()
5529        .unwrap_or_else(|p| p.into_inner())
5530        .capture_durable_history();
5531    read.read(module_id)
5532}
5533
5534fn record_terminal_with_detail(
5535    module_id: &str,
5536    terminal_ring: &Arc<Mutex<TerminalRing>>,
5537    spawn_events: &SpawnEventFeed,
5538    exit_report: &ExitReport,
5539    disposition: TerminalDisposition,
5540    disposition_detail: Option<String>,
5541) {
5542    spawn_events.emit_exited(module_id, exit_report.code, exit_report.signal);
5543    let record = TerminalRecord {
5544        exit_code: exit_report.code,
5545        exit_signal: exit_report.signal,
5546        at_ms: exit_report.at_ms,
5547        disposition,
5548        exit_kind: exit_report.kind.into(),
5549        disposition_detail,
5550    };
5551    terminal_ring
5552        .lock()
5553        .unwrap_or_else(|poisoned| poisoned.into_inner())
5554        .record_exit(module_id, record);
5555}
5556
5557fn untrack_if_registration_released(
5558    process_liveness: &SupervisorProcessLiveness,
5559    registry: &Registry,
5560    module_id: &str,
5561    snapshot: &SharedSnapshot,
5562) {
5563    match registry.get_module(module_id) {
5564        Ok(None) => process_liveness.untrack_if_current(module_id, snapshot),
5565        Ok(Some(_)) => {}
5566        Err(err) => {
5567            warn!(module_id, error = %err, "could not determine whether supervisor liveness can be untracked");
5568        }
5569    }
5570}
5571
5572/// The child's environment plan: inherit the parent's, drop ambient `CK_LOG`,
5573/// then apply the module's configured entries minus daemon-private capture keys.
5574///
5575/// Separated from `spawn_child` only so it can be asserted without spawning a
5576/// process — a duplicate of this logic in a test would pass while the real one
5577/// drifted, which is the defect class this function exists to avoid.
5578/// The subc-wire half of a spawn: `--subc <connection file>` and the launch
5579/// nonce. A `protocol: "none"` module gets neither, because it cannot use
5580/// either and the argument would stop a stock binary from starting at all.
5581/// `SUBC_MODULE_ID` is set on every path since an unread variable is inert.
5582///
5583/// The plain-spawn form, kept for the tests that assert its plan; spawns go
5584/// through [`apply_wire_spawn_args_for_role`].
5585#[cfg(test)]
5586fn apply_wire_spawn_args(
5587    command: &mut Command,
5588    spec: &ModuleSpec,
5589    connection_file_path: Option<&std::path::Path>,
5590    handle: Option<&SupervisorHandle>,
5591) -> Result<(), SuperviseError> {
5592    apply_wire_spawn_args_for_role(
5593        command,
5594        spec,
5595        connection_file_path,
5596        handle,
5597        SpawnRole::Plain,
5598    )
5599}
5600
5601/// [`apply_wire_spawn_args`] for either slot.
5602///
5603/// A plain spawn's nonce replaces the module's recorded spawn (and reserved)
5604/// nonce, as every respawn always has. A swap candidate's nonce must leave
5605/// those alone, because the incumbent is still serving and its consumers still
5606/// attest with its nonce; it is recorded as the open swap's candidate token
5607/// instead, and the recording happens before the process exists so its HELLO
5608/// can never arrive ahead of it.
5609fn apply_wire_spawn_args_for_role(
5610    command: &mut Command,
5611    spec: &ModuleSpec,
5612    connection_file_path: Option<&std::path::Path>,
5613    handle: Option<&SupervisorHandle>,
5614    role: SpawnRole,
5615) -> Result<(), SuperviseError> {
5616    command.env(SUBC_MODULE_ID_ENV, &spec.module_id);
5617    if spec.protocol == ModuleProtocol::None {
5618        return Ok(());
5619    }
5620    if let Some(connection_file_path) = connection_file_path {
5621        command.arg(SUBC_ARG).arg(connection_file_path);
5622    }
5623
5624    // Every subc-wire spawn receives a fresh one-time launch nonce for consumer
5625    // route.open attestation. Reserved modules additionally use the same nonce
5626    // for HELLO id-squatting protection. A respawn rotates both records.
5627    let nonce = generate_launch_nonce()?;
5628    if let Some(handle) = handle {
5629        match role {
5630            SpawnRole::Plain => {
5631                handle.set_spawn_nonce(&spec.module_id, nonce.clone());
5632                if spec.reserved {
5633                    handle.set_reserved_nonce(&spec.module_id, nonce.clone());
5634                }
5635            }
5636            SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, nonce.clone()),
5637        }
5638    }
5639    command.env(SUBC_LAUNCH_NONCE_ENV, nonce);
5640    Ok(())
5641}
5642
5643fn apply_child_env(command: &mut Command, spec: &ModuleSpec) {
5644    command.env_remove(CK_LOG_ENV);
5645    // The spawn role is the supervisor's to set, and only on a swap candidate
5646    // (see `apply_spawn_role`). Removing it here, rather than just not setting
5647    // it, is what makes it absent on a plain spawn: the daemon's own
5648    // environment could carry it, and so could a spec built outside daemon
5649    // config (config refuses it as an `env` key). A module reading it on a
5650    // plain restart would pick the long swap budget and leave callers waiting.
5651    command.env_remove(SUBC_SPAWN_ROLE_ENV);
5652    for (key, value) in &spec.env {
5653        // cortexkit-log currently exposes retention only as a Rust struct, not
5654        // environment names. These values are daemon-private sink metadata and
5655        // must never become a public child-process contract by being inherited.
5656        if matches!(
5657            key.as_str(),
5658            CAPTURE_MAX_FILE_MB_ENV | CAPTURE_KEEP_ENV | CAPTURE_MAX_AGE_DAYS_ENV
5659        ) || key == SUBC_SPAWN_ROLE_ENV
5660        {
5661            continue;
5662        }
5663        command.env(key, value);
5664    }
5665}
5666
5667/// Which slot a spawn fills: the module's ordinary one, or the candidate slot
5668/// of a blue/green swap.
5669#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5670enum SpawnRole {
5671    Plain,
5672    SwapCandidate,
5673}
5674
5675/// Set the spawn role for a swap candidate. A plain spawn gets nothing here;
5676/// `apply_child_env` has already removed the variable for every spawn.
5677fn apply_spawn_role(command: &mut Command, role: SpawnRole) {
5678    if role == SpawnRole::SwapCandidate {
5679        command.env(SUBC_SPAWN_ROLE_ENV, SPAWN_ROLE_SWAP_CANDIDATE);
5680    }
5681}
5682
5683fn spawn_child(
5684    spec: &ModuleSpec,
5685    connection_file_path: Option<&std::path::Path>,
5686    handle: Option<&SupervisorHandle>,
5687    ring: &Arc<Mutex<StderrRing>>,
5688    capture_logs_dir: Option<&std::path::Path>,
5689    roster: &ChildRoster,
5690    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
5691) -> Result<SupervisedChild, SuperviseError> {
5692    spawn_child_in_slot(
5693        spec,
5694        connection_file_path,
5695        handle,
5696        ring,
5697        capture_logs_dir,
5698        roster,
5699        #[cfg(target_os = "linux")]
5700        cgroup_placement,
5701        SpawnRole::Plain,
5702        false,
5703    )
5704}
5705
5706/// Spawn one process of `spec` into a slot.
5707///
5708/// `alternate_slot` picks the process's cgroup name (see `swap::cgroup_name`).
5709/// A swap candidate needs a different cgroup from the process it is replacing,
5710/// which is still alive: in the same cgroup the two would be one kill domain,
5711/// and killing a failed candidate could take the incumbent with it.
5712///
5713/// The stderr capture file is `<module_id>.stderr.log` for every process of
5714/// the module, whichever slot it is in, because that is the one file
5715/// `ck module logs` reads. During a swap's overlap both processes append to it;
5716/// the daemon writes whole lines, so the two interleave by line, which is also
5717/// the merged view an operator wants while a swap runs.
5718#[allow(clippy::too_many_arguments)]
5719fn spawn_child_in_slot(
5720    spec: &ModuleSpec,
5721    connection_file_path: Option<&std::path::Path>,
5722    handle: Option<&SupervisorHandle>,
5723    ring: &Arc<Mutex<StderrRing>>,
5724    capture_logs_dir: Option<&std::path::Path>,
5725    roster: &ChildRoster,
5726    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
5727    role: SpawnRole,
5728    alternate_slot: bool,
5729) -> Result<SupervisedChild, SuperviseError> {
5730    if roster.is_closed() {
5731        return Err(SuperviseError::Spawn {
5732            program: spec.program.clone(),
5733            source: io::Error::other("the daemon is shutting down; not starting a new process"),
5734            cgroup_path: None,
5735        });
5736    }
5737    #[cfg(target_os = "linux")]
5738    let cgroup_name = swap::cgroup_name(&spec.module_id, alternate_slot);
5739    #[cfg(not(target_os = "linux"))]
5740    let _ = alternate_slot;
5741    let mut command = Command::new(&spec.program);
5742    command.args(&spec.args);
5743    // AMBIENT `CK_LOG` MUST NOT LEAK INTO AN OTHERWISE UNCONFIGURED MODULE — but
5744    // that is the whole of the intent, so remove that one key rather than the
5745    // environment.
5746    //
5747    // This was `env_clear()` from 0.17.41 until 0.18.3, which achieved the goal
5748    // and took the POSIX environment with it. Modules spawned that way had no
5749    // HOME, XDG_RUNTIME_DIR, TMPDIR or USER, and the consequences ran past
5750    // logging:
5751    //
5752    //   * `connection_file::discover` reads XDG_RUNTIME_DIR and HOME, so with
5753    //     both unset it fell back to the temp dir alone and `ck` could not find
5754    //     a daemon running on the same machine from inside any module's process
5755    //     tree — reporting a path the file has never lived at, which reads as
5756    //     "the daemon did not write its file".
5757    //   * `default_data_home()` with HOME and XDG_DATA_HOME both unset returns
5758    //     the RELATIVE `.local/share`, so a module deriving its own store path
5759    //     resolved it against its own CWD. That is the store-fragmentation
5760    //     defect the daemon already refuses in config (`parse_doc` rejects a
5761    //     relative `storage.data_home`) arriving by derivation instead.
5762    //   * anything a module spawns inherited it: git without ~/.gitconfig,
5763    //     cargo without CARGO_HOME, ssh, python user dirs — all degrading
5764    //     quietly rather than erroring.
5765    //
5766    // Reported by iceteaSA as #104 after deploying 0.18.2, where `ck daemon`
5767    // offered one candidate under /tmp while the file sat in /run/user/1000.
5768    //
5769    // A configured module is unaffected either way: `module_spec()` puts the
5770    // resolved CK_LOG into `spec.env`, which is applied below and therefore
5771    // wins over anything ambient.
5772    apply_child_env(&mut command, spec);
5773    apply_spawn_role(&mut command, role);
5774    apply_wire_spawn_args_for_role(&mut command, spec, connection_file_path, handle, role)?;
5775
5776    #[cfg(target_os = "linux")]
5777    let cgroup_path = cgroup_placement
5778        .map(|placement| placement.module_path(&cgroup_name))
5779        .transpose()
5780        .map_err(|source| SuperviseError::Cgroup {
5781            module_id: spec.module_id.clone(),
5782            source,
5783        })?;
5784    #[cfg(not(target_os = "linux"))]
5785    let cgroup_path: Option<PathBuf> = None;
5786    #[cfg(target_os = "linux")]
5787    if let Some(path) = &cgroup_path {
5788        if let Err(error) = apply_cgroup_placement(&mut command, spec, path) {
5789            if let Some(placement) = cgroup_placement {
5790                remove_module_cgroup(placement, &cgroup_name);
5791            }
5792            return Err(error);
5793        }
5794    }
5795
5796    let output_sink = if let Some(logs_dir) = capture_logs_dir {
5797        let path = logs_dir.join(format!("{}.stderr.log", spec.module_id));
5798        match ChildOutputSink::open(&path, capture_retention(spec)) {
5799            Ok(sink) => sink,
5800            Err(error) => {
5801                warn!(
5802                    module_id = %spec.module_id,
5803                    path = %path.display(),
5804                    error = %error,
5805                    "could not open child output capture file; forwarding to stderr"
5806                );
5807                ChildOutputSink::Stderr
5808            }
5809        }
5810    } else {
5811        ChildOutputSink::Stderr
5812    };
5813
5814    command.stdout(Stdio::piped());
5815    command.stderr(Stdio::piped());
5816    command.kill_on_drop(true);
5817    // EACH MODULE LEADS ITS OWN PROCESS GROUP (the child calls setpgid(0, 0)
5818    // before exec). In the daemon's group, a service manager that kills the
5819    // job's process group when the daemon exits (launchd's default) killed
5820    // every module at the same moment its control connection closed, so no
5821    // module ever ran its EOF teardown on a daemon stop. Outside that group a
5822    // module is reached only by the daemon: the EOF it sees when its
5823    // connection closes, and the bounded stop in `child_roster` for anything
5824    // still running after that. On Linux this composes with the cgroup
5825    // placement above: that is a pre_exec write to cgroup.procs, std performs
5826    // setpgid in the child before running pre_exec callbacks, and the two
5827    // change independent process attributes.
5828    //
5829    // stdin is /dev/null because a process outside the terminal's foreground
5830    // group is stopped (SIGTTIN) if it reads the terminal, which a daemon run
5831    // by hand would otherwise hand down. Under a service manager stdin is
5832    // already /dev/null.
5833    #[cfg(unix)]
5834    command.process_group(0);
5835    command.stdin(Stdio::null());
5836
5837    // Containment, step 1 of 3 (issue #109): create the child suspended so it
5838    // cannot run a single instruction -- and therefore cannot spawn a
5839    // grandchild -- before it is in the job. See `contain_spawned_child` for the
5840    // other two steps and why the window matters.
5841    #[cfg(windows)]
5842    subc_jobobject::suspend_on_create_async(&mut command);
5843    let mut child = match command.spawn() {
5844        Ok(child) => child,
5845        Err(source) => {
5846            #[cfg(target_os = "linux")]
5847            if let Some(placement) = cgroup_placement {
5848                remove_module_cgroup(placement, &cgroup_name);
5849            }
5850            return Err(SuperviseError::Spawn {
5851                program: spec.program.clone(),
5852                source,
5853                cgroup_path,
5854            });
5855        }
5856    };
5857
5858    // Containment, steps 2 and 3: assign while suspended, then resume.
5859    #[cfg(windows)]
5860    let job = contain_spawned_child(&child, spec)?;
5861    let spawned_at_ms = unix_ms_now();
5862    let spawned_from = spec.program.clone();
5863    let spawned_file_identity = spawned_file_identity(&spawned_from);
5864    let pid = child.id().ok_or_else(|| SuperviseError::Spawn {
5865        program: spec.program.clone(),
5866        source: io::Error::other("spawned child exposed no live pid"),
5867        cgroup_path: cgroup_path.clone(),
5868    })?;
5869    let process_start_time = crate::provenance::process_start_time(pid);
5870    let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
5871    // The executable identity is the spawned path's, read above, not the
5872    // running image's: right after spawn the child may not have finished its
5873    // exec yet and would still report this daemon's own image.
5874    #[cfg(target_os = "linux")]
5875    let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
5876    #[cfg(not(target_os = "linux"))]
5877    let recorded_cgroup_name = None;
5878    let roster_guard = roster.admit(
5879        spec.module_id.clone(),
5880        pid,
5881        spec.protocol,
5882        process_start_time,
5883        crate::child_roster::RecordedIdentity {
5884            start_time: subc_os::start_time(pid),
5885            executable: spawned_file_identity.map(|identity| {
5886                crate::live_children::ExecutableIdentity {
5887                    device: identity.device,
5888                    inode: identity.inode,
5889                }
5890            }),
5891            cgroup_name: recorded_cgroup_name,
5892        },
5893    );
5894    // The check at the top of this function can pass just before daemon
5895    // shutdown begins, and the process is only in the roster from here on.
5896    // The shutdown stop returns as soon as it finds the roster empty, so a
5897    // process admitted after that look would outlive the daemon. The roster
5898    // is closed before the stop first reads it and admission happens under
5899    // the roster's lock, so either the stop sees this process or this check
5900    // sees the roster closed: end the process now rather than start a module
5901    // the daemon is about to stop.
5902    if roster.is_closed() {
5903        if let Err(error) = child.start_kill() {
5904            debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
5905        }
5906        drop(roster_guard);
5907        return Err(SuperviseError::Spawn {
5908            program: spec.program.clone(),
5909            source: io::Error::other(
5910                "the daemon began shutting down while this process was starting; ended it",
5911            ),
5912            cgroup_path,
5913        });
5914    }
5915
5916    let stdout_pump = match child.stdout.take() {
5917        Some(stdout) => Some(tokio::spawn(pump_stdout_to(stdout, output_sink.clone()))),
5918        None => {
5919            warn!(
5920                module_id = %spec.module_id,
5921                "spawned child exposed no stdout pipe; file capture will be incomplete"
5922            );
5923            None
5924        }
5925    };
5926    let stderr_pump = match child.stderr.take() {
5927        Some(stderr) => {
5928            let generation = ring
5929                .lock()
5930                .unwrap_or_else(|poisoned| poisoned.into_inner())
5931                .begin_process();
5932            Some(StderrPump {
5933                task: tokio::spawn(pump_stderr_to(
5934                    stderr,
5935                    Arc::clone(ring),
5936                    generation,
5937                    output_sink,
5938                )),
5939                generation,
5940            })
5941        }
5942        None => {
5943            // Spawning succeeded but the pipe did not materialise. Recording it as
5944            // uncaptured keeps the tail honest: the alternative is an empty tail
5945            // that reads as a module which printed nothing.
5946            ring.lock()
5947                .unwrap_or_else(|poisoned| poisoned.into_inner())
5948                .mark_not_captured("stderr pipe was not available on spawn");
5949            warn!(
5950                module_id = %spec.module_id,
5951                "spawned child exposed no stderr pipe; tail will be unavailable"
5952            );
5953            None
5954        }
5955    };
5956
5957    Ok(SupervisedChild {
5958        child,
5959        #[cfg(target_os = "linux")]
5960        module_id: cgroup_name,
5961        #[cfg(target_os = "linux")]
5962        cgroup_placement: cgroup_placement.cloned(),
5963        #[cfg(windows)]
5964        job,
5965        stdout_pump,
5966        stderr_pump,
5967        stderr_ring: Arc::clone(ring),
5968        spawned_at_ms,
5969        spawned_from,
5970        spawned_file_identity,
5971        process_start_time,
5972        process_identity,
5973        pid,
5974        roster_guard: Some(roster_guard),
5975    })
5976}
5977
5978/// Contain a freshly spawned Windows child and start it.
5979///
5980/// Steps 2 and 3 of the suspended-create contract: the job is created and the
5981/// child assigned **while it is still suspended** (step 1 is
5982/// `suspend_on_create_async` at the spawn site), then the child is resumed.
5983///
5984/// A child that is never resumed hangs forever holding a pid, so a resume
5985/// failure kills the child and fails the spawn rather than returning a
5986/// `SupervisedChild` that can never run.
5987///
5988/// An assignment failure is NOT fatal: an uncontained module behaves exactly as
5989/// it did before this existed, whereas refusing to start one would be a new
5990/// outage. It is logged at warn because it means a helper process could leak.
5991#[cfg(windows)]
5992fn contain_spawned_child(
5993    child: &Child,
5994    spec: &ModuleSpec,
5995) -> Result<Option<subc_jobobject::JobObject>, SuperviseError> {
5996    let module_id = spec.module_id.as_str();
5997    let Some(pid) = child.id() else {
5998        // The child exited between spawn and here. Its tree, if it made one,
5999        // needs no containment: nothing is left to contain.
6000        warn!(
6001            module_id,
6002            "spawned child had already exited before containment; no job object attached"
6003        );
6004        return Ok(None);
6005    };
6006
6007    let job = match subc_jobobject::JobObject::new() {
6008        Ok(job) => job,
6009        Err(source) => {
6010            warn!(
6011                module_id,
6012                error = %source,
6013                "could not create a job object; this module's helper processes will not be \
6014                 reaped on teardown"
6015            );
6016            // Resume regardless: leaving the child suspended would turn a
6017            // containment gap into a hung module.
6018            resume_suspended_child(pid, spec)?;
6019            return Ok(None);
6020        }
6021    };
6022
6023    if let Err(source) = job.assign(child) {
6024        warn!(
6025            module_id,
6026            error = %source,
6027            "could not assign the child to its job object; this module's helper processes \
6028             will not be reaped on teardown"
6029        );
6030        resume_suspended_child(pid, spec)?;
6031        return Ok(None);
6032    }
6033
6034    resume_suspended_child(pid, spec)?;
6035    Ok(Some(job))
6036}
6037
6038/// Resume a suspended child, killing it if it cannot be started.
6039///
6040/// A suspended process holds a pid and does nothing, so there is no useful
6041/// state to return: the caller gets an error and the spawn fails.
6042#[cfg(windows)]
6043fn resume_suspended_child(pid: u32, spec: &ModuleSpec) -> Result<(), SuperviseError> {
6044    if let Err(source) = subc_jobobject::resume_main_thread(pid) {
6045        // Kill it here rather than leaving a suspended process for the caller
6046        // to notice; `kill_on_drop` would eventually do this, but the module
6047        // would have been reported as running in between.
6048        let _ = std::process::Command::new("taskkill.exe")
6049            .args(["/PID", &pid.to_string(), "/T", "/F"])
6050            .stdin(Stdio::null())
6051            .stdout(Stdio::null())
6052            .stderr(Stdio::null())
6053            .status();
6054        return Err(SuperviseError::Spawn {
6055            program: spec.program.clone(),
6056            source,
6057            cgroup_path: None,
6058        });
6059    }
6060    Ok(())
6061}
6062
6063#[cfg(target_os = "linux")]
6064fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
6065    match placement.remove_module(module_id) {
6066        Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
6067        Err(error) => warn!(
6068            module_id,
6069            error = %error,
6070            "could not remove module cgroup after process exit; continuing teardown"
6071        ),
6072    }
6073}
6074
6075#[cfg(target_os = "linux")]
6076fn apply_cgroup_placement(
6077    command: &mut Command,
6078    spec: &ModuleSpec,
6079    path: &std::path::Path,
6080) -> Result<(), SuperviseError> {
6081    subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
6082        module_id: spec.module_id.clone(),
6083        source,
6084    })
6085}
6086
6087fn capture_retention(spec: &ModuleSpec) -> Retention {
6088    let defaults = Retention::default();
6089    let value = |name: &str| {
6090        spec.env
6091            .iter()
6092            .rev()
6093            .find_map(|(key, value)| (key == name).then_some(value.as_str()))
6094    };
6095    Retention {
6096        max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
6097            .and_then(|value| value.parse().ok())
6098            .unwrap_or(defaults.max_file_mb),
6099        keep: value(CAPTURE_KEEP_ENV)
6100            .and_then(|value| value.parse().ok())
6101            .unwrap_or(defaults.keep),
6102        max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
6103            .and_then(|value| value.parse().ok())
6104            .unwrap_or(defaults.max_age_days),
6105    }
6106}
6107
6108/// A fresh 256-bit CSPRNG launch nonce, lowercase hex. Used to bind a reserved
6109/// module's registration to the exact process the supervisor spawned.
6110fn generate_launch_nonce() -> Result<String, SuperviseError> {
6111    let mut bytes = [0u8; 32];
6112    getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
6113        reason: source.to_string(),
6114    })?;
6115    let mut hex = String::with_capacity(64);
6116    for b in bytes {
6117        use std::fmt::Write;
6118        let _ = write!(hex, "{b:02x}");
6119    }
6120    Ok(hex)
6121}
6122
6123/// Constant-time byte comparison so a reserved-nonce mismatch leaks no timing
6124/// signal about how many leading bytes matched.
6125fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
6126    if a.len() != b.len() {
6127        return false;
6128    }
6129    let mut diff = 0u8;
6130    for (x, y) in a.iter().zip(b.iter()) {
6131        diff |= x ^ y;
6132    }
6133    diff == 0
6134}
6135
6136fn spawn_and_mark_running(
6137    spec: &ModuleSpec,
6138    runtime: &SupervisorRuntimeConfig,
6139    snapshot: &SharedSnapshot,
6140) -> Result<SupervisedChild, SuperviseError> {
6141    let child = spawn_child(
6142        spec,
6143        runtime.connection_file_path.as_deref(),
6144        runtime.supervisor_handle.as_ref(),
6145        &runtime.stderr_ring,
6146        runtime.capture_logs_dir.as_deref(),
6147        &runtime.child_roster,
6148        #[cfg(target_os = "linux")]
6149        runtime.cgroup_placement.as_ref(),
6150    )?;
6151    set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events)?;
6152    Ok(child)
6153}
6154
6155enum RegistrationWaitOutcome {
6156    Registered,
6157    Exited(ExitReport),
6158    TimedOut,
6159}
6160
6161struct ReloadRegistrationFailure {
6162    exit_report: ExitReport,
6163    reason: String,
6164}
6165
6166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6167enum BusyGaugeObservation {
6168    Quiescent,
6169    Busy,
6170    Omitted,
6171}
6172
6173fn busy_gauge_observation(metrics: Option<&Value>, gauges: &[String]) -> BusyGaugeObservation {
6174    let Some(metrics) = metrics.and_then(Value::as_object) else {
6175        return BusyGaugeObservation::Omitted;
6176    };
6177    let mut sum = 0u128;
6178    for gauge in gauges {
6179        let Some(value) = metrics.get(gauge) else {
6180            return BusyGaugeObservation::Omitted;
6181        };
6182        let Some(value) = value.as_u64() else {
6183            return BusyGaugeObservation::Busy;
6184        };
6185        sum = sum.saturating_add(u128::from(value));
6186    }
6187    if sum == 0 {
6188        BusyGaugeObservation::Quiescent
6189    } else {
6190        BusyGaugeObservation::Busy
6191    }
6192}
6193
6194fn declared_busy_gauges(
6195    registry: &Registry,
6196    module_id: &str,
6197) -> Result<Vec<String>, SuperviseError> {
6198    busy_gauges_of(
6199        registry
6200            .get_module(module_id)
6201            .map_err(SuperviseError::Registry)?,
6202    )
6203}
6204
6205/// [`declared_busy_gauges`] for the registration a connection holds, in any
6206/// slot: after cutover the incumbent is no longer the id's active
6207/// registration, and its own manifest is the one that names its gauges.
6208fn declared_busy_gauges_for_connection(
6209    registry: &Registry,
6210    connection_id: ConnectionId,
6211) -> Result<Vec<String>, SuperviseError> {
6212    busy_gauges_of(
6213        registry
6214            .get_module_by_connection(connection_id)
6215            .map_err(SuperviseError::Registry)?,
6216    )
6217}
6218
6219fn busy_gauges_of(
6220    registration: Option<crate::registry::ModuleRegistration>,
6221) -> Result<Vec<String>, SuperviseError> {
6222    let Some(registration) = registration else {
6223        return Ok(Vec::new());
6224    };
6225    let Some(self_signals) = registration.manifest.self_signals else {
6226        return Ok(Vec::new());
6227    };
6228
6229    let mut gauges = Vec::new();
6230    for declaration in self_signals {
6231        if declaration.kind != SelfSignalKind::Busy {
6232            continue;
6233        }
6234        match declaration.anchored_to {
6235            SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
6236                gauges.extend(declared)
6237            }
6238            _ => {
6239                // An invalid Busy anchor is fail-safe: the empty name cannot be
6240                // present in a conforming health report, so this drain stays busy.
6241                gauges.push(String::new());
6242            }
6243        }
6244    }
6245    Ok(gauges)
6246}
6247
6248/// Wait for `endpoint` to have nothing in flight and, when the module declares
6249/// busy gauges, for a health probe to report them quiet. The probe is addressed
6250/// by `scope`: a swap's superseded incumbent must be asked about its own
6251/// gauges, and by module id the probe would reach the promoted candidate.
6252async fn wait_for_forwarding_quiescence(
6253    forwarding: &ForwardingTable,
6254    module_id: &str,
6255    runtime: &SupervisorRuntimeConfig,
6256    endpoint: crate::ModuleEndpointId,
6257    deadline: Instant,
6258    busy_gauges: &[String],
6259    scope: DrainScope,
6260) -> Result<bool, SuperviseError> {
6261    let mut gauges_quiescent = busy_gauges.is_empty();
6262    let mut next_probe_at = Instant::now();
6263    let mut omission_counted = false;
6264
6265    loop {
6266        let now = Instant::now();
6267        if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
6268            let report = match scope {
6269                DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
6270                DrainScope::Endpoint(endpoint) => {
6271                    probe_endpoint_health(endpoint, runtime, Some(deadline)).await
6272                }
6273            };
6274            gauges_quiescent = match report {
6275                Ok(report) => match busy_gauge_observation(report.metrics.as_ref(), busy_gauges) {
6276                    BusyGaugeObservation::Quiescent => true,
6277                    BusyGaugeObservation::Busy => false,
6278                    BusyGaugeObservation::Omitted => {
6279                        if !omission_counted {
6280                            forwarding
6281                                .counters()
6282                                .increment_drains_with_undeclared_gauge();
6283                            omission_counted = true;
6284                        }
6285                        false
6286                    }
6287                },
6288                Err(err) => {
6289                    warn!(
6290                        module_id,
6291                        error = %err,
6292                        "drain health.check did not produce declared busy gauges; treating module as busy"
6293                    );
6294                    false
6295                }
6296            };
6297            next_probe_at = Instant::now() + runtime.health.cadence.max(REGISTRY_RELEASE_POLL);
6298        }
6299
6300        let in_flight = forwarding
6301            .endpoint_in_flight_count(endpoint)
6302            .map_err(SuperviseError::Forwarding)?;
6303        if in_flight == 0 && gauges_quiescent {
6304            return Ok(true);
6305        }
6306
6307        let now = Instant::now();
6308        if now >= deadline {
6309            return Ok(false);
6310        }
6311        let mut wait = deadline
6312            .saturating_duration_since(now)
6313            .min(REGISTRY_RELEASE_POLL);
6314        if !busy_gauges.is_empty() {
6315            wait = wait.min(next_probe_at.saturating_duration_since(now));
6316        }
6317        sleep(wait).await;
6318    }
6319}
6320
6321/// The `route.closed` `drained` value implied by a quiescence-wait outcome.
6322///
6323/// `Ok` is always honest and passed straight through -- the wait actually measured
6324/// in-flight state. `Err` means the wait produced no measurement at all (the
6325/// forwarding table's lock was poisoned), so `false` is reported as the one honest
6326/// constant: the drain did not complete. Never recomputed from route state, never a
6327/// third "unknown" value -- the caller must still send a well-formed `route.closed`.
6328fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
6329    match wait_result {
6330        Ok(drained) => *drained,
6331        Err(_) => false,
6332    }
6333}
6334
6335fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
6336    for released in released_routes {
6337        let frame = match Frame::build_with_version(
6338            released.negotiated_ver,
6339            FrameType::Goodbye,
6340            control_flags(),
6341            released.channel,
6342            released.epoch,
6343            0,
6344            Vec::new(),
6345        ) {
6346            Ok(frame) => frame,
6347            Err(err) => {
6348                warn!(
6349                    route_channel = released.channel,
6350                    error = %err,
6351                    "failed to build supervisor drain route GOODBYE frame"
6352                );
6353                continue;
6354            }
6355        };
6356        if !released.close_on_delivery_failure() {
6357            crate::forwarding::send_module_route_goodbye(
6358                &forwarding.counters(),
6359                &released.sink,
6360                frame,
6361                released.module_id.as_deref(),
6362                "supervisor drain",
6363            );
6364            continue;
6365        }
6366        if let Err(err) = released.sink.try_send(frame) {
6367            warn!(
6368                target_connection_id = released.connection_id.get(),
6369                route_channel = released.channel,
6370                error = %err,
6371                "supervisor drain route GOODBYE was not delivered to client; closing target connection"
6372            );
6373            let _ = forwarding.escalate_client_delivery_failure(
6374                released.connection_id,
6375                released.channel,
6376                released.epoch,
6377                CloseReason::new(
6378                    "route_goodbye_delivery_failed",
6379                    format!(
6380                        "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
6381                        released.channel
6382                    ),
6383                ),
6384                crate::forwarding::UndeliveredFrame {
6385                    module_id: released.module_id.as_deref(),
6386                    sink: &released.sink,
6387                },
6388            );
6389        }
6390    }
6391}
6392
6393fn send_module_draining(
6394    module_id: &str,
6395    reason: RouteCloseReason,
6396    deadline_ms: u64,
6397    target: &ModuleDrainTarget,
6398) {
6399    let body = match serde_json::to_vec(&ModuleControlCommand::Draining {
6400        reason,
6401        deadline_ms,
6402    }) {
6403        Ok(body) => body,
6404        Err(err) => {
6405            warn!(
6406                module_id,
6407                error = %err,
6408                "failed to encode module draining command"
6409            );
6410            return;
6411        }
6412    };
6413    let frame = match Frame::build_with_version(
6414        target.negotiated_ver,
6415        FrameType::Push,
6416        control_flags(),
6417        0,
6418        0,
6419        0,
6420        body,
6421    ) {
6422        Ok(frame) => frame,
6423        Err(err) => {
6424            warn!(
6425                module_id,
6426                error = %err,
6427                "failed to build module draining command frame"
6428            );
6429            return;
6430        }
6431    };
6432    if let Err(err) = target.sink.try_send(frame) {
6433        warn!(
6434            module_id,
6435            target_connection_id = target.endpoint.connection_id.get(),
6436            error = %err,
6437            "module draining command was not delivered to peer"
6438        );
6439    }
6440}
6441
6442fn send_module_goodbye(module_id: &str, forwarding: &ForwardingTable, target: &ModuleDrainTarget) {
6443    let frame = match Frame::build_with_version(
6444        target.negotiated_ver,
6445        FrameType::Goodbye,
6446        control_flags(),
6447        0,
6448        0,
6449        0,
6450        Vec::new(),
6451    ) {
6452        Ok(frame) => frame,
6453        Err(err) => {
6454            warn!(
6455                module_id,
6456                error = %err,
6457                "failed to build supervisor drain module GOODBYE frame"
6458            );
6459            return;
6460        }
6461    };
6462    if let Err(err) = target.sink.try_send(frame) {
6463        warn!(
6464            module_id,
6465            target_connection_id = target.endpoint.connection_id.get(),
6466            error = %err,
6467            "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
6468        );
6469        forwarding.request_connection_close(
6470            target.endpoint.connection_id,
6471            CloseReason::new(
6472                "module_goodbye_delivery_failed",
6473                format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
6474            ),
6475        );
6476    }
6477}
6478
6479#[derive(Clone, Copy)]
6480struct ForwardingDrainContext<'a> {
6481    spec: &'a ModuleSpec,
6482    runtime: &'a SupervisorRuntimeConfig,
6483    registry: &'a Registry,
6484    scope: DrainScope,
6485}
6486
6487/// Which process a forwarding drain addresses.
6488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6489enum DrainScope {
6490    /// Whatever endpoint is active for the module id: every plain stop,
6491    /// restart and reload. Also moves the module's state to `Draining`.
6492    Active,
6493    /// One specific endpoint: a swap's incumbent after cutover. Draining it by
6494    /// module id would resolve to the promoted candidate and leave neither
6495    /// process routable. The module's state is left alone, since the promoted
6496    /// candidate is what it describes and that process is running.
6497    Endpoint(crate::ModuleEndpointId),
6498}
6499
6500/// Whether a child being drained has already been asked to stop by the time
6501/// its drain wait starts.
6502///
6503/// The drain wait is the same budget whatever this says. What it decides is
6504/// whether the supervisor must ask by signal before that wait begins: a child
6505/// that nobody asked will sit out the whole budget and then be SIGKILLed,
6506/// healthy or not.
6507#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6508enum StopNotice {
6509    /// The module was sent `module.draining` and a module GOODBYE over its own
6510    /// registered connection, and stops itself.
6511    SentOverConnection,
6512    /// The forwarding drain found no registered connection for the module: a
6513    /// subc child spawned moments ago that has not sent HELLO yet, or a
6514    /// `protocol: "none"` child, which never registers.
6515    NoConnection,
6516    /// This path sends nothing over the module's connection: the supervisor has
6517    /// no forwarding table, or the caller stops the child without a forwarding
6518    /// drain.
6519    NotSent,
6520}
6521
6522async fn begin_forwarding_drain(
6523    spec: &ModuleSpec,
6524    runtime: &SupervisorRuntimeConfig,
6525    registry: &Registry,
6526    snapshot: &SharedSnapshot,
6527    enabled: Option<bool>,
6528    reason: RouteCloseReason,
6529) -> Result<StopNotice, SuperviseError> {
6530    let Some(forwarding) = runtime.forwarding.as_ref() else {
6531        return Err(SuperviseError::ReloadUnavailable {
6532            module_id: spec.module_id.clone(),
6533            reason: "supervisor was not configured with a forwarding table".to_string(),
6534        });
6535    };
6536
6537    begin_forwarding_drain_with(
6538        forwarding,
6539        ForwardingDrainContext {
6540            spec,
6541            runtime,
6542            registry,
6543            scope: DrainScope::Active,
6544        },
6545        snapshot,
6546        enabled,
6547        reason,
6548        runtime.drain_timeout,
6549    )
6550    .await
6551}
6552
6553async fn begin_forwarding_drain_if_configured(
6554    spec: &ModuleSpec,
6555    runtime: &SupervisorRuntimeConfig,
6556    registry: &Registry,
6557    snapshot: &SharedSnapshot,
6558    enabled: Option<bool>,
6559    reason: RouteCloseReason,
6560) -> Result<StopNotice, SuperviseError> {
6561    begin_forwarding_drain_with_timeout(
6562        spec,
6563        runtime,
6564        registry,
6565        snapshot,
6566        enabled,
6567        reason,
6568        runtime.drain_timeout,
6569    )
6570    .await
6571}
6572
6573/// Like [`begin_forwarding_drain_if_configured`] but with an explicit drain
6574/// budget, for paths where the operator overrides the module's configured one
6575/// (`supervisor.restart{drain_timeout_ms}`).
6576async fn begin_forwarding_drain_with_timeout(
6577    spec: &ModuleSpec,
6578    runtime: &SupervisorRuntimeConfig,
6579    registry: &Registry,
6580    snapshot: &SharedSnapshot,
6581    enabled: Option<bool>,
6582    reason: RouteCloseReason,
6583    drain_timeout: Duration,
6584) -> Result<StopNotice, SuperviseError> {
6585    let Some(forwarding) = runtime.forwarding.as_ref() else {
6586        return Ok(StopNotice::NotSent);
6587    };
6588
6589    begin_forwarding_drain_with(
6590        forwarding,
6591        ForwardingDrainContext {
6592            spec,
6593            runtime,
6594            registry,
6595            scope: DrainScope::Active,
6596        },
6597        snapshot,
6598        enabled,
6599        reason,
6600        drain_timeout,
6601    )
6602    .await
6603}
6604
6605async fn begin_forwarding_drain_with(
6606    forwarding: &ForwardingTable,
6607    context: ForwardingDrainContext<'_>,
6608    snapshot: &SharedSnapshot,
6609    enabled: Option<bool>,
6610    reason: RouteCloseReason,
6611    drain_timeout: Duration,
6612) -> Result<StopNotice, SuperviseError> {
6613    let ForwardingDrainContext {
6614        spec,
6615        runtime,
6616        registry,
6617        scope,
6618    } = context;
6619    debug_assert_ne!(reason, RouteCloseReason::Crash);
6620    let terminal = matches!(reason, RouteCloseReason::Disable);
6621    let drain_started_at = Instant::now();
6622    let drain_deadline = drain_started_at + drain_timeout;
6623    let deadline_ms =
6624        unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
6625    let busy_gauges = match scope {
6626        DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
6627        DrainScope::Endpoint(endpoint) => {
6628            declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
6629        }
6630    };
6631
6632    // Admission gate first: route.open/commit and route REQUEST admission are closed
6633    // before the first quiescence check, so the outstanding count can only fall.
6634    let gate_started = Instant::now();
6635    let drain_target = match scope {
6636        DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
6637        DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
6638    }
6639    .map_err(SuperviseError::Forwarding)?;
6640    // The instant admission closed, and how long taking the forwarding write
6641    // lock to close it took. The timeout line reports only the quiescence
6642    // wait, so without this a drain that started late looked like one that
6643    // started on time.
6644    info!(
6645        module_id = %spec.module_id,
6646        ?reason,
6647        gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
6648        connected = drain_target.is_some(),
6649        "module drain began; route admission closed"
6650    );
6651    if scope == DrainScope::Active {
6652        update_snapshot(snapshot, Some(&spec.module_id), |state| {
6653            state.state = ModuleState::Draining;
6654            state.draining_to_replace =
6655                matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
6656            if let Some(enabled) = enabled {
6657                state.enabled = enabled;
6658            }
6659        })?;
6660    }
6661
6662    let Some(target) = drain_target.as_ref() else {
6663        // Nothing was sent: the module has no registered connection to carry
6664        // `module.draining` or a GOODBYE. The caller must not assume the child
6665        // was asked to stop.
6666        return Ok(StopNotice::NoConnection);
6667    };
6668    {
6669        send_module_draining(&spec.module_id, reason, deadline_ms, target);
6670        let routes = forwarding
6671            .endpoint_routes(target.endpoint)
6672            .map_err(SuperviseError::Forwarding)?;
6673        let routes_notified = routes.len();
6674        crate::control::send_route_control_pushes(
6675            forwarding,
6676            routes.clone(),
6677            ClientControlPush::RouteClosing {
6678                module_id: spec.module_id.clone(),
6679                reason,
6680            },
6681        );
6682        send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
6683
6684        // `route.closing` was just sent above: from here on every return path,
6685        // including an early one, MUST send `route.closed` before propagating
6686        // anything else. A client holds `closing` as a promise that a verdict is
6687        // coming; leaving early without `closed` strands it waiting forever, since
6688        // `closing` carries no timeout of its own.
6689        let wait_result = wait_for_forwarding_quiescence(
6690            forwarding,
6691            &spec.module_id,
6692            runtime,
6693            target.endpoint,
6694            drain_deadline,
6695            &busy_gauges,
6696            scope,
6697        )
6698        .await;
6699        let drained = drained_after_quiescence_wait(&wait_result);
6700        if let Err(err) = &wait_result {
6701            error!(
6702                module_id = %spec.module_id,
6703                ?reason,
6704                error = %err,
6705                "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
6706            );
6707        } else if !drained {
6708            // Name what the drain waited on. Without it the line says only that
6709            // something did not settle, and "one wedged call" and "every
6710            // session's held stream" read the same; the first is a module bug,
6711            // the second is a module that should end its streams on
6712            // module.draining. Read before teardown releases the routes.
6713            let holdouts = forwarding
6714                .endpoint_drain_holdouts(target.endpoint)
6715                .unwrap_or_default();
6716            warn!(
6717                module_id = %spec.module_id,
6718                waited = ?drain_timeout,
6719                ?reason,
6720                held_requests = holdouts.requests,
6721                held_routes = holdouts.routes,
6722                total_routes = holdouts.total_routes,
6723                top_connections = ?holdouts.top_connections,
6724                // `module_channel:corr`, so the module can find each held request
6725                // in its own log; capped, so `held_requests` is the full count.
6726                held = %holdouts
6727                    .held
6728                    .iter()
6729                    .map(|(channel, corr)| format!("{channel}:{corr}"))
6730                    .collect::<Vec<_>>()
6731                    .join(","),
6732                "route drain timed out before request quiescence; forcing teardown"
6733            );
6734        }
6735        crate::control::send_route_control_pushes(
6736            forwarding,
6737            routes,
6738            ClientControlPush::RouteClosed {
6739                module_id: spec.module_id.clone(),
6740                reason,
6741                drained,
6742                abandoned: target.abandoned_bindings.len() as u32,
6743                excluded_subscriptions: target.excluded_subscriptions,
6744                terminal: Some(terminal),
6745            },
6746        );
6747        wait_result?;
6748
6749        // `route.closed` has now been sent unconditionally above. From here the
6750        // remaining steps are cleanup (route + module GOODBYE) rather than a
6751        // promise the client is waiting on, but a lock-poisoned
6752        // `release_module_endpoint_routes` would otherwise skip the module
6753        // GOODBYE silently too -- send it before propagating the error.
6754        let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
6755            Ok(routes) => routes,
6756            Err(err) => {
6757                warn!(
6758                    module_id = %spec.module_id,
6759                    ?reason,
6760                    error = %err,
6761                    "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
6762                );
6763                send_module_goodbye(&spec.module_id, forwarding, target);
6764                return Err(SuperviseError::Forwarding(err));
6765            }
6766        };
6767        let route_goodbye_count = released_routes.len();
6768        send_route_goodbyes(forwarding, released_routes);
6769        send_module_goodbye(&spec.module_id, forwarding, target);
6770
6771        // The drain's happy path was previously silent: every emission above is
6772        // best-effort with only its failure arm logged, so "were consumers told"
6773        // was unprovable from the daemon log (surfaced by a 30-minute consumer
6774        // hang where the open question was exactly whether teardown notice went
6775        // out). One summary line makes that class decidable in one grep.
6776        info!(
6777            module_id = %spec.module_id,
6778            ?reason,
6779            routes_notified,
6780            route_goodbyes = route_goodbye_count,
6781            abandoned_reservations = target.abandoned_bindings.len(),
6782            excluded_subscriptions = target.excluded_subscriptions,
6783            drained,
6784            "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
6785        );
6786    }
6787
6788    Ok(StopNotice::SentOverConnection)
6789}
6790
6791/// Wait for the freshly spawned child to take the ACTIVE slot for `module_id`,
6792/// the only slot a plain (non-swap) spawn can register into.
6793async fn wait_for_registration_after_reload(
6794    registry: &Registry,
6795    module_id: &str,
6796    snapshot: &SharedSnapshot,
6797    child: &mut SupervisedChild,
6798    wait: Duration,
6799) -> Result<RegistrationWaitOutcome, SuperviseError> {
6800    wait_for_slot_registration(
6801        registry,
6802        crate::registry::RegistrationSlot::Active(module_id),
6803        module_id,
6804        snapshot,
6805        child,
6806        wait,
6807    )
6808    .await
6809}
6810
6811/// Wait for `child` to register into `slot`, or to exit, or for `wait` to pass.
6812///
6813/// Keyed on the slot rather than the bare module id because during a swap the
6814/// id's active slot is already held by the incumbent: an id-keyed wait would
6815/// report the incumbent's registration as the candidate's and a candidate that
6816/// never registers would look registered. A swap candidate waits on
6817/// `crate::registry::RegistrationSlot::Candidate`.
6818async fn wait_for_slot_registration(
6819    registry: &Registry,
6820    slot: crate::registry::RegistrationSlot<'_>,
6821    module_id: &str,
6822    snapshot: &SharedSnapshot,
6823    child: &mut SupervisedChild,
6824    wait: Duration,
6825) -> Result<RegistrationWaitOutcome, SuperviseError> {
6826    let deadline = Instant::now() + wait;
6827    loop {
6828        if registry
6829            .registration(slot)
6830            .map_err(SuperviseError::Registry)?
6831            .is_some()
6832        {
6833            return Ok(RegistrationWaitOutcome::Registered);
6834        }
6835
6836        let now = Instant::now();
6837        if now >= deadline {
6838            return Ok(RegistrationWaitOutcome::TimedOut);
6839        }
6840        let remaining = deadline.saturating_duration_since(now);
6841        let poll = remaining.min(REGISTRY_RELEASE_POLL);
6842
6843        tokio::select! {
6844            wait_result = child.wait() => {
6845                let status = wait_result.map_err(|source| SuperviseError::Wait {
6846                    module_id: module_id.to_string(),
6847                    source,
6848                })?;
6849                return Ok(RegistrationWaitOutcome::Exited(classify_reaped_child_exit(
6850                    snapshot,
6851                    child,
6852                    &status,
6853                )));
6854            }
6855            _ = sleep(poll) => {}
6856        }
6857    }
6858}
6859
6860fn registration_failure_exit_report(mut exit_report: ExitReport) -> ExitReport {
6861    // A replacement process that exits before HELLO did not provide service, even
6862    // if it used status 0. Count it against the restart cap as a new-binary failure.
6863    if exit_report.kind != ExitKind::DeliberateSeverance {
6864        exit_report.kind = ExitKind::Crash;
6865    }
6866    exit_report
6867}
6868
6869async fn handle_reload_child_registration_failure(
6870    spec: &ModuleSpec,
6871    runtime: &SupervisorRuntimeConfig,
6872    registry: &Registry,
6873    process_liveness: &SupervisorProcessLiveness,
6874    snapshot: &SharedSnapshot,
6875    child: &mut Option<SupervisedChild>,
6876    failure: ReloadRegistrationFailure,
6877) -> Result<(), SuperviseError> {
6878    let ReloadRegistrationFailure {
6879        exit_report,
6880        reason,
6881    } = failure;
6882    match on_child_exit(
6883        spec,
6884        runtime.restart_policy,
6885        registry,
6886        snapshot,
6887        &runtime.terminal_ring,
6888        &runtime.spawn_events,
6889        &runtime.child_roster,
6890        exit_report,
6891    )
6892    .await
6893    {
6894        NextAction::Stop {
6895            registration_released,
6896        } => {
6897            if registration_released {
6898                process_liveness.untrack_if_current(&spec.module_id, snapshot);
6899            }
6900        }
6901        NextAction::Restart { schedule } => {
6902            let delay = schedule.map_or(runtime.restart_policy.delay_for_restart(0), |schedule| {
6903                schedule.delay
6904            });
6905            if let Some(schedule) = schedule {
6906                log_crash_respawn(&spec.module_id, schedule);
6907            }
6908            sleep(delay).await;
6909            // A disable or drain that landed during the backoff cancels this
6910            // policy retry: the operator's stop must win over the respawn the
6911            // sleep counted down to.
6912            if respawn_still_pending(snapshot) {
6913                if let Err(err) = wait_for_registration_release(
6914                    registry,
6915                    &spec.module_id,
6916                    REGISTRY_RELEASE_TIMEOUT,
6917                )
6918                .await
6919                {
6920                    fail_snapshot(snapshot, Some(&spec.module_id), None);
6921                    process_liveness.untrack_if_current(&spec.module_id, snapshot);
6922                    return Err(SuperviseError::ReloadFailed {
6923                        module_id: spec.module_id.clone(),
6924                        reason: format!(
6925                            "{reason}; registration did not release before policy retry: {err}"
6926                        ),
6927                    });
6928                }
6929                process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
6930                match spawn_and_mark_running(spec, runtime, snapshot) {
6931                    Ok(next_child) => {
6932                        *child = Some(next_child);
6933                    }
6934                    Err(err) => {
6935                        fail_snapshot(snapshot, Some(&spec.module_id), None);
6936                        process_liveness.untrack_if_current(&spec.module_id, snapshot);
6937                        return Err(SuperviseError::ReloadFailed {
6938                            module_id: spec.module_id.clone(),
6939                            reason: format!("{reason}; policy retry spawn failed: {err}"),
6940                        });
6941                    }
6942                }
6943            }
6944        }
6945    }
6946
6947    Err(SuperviseError::ReloadFailed {
6948        module_id: spec.module_id.clone(),
6949        reason,
6950    })
6951}
6952
6953async fn handle_reload_spawn_failure(
6954    spec: &ModuleSpec,
6955    runtime: &SupervisorRuntimeConfig,
6956    process_liveness: &SupervisorProcessLiveness,
6957    snapshot: &SharedSnapshot,
6958    child: &mut Option<SupervisedChild>,
6959    reason: String,
6960) -> Result<(), SuperviseError> {
6961    let mut should_retry = false;
6962    let now = Instant::now();
6963    update_snapshot(snapshot, Some(&spec.module_id), |state| {
6964        clear_current_process_facts(state);
6965        if daemon_will_restart(state, &runtime.restart_policy, now) {
6966            state.record_crash_restart(&runtime.restart_policy, now);
6967            state.state = ModuleState::Restarting;
6968            should_retry = true;
6969        } else if state.enabled {
6970            state.state = ModuleState::Failed;
6971        } else {
6972            state.state = ModuleState::Disabled;
6973        }
6974    })?;
6975
6976    if should_retry {
6977        sleep(runtime.restart_policy.backoff).await;
6978        // A disable or drain that landed during the backoff cancels this
6979        // policy retry: the operator's stop must win over the respawn the
6980        // sleep counted down to.
6981        if respawn_still_pending(snapshot) {
6982            process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
6983            match spawn_and_mark_running(spec, runtime, snapshot) {
6984                Ok(next_child) => {
6985                    *child = Some(next_child);
6986                }
6987                Err(err) => {
6988                    fail_snapshot(snapshot, Some(&spec.module_id), None);
6989                    process_liveness.untrack_if_current(&spec.module_id, snapshot);
6990                    return Err(SuperviseError::ReloadFailed {
6991                        module_id: spec.module_id.clone(),
6992                        reason: format!("{reason}; policy retry spawn failed: {err}"),
6993                    });
6994                }
6995            }
6996        }
6997    } else {
6998        process_liveness.untrack_if_current(&spec.module_id, snapshot);
6999    }
7000
7001    Err(SuperviseError::ReloadFailed {
7002        module_id: spec.module_id.clone(),
7003        reason,
7004    })
7005}
7006
7007fn control_flags() -> Flags {
7008    Flags::new(false, Priority::Passive, false)
7009}
7010
7011#[allow(clippy::too_many_arguments)]
7012async fn drain_optional_child(
7013    module_id: &str,
7014    protocol: ModuleProtocol,
7015    stop_notice: StopNotice,
7016    registry: &Registry,
7017    snapshot: &SharedSnapshot,
7018    terminal_ring: &Arc<Mutex<TerminalRing>>,
7019    spawn_events: &SpawnEventFeed,
7020    child: &mut Option<SupervisedChild>,
7021    drain_timeout: Duration,
7022    final_state: ModuleState,
7023    enabled: Option<bool>,
7024) -> Result<(), SuperviseError> {
7025    if let Some(child) = child.take() {
7026        drain_child_to_state(
7027            module_id,
7028            protocol,
7029            stop_notice,
7030            registry,
7031            snapshot,
7032            terminal_ring,
7033            spawn_events,
7034            child,
7035            drain_timeout,
7036            final_state,
7037            enabled,
7038        )
7039        .await
7040    } else {
7041        update_snapshot(snapshot, Some(module_id), |state| {
7042            state.state = final_state;
7043            if let Some(enabled) = enabled {
7044                state.enabled = enabled;
7045            }
7046            clear_current_process_facts(state);
7047        })?;
7048        wait_for_registration_release(registry, module_id, REGISTRY_RELEASE_TIMEOUT).await
7049    }
7050}
7051
7052#[allow(clippy::too_many_arguments)]
7053async fn drain_child_to_state(
7054    module_id: &str,
7055    protocol: ModuleProtocol,
7056    stop_notice: StopNotice,
7057    registry: &Registry,
7058    snapshot: &SharedSnapshot,
7059    terminal_ring: &Arc<Mutex<TerminalRing>>,
7060    spawn_events: &SpawnEventFeed,
7061    mut child: SupervisedChild,
7062    drain_timeout: Duration,
7063    final_state: ModuleState,
7064    enabled: Option<bool>,
7065) -> Result<(), SuperviseError> {
7066    update_snapshot(snapshot, Some(module_id), |state| {
7067        state.state = ModuleState::Draining;
7068        state.draining_to_replace = final_state == ModuleState::Restarting;
7069        if let Some(enabled) = enabled {
7070            state.enabled = enabled;
7071        }
7072    })?;
7073
7074    // The wait below is the same budget in every case; what differs is
7075    // whether anything has ASKED the child to stop before it starts. Only a
7076    // forwarding drain that reached the module's registered connection has
7077    // (`module.draining`, then a module GOODBYE). Every other child was told
7078    // nothing: a `protocol: "none"` module, which never registers; a subc
7079    // module spawned moments ago that has not sent HELLO yet; or a stop that
7080    // runs no forwarding drain. Without a signal the budget is only a delay
7081    // in front of SIGKILL -- and the not-yet-registered child is the worst
7082    // case, because it registers into a module that is already draining,
7083    // is never told, and is killed while healthy.
7084    if stop_notice != StopNotice::SentOverConnection {
7085        if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
7086            info!(
7087                module_id,
7088                pid = child.pid,
7089                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
7090                "module has no connection yet; requesting stop by signal"
7091            );
7092        }
7093        request_graceful_stop(module_id, &child);
7094    }
7095
7096    let exit_report = match timeout(drain_timeout, child.wait()).await {
7097        Ok(Ok(status)) => classify_reaped_child_exit(snapshot, &child, &status),
7098        Ok(Err(source)) => {
7099            fail_snapshot(snapshot, Some(module_id), None);
7100            return Err(SuperviseError::Wait {
7101                module_id: module_id.to_string(),
7102                source,
7103            });
7104        }
7105        Err(_) => {
7106            // Mirror the sibling arm above: state is already `Draining`, and an
7107            // error propagated from here would strand it there -- a state
7108            // `set_enabled(true)` cannot heal (`revive_terminal` matches only
7109            // `Failed | Stopped`), leaving an operator Restart as the only exit.
7110            // `Failed` before `?` keeps the module operator-visible and
7111            // revivable. Trigger is an ESRCH race (process exits between the
7112            // drain timeout firing and the kill) or a post-kill wait failure
7113            // (issue #34).
7114            //
7115            // Logged because the kill is otherwise visible only as signal 9 in
7116            // the terminal ring, and the budget it follows can be long enough
7117            // that consumers see a stretch of refusals with no stated cause.
7118            warn!(
7119                module_id,
7120                pid = child.pid,
7121                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
7122                reason = ?final_state,
7123                ?stop_notice,
7124                "drain budget expired before the module exited; killing it"
7125            );
7126            child.start_kill().map_err(|source| {
7127                fail_snapshot(snapshot, Some(module_id), None);
7128                SuperviseError::Kill {
7129                    module_id: module_id.to_string(),
7130                    source,
7131                }
7132            })?;
7133            let status = child.wait().await.map_err(|source| {
7134                fail_snapshot(snapshot, Some(module_id), None);
7135                SuperviseError::Wait {
7136                    module_id: module_id.to_string(),
7137                    source,
7138                }
7139            })?;
7140            classify_reaped_child_exit(snapshot, &child, &status)
7141        }
7142    };
7143
7144    update_snapshot(snapshot, Some(module_id), |state| {
7145        state.state = final_state;
7146        if let Some(enabled) = enabled {
7147            state.enabled = enabled;
7148        }
7149        clear_current_process_facts(state);
7150        state.last_exit = Some(exit_report.clone());
7151        if exit_report.kind == ExitKind::DeliberateSeverance {
7152            state.lifetime_restarts += 1;
7153        }
7154    })?;
7155    record_terminal(
7156        module_id,
7157        terminal_ring,
7158        spawn_events,
7159        &exit_report,
7160        terminal_disposition(final_state),
7161    );
7162    child.drain_stderr(module_id).await;
7163
7164    wait_for_registration_release(registry, module_id, REGISTRY_RELEASE_TIMEOUT).await
7165}
7166
7167/// Ask a child that nothing else has asked to stop, by signal.
7168///
7169/// A registered subc module is asked over its own connection: the drain sends
7170/// `route.closing`/`route.closed` to its consumers, a GOODBYE per route, then a
7171/// module GOODBYE, and the module stops itself. A module that speaks no subc
7172/// wire receives none of that, and neither does a subc module that has not
7173/// registered yet, so for them the drain budget would be pure delay in front of
7174/// a SIGKILL -- and for a process with a store to flush (JetStream is the
7175/// reason `protocol: "none"` exists) a SIGKILL turns every ordinary teardown
7176/// into a recovery on the next start.
7177///
7178/// NEVER CALLED FOR A MODULE THAT WAS TOLD OVER ITS CONNECTION, and that is a
7179/// rule rather than an optimisation: that module's graceful stop is already
7180/// running by the time its child is drained, and a signal would race it.
7181///
7182/// Best-effort by construction. A child that has already exited is the ordinary
7183/// case rather than an error (the kill lands on a reaped or exiting pid), so a
7184/// failure is logged at debug and the wait-then-kill below still decides the
7185/// outcome.
7186#[cfg(unix)]
7187fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
7188    let Some(pid) = child
7189        .id()
7190        .and_then(|pid| i32::try_from(pid).ok())
7191        .and_then(rustix::process::Pid::from_raw)
7192    else {
7193        debug!(
7194            module_id,
7195            "no pid to signal for teardown; falling through to the drain wait"
7196        );
7197        return;
7198    };
7199    match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
7200        Ok(()) => debug!(
7201            module_id,
7202            "sent SIGTERM to a module nothing else asked to stop"
7203        ),
7204        Err(err) => debug!(
7205            module_id,
7206            error = %err,
7207            "SIGTERM to module failed; the drain wait and kill still apply"
7208        ),
7209    }
7210}
7211
7212/// Windows has no SIGTERM and no portable stand-in for one. The graceful stops
7213/// Windows does offer need cooperation this supervisor cannot assume: a console
7214/// control event requires sharing a console with the child, and `WM_CLOSE`
7215/// requires the child to pump a message loop. A supervised server process does
7216/// neither, so there is nothing to send and teardown is the wait followed by the
7217/// kill. Emulating a signal here would mean inventing a stop protocol, which is
7218/// the thing `protocol: "none"` exists to avoid.
7219#[cfg(not(unix))]
7220fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
7221    debug!(
7222        module_id,
7223        "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
7224    );
7225}
7226
7227fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
7228    match final_state {
7229        ModuleState::Stopped => TerminalDisposition::Stopped,
7230        ModuleState::Disabled => TerminalDisposition::Disabled,
7231        ModuleState::Restarting => TerminalDisposition::Restarting,
7232        ModuleState::Failed => TerminalDisposition::Failed,
7233        ModuleState::Starting
7234        | ModuleState::Running
7235        | ModuleState::Unresponsive
7236        | ModuleState::Draining => {
7237            unreachable!("terminal exits only finish in terminal or restarting states")
7238        }
7239    }
7240}
7241
7242/// Wait for the ACTIVE registration of `module_id` to go away, which is what a
7243/// plain stop or restart waits for before it spawns a replacement.
7244async fn wait_for_registration_release(
7245    registry: &Registry,
7246    module_id: &str,
7247    wait: Duration,
7248) -> Result<(), SuperviseError> {
7249    wait_for_slot_registration_release(
7250        registry,
7251        crate::registry::RegistrationSlot::Active(module_id),
7252        wait,
7253    )
7254    .await
7255}
7256
7257/// Wait for the registration in `slot` to go away.
7258///
7259/// Keyed on the slot rather than the bare module id because a successful swap
7260/// never empties the id's active slot (the promoted candidate is in it), so an
7261/// id-keyed wait for the incumbent's release would always time out. Draining a
7262/// swap's incumbent waits on `crate::registry::RegistrationSlot::Connection` with the
7263/// incumbent's connection instead.
7264async fn wait_for_slot_registration_release(
7265    registry: &Registry,
7266    slot: crate::registry::RegistrationSlot<'_>,
7267    wait: Duration,
7268) -> Result<(), SuperviseError> {
7269    let deadline = Instant::now() + wait;
7270    let mut release_events = registration_release_events().subscribe();
7271    let still_active = |registration: &crate::registry::ModuleRegistration| {
7272        SuperviseError::RegistrationStillActive {
7273            module_id: registration.manifest.module_id.clone(),
7274            waited: wait,
7275        }
7276    };
7277    loop {
7278        let _observed_generation = *release_events.borrow_and_update();
7279        let Some(registration) = registry
7280            .registration(slot)
7281            .map_err(SuperviseError::Registry)?
7282        else {
7283            return Ok(());
7284        };
7285
7286        let now = Instant::now();
7287        if now >= deadline {
7288            return Err(still_active(&registration));
7289        }
7290
7291        let remaining = deadline.saturating_duration_since(now);
7292        match timeout(remaining, release_events.changed()).await {
7293            Ok(Ok(())) | Ok(Err(_)) => {}
7294            Err(_) => return Err(still_active(&registration)),
7295        }
7296    }
7297}
7298
7299#[cfg(test)]
7300mod slot_registration_wait_tests {
7301    use super::*;
7302    use crate::registry::{ConnectionId, RegistrationSlot};
7303    use subc_protocol::manifest::ModuleManifest;
7304
7305    const INCUMBENT: u64 = 1;
7306    const CANDIDATE: u64 = 2;
7307
7308    fn swapped_registry() -> Arc<Registry> {
7309        let registry = Arc::new(Registry::default());
7310        let manifest = ModuleManifest::builder("m", "0.1.0").build();
7311        registry
7312            .register_with_control_ops(
7313                manifest.clone(),
7314                1,
7315                ConnectionId::new(INCUMBENT),
7316                Vec::new(),
7317            )
7318            .unwrap();
7319        registry
7320            .register_candidate_with_control_ops(
7321                manifest,
7322                1,
7323                ConnectionId::new(CANDIDATE),
7324                Vec::new(),
7325            )
7326            .unwrap();
7327        registry
7328    }
7329
7330    /// After a promotion the id's active slot is held by the new process, so an
7331    /// id-keyed wait for the incumbent's release can never succeed; the
7332    /// connection-keyed wait completes as soon as the incumbent deregisters.
7333    #[tokio::test]
7334    async fn incumbent_release_is_awaited_by_connection_not_by_module_id() {
7335        let registry = swapped_registry();
7336        registry.promote_candidate("m").unwrap().unwrap();
7337
7338        assert!(matches!(
7339            wait_for_registration_release(&registry, "m", Duration::from_millis(50)).await,
7340            Err(SuperviseError::RegistrationStillActive { .. })
7341        ));
7342
7343        // Still held while the incumbent's connection has not deregistered.
7344        assert!(matches!(
7345            wait_for_slot_registration_release(
7346                &registry,
7347                RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
7348                Duration::from_millis(50),
7349            )
7350            .await,
7351            Err(SuperviseError::RegistrationStillActive { .. })
7352        ));
7353
7354        let releaser = Arc::clone(&registry);
7355        let release = tokio::spawn(async move {
7356            sleep(Duration::from_millis(20)).await;
7357            releaser
7358                .deregister_connection(ConnectionId::new(INCUMBENT))
7359                .unwrap();
7360            notify_registration_release();
7361        });
7362        wait_for_slot_registration_release(
7363            &registry,
7364            RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
7365            Duration::from_secs(5),
7366        )
7367        .await
7368        .expect("the incumbent's own registration is released");
7369        release.await.unwrap();
7370        assert!(registry.get_module("m").unwrap().is_some());
7371    }
7372
7373    /// The candidate slot is waited on separately from the active slot: the
7374    /// incumbent's registration neither holds up nor stands in for it.
7375    #[tokio::test]
7376    async fn candidate_slot_wait_ignores_the_incumbents_registration() {
7377        let registry = swapped_registry();
7378        assert!(matches!(
7379            wait_for_slot_registration_release(
7380                &registry,
7381                RegistrationSlot::Candidate("m"),
7382                Duration::from_millis(50),
7383            )
7384            .await,
7385            Err(SuperviseError::RegistrationStillActive { .. })
7386        ));
7387        registry
7388            .deregister_connection(ConnectionId::new(CANDIDATE))
7389            .unwrap();
7390        wait_for_slot_registration_release(
7391            &registry,
7392            RegistrationSlot::Candidate("m"),
7393            Duration::from_millis(50),
7394        )
7395        .await
7396        .expect("a candidate slot with no candidate is released");
7397        assert!(registry
7398            .registration(RegistrationSlot::Active("m"))
7399            .unwrap()
7400            .is_some());
7401    }
7402}
7403
7404fn classify_exit(status: &ExitStatus) -> ExitReport {
7405    ExitReport {
7406        kind: if status.success() {
7407            ExitKind::Clean
7408        } else {
7409            ExitKind::Crash
7410        },
7411        code: status.code(),
7412        signal: exit_signal(status),
7413        at_ms: unix_ms_now(),
7414    }
7415}
7416
7417/// The terminal record for a module whose `wait()` call itself errored (e.g. the
7418/// child was already reaped out-of-band). There is no `ExitStatus` to read a code
7419/// or signal from -- `None`/`None` is the honest shape, not a guess -- but the
7420/// disposition still must be `Failed` so the terminal ring is not silently missing
7421/// an entry, matching what `fail_snapshot` records for this same arm.
7422fn wait_error_exit_report() -> ExitReport {
7423    ExitReport {
7424        kind: ExitKind::Crash,
7425        code: None,
7426        signal: None,
7427        at_ms: unix_ms_now(),
7428    }
7429}
7430
7431#[cfg(unix)]
7432fn exit_signal(status: &ExitStatus) -> Option<i32> {
7433    use std::os::unix::process::ExitStatusExt;
7434
7435    status.signal()
7436}
7437
7438#[cfg(not(unix))]
7439fn exit_signal(_status: &ExitStatus) -> Option<i32> {
7440    None
7441}
7442
7443/// Give an operator-touched module its full crash budget back.
7444///
7445/// Named for the counter it used to zero; it now empties the in-window ring,
7446/// which is the same act. `lifetime_restarts` is untouched on purpose -- the
7447/// ledger of what happened survives every operator action.
7448fn reset_restart_count(snapshot: &SharedSnapshot, module_id: &str) -> Result<(), SuperviseError> {
7449    update_snapshot(snapshot, Some(module_id), |state| {
7450        state.clear_crash_restarts();
7451    })
7452}
7453
7454fn set_running(
7455    snapshot: &SharedSnapshot,
7456    child: &SupervisedChild,
7457    module_id: &str,
7458    spawn_events: &SpawnEventFeed,
7459) -> Result<(), SuperviseError> {
7460    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
7461        module_id: Some(module_id.to_string()),
7462    })?;
7463    state.spawn_generation = spawn_events.emit_spawned(module_id, child.pid, child.spawned_at_ms);
7464    // Every caller of this is a plain spawn, which always uses the primary key;
7465    // a promoted swap candidate sets the flag itself after this returns.
7466    state.in_alternate_slot = false;
7467    state.configuration_updated_since_spawn = false;
7468    state.state = ModuleState::Running;
7469    state.enabled = true;
7470    state.process_alive = true;
7471    state.pid = child.id();
7472    state.spawned_at_ms = Some(child.spawned_at_ms);
7473    state.spawned_from = Some(child.spawned_from.clone());
7474    state.spawned_file_identity = child.spawned_file_identity;
7475    state.process_start_time = child.process_start_time;
7476    Ok(())
7477}
7478
7479fn clear_current_process_facts(state: &mut SupervisorSnapshot) {
7480    state.process_alive = false;
7481    state.pid = None;
7482    state.spawned_at_ms = None;
7483    state.spawned_from = None;
7484    state.spawned_file_identity = None;
7485    state.process_start_time = None;
7486    state.deliberate_severance = None;
7487}
7488
7489#[cfg(test)]
7490fn record_deliberate_severance(
7491    snapshot: &SharedSnapshot,
7492    identity: ProcessIdentity,
7493) -> Result<(), SuperviseError> {
7494    update_snapshot(snapshot, None, |state| {
7495        state.deliberate_severance = Some(identity);
7496    })
7497}
7498
7499fn apply_deliberate_severance_marker(
7500    snapshot: &SharedSnapshot,
7501    exited_identity: Option<ProcessIdentity>,
7502    mut exit_report: ExitReport,
7503) -> ExitReport {
7504    let marker = lock_snapshot(snapshot)
7505        .ok()
7506        .and_then(|mut state| state.deliberate_severance.take());
7507    if marker.is_some() && marker == exited_identity {
7508        exit_report.kind = ExitKind::DeliberateSeverance;
7509    }
7510    exit_report
7511}
7512
7513fn classify_reaped_child_exit(
7514    snapshot: &SharedSnapshot,
7515    child: &SupervisedChild,
7516    status: &ExitStatus,
7517) -> ExitReport {
7518    apply_deliberate_severance_marker(snapshot, child.process_identity(), classify_exit(status))
7519}
7520
7521fn fail_snapshot(
7522    snapshot: &SharedSnapshot,
7523    module_id: Option<&str>,
7524    last_exit: Option<ExitReport>,
7525) {
7526    if let Err(err) = update_snapshot(snapshot, module_id, |state| {
7527        state.state = ModuleState::Failed;
7528        clear_current_process_facts(state);
7529        if let Some(last_exit) = last_exit {
7530            state.last_exit = Some(last_exit);
7531        }
7532    }) {
7533        error!(error = %err, "failed to mark supervisor state failed");
7534    }
7535}
7536
7537fn update_snapshot(
7538    snapshot: &SharedSnapshot,
7539    module_id: Option<&str>,
7540    update: impl FnOnce(&mut SupervisorSnapshot),
7541) -> Result<(), SuperviseError> {
7542    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
7543        module_id: module_id.map(ToOwned::to_owned),
7544    })?;
7545    update(&mut state);
7546    Ok(())
7547}
7548
7549const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
7550
7551fn lock_snapshot_for_control<'a>(
7552    snapshot: &'a SharedSnapshot,
7553    module_id: &str,
7554    caller: &'static str,
7555) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
7556    let started_at = Instant::now();
7557    let guard = lock_snapshot(snapshot)?;
7558    let waited = started_at.elapsed();
7559    if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
7560        warn!(
7561            module_id = %module_id,
7562            waited_ms = waited.as_millis() as u64,
7563            caller = %caller,
7564            "slow snapshot lock"
7565        );
7566    }
7567    Ok(guard)
7568}
7569
7570fn lock_snapshot(
7571    snapshot: &SharedSnapshot,
7572) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
7573    snapshot
7574        .lock()
7575        .map_err(|_| SuperviseError::StatePoisoned { module_id: None })
7576}
7577
7578#[cfg(test)]
7579mod terminal_history_tests {
7580    use std::{
7581        path::PathBuf,
7582        sync::Arc,
7583        time::{Duration, Instant},
7584    };
7585
7586    use tokio::time::sleep;
7587
7588    use super::{
7589        apply_deliberate_severance_marker, daemon_will_restart, drain_child_to_state,
7590        drained_after_quiescence_wait, handle_reload_spawn_failure, health_restart_child,
7591        lock_snapshot, on_child_exit, record_deliberate_severance, record_wait_error_terminal,
7592        reset_restart_count, spawn_and_mark_running, update_snapshot, wait_error_exit_report,
7593        ExitKind, ExitReport, ModuleProtocol, ModuleSpec, ModuleState, NextAction, ProcessIdentity,
7594        RestartPolicy, SpawnEventKind, StopNotice, SuperviseError, SupervisedModule, Supervisor,
7595        SupervisorHandle, SupervisorHealthStatus, SupervisorSnapshot,
7596    };
7597    // The supervisor's clock, distinct from the `std::time::Instant` these tests
7598    // use for their own wall-clock deadlines: crash-restart instants must be on
7599    // the same clock the production code stamps them with, which is tokio's (and
7600    // is what `start_paused` tests can move).
7601    use super::Instant as ClockInstant;
7602    use crate::{
7603        registry::Registry,
7604        terminal_ring::{TerminalRing, TerminalRingConfig},
7605    };
7606    use std::sync::Mutex;
7607    use subc_control::TerminalDisposition;
7608
7609    /// See the twin in `control.rs` for why this derives the path from
7610    /// `current_exe()` and why the existence check is here: `--lib` alone does
7611    /// not build `[[bin]]` targets, and a bare spawn then fails with a raw
7612    /// `NotFound` that reads as a broken test rather than an unbuilt dependency.
7613    fn fake_aft_stub_path() -> PathBuf {
7614        let mut path = std::env::current_exe().expect("current_exe available in tests");
7615        path.pop();
7616        path.pop();
7617        path.push(if cfg!(windows) {
7618            "fake-aft-stub.exe"
7619        } else {
7620            "fake-aft-stub"
7621        });
7622        assert!(
7623            path.exists(),
7624            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
7625             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
7626            path.display()
7627        );
7628        path
7629    }
7630
7631    #[test]
7632    fn reserved_never_spawned_refuses_every_hello() {
7633        // The canary hole: a reserved id whose module has never spawned had NO
7634        // gate entry and admitted anyone -- the reservation protected the nonce
7635        // holder, not the NAME. Now the entry is present with no legitimate
7636        // holder and refuses all comers.
7637        let supervisor = SupervisorHandle::default();
7638        supervisor.apply_identity_configuration(&ModuleSpec {
7639            module_id: "never-spawned".to_string(),
7640            program: PathBuf::from("/usr/bin/false"),
7641            args: Vec::new(),
7642            env: Vec::new(),
7643            reserved: true,
7644            reserved_prefixes: Vec::new(),
7645            protocol: ModuleProtocol::Subc,
7646            overlap: Default::default(),
7647        });
7648        assert!(
7649            supervisor
7650                .reserved_hello_rejection("never-spawned", Some("any-forged-nonce"))
7651                .is_some(),
7652            "forged nonce must refuse on a reserved never-spawned id"
7653        );
7654        assert!(
7655            supervisor
7656                .reserved_hello_rejection("never-spawned", None)
7657                .is_some(),
7658            "absent nonce must refuse on a reserved never-spawned id"
7659        );
7660        // And a real spawn nonce minted later admits exactly that nonce.
7661        supervisor.set_spawn_nonce("never-spawned", "minted".to_string());
7662        supervisor.apply_identity_configuration(&ModuleSpec {
7663            module_id: "never-spawned".to_string(),
7664            program: PathBuf::from("/usr/bin/false"),
7665            args: Vec::new(),
7666            env: Vec::new(),
7667            reserved: true,
7668            reserved_prefixes: Vec::new(),
7669            protocol: ModuleProtocol::Subc,
7670            overlap: Default::default(),
7671        });
7672        assert!(supervisor
7673            .reserved_hello_rejection("never-spawned", Some("minted"))
7674            .is_none());
7675        assert!(supervisor
7676            .reserved_hello_rejection("never-spawned", Some("forged"))
7677            .is_some());
7678    }
7679
7680    /// Put `count` crash restarts on a snapshot's ring as if they had all just
7681    /// happened, which is what "spent budget" looks like to every reader.
7682    fn seed_crash_restarts(state: &mut SupervisorSnapshot, count: u32) {
7683        let now = ClockInstant::now();
7684        for _ in 0..count {
7685            state.crash_restarts.push_back(now);
7686        }
7687    }
7688
7689    /// Age the oldest recorded restart out of `window`, standing in for the hours
7690    /// that would otherwise have to pass. Injecting the instant is the point: a
7691    /// test that slept a real window would take ten minutes and still prove less.
7692    fn age_oldest_crash_restart_out_of_window(state: &mut SupervisorSnapshot, window: Duration) {
7693        let aged = state
7694            .crash_restarts
7695            .front()
7696            .expect("a crash restart must be recorded before it can be aged")
7697            .checked_sub(window + Duration::from_secs(1))
7698            .expect("the test clock is far enough from its origin to age an instant");
7699        state.crash_restarts[0] = aged;
7700    }
7701
7702    fn snapshot_with_restarts(enabled: bool, count: u32) -> SupervisorSnapshot {
7703        let mut state = SupervisorSnapshot::new(ModuleState::Running, enabled);
7704        seed_crash_restarts(&mut state, count);
7705        state
7706    }
7707
7708    #[test]
7709    fn daemon_owned_recovery_predicate_uses_the_pre_increment_budget() {
7710        let policy = RestartPolicy::new(3, Duration::ZERO);
7711        let now = ClockInstant::now();
7712        assert!(daemon_will_restart(
7713            &mut snapshot_with_restarts(true, 2),
7714            &policy,
7715            now
7716        ));
7717        assert!(!daemon_will_restart(
7718            &mut snapshot_with_restarts(true, 3),
7719            &policy,
7720            now
7721        ));
7722        assert!(!daemon_will_restart(
7723            &mut snapshot_with_restarts(false, 0),
7724            &policy,
7725            now
7726        ));
7727    }
7728
7729    #[test]
7730    fn crash_restart_backoff_escalates_with_in_window_count() {
7731        let policy = RestartPolicy::new(4, Duration::from_millis(100))
7732            .with_max_backoff(Duration::from_secs(30));
7733        let now = ClockInstant::now();
7734        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
7735        let schedules = (0..4)
7736            .map(|_| {
7737                state
7738                    .next_crash_restart(&policy, now)
7739                    .expect("the test policy allows four crash restarts")
7740            })
7741            .collect::<Vec<_>>();
7742
7743        assert_eq!(
7744            schedules
7745                .iter()
7746                .map(|schedule| schedule.restart_in_window)
7747                .collect::<Vec<_>>(),
7748            vec![0, 1, 2, 3]
7749        );
7750        assert_eq!(
7751            schedules
7752                .iter()
7753                .map(|schedule| schedule.delay)
7754                .collect::<Vec<_>>(),
7755            vec![
7756                Duration::from_millis(100),
7757                Duration::from_secs(1),
7758                Duration::from_secs(10),
7759                Duration::from_secs(30),
7760            ]
7761        );
7762    }
7763
7764    #[test]
7765    fn crash_restart_backoff_resets_after_ring_clear() {
7766        let policy = RestartPolicy::new(3, Duration::from_millis(100));
7767        let now = ClockInstant::now();
7768        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
7769        assert_eq!(
7770            state.next_crash_restart(&policy, now).unwrap().delay,
7771            Duration::from_millis(100)
7772        );
7773        assert_eq!(
7774            state.next_crash_restart(&policy, now).unwrap().delay,
7775            Duration::from_secs(1)
7776        );
7777
7778        state.clear_crash_restarts();
7779        let schedule = state
7780            .next_crash_restart(&policy, now)
7781            .expect("a cleared ring must allow another restart");
7782        assert_eq!(schedule.restart_in_window, 0);
7783        assert_eq!(schedule.delay, Duration::from_millis(100));
7784    }
7785
7786    #[test]
7787    fn crash_restart_backoff_ignores_aged_restarts() {
7788        let policy = RestartPolicy::new(3, Duration::from_millis(100));
7789        let now = ClockInstant::now();
7790        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
7791        state
7792            .next_crash_restart(&policy, now)
7793            .expect("the first restart is allowed");
7794        state
7795            .next_crash_restart(&policy, now)
7796            .expect("the second restart is allowed");
7797        state.crash_restarts[0] = now
7798            .checked_sub(policy.window + Duration::from_secs(1))
7799            .expect("the fake clock can age a restart past the window");
7800
7801        let schedule = state
7802            .next_crash_restart(&policy, now)
7803            .expect("an aged restart must release its slot");
7804        assert_eq!(schedule.restart_in_window, 1);
7805        assert_eq!(schedule.delay, Duration::from_secs(1));
7806        assert_eq!(state.crash_restarts.len(), 2);
7807    }
7808
7809    /// The budget is a rate: the same three spent restarts refuse a respawn
7810    /// while they are recent and allow one once they have aged past the window.
7811    /// Nothing about the module changed in between, which is the whole point.
7812    #[test]
7813    fn a_budget_spent_before_the_window_no_longer_refuses() {
7814        let policy = RestartPolicy::new(3, Duration::ZERO);
7815        let mut state = snapshot_with_restarts(true, 3);
7816        let now = ClockInstant::now();
7817        assert!(!daemon_will_restart(&mut state, &policy, now));
7818
7819        assert!(daemon_will_restart(
7820            &mut state,
7821            &policy,
7822            now + policy.window + Duration::from_secs(1)
7823        ));
7824        assert!(
7825            state.crash_restarts.is_empty(),
7826            "reading the budget must drop the instants that left the window"
7827        );
7828    }
7829
7830    fn module_with_recovery_snapshot(
7831        state: ModuleState,
7832        enabled: bool,
7833        restart_count: u32,
7834    ) -> SupervisedModule {
7835        let registry = Arc::new(Registry::default());
7836        let supervisor =
7837            Supervisor::new(Arc::clone(&registry), RestartPolicy::new(3, Duration::ZERO));
7838        let module = supervisor
7839            .spawn(ModuleSpec {
7840                module_id: "recovery-snapshot".to_string(),
7841                program: fake_aft_stub_path(),
7842                args: Vec::new(),
7843                env: Vec::new(),
7844                reserved: false,
7845                reserved_prefixes: Vec::new(),
7846                protocol: ModuleProtocol::Subc,
7847                overlap: Default::default(),
7848            })
7849            .unwrap();
7850        update_snapshot(
7851            &module.inner.snapshot,
7852            Some("recovery-snapshot"),
7853            |snapshot| {
7854                snapshot.state = state;
7855                snapshot.enabled = enabled;
7856                seed_crash_restarts(snapshot, restart_count);
7857            },
7858        )
7859        .unwrap();
7860        module
7861    }
7862
7863    #[cfg(target_os = "linux")]
7864    #[tokio::test]
7865    async fn no_cgroup_placement_does_not_block_fake_aft_stub_spawn() {
7866        let supervisor = Supervisor::new(Arc::new(Registry::default()), RestartPolicy::default())
7867            .with_cgroup_placement(None);
7868        let result = supervisor.spawn(ModuleSpec {
7869            module_id: "no-cgroup-placement".to_string(),
7870            program: fake_aft_stub_path(),
7871            args: Vec::new(),
7872            env: Vec::new(),
7873            reserved: false,
7874            reserved_prefixes: Vec::new(),
7875            protocol: ModuleProtocol::Subc,
7876            overlap: Default::default(),
7877        });
7878
7879        assert!(
7880            result.is_ok(),
7881            "no delegation must not turn an otherwise valid spawn into a failure: {result:?}"
7882        );
7883    }
7884
7885    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7886    async fn undecided_snapshot_uses_shared_restart_predicate() {
7887        assert!(module_with_recovery_snapshot(ModuleState::Running, true, 2)
7888            .will_recover_after_connection_loss()
7889            .unwrap());
7890        assert!(
7891            !module_with_recovery_snapshot(ModuleState::Running, true, 3)
7892                .will_recover_after_connection_loss()
7893                .unwrap()
7894        );
7895    }
7896
7897    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7898    async fn restarting_snapshot_at_exhausted_budget_is_non_terminal() {
7899        assert!(
7900            module_with_recovery_snapshot(ModuleState::Restarting, true, 3)
7901                .will_recover_after_connection_loss()
7902                .unwrap()
7903        );
7904    }
7905
7906    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7907    async fn terminal_phase_snapshots_are_terminal_before_budget_exhaustion() {
7908        assert!(!module_with_recovery_snapshot(ModuleState::Failed, true, 0)
7909            .will_recover_after_connection_loss()
7910            .unwrap());
7911        assert!(
7912            !module_with_recovery_snapshot(ModuleState::Disabled, true, 0)
7913                .will_recover_after_connection_loss()
7914                .unwrap()
7915        );
7916    }
7917
7918    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7919    async fn warming_snapshot_is_limited_to_startup_phases() {
7920        for state in [
7921            ModuleState::Starting,
7922            ModuleState::Running,
7923            ModuleState::Restarting,
7924        ] {
7925            assert!(
7926                module_with_recovery_snapshot(state, true, 0)
7927                    .is_warming()
7928                    .unwrap(),
7929                "{state:?} should be warming"
7930            );
7931        }
7932        for state in [
7933            ModuleState::Unresponsive,
7934            ModuleState::Draining,
7935            ModuleState::Stopped,
7936            ModuleState::Failed,
7937            ModuleState::Disabled,
7938        ] {
7939            assert!(
7940                !module_with_recovery_snapshot(state, true, 0)
7941                    .is_warming()
7942                    .unwrap(),
7943                "{state:?} should not be warming"
7944            );
7945        }
7946    }
7947
7948    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7949    async fn terminal_history_survives_respawn_and_keeps_both_crashes_in_order() {
7950        let registry = Arc::new(Registry::default());
7951        let supervisor =
7952            Supervisor::new(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO));
7953        let module = supervisor
7954            .spawn(ModuleSpec {
7955                module_id: "terminal-history".to_string(),
7956                program: fake_aft_stub_path(),
7957                args: Vec::new(),
7958                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
7959                reserved: false,
7960                reserved_prefixes: Vec::new(),
7961                protocol: ModuleProtocol::Subc,
7962                overlap: Default::default(),
7963            })
7964            .unwrap();
7965
7966        let deadline = Instant::now() + Duration::from_secs(5);
7967        loop {
7968            let history = module.terminal_history();
7969            if history.entries.len() == 2 {
7970                assert_eq!(module.status().unwrap().state, ModuleState::Failed);
7971                assert_eq!(history.dropped, 0);
7972                assert_eq!(
7973                    history
7974                        .entries
7975                        .iter()
7976                        .map(|entry| entry.exit_code)
7977                        .collect::<Vec<_>>(),
7978                    vec![Some(23), Some(23)]
7979                );
7980                assert!(history.entries[0].at_ms <= history.entries[1].at_ms);
7981                return;
7982            }
7983            assert!(
7984                Instant::now() < deadline,
7985                "module did not retain two terminal exits: {history:?}"
7986            );
7987            sleep(Duration::from_millis(10)).await;
7988        }
7989    }
7990
7991    /// A disable issued while a crash respawn is still backing off must preempt
7992    /// that respawn: the operator's stop wins, the disable must not queue behind
7993    /// the backoff, and the module must never come back up afterwards.
7994    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7995    async fn disable_during_crash_backoff_cancels_pending_respawn() {
7996        let backoff = Duration::from_secs(2);
7997        let supervisor = Supervisor::new(
7998            Arc::new(Registry::default()),
7999            RestartPolicy::new(10, backoff),
8000        );
8001        let module = supervisor
8002            .spawn(ModuleSpec {
8003                module_id: "disable-during-backoff".to_string(),
8004                program: fake_aft_stub_path(),
8005                args: Vec::new(),
8006                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
8007                reserved: false,
8008                reserved_prefixes: Vec::new(),
8009                protocol: ModuleProtocol::Subc,
8010                overlap: Default::default(),
8011            })
8012            .unwrap();
8013
8014        // Wait for the first crash to put the module into its backoff window.
8015        let deadline = Instant::now() + Duration::from_secs(5);
8016        loop {
8017            if module.status().unwrap().state == ModuleState::Restarting {
8018                break;
8019            }
8020            assert!(
8021                Instant::now() < deadline,
8022                "module never entered the crash backoff"
8023            );
8024            sleep(Duration::from_millis(10)).await;
8025        }
8026
8027        let started = Instant::now();
8028        module.set_enabled(false).await.unwrap();
8029        let waited = started.elapsed();
8030
8031        assert!(
8032            waited < backoff / 2,
8033            "disable waited {waited:?} behind the {backoff:?} crash backoff; the operator command must preempt the pending respawn"
8034        );
8035        assert_eq!(module.status().unwrap().state, ModuleState::Disabled);
8036
8037        // Outlast the backoff: the respawn it was counting down to must never run.
8038        sleep(backoff + Duration::from_millis(500)).await;
8039        let status = module.status().unwrap();
8040        assert_eq!(status.state, ModuleState::Disabled);
8041        assert_eq!(
8042            status.spawn_generation, 1,
8043            "module respawned after the operator disabled it"
8044        );
8045    }
8046
8047    /// Each restart-producing arm has its own state transition. Keeping their
8048    /// lifetime count assertions adjacent prevents a later new arm from silently
8049    /// spending budget without recording the historical restart.
8050    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8051    async fn every_restart_increment_path_advances_lifetime_count() {
8052        let supervisor = Supervisor::new(
8053            Arc::new(Registry::default()),
8054            RestartPolicy::new(1, Duration::ZERO),
8055        );
8056        let runtime = supervisor.runtime_config();
8057        let spec = ModuleSpec {
8058            module_id: "lifetime-increment-path".to_string(),
8059            program: PathBuf::from("/unused/lifetime-increment-path"),
8060            args: Vec::new(),
8061            env: Vec::new(),
8062            reserved: false,
8063            reserved_prefixes: Vec::new(),
8064            protocol: ModuleProtocol::Subc,
8065            overlap: Default::default(),
8066        };
8067
8068        let crash_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8069        assert!(matches!(
8070            on_child_exit(
8071                &spec,
8072                runtime.restart_policy,
8073                &supervisor.registry,
8074                &crash_snapshot,
8075                &runtime.terminal_ring,
8076                &runtime.spawn_events,
8077                &runtime.child_roster,
8078                ExitReport {
8079                    kind: ExitKind::Crash,
8080                    code: Some(1),
8081                    signal: None,
8082                    at_ms: 1,
8083                },
8084            )
8085            .await,
8086            NextAction::Restart { schedule: _ }
8087        ));
8088        let (crash_restarts, crash_lifetime) = {
8089            let state = lock_snapshot(&crash_snapshot).unwrap();
8090            (state.crash_restarts.len(), state.lifetime_restarts)
8091        };
8092        assert_eq!(crash_restarts, 1);
8093        assert_eq!(crash_lifetime, 1);
8094
8095        let health_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8096        let mut health_child = None;
8097        assert!(matches!(
8098            health_restart_child(
8099                &spec,
8100                &runtime,
8101                &supervisor.registry,
8102                &supervisor.process_liveness,
8103                &health_snapshot,
8104                &mut health_child,
8105                SupervisorHealthStatus::Failing,
8106                None,
8107                2,
8108            )
8109            .await,
8110            Err(SuperviseError::Spawn { .. })
8111        ));
8112        let (health_restarts, health_lifetime) = {
8113            let state = lock_snapshot(&health_snapshot).unwrap();
8114            (state.crash_restarts.len(), state.lifetime_restarts)
8115        };
8116        assert_eq!(health_restarts, 1);
8117        assert_eq!(health_lifetime, 1);
8118
8119        let reload_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8120        let mut reload_child = None;
8121        assert!(matches!(
8122            handle_reload_spawn_failure(
8123                &spec,
8124                &runtime,
8125                &supervisor.process_liveness,
8126                &reload_snapshot,
8127                &mut reload_child,
8128                "forced reload spawn failure".to_string(),
8129            )
8130            .await,
8131            Err(SuperviseError::ReloadFailed { .. })
8132        ));
8133        let (reload_restarts, reload_lifetime) = {
8134            let state = lock_snapshot(&reload_snapshot).unwrap();
8135            (state.crash_restarts.len(), state.lifetime_restarts)
8136        };
8137        assert_eq!(reload_restarts, 1);
8138        assert_eq!(reload_lifetime, 1);
8139    }
8140
8141    #[tokio::test]
8142    async fn deliberately_severed_live_child_records_lifetime_without_spending_restart_budget() {
8143        let supervisor = Supervisor::new(
8144            Arc::new(Registry::default()),
8145            RestartPolicy::new(3, Duration::ZERO),
8146        );
8147        let runtime = supervisor.runtime_config();
8148        let spec = ModuleSpec {
8149            module_id: "deliberately-severed".to_string(),
8150            program: PathBuf::from("/unused/deliberately-severed"),
8151            args: Vec::new(),
8152            env: Vec::new(),
8153            reserved: false,
8154            reserved_prefixes: Vec::new(),
8155            protocol: ModuleProtocol::Subc,
8156            overlap: Default::default(),
8157        };
8158        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8159        let process = ProcessIdentity {
8160            pid: 41,
8161            start_time: 101,
8162        };
8163        record_deliberate_severance(&snapshot, process).unwrap();
8164        let exit_report = apply_deliberate_severance_marker(
8165            &snapshot,
8166            Some(process),
8167            ExitReport {
8168                kind: ExitKind::Crash,
8169                code: Some(1),
8170                signal: None,
8171                at_ms: 1,
8172            },
8173        );
8174        assert_eq!(exit_report.kind, ExitKind::DeliberateSeverance);
8175
8176        assert!(matches!(
8177            on_child_exit(
8178                &spec,
8179                runtime.restart_policy,
8180                &supervisor.registry,
8181                &snapshot,
8182                &runtime.terminal_ring,
8183                &runtime.spawn_events,
8184                &runtime.child_roster,
8185                exit_report,
8186            )
8187            .await,
8188            NextAction::Restart { schedule: _ }
8189        ));
8190        let state = lock_snapshot(&snapshot).unwrap();
8191        assert_eq!(state.lifetime_restarts, 1);
8192        assert_eq!(state.crash_restarts.len(), 0);
8193    }
8194
8195    #[tokio::test]
8196    async fn genuine_crash_spends_restart_budget_and_records_lifetime() {
8197        let supervisor = Supervisor::new(
8198            Arc::new(Registry::default()),
8199            RestartPolicy::new(3, Duration::ZERO),
8200        );
8201        let runtime = supervisor.runtime_config();
8202        let spec = ModuleSpec {
8203            module_id: "genuine-crash".to_string(),
8204            program: PathBuf::from("/unused/genuine-crash"),
8205            args: Vec::new(),
8206            env: Vec::new(),
8207            reserved: false,
8208            reserved_prefixes: Vec::new(),
8209            protocol: ModuleProtocol::Subc,
8210            overlap: Default::default(),
8211        };
8212        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8213
8214        assert!(matches!(
8215            on_child_exit(
8216                &spec,
8217                runtime.restart_policy,
8218                &supervisor.registry,
8219                &snapshot,
8220                &runtime.terminal_ring,
8221                &runtime.spawn_events,
8222                &runtime.child_roster,
8223                ExitReport {
8224                    kind: ExitKind::Crash,
8225                    code: Some(1),
8226                    signal: None,
8227                    at_ms: 1,
8228                },
8229            )
8230            .await,
8231            NextAction::Restart { schedule: _ }
8232        ));
8233        let state = lock_snapshot(&snapshot).unwrap();
8234        assert_eq!(state.lifetime_restarts, 1);
8235        assert_eq!(state.crash_restarts.len(), 1);
8236    }
8237
8238    fn crash_exit_report(at_ms: u64) -> ExitReport {
8239        ExitReport {
8240            kind: ExitKind::Crash,
8241            code: Some(1),
8242            signal: None,
8243            at_ms,
8244        }
8245    }
8246
8247    fn windowed_crash_spec(module_id: &str) -> ModuleSpec {
8248        ModuleSpec {
8249            module_id: module_id.to_string(),
8250            program: PathBuf::from("/unused").join(module_id),
8251            args: Vec::new(),
8252            env: Vec::new(),
8253            reserved: false,
8254            reserved_prefixes: Vec::new(),
8255            protocol: ModuleProtocol::Subc,
8256            overlap: Default::default(),
8257        }
8258    }
8259
8260    /// A real crash loop still stops. Three crashes with nothing aging out spend
8261    /// a budget of two and the third respawn is refused, and both surfaces an
8262    /// operator has -- the log line and the retained terminal record -- name the
8263    /// window rather than only the cap, because `max_restarts=2` alone is what
8264    /// this budget used to mean.
8265    #[tokio::test]
8266    async fn three_crashes_inside_the_window_stop_the_module_and_name_the_window() {
8267        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::ERROR);
8268        let supervisor = Supervisor::new(
8269            Arc::new(Registry::default()),
8270            RestartPolicy::new(2, Duration::ZERO),
8271        );
8272        let runtime = supervisor.runtime_config();
8273        let spec = windowed_crash_spec("crash-loop-in-window");
8274        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8275
8276        for attempt in 1..=2 {
8277            assert!(
8278                matches!(
8279                    on_child_exit(
8280                        &spec,
8281                        runtime.restart_policy,
8282                        &supervisor.registry,
8283                        &snapshot,
8284                        &runtime.terminal_ring,
8285                        &runtime.spawn_events,
8286                        &runtime.child_roster,
8287                        crash_exit_report(attempt),
8288                    )
8289                    .await,
8290                    NextAction::Restart { schedule: _ }
8291                ),
8292                "crash {attempt} is inside the budget and must respawn"
8293            );
8294        }
8295
8296        assert!(matches!(
8297            on_child_exit(
8298                &spec,
8299                runtime.restart_policy,
8300                &supervisor.registry,
8301                &snapshot,
8302                &runtime.terminal_ring,
8303                &runtime.spawn_events,
8304                &runtime.child_roster,
8305                crash_exit_report(3),
8306            )
8307            .await,
8308            NextAction::Stop { .. }
8309        ));
8310
8311        {
8312            let state = lock_snapshot(&snapshot).unwrap();
8313            assert_eq!(state.state, ModuleState::Failed);
8314            assert_eq!(state.crash_restarts.len(), 2);
8315            assert_eq!(state.lifetime_restarts, 2);
8316        }
8317
8318        let history = runtime
8319            .terminal_ring
8320            .lock()
8321            .expect("terminal ring is not poisoned")
8322            .snapshot();
8323        let last = history
8324            .entries
8325            .last()
8326            .expect("the refused crash is retained");
8327        assert_eq!(last.disposition, TerminalDisposition::Failed);
8328        assert_eq!(
8329            last.disposition_detail.as_deref(),
8330            Some("crash budget exhausted: max_restarts=2 within window_secs=600")
8331        );
8332
8333        let captured = crate::router::test_log::captured_logs(&logs);
8334        assert!(
8335            captured.contains("crash budget exhausted: max_restarts=2 within window_secs=600"),
8336            "the stop must be logged with its window: {captured}"
8337        );
8338    }
8339
8340    /// The rate, stated as a test: three crashes where the first has aged past
8341    /// the window are two crashes as far as the budget is concerned, so the
8342    /// third respawn is allowed and the ring holds only the two recent ones.
8343    ///
8344    /// This is the case a lifetime counter got wrong -- and the case the daemon
8345    /// now hits routinely, since a module exits non-zero every time its
8346    /// connection to the daemon drops.
8347    #[tokio::test]
8348    async fn a_crash_older_than_the_window_frees_its_slot_for_a_later_crash() {
8349        let supervisor = Supervisor::new(
8350            Arc::new(Registry::default()),
8351            RestartPolicy::new(2, Duration::ZERO),
8352        );
8353        let runtime = supervisor.runtime_config();
8354        let spec = windowed_crash_spec("crash-across-windows");
8355        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8356
8357        for attempt in 1..=2 {
8358            assert!(matches!(
8359                on_child_exit(
8360                    &spec,
8361                    runtime.restart_policy,
8362                    &supervisor.registry,
8363                    &snapshot,
8364                    &runtime.terminal_ring,
8365                    &runtime.spawn_events,
8366                    &runtime.child_roster,
8367                    crash_exit_report(attempt),
8368                )
8369                .await,
8370                NextAction::Restart { schedule: _ }
8371            ));
8372        }
8373
8374        // The oldest crash moves out of the window; nothing else about the
8375        // module changes.
8376        update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8377            age_oldest_crash_restart_out_of_window(state, runtime.restart_policy.window);
8378        })
8379        .unwrap();
8380
8381        assert!(
8382            matches!(
8383                on_child_exit(
8384                    &spec,
8385                    runtime.restart_policy,
8386                    &supervisor.registry,
8387                    &snapshot,
8388                    &runtime.terminal_ring,
8389                    &runtime.spawn_events,
8390                    &runtime.child_roster,
8391                    crash_exit_report(3),
8392                )
8393                .await,
8394                NextAction::Restart { schedule: _ }
8395            ),
8396            "a crash older than the window must not hold a budget slot"
8397        );
8398
8399        let state = lock_snapshot(&snapshot).unwrap();
8400        assert_eq!(state.state, ModuleState::Restarting);
8401        assert_eq!(
8402            state.crash_restarts.len(),
8403            2,
8404            "the aged instant is dropped and the new one takes its place"
8405        );
8406        assert_eq!(
8407            state.lifetime_restarts, 3,
8408            "the ledger counts every restart, including the ones the window forgot"
8409        );
8410    }
8411
8412    /// An operator restart hands the budget back whole, and the ledger keeps
8413    /// counting. Those are different questions -- "how close is this module to
8414    /// being stopped" and "how many times has it been replaced" -- and the
8415    /// operator action answers only the first.
8416    #[tokio::test]
8417    async fn an_operator_restart_clears_the_ring_and_leaves_the_ledger_alone() {
8418        let supervisor = Supervisor::new(
8419            Arc::new(Registry::default()),
8420            RestartPolicy::new(2, Duration::ZERO),
8421        );
8422        let runtime = supervisor.runtime_config();
8423        let spec = windowed_crash_spec("operator-cleared-budget");
8424        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8425
8426        for attempt in 1..=2 {
8427            assert!(matches!(
8428                on_child_exit(
8429                    &spec,
8430                    runtime.restart_policy,
8431                    &supervisor.registry,
8432                    &snapshot,
8433                    &runtime.terminal_ring,
8434                    &runtime.spawn_events,
8435                    &runtime.child_roster,
8436                    crash_exit_report(attempt),
8437                )
8438                .await,
8439                NextAction::Restart { schedule: _ }
8440            ));
8441        }
8442
8443        reset_restart_count(&snapshot, &spec.module_id).unwrap();
8444        {
8445            let state = lock_snapshot(&snapshot).unwrap();
8446            assert!(
8447                state.crash_restarts.is_empty(),
8448                "an operator restart returns the full budget"
8449            );
8450            assert_eq!(
8451                state.lifetime_restarts, 2,
8452                "clearing the budget must not unmake the crashes"
8453            );
8454        }
8455
8456        assert!(
8457            matches!(
8458                on_child_exit(
8459                    &spec,
8460                    runtime.restart_policy,
8461                    &supervisor.registry,
8462                    &snapshot,
8463                    &runtime.terminal_ring,
8464                    &runtime.spawn_events,
8465                    &runtime.child_roster,
8466                    crash_exit_report(3),
8467                )
8468                .await,
8469                NextAction::Restart { schedule: _ }
8470            ),
8471            "the cleared budget must be spendable again"
8472        );
8473        let state = lock_snapshot(&snapshot).unwrap();
8474        assert_eq!(state.crash_restarts.len(), 1);
8475        assert_eq!(state.lifetime_restarts, 3);
8476    }
8477
8478    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8479    async fn severance_marker_for_a_dead_child_does_not_label_its_successor() {
8480        let severed = ProcessIdentity {
8481            pid: 41,
8482            start_time: 101,
8483        };
8484        let successor = ProcessIdentity {
8485            pid: 41,
8486            start_time: 202,
8487        };
8488        let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
8489        update_snapshot(&module.inner.snapshot, Some("recovery-snapshot"), |state| {
8490            state.pid = Some(successor.pid);
8491            state.process_start_time = Some(successor.start_time);
8492        })
8493        .unwrap();
8494        assert!(!module.record_deliberate_severance(severed).unwrap());
8495
8496        let exit_report = apply_deliberate_severance_marker(
8497            &module.inner.snapshot,
8498            Some(successor),
8499            ExitReport {
8500                kind: ExitKind::Crash,
8501                code: Some(1),
8502                signal: None,
8503                at_ms: 1,
8504            },
8505        );
8506
8507        assert_eq!(exit_report.kind, ExitKind::Crash);
8508    }
8509
8510    #[tokio::test]
8511    async fn drain_reap_marks_deliberate_severance_and_records_lifetime_without_budget() {
8512        let registry = Registry::default();
8513        let supervisor = Supervisor::new(
8514            Arc::new(Registry::default()),
8515            RestartPolicy::new(3, Duration::ZERO),
8516        );
8517        let runtime = supervisor.runtime_config();
8518        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8519        let spec = ModuleSpec {
8520            module_id: "drain-deliberate-severance".to_string(),
8521            program: fake_aft_stub_path(),
8522            args: Vec::new(),
8523            env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
8524            reserved: false,
8525            reserved_prefixes: Vec::new(),
8526            protocol: ModuleProtocol::Subc,
8527            overlap: Default::default(),
8528        };
8529        let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
8530        let process = ProcessIdentity {
8531            pid: 41,
8532            start_time: 101,
8533        };
8534        child.process_identity = Some(process);
8535        update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8536            state.pid = Some(process.pid);
8537            state.process_start_time = Some(process.start_time);
8538        })
8539        .unwrap();
8540        record_deliberate_severance(&snapshot, process).unwrap();
8541
8542        drain_child_to_state(
8543            &spec.module_id,
8544            spec.protocol,
8545            // The child exits on its own; no signal may change the exit this
8546            // test classifies.
8547            StopNotice::SentOverConnection,
8548            &registry,
8549            &snapshot,
8550            &runtime.terminal_ring,
8551            &runtime.spawn_events,
8552            child,
8553            Duration::from_secs(1),
8554            ModuleState::Stopped,
8555            Some(false),
8556        )
8557        .await
8558        .unwrap();
8559
8560        let state = lock_snapshot(&snapshot).unwrap();
8561        assert_eq!(
8562            state.last_exit.as_ref().map(|exit| exit.kind),
8563            Some(ExitKind::DeliberateSeverance)
8564        );
8565        assert_eq!(state.lifetime_restarts, 1);
8566        assert_eq!(state.crash_restarts.len(), 0);
8567        drop(state);
8568        let history = runtime.terminal_ring.lock().unwrap().snapshot();
8569        assert_eq!(
8570            history.entries[0].exit_kind,
8571            subc_control::TerminalExitKind::DeliberateSeverance
8572        );
8573    }
8574
8575    #[tokio::test]
8576    async fn ordinary_drain_reap_does_not_record_a_lifetime_restart() {
8577        let registry = Registry::default();
8578        let supervisor = Supervisor::new(
8579            Arc::new(Registry::default()),
8580            RestartPolicy::new(3, Duration::ZERO),
8581        );
8582        let runtime = supervisor.runtime_config();
8583        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
8584        let spec = ModuleSpec {
8585            module_id: "ordinary-drain".to_string(),
8586            program: fake_aft_stub_path(),
8587            args: Vec::new(),
8588            env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
8589            reserved: false,
8590            reserved_prefixes: Vec::new(),
8591            protocol: ModuleProtocol::Subc,
8592            overlap: Default::default(),
8593        };
8594        let child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
8595
8596        drain_child_to_state(
8597            &spec.module_id,
8598            spec.protocol,
8599            // The child exits on its own; no signal may change the exit this
8600            // test classifies.
8601            StopNotice::SentOverConnection,
8602            &registry,
8603            &snapshot,
8604            &runtime.terminal_ring,
8605            &runtime.spawn_events,
8606            child,
8607            Duration::from_secs(1),
8608            ModuleState::Stopped,
8609            Some(false),
8610        )
8611        .await
8612        .unwrap();
8613
8614        let state = lock_snapshot(&snapshot).unwrap();
8615        assert_eq!(
8616            state.last_exit.as_ref().map(|exit| exit.kind),
8617            Some(ExitKind::Crash)
8618        );
8619        assert_eq!(state.lifetime_restarts, 0);
8620        assert_eq!(state.crash_restarts.len(), 0);
8621    }
8622
8623    #[test]
8624    fn fatal_connection_teardown_cannot_arm_a_marker_for_a_surviving_process() {
8625        // The server's generic fatal-routing branch only knows that the
8626        // connection failed; it does not know that the daemon deliberately
8627        // initiated a process-killing severance. Keep this seam explicit so a
8628        // future connection error path cannot silently reintroduce the stale
8629        // exemption that mislabels a later genuine crash.
8630        assert!(!include_str!("server.rs")
8631            .contains("router.record_deliberate_connection_severance(ctx.connection_id)"));
8632    }
8633
8634    /// The `route.closed` `drained` value must be the quiescence wait's own
8635    /// measurement (`Ok`), never invented -- except on `Err`, where there is no
8636    /// measurement at all and `false` is the one honest constant. This is the exact
8637    /// logic `begin_forwarding_drain_with` now applies before sending `route.closed`
8638    /// on every return path, including the one that used to return early via `?`
8639    /// with `route.closing` already sent and no `route.closed` ever following.
8640    #[test]
8641    fn drained_after_quiescence_wait_passes_ok_through_and_forces_false_on_err() {
8642        assert!(drained_after_quiescence_wait(&Ok(true)));
8643        assert!(!drained_after_quiescence_wait(&Ok(false)));
8644        assert!(!drained_after_quiescence_wait(&Err(
8645            SuperviseError::StatePoisoned { module_id: None }
8646        )));
8647    }
8648
8649    /// `supervise_loop`'s `wait()`-error arm now calls `record_terminal` like every
8650    /// other exit path does, so a module whose child `wait()` itself errored (e.g.
8651    /// already reaped out-of-band) still leaves a terminal record rather than none
8652    /// at all. Triggering the real `wait()` I/O error from an integration test would
8653    /// need a genuine already-reaped-child race, which is OS-specific and not
8654    /// something this suite attempts elsewhere; this test instead verifies the
8655    /// record produced for that arm end-to-end through the real `TerminalRing`, and
8656    /// the call site itself is verified by inspection to sit in that exact arm.
8657    #[test]
8658    fn wait_error_exit_report_records_a_failed_terminal_with_no_code_or_signal() {
8659        let ring = Arc::new(Mutex::new(TerminalRing::new(
8660            TerminalRingConfig::default(),
8661            0,
8662        )));
8663        record_wait_error_terminal("wait-error", &ring, &super::SpawnEventFeed::default());
8664
8665        let snapshot = ring.lock().unwrap().snapshot();
8666        assert_eq!(snapshot.entries.len(), 1);
8667        let entry = &snapshot.entries[0];
8668        assert_eq!(entry.exit_code, None);
8669        assert_eq!(entry.exit_signal, None);
8670        assert_eq!(entry.disposition, TerminalDisposition::Failed);
8671    }
8672
8673    #[test]
8674    fn wait_error_exit_path_preserves_spawn_event_density() {
8675        let feed = super::SpawnEventFeed::default();
8676        feed.configure_incarnation("wait-error-density".to_string());
8677        feed.emit_spawned("wait-error", 41, 1);
8678        let ring = Arc::new(Mutex::new(TerminalRing::new(
8679            TerminalRingConfig::default(),
8680            0,
8681        )));
8682
8683        record_wait_error_terminal("wait-error", &ring, &feed);
8684        feed.emit_spawned("after-wait-error", 42, 2);
8685
8686        let state = feed.0.lock().unwrap();
8687        let sequences = state
8688            .events
8689            .iter()
8690            .map(|event| event.cursor.seq)
8691            .collect::<Vec<_>>();
8692        assert_eq!(sequences, vec![1, 2, 3]);
8693        assert_eq!(state.events[1].kind, SpawnEventKind::Exited);
8694        assert_eq!(state.events[1].exit_code, None);
8695        assert_eq!(state.events[1].exit_signal, None);
8696    }
8697
8698    /// Pins the report's `kind` too: the wait-error arm treats an unwaitable child
8699    /// as a crash (matching `fail_snapshot`'s `Failed` disposition for this arm),
8700    /// not a clean exit it never actually observed.
8701    #[test]
8702    fn wait_error_exit_report_is_classified_as_a_crash() {
8703        assert_eq!(wait_error_exit_report().kind, ExitKind::Crash);
8704    }
8705}
8706
8707#[cfg(test)]
8708mod health_evidence_tests {
8709    use super::{HealthProbeError, HealthProbeEvidence};
8710    use std::collections::HashSet;
8711
8712    /// The evidential asymmetry, asserted rather than described.
8713    ///
8714    /// Exactly ONE observation is proof a module cannot serve, and the one that
8715    /// fires under CPU starvation is not it. Before the split, all fifteen
8716    /// construction sites collapsed into a single String, so a timeout carried the
8717    /// same weight as a dead lane -- which is how a healthy module was restarted
8718    /// three times in one day.
8719    #[test]
8720    fn only_a_dead_lane_is_proof_of_death() {
8721        assert!(HealthProbeError::lane_dead("gone").is_proof_of_death());
8722        // Three non-proof classes, each for a different reason: silence is
8723        // consistent with health, a bad answer proves the module ALIVE, and a
8724        // daemon-side fault never reached the module at all.
8725        assert!(!HealthProbeError::no_answer("timed out").is_proof_of_death());
8726        assert!(!HealthProbeError::bad_answer("garbage").is_proof_of_death());
8727        assert!(!HealthProbeError::misconfigured("no table").is_proof_of_death());
8728    }
8729
8730    /// Labels must be distinct, or the operator-facing distinction is cosmetic.
8731    ///
8732    /// A shared label renders two different observations identically in the line an
8733    /// operator reads after an unexplained restart -- the exact confusion this
8734    /// change removes.
8735    #[test]
8736    fn every_evidence_class_has_a_distinct_label() {
8737        let labels = [
8738            HealthProbeError::lane_dead("").label(),
8739            HealthProbeError::no_answer("").label(),
8740            HealthProbeError::bad_answer("").label(),
8741            HealthProbeError::misconfigured("").label(),
8742        ];
8743        let unique: HashSet<_> = labels.iter().collect();
8744        assert_eq!(unique.len(), labels.len(), "labels collided: {labels:?}");
8745    }
8746
8747    /// The class is additional information, not a replacement.
8748    ///
8749    /// An operator needs both "this was silence" and the specific text saying how
8750    /// long we waited; a classification that swallowed the message would trade one
8751    /// missing distinction for another.
8752    #[test]
8753    fn classification_preserves_the_original_message() {
8754        let err = HealthProbeError::no_answer("module did not answer within 5s");
8755        assert_eq!(err.to_string(), "module did not answer within 5s");
8756        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
8757    }
8758}
8759
8760#[cfg(test)]
8761mod health_tombstone_tests {
8762    use std::{path::PathBuf, sync::Arc, time::Duration};
8763
8764    use subc_protocol::{
8765        manifest::Concurrency,
8766        session::{HealthStatus, ModuleControlResponse},
8767    };
8768    use tokio::sync::mpsc;
8769
8770    use super::{
8771        probe_module_health, HealthAction, HealthConfig, HealthProbeEvidence, ModuleProtocol,
8772        ModuleSpec, RestartPolicy, Supervisor, SupervisorRuntimeConfig,
8773    };
8774    use crate::{
8775        control::ControlHandler,
8776        forwarding::{ForwardingTable, ModuleControlRpcCompletion, ModuleControlRpcOutcome},
8777        registry::{ConnectionId, Registry},
8778        router::FrameSink,
8779    };
8780
8781    struct ProbeHarness {
8782        spec: ModuleSpec,
8783        runtime: SupervisorRuntimeConfig,
8784        forwarding: Arc<ForwardingTable>,
8785        module_connection: ConnectionId,
8786        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
8787        handler: ControlHandler,
8788        module: super::SupervisedModule,
8789    }
8790
8791    fn probe_harness() -> ProbeHarness {
8792        let registry = Arc::new(Registry::default());
8793        let forwarding = Arc::new(ForwardingTable::default());
8794        let supervisor_handle = super::SupervisorHandle::new();
8795        let health = HealthConfig {
8796            cadence: Duration::from_secs(30),
8797            deadline: Duration::from_secs(5),
8798            failure_threshold: 3,
8799            on_degraded: HealthAction::Report,
8800            on_failing: HealthAction::Report,
8801            critical: false,
8802        };
8803        let supervisor = Supervisor::new(Arc::clone(&registry), RestartPolicy::default())
8804            .with_forwarding(Arc::clone(&forwarding))
8805            .with_handle(supervisor_handle.clone())
8806            .with_health_config(health);
8807        let spec = ModuleSpec {
8808            module_id: "late-health-module".to_string(),
8809            program: PathBuf::from("disabled-module"),
8810            args: Vec::new(),
8811            env: Vec::new(),
8812            reserved: false,
8813            reserved_prefixes: Vec::new(),
8814            protocol: ModuleProtocol::Subc,
8815            overlap: Default::default(),
8816        };
8817        let module = supervisor
8818            .supervise_configured(spec.clone(), false)
8819            .unwrap();
8820        let runtime = supervisor.runtime_config();
8821        let handler = ControlHandler::with_forwarding(registry, Arc::clone(&forwarding))
8822            .with_supervisor(supervisor_handle);
8823        let module_connection = ConnectionId::new(700);
8824        let (module_tx, module_rx) = mpsc::channel(8);
8825        forwarding
8826            .register_module_connection(
8827                module_connection,
8828                spec.module_id.clone(),
8829                subc_protocol::PROTOCOL_VERSION,
8830                Concurrency::ModuleManaged,
8831                FrameSink::new(module_tx),
8832            )
8833            .unwrap();
8834
8835        ProbeHarness {
8836            spec,
8837            runtime,
8838            forwarding,
8839            module_connection,
8840            module_rx,
8841            handler,
8842            module,
8843        }
8844    }
8845
8846    async fn finish_after(
8847        harness: &mut ProbeHarness,
8848        stall: Duration,
8849    ) -> ModuleControlRpcCompletion {
8850        assert!(stall > harness.runtime.health.deadline);
8851        let deadline = harness.runtime.health.deadline;
8852        let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
8853        let answer = async {
8854            let frame = harness.module_rx.recv().await.expect("health.check frame");
8855            tokio::time::advance(deadline).await;
8856            tokio::task::yield_now().await;
8857            tokio::time::advance(stall - deadline).await;
8858            harness
8859                .forwarding
8860                .complete_module_control_rpc(
8861                    harness.module_connection,
8862                    frame.header.corr,
8863                    Some("health.check"),
8864                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
8865                        status: HealthStatus::Ok,
8866                        detail: None,
8867                        metrics: None,
8868                    }),
8869                )
8870                .unwrap()
8871        };
8872        let (probe_result, completion) = tokio::join!(probe, answer);
8873        let err = probe_result.expect_err("probe must miss its deadline");
8874        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
8875        completion
8876    }
8877
8878    async fn time_out_without_answer(harness: &mut ProbeHarness) {
8879        let deadline = harness.runtime.health.deadline;
8880        let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
8881        let exhaust_deadline = async {
8882            let _frame = harness.module_rx.recv().await.expect("health.check frame");
8883            tokio::time::advance(deadline).await;
8884            tokio::task::yield_now().await;
8885        };
8886        let (probe_result, ()) = tokio::join!(probe, exhaust_deadline);
8887        let err = probe_result.expect_err("probe must miss its deadline");
8888        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
8889    }
8890
8891    #[tokio::test(start_paused = true)]
8892    async fn late_health_answers_record_start_anchored_latency_for_two_stalls() {
8893        let mut harness = probe_harness();
8894
8895        let first = finish_after(&mut harness, Duration::from_secs(8)).await;
8896        let first_latency = match &first {
8897            ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
8898            other => panic!("late answer was not retained: {other:?}"),
8899        };
8900        assert!(harness.handler.observe_module_control_completion(first));
8901
8902        let second = finish_after(&mut harness, Duration::from_secs(11)).await;
8903        let second_latency = match &second {
8904            ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
8905            other => panic!("late answer was not retained: {other:?}"),
8906        };
8907        assert!(harness.handler.observe_module_control_completion(second));
8908
8909        assert_eq!(first_latency, Duration::from_secs(8));
8910        assert_eq!(
8911            second_latency - first_latency,
8912            Duration::from_secs(3),
8913            "latency must grow linearly with the additional stall"
8914        );
8915        let health = harness.module.status().unwrap().health;
8916        assert_eq!(health.late_answer_count, 2);
8917        assert_eq!(health.last_late_answer_latency_ms, Some(11_000));
8918    }
8919
8920    /// A module that answers every probe late must never march to the kill
8921    /// threshold: the late answer proves it is alive, so it must clear the miss
8922    /// streak the timeout recorded. Without the reset, a CPU-starved module
8923    /// that serves every probe seconds past the deadline accumulates
8924    /// `consecutive_failures` to the threshold and is killed — the exact
8925    /// sequence from the 2026-08-14 aft disable, where the daemon logged
8926    /// "proves the module is alive" five times while counting five misses.
8927    #[tokio::test(start_paused = true)]
8928    async fn late_answer_clears_the_consecutive_failure_streak() {
8929        let mut harness = probe_harness();
8930
8931        // Timeout recorded first: the probe path saw no answer in time.
8932        time_out_without_answer(&mut harness).await;
8933        harness
8934            .module
8935            .record_health_probe_failure_for_test("[no-answer] test miss")
8936            .unwrap();
8937        assert_eq!(
8938            harness.module.status().unwrap().health.consecutive_failures,
8939            1,
8940            "precondition: the miss must be on the streak before the late answer"
8941        );
8942
8943        // The stalled reply then lands: proof of life.
8944        let late = finish_after(&mut harness, Duration::from_secs(9)).await;
8945        assert!(matches!(
8946            late,
8947            ModuleControlRpcCompletion::LateHealthAnswer { .. }
8948        ));
8949        assert!(harness.handler.observe_module_control_completion(late));
8950
8951        let health = harness.module.status().unwrap().health;
8952        assert_eq!(
8953            health.consecutive_failures, 0,
8954            "a late answer is an answer: the streak must reset"
8955        );
8956        assert_eq!(health.late_answer_count, 1);
8957    }
8958
8959    #[tokio::test(start_paused = true)]
8960    async fn repeated_serial_probe_cycles_keep_one_tombstone_per_endpoint() {
8961        let mut harness = probe_harness();
8962
8963        for _ in 0..20 {
8964            time_out_without_answer(&mut harness).await;
8965            assert_eq!(
8966                harness.forwarding.health_probe_tombstone_count().unwrap(),
8967                1
8968            );
8969        }
8970    }
8971}
8972
8973#[cfg(test)]
8974mod child_env_tests {
8975    use super::{
8976        apply_child_env, apply_spawn_role, apply_wire_spawn_args, ModuleProtocol, ModuleSpec,
8977        SpawnRole, SupervisorHandle, SPAWN_ROLE_SWAP_CANDIDATE, SUBC_ARG, SUBC_LAUNCH_NONCE_ENV,
8978        SUBC_MODULE_ID_ENV, SUBC_SPAWN_ROLE_ENV,
8979    };
8980    use std::{ffi::OsStr, path::PathBuf};
8981    use tokio::process::Command;
8982
8983    fn spec(env: Vec<(String, String)>) -> ModuleSpec {
8984        ModuleSpec {
8985            module_id: "env-plan".to_string(),
8986            program: PathBuf::from("/nonexistent"),
8987            args: Vec::new(),
8988            env,
8989            reserved: false,
8990            reserved_prefixes: Vec::new(),
8991            protocol: ModuleProtocol::Subc,
8992            overlap: Default::default(),
8993        }
8994    }
8995
8996    /// Ambient `CK_LOG` is REMOVED for an unconfigured module, and a configured
8997    /// one still gets its own.
8998    ///
8999    /// This is the narrow goal `env_clear()` was reached for, and the reason the
9000    /// fix is `env_remove` rather than deleting the line: an operator's ambient
9001    /// filter silently becoming an unconfigured module's log level is a real
9002    /// defect, just a much smaller one than clearing the environment.
9003    ///
9004    /// Asserted on the command plan rather than a spawned child because proving
9005    /// the ABSENCE of an inherited variable needs the parent's environment
9006    /// mutated, and `forbid(unsafe_code)` refuses that. `get_envs()` reports a
9007    /// removal as `(key, None)`, which is exactly the distinction wanted: not
9008    /// "absent because nobody set it" but "explicitly unset for the child".
9009    #[test]
9010    fn ambient_ck_log_is_removed_and_a_configured_one_survives() {
9011        let mut command = Command::new("/nonexistent");
9012        apply_child_env(&mut command, &spec(Vec::new()));
9013        let removed = command
9014            .as_std()
9015            .get_envs()
9016            .any(|(key, value)| key == OsStr::new("CK_LOG") && value.is_none());
9017        assert!(
9018            removed,
9019            "ambient CK_LOG must be explicitly removed for an unconfigured module"
9020        );
9021
9022        let mut configured = Command::new("/nonexistent");
9023        apply_child_env(
9024            &mut configured,
9025            &spec(vec![("CK_LOG".to_string(), "debug".to_string())]),
9026        );
9027        let effective = configured
9028            .as_std()
9029            .get_envs()
9030            .filter(|(key, _)| *key == OsStr::new("CK_LOG"))
9031            .last()
9032            .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
9033        assert_eq!(
9034            effective,
9035            Some(Some("debug".to_string())),
9036            "a module's configured CK_LOG must survive the ambient removal"
9037        );
9038    }
9039
9040    /// A `protocol: "none"` spawn carries NO `--subc` argument and NO launch
9041    /// nonce; a subc-wire spawn carries both. Asserted on the command plan for
9042    /// the same reason as the CK_LOG test above.
9043    ///
9044    /// The argument is the load-bearing half: a stock binary exits on an
9045    /// unknown flag before it listens, so with `--subc` appended the mode
9046    /// could not supervise the one process it exists for. Found by the first
9047    /// conformance run (nats-server: `flag provided but not defined: -subc`).
9048    #[test]
9049    fn protocol_none_spawn_carries_no_subc_argument_and_no_nonce() {
9050        let connection_file = std::path::Path::new("/run/subc-connection.json");
9051        let handle = SupervisorHandle::new();
9052
9053        let mut none_spec = spec(Vec::new());
9054        none_spec.protocol = ModuleProtocol::None;
9055        let mut none = Command::new("/nonexistent");
9056        apply_wire_spawn_args(&mut none, &none_spec, Some(connection_file), Some(&handle))
9057            .expect("protocol-none spawn args apply");
9058        let none_args: Vec<String> = none
9059            .as_std()
9060            .get_args()
9061            .map(|a| a.to_string_lossy().into_owned())
9062            .collect();
9063        assert!(
9064            !none_args.iter().any(|a| a == SUBC_ARG),
9065            "protocol:none argv must not carry --subc; got {none_args:?}"
9066        );
9067        let none_has_nonce = none
9068            .as_std()
9069            .get_envs()
9070            .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some());
9071        assert!(
9072            !none_has_nonce,
9073            "protocol:none spawn must not receive a launch nonce"
9074        );
9075        let none_has_module_id = none
9076            .as_std()
9077            .get_envs()
9078            .any(|(key, value)| key == OsStr::new(SUBC_MODULE_ID_ENV) && value.is_some());
9079        assert!(
9080            none_has_module_id,
9081            "SUBC_MODULE_ID is inert and stays on every path"
9082        );
9083        assert!(
9084            handle.spawn_nonce(&none_spec.module_id).is_none(),
9085            "no nonce record for a process that will never present one"
9086        );
9087
9088        // Control: the subc-wire path is unchanged by the branch above.
9089        let wire_spec = spec(Vec::new());
9090        let mut wire = Command::new("/nonexistent");
9091        apply_wire_spawn_args(&mut wire, &wire_spec, Some(connection_file), Some(&handle))
9092            .expect("subc-wire spawn args apply");
9093        let wire_args: Vec<String> = wire
9094            .as_std()
9095            .get_args()
9096            .map(|a| a.to_string_lossy().into_owned())
9097            .collect();
9098        assert_eq!(
9099            wire_args,
9100            vec![
9101                SUBC_ARG.to_string(),
9102                connection_file.to_string_lossy().into_owned()
9103            ],
9104            "a subc-wire spawn still carries --subc <path>"
9105        );
9106        assert!(wire
9107            .as_std()
9108            .get_envs()
9109            .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()));
9110        assert!(handle.spawn_nonce(&wire_spec.module_id).is_some());
9111    }
9112
9113    /// A plain spawn EXPLICITLY REMOVES the spawn role, even when the module's
9114    /// spec tries to set it; only a swap candidate carries it.
9115    ///
9116    /// "Set it only on candidates" is not enough, because spawn applies the
9117    /// spec's env verbatim and the daemon's own environment is inherited: either
9118    /// could hand a plain restart the swap role, and a module reading it would
9119    /// warm on its long swap budget while callers wait. Asserted as an explicit
9120    /// removal (`(key, None)`), not mere absence, for the reason the `CK_LOG`
9121    /// test above gives.
9122    #[test]
9123    fn plain_spawn_removes_the_spawn_role_even_when_the_spec_sets_it() {
9124        let role = |command: &Command| {
9125            command
9126                .as_std()
9127                .get_envs()
9128                .filter(|(key, _)| *key == OsStr::new(SUBC_SPAWN_ROLE_ENV))
9129                .last()
9130                .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()))
9131        };
9132        let forged = spec(vec![(
9133            SUBC_SPAWN_ROLE_ENV.to_string(),
9134            SPAWN_ROLE_SWAP_CANDIDATE.to_string(),
9135        )]);
9136
9137        let mut plain = Command::new("/nonexistent");
9138        apply_child_env(&mut plain, &forged);
9139        apply_spawn_role(&mut plain, SpawnRole::Plain);
9140        assert_eq!(
9141            role(&plain),
9142            Some(None),
9143            "a plain spawn must remove SUBC_SPAWN_ROLE, whatever the spec says"
9144        );
9145
9146        let mut candidate = Command::new("/nonexistent");
9147        apply_child_env(&mut candidate, &spec(Vec::new()));
9148        apply_spawn_role(&mut candidate, SpawnRole::SwapCandidate);
9149        assert_eq!(
9150            role(&candidate),
9151            Some(Some(SPAWN_ROLE_SWAP_CANDIDATE.to_string()))
9152        );
9153    }
9154
9155    /// Daemon-private capture retention keys never reach the child.
9156    ///
9157    /// cortexkit-log exposes retention as a Rust struct with no environment
9158    /// names, so these entries are supervisor metadata. Passing them through
9159    /// would invent a public child-process contract by accident.
9160    #[test]
9161    fn daemon_private_capture_keys_are_not_passed_to_the_child() {
9162        let mut command = Command::new("/nonexistent");
9163        apply_child_env(
9164            &mut command,
9165            &spec(vec![
9166                (super::CAPTURE_KEEP_ENV.to_string(), "5".to_string()),
9167                ("KEPT".to_string(), "yes".to_string()),
9168            ]),
9169        );
9170        let keys: Vec<String> = command
9171            .as_std()
9172            .get_envs()
9173            .filter(|(_, value)| value.is_some())
9174            .map(|(key, _)| key.to_string_lossy().into_owned())
9175            .collect();
9176        assert!(keys.contains(&"KEPT".to_string()), "got {keys:?}");
9177        assert!(
9178            !keys.contains(&super::CAPTURE_KEEP_ENV.to_string()),
9179            "daemon-private capture key leaked to the child: {keys:?}"
9180        );
9181    }
9182}
9183
9184#[cfg(test)]
9185mod jitter_tests {
9186    use super::jittered_health_delay;
9187    use std::{collections::HashSet, time::Duration};
9188
9189    /// Module ids drawn from a real fleet, so the dispersal claim is about names
9190    /// that actually occur rather than invented ones.
9191    ///
9192    /// This is a SAMPLE, not a registry: the property under test is that distinct
9193    /// ids disperse, which holds for any set of distinct strings. Several entries
9194    /// are already historical (modules get renamed), and that costs nothing here --
9195    /// but it means a reader must not mistake this for the live module set, and a
9196    /// rename sweep will match it without there being anything to change.
9197    const FLEET: [&str; 14] = [
9198        "aft",
9199        "alfonso-core",
9200        "magic-context",
9201        "broca",
9202        "thalamus",
9203        "quota",
9204        "engram",
9205        "plexus",
9206        "cerebellum",
9207        "astrocyte",
9208        "synapse",
9209        "subc-mcp",
9210        "cortexkit-credentials",
9211        "subc-federation",
9212    ];
9213
9214    /// Probes must not converge after a fleet-wide restart.
9215    ///
9216    /// This is the property the jitter exists for: every module reconnects at
9217    /// once, and without dispersal all fourteen would then probe on the same
9218    /// tick forever. Nothing failed visibly when this went untested -- a
9219    /// convergent fleet still probes correctly, just in a burst, so the symptom
9220    /// is a periodic load spike that looks like whatever else is running.
9221    #[test]
9222    fn probe_delays_disperse_across_the_fleet() {
9223        let cadence = Duration::from_secs(30);
9224        let delays: HashSet<Duration> = FLEET
9225            .iter()
9226            .map(|id| jittered_health_delay(id, 0, cadence))
9227            .collect();
9228        assert_eq!(
9229            delays.len(),
9230            FLEET.len(),
9231            "every supervised module must land on its own probe offset"
9232        );
9233    }
9234
9235    /// The offset may only ever DELAY a probe, never bring it forward.
9236    ///
9237    /// A delay below the cadence would probe a module more often than
9238    /// configured, which is the opposite of what an operator asked for and
9239    /// would tighten the failure budget without anyone changing it.
9240    #[test]
9241    fn jitter_only_delays_and_stays_within_one_tenth_of_cadence() {
9242        let cadence = Duration::from_secs(30);
9243        let span = cadence / 10;
9244        for id in FLEET {
9245            for probe_index in 0..8 {
9246                let delay = jittered_health_delay(id, probe_index, cadence);
9247                assert!(
9248                    delay >= cadence,
9249                    "{id}#{probe_index}: jitter must not shorten the cadence"
9250                );
9251                assert!(
9252                    delay < cadence + span,
9253                    "{id}#{probe_index}: jitter must stay inside one tenth of the cadence"
9254                );
9255            }
9256        }
9257    }
9258
9259    /// A module keeps its offset across daemon restarts.
9260    ///
9261    /// The delay is derived rather than randomised precisely so a restart does
9262    /// not re-roll every module into a fresh chance of collision. A random
9263    /// source would satisfy the dispersal test above and quietly lose this.
9264    #[test]
9265    fn a_module_offset_is_stable_across_restarts() {
9266        let cadence = Duration::from_secs(30);
9267        for id in FLEET {
9268            assert_eq!(
9269                jittered_health_delay(id, 0, cadence),
9270                jittered_health_delay(id, 0, cadence),
9271                "{id}: the same module and probe index must produce the same offset"
9272            );
9273        }
9274    }
9275
9276    /// A zero cadence disables probing rather than producing a busy loop.
9277    #[test]
9278    fn zero_cadence_yields_zero_delay() {
9279        assert_eq!(
9280            jittered_health_delay("aft", 0, Duration::ZERO),
9281            Duration::ZERO
9282        );
9283    }
9284}
9285
9286#[cfg(all(test, target_os = "linux"))]
9287mod cgroup_placement_tests {
9288    use super::{
9289        apply_cgroup_placement, remove_module_cgroup, ModuleProtocol, ModuleSpec, SuperviseError,
9290        SupervisedChild,
9291    };
9292    use crate::stderr_tail::{StderrRing, StderrTailConfig};
9293    use std::{
9294        fs, io,
9295        path::{Path, PathBuf},
9296        sync::{Arc, Mutex},
9297    };
9298    use subc_test_support::TestTempDir;
9299    use tokio::process::Command;
9300
9301    #[test]
9302    fn failed_parent_cgroup_open_is_a_cgroup_supervision_error() {
9303        let path = Path::new("/definitely-missing-subc-cgroup");
9304        let mut command = Command::new("true");
9305        let error = apply_cgroup_placement(
9306            &mut command,
9307            &ModuleSpec {
9308                module_id: "broken-cgroup".to_string(),
9309                program: PathBuf::from("true"),
9310                args: Vec::new(),
9311                env: Vec::new(),
9312                reserved: false,
9313                reserved_prefixes: Vec::new(),
9314                protocol: ModuleProtocol::Subc,
9315                overlap: Default::default(),
9316            },
9317            path,
9318        )
9319        .expect_err("a parent cgroup open failure must reject the supervised spawn");
9320        let reason = error.to_string();
9321
9322        assert!(
9323            matches!(error, SuperviseError::Cgroup { .. }),
9324            "parent cgroup open must be reported as a cgroup supervision error: {reason}"
9325        );
9326        assert!(
9327            reason.contains("/definitely-missing-subc-cgroup/cgroup.procs"),
9328            "parent cgroup open failure must name cgroup.procs: {reason}"
9329        );
9330    }
9331
9332    #[tokio::test]
9333    async fn reaping_a_child_removes_its_empty_module_cgroup() {
9334        let root = TestTempDir::new("supervisor-reap-cgroup");
9335        fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
9336        let placement = subc_cgroup::prepare_at(&root)
9337            .expect("prepare scratch cgroup root")
9338            .expect("scratch root has a cgroup.procs marker");
9339        let module_id = "reaped-module";
9340        let module = placement
9341            .module_path(module_id)
9342            .expect("create scratch module cgroup");
9343        let child = Command::new("true")
9344            .spawn()
9345            .expect("spawn short-lived child");
9346        let pid = child.id().expect("spawned child has pid");
9347        let mut child = SupervisedChild {
9348            child,
9349            module_id: module_id.to_string(),
9350            cgroup_placement: Some(placement),
9351            stdout_pump: None,
9352            stderr_pump: None,
9353            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
9354            spawned_at_ms: 0,
9355            spawned_from: PathBuf::from("true"),
9356            spawned_file_identity: None,
9357            process_start_time: None,
9358            process_identity: None,
9359            pid,
9360            roster_guard: None,
9361        };
9362
9363        child.wait().await.expect("reap short-lived child");
9364
9365        assert!(
9366            !module.exists(),
9367            "reaping the supervised child must remove its empty cgroup"
9368        );
9369    }
9370
9371    #[test]
9372    fn non_empty_cgroup_removal_is_reported_without_blocking_teardown() {
9373        let root = TestTempDir::new("supervisor-non-empty-cgroup");
9374        fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
9375        let placement = subc_cgroup::prepare_at(&root)
9376            .expect("prepare scratch cgroup root")
9377            .expect("scratch root has a cgroup.procs marker");
9378        let module = placement
9379            .module_path("surviving-module")
9380            .expect("create scratch module cgroup");
9381        fs::write(module.join("surviving-process"), b"still present")
9382            .expect("make scratch cgroup non-empty");
9383        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
9384
9385        remove_module_cgroup(&placement, "surviving-module");
9386
9387        let logs = crate::router::test_log::captured_logs(&logs);
9388        assert!(
9389            module.exists(),
9390            "failed removal must leave the cgroup intact"
9391        );
9392        assert!(
9393            logs.contains("could not remove module cgroup after process exit; continuing teardown")
9394                && logs.contains("surviving-module"),
9395            "best-effort removal must report the failure without returning it: {logs}"
9396        );
9397    }
9398
9399    #[test]
9400    fn cgroup_pre_exec_spawn_failure_names_the_cgroup_path() {
9401        let cgroup_path = PathBuf::from("/sys/fs/cgroup/subc-modules/broken-module");
9402        let reason = SuperviseError::Spawn {
9403            program: PathBuf::from("/bin/true"),
9404            source: io::Error::from_raw_os_error(13),
9405            cgroup_path: Some(cgroup_path.clone()),
9406        }
9407        .to_string();
9408
9409        assert!(
9410            reason.contains(&cgroup_path.display().to_string()),
9411            "a pre_exec spawn failure must name the cgroup path: {reason}"
9412        );
9413    }
9414}
9415
9416#[cfg(test)]
9417mod spawn_subscriber_lag_tests {
9418    use super::*;
9419
9420    /// A subscriber whose connection stops draining is dropped once its frame
9421    /// channel fills. The client must learn that from a terminal Error frame
9422    /// after the frames already queued for it, not from a stream that simply
9423    /// goes quiet.
9424    #[tokio::test]
9425    async fn lagged_spawn_subscriber_receives_a_terminal_lagged_error_after_its_queued_frames() {
9426        let feed = SpawnEventFeed::default();
9427        feed.configure_incarnation("lag-incarnation".to_string());
9428        // A one-slot connection queue that nobody reads until the emits are
9429        // done: the forwarder parks on it and the subscriber channel fills.
9430        let (tx, mut rx) = mpsc::channel(1);
9431        feed.subscribe(ConnectionId::new(1), 7, 1, None, FrameSink::new(tx))
9432            .expect("subscribe");
9433        let emitted = SPAWN_SUBSCRIBER_BUFFER + 16;
9434        for index in 0..emitted {
9435            feed.emit_spawned(&format!("lag-module-{index}"), 1000, 0);
9436            // Let the forwarder take what it can so the fill point is the
9437            // subscriber channel, not a scheduling accident.
9438            tokio::task::yield_now().await;
9439        }
9440        assert_eq!(
9441            feed.subscriber_count(),
9442            0,
9443            "the lagged subscriber must be removed"
9444        );
9445
9446        let mut data = Vec::new();
9447        let mut last = None;
9448        loop {
9449            let next = tokio::time::timeout(Duration::from_secs(5), rx.recv())
9450                .await
9451                .expect("the forwarder must finish once the subscriber is dropped");
9452            let Some(outbound) = next else { break };
9453            let frame = outbound.frame;
9454            if frame.header.ty == FrameType::StreamData {
9455                assert!(last.is_none(), "no data may follow the terminal frame");
9456                let event: SpawnEvent = serde_json::from_slice(&frame.body).unwrap();
9457                data.push(event.cursor.seq);
9458            } else {
9459                assert!(last.is_none(), "exactly one terminal frame");
9460                last = Some(frame);
9461            }
9462        }
9463        assert!(!data.is_empty(), "queued frames drain before the terminal");
9464        for pair in data.windows(2) {
9465            assert_eq!(
9466                pair[1],
9467                pair[0] + 1,
9468                "queued frames arrive dense and in order"
9469            );
9470        }
9471        let terminal = last.expect("a lagged subscriber must receive a terminal frame");
9472        assert_eq!(terminal.header.ty, FrameType::Error);
9473        assert_eq!(terminal.header.corr, 7);
9474        let body: subc_protocol::ErrorBody = serde_json::from_slice(&terminal.body).unwrap();
9475        assert_eq!(body.code, SPAWN_SUBSCRIBER_LAGGED_CODE);
9476        let detail = body.detail.expect("lagged error carries detail");
9477        assert_eq!(
9478            detail["first_undelivered_cursor"]["seq"],
9479            data.last().unwrap() + 1,
9480            "the named cursor is the first event the subscriber did not receive"
9481        );
9482        assert_eq!(
9483            detail["first_undelivered_cursor"]["daemon_incarnation"],
9484            "lag-incarnation"
9485        );
9486    }
9487}
9488
9489#[cfg(test)]
9490mod terminal_history_read_concurrency_tests {
9491    use super::*;
9492    use crate::terminal_journal::read_pause;
9493    use std::sync::mpsc as std_mpsc;
9494    use subc_test_support::TestTempDir;
9495
9496    fn journaled_ring(
9497        journal: &Arc<crate::terminal_journal::TerminalJournal>,
9498    ) -> Arc<Mutex<TerminalRing>> {
9499        Arc::new(Mutex::new(
9500            TerminalRing::new(TerminalRingConfig::default(), 1)
9501                .with_journal(Some(Arc::clone(journal))),
9502        ))
9503    }
9504
9505    fn crash(at_ms: u64) -> ExitReport {
9506        ExitReport {
9507            kind: ExitKind::Crash,
9508            code: Some(1),
9509            signal: None,
9510            at_ms,
9511        }
9512    }
9513
9514    /// Record an exit on another thread and report whether it finished within
9515    /// `bound`. The recorder thread is left running if it did not.
9516    fn record_within(
9517        module_id: &'static str,
9518        ring: &Arc<Mutex<TerminalRing>>,
9519        at_ms: u64,
9520        bound: Duration,
9521    ) -> bool {
9522        let ring = Arc::clone(ring);
9523        let (done, done_rx) = std_mpsc::channel();
9524        std::thread::spawn(move || {
9525            record_terminal(
9526                module_id,
9527                &ring,
9528                &SpawnEventFeed::default(),
9529                &crash(at_ms),
9530                TerminalDisposition::Restarting,
9531            );
9532            let _ = done.send(());
9533        });
9534        done_rx.recv_timeout(bound).is_ok()
9535    }
9536
9537    /// A history read in progress must not hold the journal writer (which every
9538    /// module's exit recording needs) or the module's own ring. Exits recorded
9539    /// while the read is paused complete promptly; the paused read answers as of
9540    /// the moment it started, and the next read has each exit exactly once.
9541    #[test]
9542    fn exits_recorded_during_a_paused_history_read_are_not_blocked_or_half_merged() {
9543        let dir = TestTempDir::new("terminal-history-concurrent-read");
9544        let path = dir.join("terminals.jsonl");
9545        let journal = Arc::new(crate::terminal_journal::TerminalJournal::open(
9546            path.clone(),
9547            "daemon".into(),
9548        ));
9549        let reader_ring = journaled_ring(&journal);
9550        let other_ring = journaled_ring(&journal);
9551        assert!(record_within(
9552            "reader-module",
9553            &reader_ring,
9554            10,
9555            Duration::from_secs(5)
9556        ));
9557
9558        let (started, release) = read_pause::install(&path);
9559        let reading = {
9560            let ring = Arc::clone(&reader_ring);
9561            std::thread::spawn(move || durable_terminal_history_of(&ring, "reader-module"))
9562        };
9563        started
9564            .recv_timeout(Duration::from_secs(5))
9565            .expect("the history read reached its pause");
9566
9567        let bound = Duration::from_secs(1);
9568        assert!(
9569            record_within("other-module", &other_ring, 20, bound),
9570            "another module's exit waited on a history read (journal writer held)"
9571        );
9572        assert!(
9573            record_within("reader-module", &reader_ring, 30, bound),
9574            "the read module's own exit waited on its history read (ring held)"
9575        );
9576
9577        drop(release);
9578        let paused = reading.join().unwrap();
9579        assert_eq!(
9580            paused.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
9581            vec![10],
9582            "an exit recorded after the read began lands in neither half of it"
9583        );
9584        assert_eq!(paused.journal_skipped_lines, 0);
9585        assert_eq!(paused.journal_read_errors, 0);
9586
9587        let after = durable_terminal_history_of(&reader_ring, "reader-module");
9588        assert_eq!(
9589            after.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
9590            vec![10, 30],
9591            "the next read merges ring and journal with no duplicate"
9592        );
9593        assert_eq!(after.journal_skipped_lines, 0);
9594    }
9595}
9596
9597/// What a restart does with the exited process's stderr reader. These drive
9598/// the same `settle_stderr_pump` the supervisor calls, with a reader the test
9599/// holds, so a reader that has not been scheduled by the bound is a controlled
9600/// input rather than something only a loaded machine produces.
9601#[cfg(test)]
9602mod stderr_settle_tests {
9603    use std::{
9604        future::Future,
9605        io,
9606        pin::Pin,
9607        sync::{Arc, Mutex},
9608        task::{Context, Poll},
9609        time::Duration,
9610    };
9611
9612    use tokio::{
9613        io::{AsyncRead, ReadBuf},
9614        sync::oneshot,
9615        time::Instant,
9616    };
9617
9618    use super::{settle_stderr_pump, StderrPump};
9619    use crate::stderr_tail::{
9620        pump_stderr_to, CaptureState, OutputSink, StderrRing, StderrTailConfig, TailEntry,
9621    };
9622
9623    const BOUND: Duration = Duration::from_millis(250);
9624
9625    /// Yields `before`, then stays pending until the gate is released, then
9626    /// yields `after` and reaches EOF. The bytes after the gate were written
9627    /// by a process that has already exited; only the reader is behind.
9628    struct HeldReader {
9629        before: Option<Vec<u8>>,
9630        gate: Option<oneshot::Receiver<()>>,
9631        after: io::Cursor<Vec<u8>>,
9632    }
9633
9634    impl AsyncRead for HeldReader {
9635        fn poll_read(
9636            mut self: Pin<&mut Self>,
9637            cx: &mut Context<'_>,
9638            buf: &mut ReadBuf<'_>,
9639        ) -> Poll<io::Result<()>> {
9640            if let Some(bytes) = self.before.take() {
9641                buf.put_slice(&bytes);
9642                return Poll::Ready(Ok(()));
9643            }
9644            if let Some(gate) = self.gate.as_mut() {
9645                match Pin::new(gate).poll(cx) {
9646                    Poll::Pending => return Poll::Pending,
9647                    Poll::Ready(_) => self.gate = None,
9648                }
9649            }
9650            Pin::new(&mut self.after).poll_read(cx, buf)
9651        }
9652    }
9653
9654    struct DiscardSink;
9655
9656    impl OutputSink for DiscardSink {
9657        fn write_line(&mut self, _line: &[u8]) {}
9658    }
9659
9660    fn line(text: &str) -> TailEntry {
9661        TailEntry::Line {
9662            text: text.to_string(),
9663            truncated: false,
9664        }
9665    }
9666
9667    fn lock(ring: &Arc<Mutex<StderrRing>>) -> std::sync::MutexGuard<'_, StderrRing> {
9668        ring.lock().unwrap()
9669    }
9670
9671    /// Start a reader for a new process generation that delivers `before`
9672    /// immediately and `after` only once the returned sender fires (or is
9673    /// dropped).
9674    fn held_pump(
9675        ring: &Arc<Mutex<StderrRing>>,
9676        before: &str,
9677        after: &str,
9678    ) -> (StderrPump, oneshot::Sender<()>) {
9679        let generation = lock(ring).begin_process();
9680        let (release, gate) = oneshot::channel();
9681        let reader = HeldReader {
9682            before: Some(before.as_bytes().to_vec()),
9683            gate: Some(gate),
9684            after: io::Cursor::new(after.as_bytes().to_vec()),
9685        };
9686        let task = tokio::spawn(pump_stderr_to(
9687            reader,
9688            Arc::clone(ring),
9689            generation,
9690            DiscardSink,
9691        ));
9692        (StderrPump { task, generation }, release)
9693    }
9694
9695    async fn wait_until(ring: &Arc<Mutex<StderrRing>>, done: impl Fn(&StderrRing) -> bool) {
9696        for _ in 0..1000 {
9697            if done(&lock(ring)) {
9698                return;
9699            }
9700            tokio::time::sleep(Duration::from_millis(1)).await;
9701        }
9702        panic!(
9703            "ring never reached the expected state: {:?}",
9704            lock(ring).snapshot(None, None)
9705        );
9706    }
9707
9708    #[tokio::test(start_paused = true)]
9709    async fn a_crash_line_the_reader_had_not_reached_by_the_bound_is_kept_before_the_restart() {
9710        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
9711        let (pump, release) = held_pump(&ring, "booting\n", "config error: missing storage\n");
9712
9713        settle_stderr_pump("crasher", &ring, pump, BOUND).await;
9714        let before_release = lock(&ring).snapshot(None, None);
9715        assert!(
9716            matches!(before_release.capture, CaptureState::Incomplete { .. }),
9717            "a reader that has not reached EOF cannot claim a whole tail: {before_release:?}"
9718        );
9719
9720        // The restart: the next process starts and writes before the old
9721        // reader catches up.
9722        let next = lock(&ring).begin_process();
9723        lock(&ring).push_line_from(next, "next process booting");
9724        release.send(()).unwrap();
9725        wait_until(&ring, |ring| {
9726            ring.snapshot(None, None).capture == CaptureState::Captured
9727        })
9728        .await;
9729
9730        assert_eq!(
9731            lock(&ring).snapshot(None, None).entries,
9732            vec![
9733                line("booting"),
9734                line("config error: missing storage"),
9735                TailEntry::ProcessStart,
9736                line("next process booting"),
9737            ],
9738            "the crash's last line must survive a slow reader and stay in the crashed process's section"
9739        );
9740    }
9741
9742    #[tokio::test(start_paused = true)]
9743    async fn a_pipe_held_open_by_a_descendant_reads_incomplete_without_delaying_the_restart_past_the_bound(
9744    ) {
9745        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
9746        // `_held` is never fired: a descendant keeps the pipe open for the
9747        // whole test.
9748        let (pump, _held) = held_pump(&ring, "parent exiting\n", "");
9749
9750        let started = Instant::now();
9751        settle_stderr_pump("orphaning", &ring, pump, BOUND).await;
9752        assert_eq!(
9753            started.elapsed(),
9754            BOUND,
9755            "the restart must wait exactly the bound for a pipe that stays open, no longer"
9756        );
9757
9758        let next = lock(&ring).begin_process();
9759        lock(&ring).push_line_from(next, "next process booting");
9760        tokio::time::sleep(Duration::from_secs(60)).await;
9761
9762        let snapshot = lock(&ring).snapshot(None, None);
9763        match &snapshot.capture {
9764            CaptureState::Incomplete { reason } => assert!(
9765                reason.contains("had not reached EOF") && reason.contains("250ms"),
9766                "the reason must say what is missing and after how long: {reason}"
9767            ),
9768            other => panic!("expected Incomplete while the pipe is held open, got {other:?}"),
9769        }
9770        assert_eq!(
9771            snapshot.entries,
9772            vec![
9773                line("parent exiting"),
9774                TailEntry::ProcessStart,
9775                line("next process booting"),
9776            ]
9777        );
9778    }
9779
9780    #[tokio::test(start_paused = true)]
9781    async fn a_reader_that_reaches_eof_within_the_bound_leaves_the_tail_captured() {
9782        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
9783        let (pump, release) = held_pump(&ring, "one\n", "two\n");
9784        release.send(()).unwrap();
9785
9786        settle_stderr_pump("clean", &ring, pump, BOUND).await;
9787
9788        let snapshot = lock(&ring).snapshot(None, None);
9789        assert_eq!(snapshot.capture, CaptureState::Captured);
9790        assert_eq!(snapshot.entries, vec![line("one"), line("two")]);
9791    }
9792}
9793
9794/// Containment of a module's process tree (issue #109).
9795///
9796/// The behaviour these defend against is a module helper surviving its module:
9797/// on a real machine the Synapse embedding module's CUDA worker holds ~2.2 GB of
9798/// VRAM, so a leaked grandchild is a leaked GPU allocation, and a day of restarts
9799/// compounds it.
9800///
9801/// They run against the SUPERVISOR rather than the job-object crate because the
9802/// claim is about teardown: a crate-level test proves a job can reap a tree, not
9803/// that the daemon's drain path reaches it.
9804///
9805/// Windows-only, like the mechanism. On Unix this arm compiles out; the cgroup
9806/// lane there is a separate containment path with its own tests.
9807#[cfg(all(test, windows))]
9808mod job_containment_tests {
9809    use super::*;
9810    use std::{
9811        path::{Path, PathBuf},
9812        sync::{Arc, Mutex},
9813        time::{Duration, Instant},
9814    };
9815    use subc_test_support::TestTempDir;
9816
9817    /// The stub, expected beside this test executable.
9818    ///
9819    /// The existence check is here for the reason its twin at `fake_aft_stub_path`
9820    /// documents: `--lib` does not build `[[bin]]` targets, and a bare spawn
9821    /// failure then reads as a broken test rather than an unbuilt dependency.
9822    fn stub_path() -> PathBuf {
9823        let mut path = std::env::current_exe().expect("current_exe available in tests");
9824        path.pop();
9825        path.pop();
9826        path.push("fake-aft-stub.exe");
9827        assert!(
9828            path.exists(),
9829            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
9830             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
9831            path.display()
9832        );
9833        path
9834    }
9835
9836    /// Poll for the grandchild pid the stub records, and parse it.
9837    fn read_grandchild_pid(path: &Path) -> u32 {
9838        let deadline = Instant::now() + Duration::from_secs(10);
9839        loop {
9840            if let Ok(contents) = std::fs::read_to_string(path) {
9841                if let Ok(pid) = contents.trim().parse() {
9842                    return pid;
9843                }
9844            }
9845            assert!(
9846                Instant::now() < deadline,
9847                "the stub never recorded a grandchild pid at {}",
9848                path.display()
9849            );
9850            std::thread::sleep(Duration::from_millis(10));
9851        }
9852    }
9853
9854    /// Everything one fixture run needs, so the two tests below differ in exactly
9855    /// one place: whether the child is contained.
9856    struct Fixture {
9857        _dir: TestTempDir,
9858        module_id: String,
9859        grandchild: u32,
9860        child: Option<SupervisedChild>,
9861        registry: Arc<Registry>,
9862        snapshot: Arc<Mutex<SupervisorSnapshot>>,
9863        terminal_ring: Arc<Mutex<TerminalRing>>,
9864        spawn_events: SpawnEventFeed,
9865    }
9866
9867    fn fixture(label: &str, module_id: &str) -> Fixture {
9868        let dir = TestTempDir::new(label);
9869        let pid_file = dir.join("grandchild.pid");
9870        let supervisor = Supervisor::new(
9871            Arc::new(Registry::default()),
9872            RestartPolicy::new(3, Duration::ZERO),
9873        );
9874        let runtime = supervisor.runtime_config();
9875        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
9876        let spec = ModuleSpec {
9877            module_id: module_id.to_string(),
9878            program: stub_path(),
9879            // Zero args deliberately: a `--subc` argument would make the stub dial
9880            // a daemon that is not there, and the failure would land in the same
9881            // stderr ring this fixture exists to keep quiet.
9882            args: Vec::new(),
9883            env: vec![
9884                ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
9885                (
9886                    "FAKE_AFT_GRANDCHILD_PID_FILE".to_string(),
9887                    pid_file.display().to_string(),
9888                ),
9889            ],
9890            reserved: false,
9891            reserved_prefixes: Vec::new(),
9892            protocol: ModuleProtocol::Subc,
9893            overlap: Default::default(),
9894        };
9895        let child = spawn_and_mark_running(&spec, &runtime, &snapshot)
9896            .expect("spawn the supervised fixture");
9897        let grandchild = read_grandchild_pid(&pid_file);
9898        Fixture {
9899            _dir: dir,
9900            module_id: module_id.to_string(),
9901            grandchild,
9902            child: Some(child),
9903            registry: Arc::new(Registry::default()),
9904            snapshot,
9905            terminal_ring: Arc::clone(&runtime.terminal_ring),
9906            spawn_events: SpawnEventFeed::default(),
9907        }
9908    }
9909
9910    impl Fixture {
9911        /// Drain through the supervisor's own teardown path.
9912        async fn drain(&mut self) {
9913            let child = self
9914                .child
9915                .take()
9916                .expect("the fixture child is still present");
9917            drain_child_to_state(
9918                &self.module_id,
9919                ModuleProtocol::Subc,
9920                // No forwarding table in this fixture, so nothing reaches the
9921                // child over a connection.
9922                StopNotice::NotSent,
9923                &self.registry,
9924                &self.snapshot,
9925                &self.terminal_ring,
9926                &self.spawn_events,
9927                child,
9928                Duration::from_millis(500),
9929                ModuleState::Stopped,
9930                Some(false),
9931            )
9932            .await
9933            .expect("drain the supervised fixture");
9934        }
9935    }
9936
9937    /// Teardown reaps the grandchild, not merely the direct child.
9938    ///
9939    /// This is the assertion the change exists for. Before containment the
9940    /// grandchild survived: it is a separate process, and `start_kill` is
9941    /// `TerminateProcess` scoped to one pid.
9942    #[tokio::test]
9943    async fn teardown_reaps_the_grandchild() {
9944        let mut fixture = fixture("teardown-grandchild", "tree-teardown");
9945        let grandchild = fixture.grandchild;
9946
9947        assert!(
9948            subc_jobobject::process_exists(grandchild),
9949            "grandchild {grandchild} must be alive before teardown, or this proves nothing"
9950        );
9951
9952        fixture.drain().await;
9953
9954        assert!(
9955            subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
9956            "grandchild {grandchild} outlived module teardown: the tree was not contained"
9957        );
9958    }
9959
9960    /// The mutation control: with containment withheld, the grandchild survives
9961    /// the same kill.
9962    ///
9963    /// This is the defect reproduction from #109 — a direct-child kill reaches
9964    /// one pid, and the grandchild is a different process. It spawns OUTSIDE the
9965    /// supervisor because `spawn_and_mark_running` now always contains on
9966    /// Windows, which is the point: there is no longer a path that spawns
9967    /// uncontained, so the control has to construct one.
9968    ///
9969    /// Its job is to keep `teardown_reaps_the_grandchild` honest. If the
9970    /// grandchild ever dies here, that test is passing for a reason unrelated to
9971    /// the job object and the containment claim is unproven.
9972    #[test]
9973    fn an_uncontained_grandchild_survives_a_direct_child_kill() {
9974        let dir = TestTempDir::new("teardown-uncontained");
9975        let pid_file = dir.join("grandchild.pid");
9976        let mut child = std::process::Command::new(stub_path())
9977            .env("FAKE_AFT_NEVER_CONNECT", "1")
9978            .env(
9979                "FAKE_AFT_GRANDCHILD_PID_FILE",
9980                pid_file.display().to_string(),
9981            )
9982            .stdin(std::process::Stdio::null())
9983            .stdout(std::process::Stdio::null())
9984            .stderr(std::process::Stdio::null())
9985            .spawn()
9986            .expect("spawn the uncontained fixture");
9987        let grandchild = read_grandchild_pid(&pid_file);
9988
9989        // Exactly what the pre-fix teardown did: kill the direct child.
9990        child.kill().expect("kill the direct child");
9991        let _ = child.wait();
9992
9993        assert!(
9994            subc_jobobject::process_exists(grandchild),
9995            "grandchild {grandchild} died with the direct child, so this control no longer \
9996             distinguishes contained from uncontained teardown and the regression test is \
9997             passing vacuously"
9998        );
9999
10000        // The orphan this control demonstrates is the leak the fix prevents, so
10001        // the control must not leave one behind.
10002        kill_tree(grandchild);
10003    }
10004
10005    /// Crash durability: closing the containment handle reaps the tree with no
10006    /// teardown code running at all.
10007    ///
10008    /// This is the case `taskkill /T` cannot cover — a daemon that dies cannot
10009    /// call anything — and it is why containment is a kernel property of the
10010    /// handle rather than a step in the drain. Discovered by getting the
10011    /// mutation control wrong: clearing `job` to "disable" containment instead
10012    /// killed the tree, which is the guarantee, not a mistake.
10013    #[tokio::test]
10014    async fn dropping_containment_reaps_the_grandchild() {
10015        let mut fixture = fixture("drop-containment", "tree-drop");
10016        let grandchild = fixture.grandchild;
10017
10018        assert!(subc_jobobject::process_exists(grandchild));
10019
10020        // No `drain` call, no kill: dropping the handle is the entire mechanism.
10021        fixture.child.as_mut().expect("child present").job = None;
10022
10023        assert!(
10024            subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
10025            "grandchild {grandchild} survived the containment handle closing, so a daemon \
10026             crash would leave the tree behind"
10027        );
10028    }
10029
10030    /// Kill a pid and its tree, then confirm it is gone.
10031    fn kill_tree(pid: u32) {
10032        let _ = std::process::Command::new("taskkill.exe")
10033            .args(["/PID", &pid.to_string(), "/T", "/F"])
10034            .stdin(std::process::Stdio::null())
10035            .stdout(std::process::Stdio::null())
10036            .stderr(std::process::Stdio::null())
10037            .status();
10038        assert!(
10039            subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10)),
10040            "could not clean up grandchild {pid}"
10041        );
10042    }
10043}