Skip to main content

subc_daemon/
supervise.rs

1//! Identity policy updates read the running-protocol snapshot before taking the
2//! nonce locks. Nested identity locks are taken in this order: spawn nonces,
3//! reserved nonces, then `SupervisorHandle::implicit_protocol_none`.
4
5#[cfg(all(test, target_os = "linux"))]
6#[path = "supervise/audit_identity_tests.rs"]
7mod audit_identity_tests;
8mod resource_launch;
9pub(crate) use resource_launch::{ResourceCommitError, ResourceLaunch};
10
11use std::{
12    collections::{HashMap, HashSet, VecDeque},
13    error::Error,
14    fmt, io,
15    path::PathBuf,
16    process::{ExitStatus, Stdio},
17    sync::{Arc, Mutex, OnceLock},
18    time::{Duration, SystemTime, UNIX_EPOCH},
19};
20
21use cortexkit_log::Retention;
22use serde_json::Value;
23use sha2::{Digest, Sha256};
24use subc_control::{
25    ClientControlPush, LiveSpawn, ModuleProtocol, RouteCloseReason, SpawnCursor, SpawnEvent,
26    SpawnEventKind, SpawnSnapshot, SupervisorHealthStatus, TerminalDisposition, TerminalExitKind,
27};
28use subc_protocol::{
29    manifest::{SelfSignalKind, SignalAnchor},
30    session::{
31        HealthReport, HealthStatus, ModuleControlCommand, ModuleControlRequest,
32        MODULE_CONTROL_OP_HEALTH_CHECK,
33    },
34    Flags, FrameType, Principal, Priority, SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV,
35};
36use tokio::{
37    process::{Child, Command},
38    sync::{mpsc, oneshot, watch, Mutex as AsyncMutex},
39    task::JoinHandle,
40    time::{sleep, sleep_until, timeout, timeout_at, Instant},
41};
42use tracing::{debug, error, info, warn};
43
44use crate::{
45    child_roster::ChildRoster,
46    daemon_config::{
47        CAPTURE_KEEP_ENV, CAPTURE_MAX_AGE_DAYS_ENV, CAPTURE_MAX_FILE_MB_ENV, CK_LOG_ENV,
48    },
49    forwarding::{
50        CloseReason, ForwardingError, ForwardingTable, GoodbyeTarget, ModuleControlRpcOutcome,
51        ModuleDrainTarget, PendingModuleControlRpc,
52    },
53    provenance::{ExecutableIdentityProbe, SpawnedFileIdentity},
54    registry::{ConnectionId, RegistrationEndReason, RegistryError},
55    stderr_tail::{
56        pump_stderr_to, pump_stdout_to, ChildOutputSink, StderrRing, StderrTailConfig,
57        StderrTailSnapshot,
58    },
59    terminal_ring::{TerminalHistorySnapshot, TerminalRecord, TerminalRing, TerminalRingConfig},
60    Frame, FrameSink, Registry,
61};
62
63#[cfg(not(windows))]
64use crate::provenance::spawned_file_identity;
65
66#[path = "supervise_swap.rs"]
67mod swap;
68
69#[path = "supervise_activity.rs"]
70mod activity;
71
72#[cfg(unix)]
73#[path = "supervise/admission.rs"]
74mod admission;
75mod admission_exit;
76#[cfg(all(test, target_os = "linux"))]
77mod async_spawn_tests;
78#[cfg(all(test, windows))]
79mod carried_job_tests;
80mod config_delivery;
81mod content_binding;
82mod program_binding;
83mod registration;
84pub(crate) mod script;
85/// Each launch nonce, mapped to its launch's module id and the launch.
86type NonceLaunches = HashMap<String, (String, std::sync::Weak<RegistrationSpawn>)>;
87pub(crate) use registration::NonceAttestation;
88#[cfg(all(test, unix))]
89pub(crate) use registration::RegistrationProof;
90pub(crate) use registration::RegistrationSpawn;
91pub(crate) use registration::REGISTRATION_CHANNEL_CLOSED;
92#[cfg(all(test, unix))]
93pub(crate) mod unix_channel_placement_tests;
94use program_binding::ProgramBindingPublication;
95mod config_exit_failure;
96#[cfg(all(test, any(target_os = "linux", windows)))]
97mod missing_path_tests;
98#[cfg(all(test, unix))]
99mod program_binding_tests;
100#[cfg(all(test, windows))]
101mod program_binding_windows_tests;
102#[cfg(all(test, windows))]
103mod windows_channel_tests;
104pub use config_exit_failure::ModuleStopReason;
105#[cfg(all(test, unix))]
106mod config_exit_hold_tests;
107pub(crate) mod containment;
108#[cfg(all(test, unix))]
109mod containment_tests;
110mod slow_retry;
111use slow_retry::{FailedRetry, FailureContext};
112mod host_health;
113use host_health::HostHealth;
114
115#[cfg(all(test, unix))]
116mod mark_readiness_tests;
117#[cfg(all(test, unix))]
118mod slow_retry_tests;
119
120/// Command-line flag used by supervised modules to find subc.
121///
122/// subc launches module-mode children as `<module> --subc <connection-file-path>`.
123/// The path points at the TCP+key connection file; it is not an ambient signal and
124/// is never inherited by standalone children.
125pub const SUBC_ARG: &str = "--subc";
126
127const DEFAULT_MAX_RESTARTS: u32 = 3;
128const DEFAULT_BACKOFF: Duration = Duration::from_millis(100);
129const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
130/// The span `DEFAULT_MAX_RESTARTS` is counted over. Ten minutes is long enough
131/// to contain a real crash loop (which respawns in seconds) and short enough
132/// that unrelated crashes hours apart never accumulate into a permanent stop.
133const DEFAULT_RESTART_WINDOW: Duration = Duration::from_secs(600);
134/// How long a drain waits for already-dispatched requests to finalize before
135/// the child is torn down. Sized for TOOL-SCALE work (bash, inspect, builds),
136/// not RPC-scale: the original 2s value silently cut nearly every real tool
137/// call at the fence, making the wait-for-finalize design decorative for the
138/// workloads it existed for. Quiescence short-circuits, so an idle module
139/// restarts immediately regardless of this value; the budget is spent only
140/// when a genuine in-flight request is worth finishing. Per-module override:
141/// `drain_timeout_ms` in subc.jsonc; per-restart override: the operator's
142/// `supervisor.restart{drain_timeout_ms}` (0 = cut now, for wedge bounces
143/// where a stuck request will never settle).
144pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
145// Child admission durably records identity before exec. Disk pressure can make
146// fsync slow without implying a failed child start, so allow a generous budget.
147#[cfg(any(unix, feature = "test-support"))]
148const ADMISSION_TIMEOUT: Duration = Duration::from_secs(30);
149
150/// Daemon-side child-admission budget, for integration-test RPC deadlines.
151#[cfg(feature = "test-support")]
152pub const CHILD_ADMISSION_TIMEOUT: Duration = ADMISSION_TIMEOUT;
153
154pub(crate) const DEFAULT_REGISTER_TIMEOUT: Duration = Duration::from_secs(120);
155const REGISTRY_RELEASE_TIMEOUT: Duration = Duration::from_secs(1);
156const REGISTRY_RELEASE_POLL: Duration = Duration::from_millis(10);
157/// How long a drain waits after one busy-gauge probe completes before it asks
158/// again.
159///
160/// A drain re-probes on this short interval of its own rather than on the
161/// module's health cadence. The default cadence (30 s) equals the default
162/// drain ceiling, so a cadence-paced drain that found the module busy at its
163/// first probe never asked a second time: it waited out the whole ceiling and
164/// forced GOODBYE even after the gauges had read zero. The interval is counted
165/// from the moment the previous probe finished, and probes run one at a time,
166/// so a slow module is never asked more often than it can answer. Periodic
167/// health checks outside a drain keep using the configured cadence.
168const DRAIN_BUSY_REPROBE_INTERVAL: Duration = Duration::from_millis(250);
169/// How long a restart waits for the exited process's output readers.
170///
171/// The restart does not depend on either output reader finishing. A stderr
172/// reader still running at this bound is left running, and its later output goes
173/// into the exited process's own section of the stderr ring (see
174/// `StderrRing::push_line_from`), ending naturally at EOF on its pipe. So the
175/// bound no longer decides whether a crash's last lines are kept: under load
176/// the reader may simply not have been scheduled yet, and cutting it there
177/// discarded exactly the lines that explained the crash.
178///
179/// What the bound still decides is when the tail starts reporting
180/// `Incomplete`: a pipe open past it usually means a descendant of the exited
181/// process still holds it, and the tail cannot claim to be whole until that
182/// pipe closes. That is also the only case in which the wait costs the restart
183/// anything, because a pipe with no other holder reaches EOF when the process
184/// exits. Under load a slow reader can show `Incomplete` briefly; it returns to
185/// `Captured` at EOF with nothing lost.
186///
187/// The stdout reader carries no ring, only the capture file. It also continues
188/// to EOF after this bound: child exit closes the writer but does not mean the
189/// reader has consumed all buffered bytes. Late output from either pipe can
190/// therefore reach the shared capture file after the successor starts.
191const STDERR_PUMP_DRAIN_TIMEOUT: Duration = Duration::from_millis(250);
192/// Maximum number of supervised process spawn/exit facts retained per daemon incarnation.
193pub const SPAWN_EVENT_RING_CAPACITY: usize = 4096;
194const SPAWN_SUBSCRIBER_BUFFER: usize = SPAWN_EVENT_RING_CAPACITY + 1;
195/// Terminal Error code for a `supervisor.spawn_subscribe` stream the daemon
196/// dropped because the subscriber stopped draining its frames. The detail's
197/// `first_undelivered_cursor` names the first event it did not receive; the
198/// client resubscribes from the last cursor it did receive.
199pub(crate) const SPAWN_SUBSCRIBER_LAGGED_CODE: &str = "spawn_subscriber_lagged";
200
201#[cfg(target_os = "macos")]
202struct PrivacyExec {
203    content_check: Option<tokio::task::JoinHandle<Result<(), crate::config_gate::GateError>>>,
204    gated: bool,
205    admission_binding: Option<ProgramBindingPublication>,
206    reader: tokio::io::unix::AsyncFd<std::io::PipeReader>,
207    deadline: tokio::time::Instant,
208    expected: Option<subc_os::FileIdentity>,
209    trampoline: Option<subc_os::FileIdentity>,
210    signature: Option<Arc<subc_os::privacy_identity::SuspendedSignature>>,
211    module_id: String,
212    #[cfg(test)]
213    confirmation_pause: Option<(String, Option<tokio::net::TcpStream>)>,
214    #[cfg(test)]
215    image_probe: Option<fn(u32) -> Option<subc_os::Observation>>,
216    #[cfg(test)]
217    image_read_delay: Option<Duration>,
218}
219
220#[cfg(all(test, target_os = "macos"))]
221pub(crate) fn test_privacy_trampoline() -> PathBuf {
222    // The fixture bin lives in the profile folder the unit-test executable was
223    // built into. This honors custom CARGO_TARGET_DIR too.
224    let path = cortexkit_test_support::cargo_profile_bin("privacy-trampoline-fixture");
225    // Without the fixture every macOS spawn is refused, and the tests that
226    // spawn fail later as a module in state Failed, which names the wrong
227    // cause. `cargo test -p subc-daemon --lib` alone does not build it.
228    assert!(
229        path.exists(),
230        "privacy-trampoline-fixture not built at {}: run `cargo build -p subc-daemon \
231         --bins --features test-support` or `cargo test -p subc-daemon` first",
232        path.display()
233    );
234    path
235}
236
237#[cfg(target_os = "macos")]
238fn probe_privacy_trampoline(path: &std::path::Path) -> Result<(), String> {
239    use std::io::Read;
240    let mut probe = subc_os::child_spawn::spawn(
241        std::process::Command::new(path)
242            .args(["__disclaim-exec", "--probe-suspended"])
243            .stdin(Stdio::null())
244            .stdout(Stdio::piped())
245            .stderr(Stdio::piped()),
246    )
247    .map_err(|error| {
248        format!(
249            "privacy trampoline probe failed for {}: {error}",
250            path.display()
251        )
252    })?;
253    let deadline = std::time::Instant::now() + Duration::from_secs(5);
254    let status = loop {
255        match probe.try_wait() {
256            Ok(Some(status)) => break status,
257            Ok(None) if std::time::Instant::now() < deadline => {
258                std::thread::sleep(Duration::from_millis(5))
259            }
260            result => {
261                let _ = probe.kill();
262                let _ = probe.wait();
263                return Err(format!(
264                    "privacy trampoline probe failed or timed out for {}: {result:?}",
265                    path.display()
266                ));
267            }
268        }
269    };
270    let mut answer = String::new();
271    if let Some(stdout) = probe.stdout.take() {
272        let _ = stdout.take(256).read_to_string(&mut answer);
273    }
274    if status.success() && answer.trim() == subc_os::privacy_identity::SUSPENDED_TRAMPOLINE_PROBE {
275        return Ok(());
276    }
277    let mut diagnostic = String::new();
278    if let Some(stderr) = probe.stderr.take() {
279        let _ = stderr.take(1024).read_to_string(&mut diagnostic);
280    }
281    let cause = diagnostic
282        .trim()
283        .strip_prefix("ck-subc: own privacy identity refused: ")
284        .unwrap_or("binary does not implement the privacy trampoline protocol");
285    Err(format!(
286        "{cause}: probe of {} exited {status}",
287        path.display()
288    ))
289}
290
291#[cfg(target_os = "macos")]
292fn privacy_command(
293    spec: &ModuleSpec,
294    binding: &SpawnProgramBinding,
295    roster: &ChildRoster,
296    gated: bool,
297) -> Result<
298    (
299        Command,
300        Option<PrivacyExec>,
301        subc_os::privacy_identity::ExecAcknowledgement,
302    ),
303    SuperviseError,
304> {
305    let failure = |cause: String| {
306        warn!(module_id = %spec.module_id, %cause, "privacy identity trampoline refused module spawn");
307        SuperviseError::Spawn {
308            program: spec.program.clone(),
309            source: io::Error::other(cause),
310            cgroup_path: None,
311        }
312    };
313    let trampoline = roster.privacy_trampoline().map_err(failure)?;
314    let expected = Some(binding.identity);
315    let trampoline_image = subc_os::file_identity(&trampoline);
316    let signature = gated
317        .then(|| {
318            subc_os::privacy_identity::SuspendedSignature::capture(&binding._file, &binding.path)
319                .map(Arc::new)
320        })
321        .transpose()
322        .map_err(|error| failure(error.to_string()))?;
323    if expected == trampoline_image {
324        return Err(failure(
325            "privacy identity module executable is missing or is the trampoline itself".to_string(),
326        ));
327    }
328    let (reader, ack) = subc_os::privacy_identity::ExecAcknowledgement::pipe()
329        .map_err(|error| failure(error.to_string()))?;
330    let reader =
331        tokio::io::unix::AsyncFd::new(reader).map_err(|error| failure(error.to_string()))?;
332    let mut command = Command::new(&trampoline);
333    command
334        .arg(if gated {
335            "__disclaim-exec-suspended"
336        } else {
337            "__disclaim-exec"
338        })
339        .arg(ack.fd().to_string())
340        .arg(&binding.path);
341    Ok((
342        command,
343        Some(PrivacyExec {
344            gated,
345            admission_binding: None,
346            content_check: None,
347            reader,
348            deadline: tokio::time::Instant::now() + Duration::from_secs(5),
349            expected,
350            trampoline: trampoline_image,
351            signature,
352            module_id: spec.module_id.clone(),
353            #[cfg(test)]
354            image_probe: None,
355            #[cfg(test)]
356            image_read_delay: spec
357                .env
358                .iter()
359                .find(|(key, _)| key == "SUBC_TEST_PRIVACY_IMAGE_DELAY_MS")
360                .map(|(_, millis)| Duration::from_millis(millis.parse().unwrap())),
361            #[cfg(test)]
362            confirmation_pause: spec
363                .env
364                .iter()
365                .find(|(key, _)| key == "SUBC_TEST_BEFORE_EXEC_CONFIRM")
366                .map(|(_, address)| (address.clone(), None)),
367        }),
368        ack,
369    ))
370}
371
372#[cfg(unix)]
373type SpawnRegistrationChannel = std::os::unix::net::UnixStream;
374#[cfg(windows)]
375type SpawnRegistrationChannel = subc_os::registration_channel::RegistrationPipe;
376#[cfg(test)]
377type CapturedRegistrationChannels =
378    Arc<Mutex<Option<Vec<(Arc<RegistrationSpawn>, CapturedRegistrationEndpoint)>>>>;
379#[cfg(test)]
380struct CapturedRegistrationEndpoint {
381    _channel: SpawnRegistrationChannel,
382}
383#[cfg(test)]
384impl fmt::Debug for CapturedRegistrationEndpoint {
385    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386        f.write_str("CapturedRegistrationEndpoint")
387    }
388}
389
390struct SupervisedChild {
391    registration_spawn: Option<Arc<RegistrationSpawn>>,
392    /// Owned daemon endpoint, retained for the per-spawn registration service.
393    #[cfg(any(unix, windows))]
394    registration_channel: Option<SpawnRegistrationChannel>,
395    live_program_binding: Option<Arc<content_binding::LiveProgramBinding>>,
396    registered_config_connection: Option<ConnectionId>,
397    admission_base: Option<subc_config::Digest>,
398    registration_declaration: Option<String>,
399    _program_binding: Option<ProgramBindingPublication>,
400    subtree_target: crate::subtree_resources::Target,
401    child: containment::ProcessChild,
402    exec: crate::activity::ExecOwner,
403    #[cfg(windows)]
404    nonce_delivery: Option<subc_os::LaunchNoncePipeDelivery>,
405    #[cfg(target_os = "macos")]
406    privacy_exec: Option<PrivacyExec>,
407    /// Set once this launch's exec acknowledgement confirms the module image.
408    /// On macOS the pid first runs the `ck-subc` launch trampoline (see
409    /// `subc_os::privacy_identity`), which then replaces itself with the
410    /// module. The supervisor owns and can kill that pid from spawn, but
411    /// status readers report it only after this latch is set, so nothing
412    /// reports the trampoline's image as the module's.
413    #[cfg(target_os = "macos")]
414    report_ready: Arc<OnceLock<()>>,
415    /// Supervisor failure detail retained for the terminal record, including
416    /// image refusals and first-HELLO timeouts after a successful spawn.
417    spawn_failure: Option<String>,
418    /// Set only after a kill requested because launch admission failed was
419    /// accepted, never for an operator, health, or shutdown kill.
420    admission_kill_sent: bool,
421    /// The protocol this process was launched with. A reload can store a new
422    /// launch spec with a different protocol, but that takes effect only at the
423    /// next spawn, so this process keeps being handled by the protocol it
424    /// actually speaks.
425    protocol: ModuleProtocol,
426    /// This container's cgroup name: a bounded module/slot label followed by a
427    /// unique suffix (when cgroup placement is on). Carried replacements reuse
428    /// the name; ordinary launches each get a fresh container. A
429    /// retired process in a slot may still be draining when a later one is
430    /// spawned into that slot, so the suffix keeps the later process out of
431    /// the retired one's cgroup, which is the domain a kill applies to.
432    #[cfg(target_os = "linux")]
433    module_id: String,
434    #[cfg(target_os = "linux")]
435    cgroup_placement: Option<subc_cgroup::Placement>,
436    /// The job for an ordinary, non-carried launch. For carried
437    /// launches the actor owns it and the child holds only a weak container link.
438    ///
439    /// Dropping this handle is what reaps a surviving tree when no supervisor
440    /// code runs — a daemon crash — because the job carries
441    /// `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`.
442    ///
443    /// That limit is not crash-only, and the difference is worth knowing: a
444    /// Windows daemon *stop* is `taskkill` or the scheduler's `/End` — the
445    /// SIGTERM handler is `#[cfg(unix)]` — so the daemon dies with no stop
446    /// notice and the kernel closes the job handle, `TerminateProcess`ing every
447    /// module at once. Before this change they survived that, saw EOF on the
448    /// control socket, and ran their own teardown; Unix keeps that path
449    /// deliberately, so a module can seal a WAL or close a capture rather than
450    /// be killed mid-write. So this trades graceful teardown on every Windows
451    /// daemon stop for containment on a crash, which is the right way round
452    /// today: orphaned GPU workers are a reported, recurring problem, and the
453    /// modules that write most heavily do not run on Windows.
454    ///
455    /// The fix is a real Windows stop path — the daemon draining before it
456    /// exits, the twin of the Unix SIGTERM handler. Once it exists, this limit
457    /// reaches only what the drain left behind, which is what it should reach.
458    #[cfg(windows)]
459    job: Option<Arc<Mutex<subc_jobobject::JobObject>>>,
460    stdout_pump: Option<JoinHandle<()>>,
461    stderr_pump: Option<StderrPump>,
462    stderr_ring: Arc<Mutex<StderrRing>>,
463    /// Conservative monotonic bound sampled before `command.spawn()`, not when
464    /// identity recording finishes or the spawn generation is published.
465    spawned_at: Instant,
466    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
467    /// Ordinary spawns must send their first HELLO within this budget. Once
468    /// accepted, a later disconnect must not restart the registration clock.
469    registration_deadline: Option<Instant>,
470    registration_watch: Option<RegistrationWatch>,
471    spawned_at_ms: u64,
472    spawned_from: PathBuf,
473    launch_spec_digest: LaunchSpecDigest,
474    spawned_file_identity: Option<SpawnedFileIdentity>,
475    process_start_time: Option<u64>,
476    process_identity: Option<ProcessIdentity>,
477    pid: u32,
478    /// This process's entry in the daemon's child roster, released when the
479    /// process is reaped or this handle is dropped.
480    roster_guard: Option<crate::child_roster::RosterGuard>,
481}
482
483impl SupervisedChild {
484    fn retire_registration(&self) {
485        // All exit observers enter here before cleanup can await. The retired
486        // program-binding flag and the registration's Dead state make repeated
487        // observations harmless, even when another task observes the group
488        // leader retained unreaped to reserve its process-group id.
489        if let Some(spawn) = &self.registration_spawn {
490            spawn.retire();
491        } else if let Some(binding) = &self._program_binding {
492            binding.retire();
493        }
494        #[cfg(unix)]
495        if let Some(channel) = &self.registration_channel {
496            let _ = channel.shutdown(std::net::Shutdown::Both);
497        }
498        #[cfg(windows)]
499        if let Some(channel) = &self.registration_channel {
500            if let Ok(shutdown) = channel.shutdown_handle() {
501                shutdown.shutdown();
502            }
503        }
504    }
505    fn registered_since_spawn(&self) -> bool {
506        self.registration_watch
507            .as_ref()
508            .is_some_and(|watch| *watch.changes.borrow() != watch.baseline)
509    }
510
511    fn awaiting_registration(&self) -> bool {
512        // Admission failure retires the channel before its kill becomes
513        // waitable. That closure must not replace the admission failure with
514        // a registration failure and spend crash restart budget.
515        let admission_failed = self.admission_kill_sent && self.spawn_failure.is_some();
516        !admission_failed && !self.registered_since_spawn()
517    }
518
519    fn id(&self) -> Option<u32> {
520        Some(self.pid)
521    }
522
523    fn process_identity(&self) -> Option<ProcessIdentity> {
524        self.process_identity
525    }
526
527    fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
528        let result = self.child.try_wait();
529        if !matches!(result, Ok(None)) {
530            self.retire_registration();
531            #[cfg(any(unix, windows))]
532            self.registration_channel.take();
533            if let Some(binding) = &self._program_binding {
534                binding.retire();
535            }
536        }
537        result
538    }
539
540    async fn wait(&mut self) -> io::Result<ExitStatus> {
541        #[cfg(target_os = "macos")]
542        self.confirm_privacy_exec().await;
543        // The roster entry is NOT released here. A daemon shutdown waits for the
544        // roster to empty and then exits the process, so releasing at the reap
545        // let it exit before the exit handler wrote this child's terminal record
546        // (the stderr drain and snapshot update sit in between), and the
547        // shutdown's own `daemon_shutdown` record was intermittently lost. The
548        // caller releases it after recording the exit (`release_roster`), and
549        // dropping the handle releases it too.
550        let result = self.child.wait().await;
551        self.retire_registration();
552        #[cfg(any(unix, windows))]
553        self.registration_channel.take();
554        // All plain and swap waits pass here. Revoke the reaped child's nonce
555        // before cgroup cleanup, stderr draining or exit observation can await.
556        if let Some(binding) = &self._program_binding {
557            binding.retire();
558        }
559        #[cfg(all(test, target_os = "linux"))]
560        if let Some(binding) = &self._program_binding {
561            binding.pause_after_wait_for_test().await;
562        }
563        #[cfg(target_os = "linux")]
564        if result.is_ok() && self.child.container().is_none() {
565            if let Some(placement) = self.cgroup_placement.as_ref() {
566                // Ordinary children still own a per-spawn cgroup: returning
567                // from wait must leave it empty and removed, as before carry.
568                // Keep cleanup ownership across cancellation until it finishes.
569                cleanup_reaped_cgroup(placement, &self.module_id).await;
570                self.cgroup_placement = None;
571            }
572        }
573        result
574    }
575
576    async fn finish_exit(&mut self, carry: bool) -> io::Result<()> {
577        self.retire_registration();
578        // Idempotent fallback for cleanup paths that did not call wait.
579        if let Some(binding) = self._program_binding.take() {
580            binding.retire();
581        }
582        if self.child.container().is_some() {
583            if !carry {
584                self.child.terminate_container().await;
585            }
586        } else {
587            #[cfg(target_os = "linux")]
588            if let Some(placement) = self.cgroup_placement.as_ref() {
589                cleanup_reaped_cgroup(placement, &self.module_id).await;
590                self.cgroup_placement = None;
591            }
592        }
593        self.child.reap().await?;
594        self.release_roster();
595        Ok(())
596    }
597
598    #[cfg(target_os = "macos")]
599    async fn confirm_privacy_exec(&mut self) {
600        if self
601            .privacy_exec
602            .as_ref()
603            .is_some_and(|pending| pending.content_check.is_some())
604        {
605            self.finish_privacy_content_check().await;
606            return;
607        }
608        let Some(pending) = &mut self.privacy_exec else {
609            return;
610        };
611        let result = tokio::time::timeout_at(pending.deadline, async {
612            let mut record = Vec::new();
613            loop {
614                let mut ready = pending.reader.readable().await?;
615                let read = ready.try_io(|reader| {
616                    use std::io::Read;
617                    let mut reader = reader.get_ref();
618                    let mut buffer = [0u8; 256];
619                    reader.read(&mut buffer).map(|count| (count, buffer))
620                });
621                match read {
622                    Ok(Ok((0, _))) => return Ok::<_, io::Error>(record),
623                    Ok(Ok((count, buffer))) => {
624                        if record.len() + count > 1024 {
625                            return Err(io::Error::other(
626                                "privacy exec refusal record is too long",
627                            ));
628                        }
629                        record.extend_from_slice(&buffer[..count]);
630                    }
631                    Ok(Err(error)) => return Err(error),
632                    Err(_) => continue,
633                }
634            }
635        })
636        .await;
637        #[cfg(test)]
638        let result = if let Some((address, stream)) = &mut pending.confirmation_pause {
639            use tokio::io::{AsyncReadExt, AsyncWriteExt};
640            if stream.is_none() {
641                *stream = Some(
642                    tokio::net::TcpStream::connect(address.as_str())
643                        .await
644                        .unwrap(),
645                );
646                stream.as_mut().unwrap().write_all(b"R").await.unwrap();
647                stream
648                    .as_mut()
649                    .unwrap()
650                    .write_all(&self.pid.to_ne_bytes())
651                    .await
652                    .unwrap();
653            }
654            let mut reply = [0];
655            stream
656                .as_mut()
657                .unwrap()
658                .read_exact(&mut reply)
659                .await
660                .unwrap();
661            pending.confirmation_pause = None;
662            if &reply == b"F" {
663                Ok(Err(io::Error::other("injected late exec refusal")))
664            } else {
665                assert_eq!(&reply, b"X");
666                result
667            }
668        } else {
669            result
670        };
671        // Keep the reader in self across await: select cancellation must not
672        // discard the handshake or reset its original five-second deadline.
673        // Use try_wait so a child reaped during confirmation has its program
674        // binding retired before another command can use its nonce.
675        let waited = if matches!(&result, Ok(Ok(record)) if record.is_empty()) {
676            Some(self.try_wait())
677        } else {
678            None
679        };
680        let pending = self.privacy_exec.as_ref().expect("pending exec");
681        let cause = match result {
682            Err(_) => Some("privacy identity trampoline did not exec within 5s".to_string()),
683            Ok(Err(error)) => Some(format!(
684                "privacy identity exec acknowledgement failed: {error}"
685            )),
686            Ok(Ok(record)) if !record.is_empty() => Some(
687                std::str::from_utf8(&record)
688                    .ok()
689                    .and_then(|record| {
690                        record
691                            .trim()
692                            .strip_prefix(subc_os::privacy_identity::EXEC_REFUSAL_TAG)
693                    })
694                    .filter(|cause| !cause.is_empty())
695                    .unwrap_or("invalid privacy exec refusal record")
696                    .to_string(),
697            ),
698            Ok(Ok(_)) if !pending.gated => match waited.expect("exec EOF checked child") {
699                Ok(Some(_)) => None,
700                Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
701                Ok(None) => {
702                    #[cfg(test)]
703                    if let Some(delay) = pending.image_read_delay {
704                        tokio::time::sleep(delay).await;
705                    }
706                    let image = observe_spawned_image(self.pid);
707                    #[cfg(test)]
708                    let image = pending.image_probe.map_or(image, |probe| probe(self.pid));
709                    // An unstamped module can re-exec before we wake to read its
710                    // image. Only the trampoline image proves exec never happened;
711                    // retain the observed image for later orphan identification.
712                    if let Some(image) = image.filter(|image| {
713                        image.executable.is_some() && image.executable != pending.trampoline
714                    }) {
715                        match self
716                            .roster_guard
717                            .as_ref()
718                            .map(|guard| guard.confirm_executable(image))
719                            .transpose()
720                        {
721                            Err(error) => Some(format!(
722                                "could not durably record confirmed module image: {error}"
723                            )),
724                            Ok(_) => {
725                                let _ = self.report_ready.set(());
726                                None
727                            }
728                        }
729                    } else if image.is_none()
730                        || image.is_some_and(|image| image.executable.is_none())
731                    {
732                        // Empty EOF acknowledged exec. An image disappearing
733                        // during observation is an ordinary module exit.
734                        match tokio::time::timeout_at(pending.deadline, self.child.wait()).await {
735                            Ok(result) => {
736                                self.retire_registration();
737                                self.registration_channel.take();
738                                if let Some(binding) = &self._program_binding {
739                                    binding.retire();
740                                }
741                                result.err().map(|error| format!("privacy identity trampoline wait failed: {error}"))
742                            }
743                            Err(_) => Some("privacy identity module executable remained unreadable until the 5s exec deadline".to_string()),
744                        }
745                    } else {
746                        Some("privacy identity trampoline did not exec the module".to_string())
747                    }
748                }
749            },
750            Ok(Ok(_)) => match waited.expect("exec EOF checked child") {
751                Ok(Some(_)) => {
752                    Some("privacy identity target exited before suspended admission".to_string())
753                }
754                Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
755                Ok(None) => {
756                    // CLOEXEC closes the ack just before the kernel reports the
757                    // suspended target. EOF alone must never admit a running image.
758                    let stopped = tokio::time::timeout_at(pending.deadline, async {
759                        loop {
760                            if subc_os::privacy_identity::SuspendedSignature::is_suspended(
761                                self.pid,
762                            )? {
763                                return Ok::<_, io::Error>(());
764                            }
765                            tokio::time::sleep(Duration::from_millis(1)).await;
766                        }
767                    })
768                    .await;
769                    match stopped {
770                        Err(_) => {
771                            Some("privacy identity target was not suspended within 5s".to_string())
772                        }
773                        Ok(Err(error)) => Some(format!(
774                            "privacy identity suspended target unavailable: {error}"
775                        )),
776                        Ok(Ok(())) => {
777                            let image = observe_spawned_image(self.pid);
778                            if image.is_some_and(|image| {
779                                image.executable.is_some()
780                                    && image.executable != pending.trampoline
781                                    && image.executable == pending.expected
782                            }) {
783                                None
784                            } else {
785                                Some("privacy identity trampoline executable mismatch: expected the suspended module program".to_string())
786                            }
787                        }
788                    }
789                }
790            },
791        };
792        #[cfg(test)]
793        if let Some(binding) = &self._program_binding {
794            binding.pause_after_wait_for_test().await;
795        }
796        if cause.is_none() && pending.gated {
797            let publication = pending.admission_binding.clone();
798            let live = self.live_program_binding.clone();
799            let signature = Arc::clone(pending.signature.as_ref().expect("gated signature"));
800            let pid = self.pid;
801            let gated = pending.gated;
802            self.privacy_exec
803                .as_mut()
804                .expect("pending exec")
805                .content_check = Some(tokio::task::spawn_blocking(move || {
806                signature.verify(pid).map_err(|error| {
807                    crate::config_gate::GateError::new("program_refused", error)
808                })?;
809                if !gated {
810                    return Ok(());
811                }
812                match (publication, live) {
813                    (Some(publication), _) => publication.verify(),
814                    (None, Some(live)) => live.check(),
815                    _ => Err(crate::config_gate::GateError::new(
816                        "config_delivery_deferred",
817                        "live program witness is unavailable",
818                    )),
819                }
820            }));
821            self.finish_privacy_content_check().await;
822        } else {
823            self.finish_privacy_exec(cause);
824        }
825    }
826
827    #[cfg(target_os = "macos")]
828    async fn finish_privacy_content_check(&mut self) {
829        let result = self
830            .privacy_exec
831            .as_mut()
832            .expect("pending exec")
833            .content_check
834            .as_mut()
835            .expect("pending content check")
836            .await;
837        let cause = match result {
838            Ok(Ok(())) => None,
839            Ok(Err(error)) => Some(format!("{}: {}", error.code, error.detail)),
840            Err(error) => Some(format!(
841                "config_delivery_deferred: content check stopped: {error}"
842            )),
843        };
844        self.finish_privacy_exec(cause);
845    }
846
847    #[cfg(target_os = "macos")]
848    fn finish_privacy_exec(&mut self, mut cause: Option<String>) {
849        let mut pending = self.privacy_exec.take().expect("pending exec");
850        if cause.is_none() && pending.gated {
851            let admission = (|| -> io::Result<()> {
852                let image = observe_spawned_image(self.pid)
853                    .filter(|image| image.executable == pending.expected)
854                    .ok_or_else(|| io::Error::other("suspended executable mismatch"))?;
855                if let Some(guard) = &self.roster_guard {
856                    guard.confirm_executable(image)?;
857                }
858                pending
859                    .signature
860                    .as_ref()
861                    .expect("gated signature")
862                    .resume(self.pid)?;
863                let _ = self.report_ready.set(());
864                info!(module_id = %pending.module_id, pid = self.pid,
865                    "verified suspended module resumed with own privacy identity");
866                Ok(())
867            })();
868            if let Err(error) = admission {
869                cause = Some(format!("program_refused: {error}"));
870            }
871        }
872        if cause.is_some() {
873            if let Some(spawn) = &self.registration_spawn {
874                spawn.refuse();
875            }
876            if let Some(binding) = &mut pending.admission_binding {
877                binding.reject();
878            }
879        } else if let Some(spawn) = &self.registration_spawn {
880            spawn.ready();
881        }
882        // Exec confirmation describes launch success, not roster retirement.
883        // Keep even a reaped child recorded until its terminal history exists.
884        self.exec.0.finish(if cause.is_some() {
885            crate::activity::ExecState::Refused
886        } else {
887            crate::activity::ExecState::CommittedExec
888        });
889        if let Some(cause) = cause {
890            warn!(module_id = %pending.module_id, pid = self.pid, %cause, "privacy identity trampoline refused module spawn");
891            self.spawn_failure = Some(
892                if pending.gated
893                    && (cause.contains("executable mismatch")
894                        || cause.starts_with("program_refused:"))
895                {
896                    format!("program_refused: {cause}")
897                } else if pending.gated {
898                    format!("config_delivery_deferred: {cause}")
899                } else {
900                    cause
901                },
902            );
903            // No resume signal is sent on failure; kill the entire fresh group
904            // even if a faulty trampoline did not honor the suspended protocol.
905            let _ = self.start_admission_kill();
906        }
907    }
908
909    /// Releases the leader's roster entry after recording and finalizing its
910    /// exit. A carried container retains its separate roster entry and, for a
911    /// Unix process group, its unreaped first leader that reserves the group ID.
912    fn release_roster(&mut self) {
913        self.roster_guard = None;
914    }
915
916    /// Kill the child and, where containment is available, its process tree.
917    ///
918    /// `Child::kill` is `TerminateProcess` scoped to one pid, so a module with a
919    /// helper process leaked the helper — the Synapse embedding module's CUDA
920    /// worker holds the GPU allocation, so the leak cost VRAM until the next
921    /// restart of something else. Terminating the job reaches grandchildren that
922    /// a tree walk cannot, including one whose parent has already exited and
923    /// been reparented away.
924    ///
925    /// Best-effort like `request_graceful_stop`: a job failure is logged and the
926    /// direct-child kill still decides the outcome, so containment can never
927    /// change whether a module is reported as stopped.
928    fn start_kill(&mut self) -> io::Result<()> {
929        self.retire_registration();
930        if let Some(container) = self.child.container() {
931            container.hard_kill();
932            return self.kill_leader();
933        }
934        #[cfg(windows)]
935        if let Some(job) = &self.job {
936            if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
937                debug!(
938                    error = %error,
939                    "job termination failed; the direct-child kill still owns the outcome"
940                );
941            }
942        }
943        #[cfg(target_os = "linux")]
944        kill_module_cgroup(self.cgroup_placement.as_ref(), &self.module_id);
945        self.child.start_kill()
946    }
947
948    fn kill_leader(&mut self) -> io::Result<()> {
949        self.retire_registration();
950        self.child.start_kill()
951    }
952
953    fn start_admission_kill(&mut self) -> io::Result<()> {
954        self.retire_registration();
955        #[cfg(windows)]
956        let result = {
957            // Preserve the leader's distinctive status before ending the whole
958            // container/job; descendants must not wait for exit finalization.
959            let result = self
960                .spawned_file_identity
961                .as_ref()
962                .and_then(|identity| identity.windows_image.as_ref())
963                .ok_or_else(|| io::Error::other("admission child handle unavailable"))
964                .and_then(|image| {
965                    image.process().terminate_with_exit_code(
966                        admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE as u32,
967                    )
968                });
969            if let Some(container) = self.child.container() {
970                container.hard_kill();
971            } else if let Some(job) = &self.job {
972                if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
973                    debug!(%error, "job termination failed after admission leader termination");
974                }
975            }
976            result
977        };
978        #[cfg(not(windows))]
979        let result = self.start_kill().map(|()| true);
980        #[cfg(unix)]
981        let result = {
982            // A leader can exit before its helpers. Still end the fresh group
983            // even when the direct-child kill reports that the leader is gone.
984            let group_sent = self.child.container().is_none()
985                && rustix::process::Pid::from_raw(self.pid as i32).is_some_and(|group| {
986                    rustix::process::kill_process_group(group, rustix::process::Signal::KILL)
987                        .is_ok()
988                });
989            if group_sent {
990                Ok(true)
991            } else {
992                result
993            }
994        };
995        self.admission_kill_sent |= result?;
996        Ok(())
997    }
998
999    async fn drain_stderr(&mut self, module_id: &str) {
1000        if let Some(pump) = self.stdout_pump.take() {
1001            settle_stdout_pump(module_id, pump, STDERR_PUMP_DRAIN_TIMEOUT).await;
1002        }
1003
1004        let Some(pump) = self.stderr_pump.take() else {
1005            return;
1006        };
1007        settle_stderr_pump(
1008            module_id,
1009            &self.stderr_ring,
1010            pump,
1011            STDERR_PUMP_DRAIN_TIMEOUT,
1012        )
1013        .await;
1014    }
1015}
1016
1017/// Bound the restart's wait, not the lifetime of the exited child's stdout
1018/// reader. Slow pipe reads or capture writes must not turn the bound into lost
1019/// output; dropping the handle lets the reader finish at EOF, like stderr.
1020async fn settle_stdout_pump(module_id: &str, mut pump: JoinHandle<()>, bound: Duration) {
1021    match timeout(bound, &mut pump).await {
1022        Ok(Ok(())) => {}
1023        Ok(Err(error)) => {
1024            warn!(module_id, error = %error, "stdout pump ended unexpectedly");
1025        }
1026        Err(_) => {
1027            drop(pump);
1028            warn!(
1029                module_id,
1030                waited = ?bound,
1031                "stdout pipe of the exited process has not drained; its reader keeps running without delaying the restart"
1032            );
1033        }
1034    }
1035}
1036
1037/// The reader task for one process's stderr, with the ring generation its
1038/// lines are attributed to.
1039struct StderrPump {
1040    task: JoinHandle<()>,
1041    generation: u64,
1042}
1043
1044/// Retire an exited process's stderr reader and wait up to `bound` for it to
1045/// reach EOF. A reader still running at the bound is detached, not stopped: it
1046/// keeps filling the exited process's section of the ring until its pipe
1047/// closes, and the tail reads `Incomplete` until then. See
1048/// [`STDERR_PUMP_DRAIN_TIMEOUT`] for why.
1049async fn settle_stderr_pump(
1050    module_id: &str,
1051    ring: &Arc<Mutex<StderrRing>>,
1052    pump: StderrPump,
1053    bound: Duration,
1054) {
1055    let lock = || ring.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1056    let StderrPump {
1057        mut task,
1058        generation,
1059    } = pump;
1060    lock().retire_pump(generation);
1061    match timeout(bound, &mut task).await {
1062        Ok(Ok(())) => {}
1063        Ok(Err(err)) => {
1064            let mut ring = lock();
1065            ring.mark_incomplete_from(generation, format!("stderr pump ended unexpectedly: {err}"));
1066            ring.finish_pump(generation);
1067            warn!(module_id, error = %err, "stderr pump ended before clean EOF");
1068        }
1069        Err(_) => {
1070            // Dropping the handle detaches the task; it ends at EOF on its pipe.
1071            drop(task);
1072            lock().mark_pump_late(
1073                generation,
1074                format!(
1075                    "stderr of the exited process had not reached EOF {bound:?} after it was \
1076                     retired (a descendant may still hold the pipe open); lines it still \
1077                     writes are kept in that process's section"
1078                ),
1079            );
1080            warn!(
1081                module_id,
1082                waited = ?bound,
1083                "stderr pipe of the exited process is still open; its reader keeps running without delaying the restart"
1084            );
1085        }
1086    }
1087}
1088
1089fn registration_release_events() -> &'static watch::Sender<u64> {
1090    static EVENTS: OnceLock<watch::Sender<u64>> = OnceLock::new();
1091    EVENTS.get_or_init(|| {
1092        let (sender, _receiver) = watch::channel(0);
1093        sender
1094    })
1095}
1096
1097pub(crate) fn notify_registration_release() {
1098    let events = registration_release_events();
1099    let next_generation = (*events.borrow()).wrapping_add(1);
1100    events.send_replace(next_generation);
1101}
1102
1103/// The installed companion that evaluates a script module.
1104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1105#[non_exhaustive]
1106pub enum ScriptRuntime {
1107    Bun,
1108    Python,
1109}
1110
1111impl ScriptRuntime {
1112    pub const fn as_str(self) -> &'static str {
1113        match self {
1114            Self::Bun => "bun",
1115            Self::Python => "python",
1116        }
1117    }
1118}
1119
1120/// Script content and the runtime approved to evaluate it.
1121#[derive(Debug, Clone, PartialEq, Eq)]
1122#[non_exhaustive]
1123pub struct ScriptEntry {
1124    pub runtime: ScriptRuntime,
1125    pub path: PathBuf,
1126}
1127
1128impl ScriptEntry {
1129    pub fn new(runtime: ScriptRuntime, path: PathBuf) -> Self {
1130        Self { runtime, path }
1131    }
1132}
1133
1134/// How to launch one singleton module process.
1135#[derive(Debug, Clone, PartialEq, Eq)]
1136pub struct ModuleSpec {
1137    pub module_id: String,
1138    pub program: PathBuf,
1139    /// Bundled script content. The program is always the installed runtime runner.
1140    pub script: Option<ScriptEntry>,
1141    pub args: Vec<String>,
1142    pub env: Vec<(String, String)>,
1143    /// When true this is a reserved module: each spawn gets a fresh one-time launch
1144    /// nonce that the child must echo in its HELLO, so only the daemon-spawned
1145    /// process can register this module_id (a security-boundary module like the
1146    /// credential vault must not be impersonable while it is down/restarting).
1147    pub reserved: bool,
1148    /// Module-id prefixes this supervised module owns for reserved HELLO checks.
1149    /// Prefixes come from daemon config and must end in `:` before they reach the
1150    /// supervisor; the owner module's current spawn nonce authorizes claims under
1151    /// each prefix.
1152    pub reserved_prefixes: Vec<String>,
1153    /// The wire protocol this module speaks, as DECLARED in daemon config.
1154    ///
1155    /// [`ModuleProtocol::None`] changes five things and nothing else: wire health
1156    /// probing is suppressed (an optional HTTP probe can replace it), teardown sends SIGTERM before waiting,
1157    /// `route.open` is refused, the spawn passes NO `--subc <path>` argument
1158    /// and NO launch nonce, and a clean exit the daemon did not request is
1159    /// restarted as a crash rather than recorded as a stop (see `on_child_exit`:
1160    /// a stock program exits 0 on a stray SIGTERM, and a stop would leave it
1161    /// down for good). `SUBC_MODULE_ID` still goes into the environment,
1162    /// because a process ignores an environment variable it does not read.
1163    ///
1164    /// The argument is the part that cannot be "harmless to a process that
1165    /// ignores it": a stock binary exits on an unknown flag before it listens
1166    /// (`nats-server`: "flag provided but not defined: -subc"), which is how the
1167    /// first conformance run against this mode found it. The nonce is withheld
1168    /// because a process that will never present it gains nothing from holding
1169    /// it, and a secret in the environment of a process that does not need it is
1170    /// a leak surface for no benefit.
1171    pub protocol: ModuleProtocol,
1172    /// Whether two processes of this module may run at once, which is what a
1173    /// blue/green swap does for the length of its overlap. Declared in daemon
1174    /// config because the daemon must be able to answer it while the module is
1175    /// down, and so a module cannot talk itself into it after registering.
1176    pub overlap: ModuleOverlap,
1177    /// Keep module-started helpers in the same container across replacements.
1178    /// This is a daemon-config policy, fixed for the lifetime of a container;
1179    /// stopping the module or losing its supervisor still destroys the container.
1180    pub carry_containment: bool,
1181}
1182
1183/// Only the configured launch inputs enter this value; spawned connection paths,
1184/// nonces and inherited environment never do. Its bytes remain daemon-private.
1185#[derive(Clone, PartialEq, Eq)]
1186pub(crate) struct LaunchSpecDigest([u8; 32]);
1187
1188impl fmt::Debug for LaunchSpecDigest {
1189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1190        f.write_str("LaunchSpecDigest([redacted])")
1191    }
1192}
1193
1194impl LaunchSpecDigest {
1195    pub(crate) fn from_spec(spec: &ModuleSpec) -> Self {
1196        fn field(hash: &mut Sha256, bytes: &[u8]) {
1197            hash.update((bytes.len() as u64).to_le_bytes());
1198            hash.update(bytes);
1199        }
1200        let mut hash = Sha256::new();
1201        if let Some(script) = &spec.script {
1202            field(
1203                &mut hash,
1204                match script.runtime {
1205                    ScriptRuntime::Bun => b"bun-script",
1206                    ScriptRuntime::Python => b"python-script",
1207                },
1208            );
1209            field(&mut hash, script.path.as_os_str().as_encoded_bytes());
1210        }
1211        if let Some(program) = spec.program.to_str() {
1212            field(&mut hash, b"utf8-program");
1213            field(&mut hash, program.as_bytes());
1214        } else {
1215            // The daemon config is UTF-8, but in-process callers may provide
1216            // native paths: lossy conversion would collapse distinct programs.
1217            #[cfg(unix)]
1218            {
1219                use std::os::unix::ffi::OsStrExt;
1220                field(&mut hash, b"unix-program");
1221                field(&mut hash, spec.program.as_os_str().as_bytes());
1222            }
1223            #[cfg(windows)]
1224            {
1225                use std::os::windows::ffi::OsStrExt;
1226                field(&mut hash, b"windows-program");
1227                let bytes = spec
1228                    .program
1229                    .as_os_str()
1230                    .encode_wide()
1231                    .flat_map(u16::to_le_bytes)
1232                    .collect::<Vec<_>>();
1233                field(&mut hash, &bytes);
1234            }
1235            #[cfg(not(any(unix, windows)))]
1236            field(&mut hash, spec.program.to_string_lossy().as_bytes());
1237        }
1238        hash.update((spec.args.len() as u64).to_le_bytes());
1239        for arg in &spec.args {
1240            field(&mut hash, arg.as_bytes());
1241        }
1242        let mut env = spec.env.iter().collect::<Vec<_>>();
1243        env.sort_unstable();
1244        hash.update((env.len() as u64).to_le_bytes());
1245        for (key, value) in env {
1246            field(&mut hash, key.as_bytes());
1247            field(&mut hash, value.as_bytes());
1248        }
1249        field(
1250            &mut hash,
1251            match spec.protocol {
1252                ModuleProtocol::Subc => b"subc",
1253                ModuleProtocol::None => b"none",
1254            },
1255        );
1256        Self(hash.finalize().into())
1257    }
1258}
1259
1260/// Whether a module tolerates a second process of itself running alongside.
1261///
1262/// Most modules are single-writer on their store (a WAL, a capture log, a
1263/// resident index behind a writer barrier), and two processes on one store
1264/// corrupt it. So a swap, which overlaps the old and new process by design,
1265/// is refused unless the module's config opts in with `overlap: "safe"`.
1266#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1267pub enum ModuleOverlap {
1268    /// Never run two processes of this module at once. The default.
1269    #[default]
1270    Exclusive,
1271    /// The module has said a second process of itself is harmless for the
1272    /// length of a swap.
1273    ///
1274    /// Declare it only if a second instance can run for a few seconds without
1275    /// touching ANY single-writer store: every database, WAL, index, projector
1276    /// and scheduled job the module owns. A lease on part of that state is not
1277    /// enough. broca's session lease guards WAL appends while its run index, its
1278    /// store projector and its archive fold timer (which unlinks live WAL files)
1279    /// stay single-writer, so broca is exclusive despite holding a lease. The
1280    /// refusal only fires after this has been decided, so the decision is the
1281    /// check.
1282    Safe,
1283}
1284
1285impl ModuleOverlap {
1286    pub fn as_str(self) -> &'static str {
1287        match self {
1288            Self::Exclusive => "exclusive",
1289            Self::Safe => "safe",
1290        }
1291    }
1292}
1293
1294/// Environment variable telling a spawned module which case it was started
1295/// for, before it sends HELLO. Only a swap candidate carries it, as
1296/// [`SPAWN_ROLE_SWAP_CANDIDATE`]; every other spawn has it removed.
1297///
1298/// It chooses a warm-up budget, nothing else: a swap candidate can warm for
1299/// longer because nobody waits on it, while a plain restart must flip ready
1300/// quickly because callers see `module_warming` until it does. Absence means
1301/// plain restart, the safe reading. The daemon trusts nothing about it; the
1302/// candidate is proven by its launch nonce at HELLO.
1303pub const SUBC_SPAWN_ROLE_ENV: &str = "SUBC_SPAWN_ROLE";
1304/// The one value of [`SUBC_SPAWN_ROLE_ENV`] the daemon sets.
1305pub const SPAWN_ROLE_SWAP_CANDIDATE: &str = "swap_candidate";
1306/// How long a swap waits for its candidate to register and declare itself
1307/// ready when the operator does not say. A module warming as a swap candidate
1308/// may take up to 90 s (aft's ceiling, the largest in the fleet), so the
1309/// daemon allows that plus time to start the process and send HELLO.
1310pub const DEFAULT_SWAP_READY_TIMEOUT: Duration = Duration::from_secs(100);
1311
1312/// Bounded restart policy for crash exits.
1313///
1314/// `max_restarts` is the number of replacement processes allowed after the
1315/// initial spawn WITHIN `window`. After that many crash restarts inside one
1316/// window the module enters [`ModuleState::Failed`] and the supervisor stops
1317/// the crash loop.
1318///
1319/// The budget is a RATE, not a lifetime total. It used to be a lifetime total,
1320/// and that only survived because crashes were rare: a module that crashed
1321/// three times across a week was disabled forever by crashes that had nothing
1322/// to do with each other. That stopped being survivable once modules began
1323/// exiting non-zero whenever the daemon's connection to them drops, because
1324/// then every daemon-side connection drop spends a unit of the same budget and
1325/// one flappy hour permanently stops a healthy module. Restarts older than
1326/// `window` release their slot, so a module that crashed twice yesterday has a
1327/// full budget today, while a genuine crash loop -- which is fast by
1328/// definition -- still reaches the cap and stops.
1329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1330pub struct RestartPolicy {
1331    pub max_restarts: u32,
1332    /// Base delay before a crash replacement. The actual delay escalates with
1333    /// the number of recent crash replacements and is capped by `max_backoff`.
1334    pub backoff: Duration,
1335    /// Maximum delay before a crash replacement.
1336    pub max_backoff: Duration,
1337    /// The span `max_restarts` is counted over. `Duration::ZERO` makes the
1338    /// budget effectively infinite (nothing is ever in-window), which is why
1339    /// daemon config refuses `window_secs: 0` rather than quietly accepting it.
1340    pub window: Duration,
1341}
1342
1343impl RestartPolicy {
1344    /// A policy with the default crash window. Callers that care about the
1345    /// window say so with [`Self::with_window`]; the ones that do not are
1346    /// asking for the standard rate limit, not for no limit.
1347    pub fn new(max_restarts: u32, backoff: Duration) -> Self {
1348        Self {
1349            max_restarts,
1350            backoff,
1351            max_backoff: DEFAULT_MAX_BACKOFF,
1352            window: DEFAULT_RESTART_WINDOW,
1353        }
1354    }
1355
1356    pub fn with_max_backoff(mut self, max_backoff: Duration) -> Self {
1357        self.max_backoff = max_backoff;
1358        self
1359    }
1360
1361    pub fn with_window(mut self, window: Duration) -> Self {
1362        self.window = window;
1363        self
1364    }
1365
1366    /// Calculate the capped exponential delay for the next crash replacement.
1367    /// `restart_in_window` is zero for the first replacement after an operator
1368    /// action (restart, reload, re-enable) cleared the crash ring, or after all
1369    /// older crash replacements have aged out of the window.
1370    fn delay_for_restart(&self, restart_in_window: u32) -> Duration {
1371        if self.backoff.is_zero() || self.max_backoff.is_zero() {
1372            return Duration::ZERO;
1373        }
1374
1375        let mut delay = self.backoff;
1376        for _ in 0..restart_in_window {
1377            if delay >= self.max_backoff {
1378                return self.max_backoff;
1379            }
1380            delay = delay
1381                .checked_mul(10)
1382                .unwrap_or(self.max_backoff)
1383                .min(self.max_backoff);
1384        }
1385        delay.min(self.max_backoff)
1386    }
1387
1388    /// The one sentence that explains a budget-exhausted stop, used for both the
1389    /// log line and the terminal record so the two cannot drift. It names the
1390    /// window because `max_restarts=3` alone reads as a lifetime cap, which is
1391    /// exactly what this budget is not.
1392    fn budget_exhausted_detail(&self) -> String {
1393        format!(
1394            "crash budget exhausted: max_restarts={} within window_secs={}",
1395            self.max_restarts,
1396            self.window.as_secs()
1397        )
1398    }
1399}
1400
1401impl Default for RestartPolicy {
1402    fn default() -> Self {
1403        Self {
1404            max_restarts: DEFAULT_MAX_RESTARTS,
1405            backoff: DEFAULT_BACKOFF,
1406            max_backoff: DEFAULT_MAX_BACKOFF,
1407            window: DEFAULT_RESTART_WINDOW,
1408        }
1409    }
1410}
1411
1412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1413struct CrashRestartSchedule {
1414    restart_in_window: u32,
1415    delay: Duration,
1416}
1417
1418/// Whether the daemon itself will bring this module back after the exit being
1419/// handled: it is enabled AND its in-window crash restarts are below the cap.
1420///
1421/// Takes `&mut` because reading the budget prunes it. Instants that fell out of
1422/// the window are dropped here rather than by a timer, so the count is right
1423/// the moment somebody asks and no bookkeeping runs for idle modules.
1424fn daemon_will_restart(
1425    state: &mut SupervisorSnapshot,
1426    policy: &RestartPolicy,
1427    now: Instant,
1428) -> bool {
1429    state.enabled && state.crash_restarts_in_window(policy.window, now) < policy.max_restarts
1430}
1431
1432const DEFAULT_HEALTH_CADENCE: Duration = Duration::from_secs(30);
1433const DEFAULT_HEALTH_DEADLINE: Duration = Duration::from_secs(5);
1434const DEFAULT_HEALTH_FAILURE_THRESHOLD: u32 = 3;
1435const MAX_HEALTH_METRICS_BYTES: usize = 16 * 1024;
1436
1437#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1438pub enum HealthAction {
1439    Report,
1440    Restart,
1441    Alert,
1442}
1443
1444impl fmt::Display for HealthAction {
1445    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1446        f.write_str(match self {
1447            Self::Report => "report",
1448            Self::Restart => "restart",
1449            Self::Alert => "alert",
1450        })
1451    }
1452}
1453
1454#[derive(Debug, Clone, PartialEq, Eq)]
1455pub struct HealthConfig {
1456    /// Optional loopback HTTP endpoint for a managed non-wire process.
1457    /// Changing it applies live on rescan; the process protocol changes only
1458    /// at its next spawn.
1459    pub http: Option<String>,
1460    pub cadence: Duration,
1461    pub deadline: Duration,
1462    pub failure_threshold: u32,
1463    pub on_degraded: HealthAction,
1464    pub on_failing: HealthAction,
1465    pub critical: bool,
1466}
1467
1468impl Default for HealthConfig {
1469    fn default() -> Self {
1470        Self {
1471            http: None,
1472            cadence: DEFAULT_HEALTH_CADENCE,
1473            deadline: DEFAULT_HEALTH_DEADLINE,
1474            failure_threshold: DEFAULT_HEALTH_FAILURE_THRESHOLD,
1475            on_degraded: HealthAction::Report,
1476            on_failing: HealthAction::Report,
1477            critical: false,
1478        }
1479    }
1480}
1481
1482/// The supervisor's view of one module's health, relayed to clients over
1483/// channel-0 and rendered by `ck health`.
1484///
1485/// THIS TYPE IS WHERE THE ABSENCE MEANINGS ARE CREATED, which is why they are
1486/// stated here rather than only at the wire type a consumer reads. A reader can
1487/// look up what `None` means; only a writer can silently change it, and the
1488/// writer has no reason to go looking at a downstream contract before editing.
1489///
1490/// `last_probe_ms: None` MEANS NEVER PROBED, not probed-long-ago. It is cleared
1491/// back to `None` on re-registration precisely so a respawned module does not
1492/// carry its predecessor's timestamp — so an old value and an absent one call for
1493/// opposite readings, and anything that defaulted this to a number would make a
1494/// never-probed module indistinguishable from one probed at the epoch.
1495///
1496/// `detail` and `metrics` are `None` when the module published none on this
1497/// probe, which does not mean it reported nothing wrong — it is also the shape
1498/// when the probe never reached it. `last_probe_ms` is what separates those.
1499#[derive(Debug, Clone, PartialEq)]
1500pub struct ModuleHealthStatus {
1501    pub status: SupervisorHealthStatus,
1502    pub last_probe_ms: Option<u64>,
1503    pub detail: Option<String>,
1504    pub metrics: Option<Value>,
1505    pub consecutive_failures: u32,
1506    /// Number of replies received after a recurring health probe's deadline.
1507    /// Unlike a timeout, every increment proves the module was alive.
1508    pub late_answer_count: u64,
1509    /// End-to-end latency of the newest late reply, measured from probe start.
1510    pub last_late_answer_latency_ms: Option<u64>,
1511    pub last_action: Option<String>,
1512    /// Set together with `last_action`; the pair moves as one, and both being
1513    /// absent means no escalation has ever been taken rather than that the last
1514    /// one succeeded.
1515    pub last_action_ms: Option<u64>,
1516}
1517
1518impl Default for ModuleHealthStatus {
1519    fn default() -> Self {
1520        Self {
1521            status: SupervisorHealthStatus::Unknown,
1522            last_probe_ms: None,
1523            detail: None,
1524            metrics: None,
1525            consecutive_failures: 0,
1526            late_answer_count: 0,
1527            last_late_answer_latency_ms: None,
1528            last_action: None,
1529            last_action_ms: None,
1530        }
1531    }
1532}
1533
1534/// Typed lifecycle state for a supervised module.
1535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1536pub enum ModuleState {
1537    Starting,
1538    Running,
1539    Unresponsive,
1540    Restarting,
1541    Draining,
1542    Stopped,
1543    Failed,
1544    Disabled,
1545}
1546
1547impl fmt::Display for ModuleState {
1548    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1549        f.write_str(match self {
1550            Self::Starting => "starting",
1551            Self::Running => "running",
1552            Self::Unresponsive => "unresponsive",
1553            Self::Restarting => "restarting",
1554            Self::Draining => "draining",
1555            Self::Stopped => "stopped",
1556            Self::Failed => "failed",
1557            Self::Disabled => "disabled",
1558        })
1559    }
1560}
1561
1562/// Supervisor classification of a child-process exit.
1563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1564pub enum ExitKind {
1565    Clean,
1566    Crash,
1567    DeliberateSeverance,
1568}
1569
1570impl From<ExitKind> for TerminalExitKind {
1571    fn from(kind: ExitKind) -> Self {
1572        match kind {
1573            ExitKind::Clean => Self::Clean,
1574            ExitKind::Crash => Self::Crash,
1575            ExitKind::DeliberateSeverance => Self::DeliberateSeverance,
1576        }
1577    }
1578}
1579
1580/// Exact process identity retained when a supervised module registers its
1581/// connection. PID reuse makes a PID alone insufficient evidence of ownership.
1582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1583pub(crate) struct ProcessIdentity {
1584    pub(crate) pid: u32,
1585    pub(crate) start_time: u64,
1586}
1587
1588/// Last observed child exit, if any.
1589#[derive(Debug, Clone, PartialEq, Eq)]
1590pub struct ExitReport {
1591    pub kind: ExitKind,
1592    pub code: Option<i32>,
1593    pub signal: Option<i32>,
1594    pub at_ms: u64,
1595}
1596
1597/// Point-in-time module status answerable by subc without forwarding to the
1598/// module process.
1599#[derive(Debug, Clone, PartialEq)]
1600pub struct ModuleStatus {
1601    pub(crate) admission_refused: Option<String>,
1602    pub(crate) legacy_registration_spawn: bool,
1603    pub(crate) registration_declaration: Option<String>,
1604    pub module_id: String,
1605    /// Retained configuration-exit infrastructure failure. Cleared only after a
1606    /// successful launch; an ordinary stop has no infrastructure stop reason.
1607    pub stop_reason: Option<ModuleStopReason>,
1608    /// A previous daemon's unresolved process, not a child owned by this supervisor.
1609    pub waiting_for_previous_pid: Option<u32>,
1610    /// Why the previous instance still prevents a new start.
1611    pub waiting_for_previous_detail: Option<String>,
1612    /// The daemon's Windows per-spawn record: `pipe` after the process it
1613    /// spawned read all nonce bytes, otherwise `env` for the offered copy.
1614    /// List/status reports use this record, not the source the module sends
1615    /// in its registration message's manifest.provenance.launch_nonce_source.
1616    pub launch_nonce_source: Option<String>,
1617    pub state: ModuleState,
1618    pub enabled: bool,
1619    pub process_alive: bool,
1620    pub registration_active: bool,
1621    /// The module's declared wire protocol, carried beside `live` because it is
1622    /// what makes `live` readable: the two fields answer one question together.
1623    /// While a process is alive this is its launch declaration, not a later
1624    /// pending-reload edit. When down it is the configured next launch protocol.
1625    pub protocol: ModuleProtocol,
1626    /// Whether the module is serving, under the strongest definition the daemon
1627    /// can assert for its protocol.
1628    ///
1629    /// A subc module must also be REGISTERED: its process being alive says
1630    /// nothing about whether it can take a request. A `protocol: "none"` module
1631    /// never registers, so that term is dropped and this falls back to "enabled,
1632    /// running, and the process the daemon launched is alive" -- which is all
1633    /// the daemon observes about a process that speaks no subc wire. It stays a
1634    /// `bool` on the wire for compatibility; renderers pair it with `protocol`
1635    /// rather than printing it bare.
1636    pub live: bool,
1637    /// Crash restarts spent INSIDE `restart_window` as of this read. Older
1638    /// restarts have already released their slot, so this count can go down
1639    /// without anybody touching the module.
1640    pub restart_count: u32,
1641    /// Replacement processes spawned over this module's entire supervisor lifetime;
1642    /// unlike `restart_count`, this value is never reset by an operator action
1643    /// and never falls out of a window.
1644    pub lifetime_restarts: u32,
1645    pub spawn_generation: u64,
1646    /// Retained daemon-local outcome; the legacy control response omits it.
1647    pub swap_outcome: Option<SwapOutcome>,
1648    /// The budget `restart_count` is spent against. Carried alongside the count
1649    /// because the count alone does not say how close the module is to being
1650    /// disabled, and reporting one without the other is what makes an
1651    /// about-to-be-retired module look ordinary.
1652    pub max_restarts: u32,
1653    /// The span `restart_count` is counted over. Carried with the pair above for
1654    /// the same reason they are carried together: "2 of 3" means one thing for a
1655    /// ten-minute window and something else entirely for a lifetime.
1656    pub restart_window: Duration,
1657    /// Effective drain and restart timing policy used by this running module.
1658    /// These values are carried together with the restart budget so status
1659    /// readers can compare configured intent with what the supervisor applied.
1660    pub drain_timeout: Duration,
1661    pub restart_backoff: Duration,
1662    pub restart_max_backoff: Duration,
1663    /// The module's process. On macOS this stays absent while the `ck-subc`
1664    /// launch trampoline is still running in that pid, and appears once the
1665    /// exec acknowledgement confirms the module image has replaced it. Launch
1666    /// time and the supervisor's own hold on the process are unaffected.
1667    pub pid: Option<u32>,
1668    pub spawned_at_ms: Option<u64>,
1669    pub spawned_from: Option<PathBuf>,
1670    pub(crate) launch_spec_digest: Option<LaunchSpecDigest>,
1671    pub process_start_time: Option<u64>,
1672    pub last_exit: Option<ExitReport>,
1673    pub health: ModuleHealthStatus,
1674}
1675
1676#[cfg(test)]
1677#[derive(Debug, Clone, Copy, PartialEq)]
1678struct ActorSelectCheckpoint {
1679    generation: u64,
1680    turn: u64,
1681    registered_connection: Option<ConnectionId>,
1682    next_probe_at: Option<Instant>,
1683    wake_after: Option<Duration>,
1684}
1685
1686#[derive(Debug, Clone, PartialEq)]
1687struct SupervisorSnapshot {
1688    admission_refused: Option<String>,
1689    /// Distinguishes an admission-parked actor from an unrelated terminal exit.
1690    config_hold_parked: bool,
1691    /// Preserve daemon attribution for a paused start so a failing release can
1692    /// schedule the next slow retry instead of treating the start as operator work.
1693    config_hold_daemon_initiated: bool,
1694    /// The approval that owns the parked attempt, not whichever approval is latest.
1695    config_hold_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
1696    /// Retain an approved launch failure across competing reconciliation passes.
1697    approved_start_failure: Option<(crate::config_gate::runtime::ApprovalIdentity, String)>,
1698    legacy_registration_spawn: bool,
1699    registration_declaration: Option<String>,
1700    stop_reason: Option<ModuleStopReason>,
1701    config_exit_failed_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
1702    subtree_target: crate::subtree_resources::Target,
1703    failed_retry: FailedRetry,
1704    exec_outcome: Option<Arc<crate::activity::ExecOutcome>>,
1705    #[cfg(windows)]
1706    pipe_consumed: Option<Arc<OnceLock<()>>>,
1707    /// Counts running-child loop turns, not executor polls of a parked wait.
1708    #[cfg(test)]
1709    actor_turns: u64,
1710    /// Running select after exec confirmation and with no unconsumed registry
1711    /// event. Recording a spawn or starting a loop turn is not this barrier.
1712    #[cfg(test)]
1713    actor_select: Option<ActorSelectCheckpoint>,
1714    state: ModuleState,
1715    enabled: bool,
1716    process_alive: bool,
1717    spawned_protocol: Option<ModuleProtocol>,
1718    spawn_failure: Option<String>,
1719    waiting_for_previous_pid: Option<u32>,
1720    waiting_for_previous_detail: Option<String>,
1721    /// When each crash restart was spent, oldest first. This IS the crash
1722    /// budget: its in-window length is the count an operator sees and the count
1723    /// the restart decision is made against, so there is no second counter that
1724    /// can disagree with it. Bounded by `max_restarts`, and cleared by the same
1725    /// operator actions that used to zero the old lifetime counter.
1726    crash_restarts: VecDeque<Instant>,
1727    lifetime_restarts: u32,
1728    /// Successful child spawns in this daemon incarnation.
1729    ///
1730    /// `lifetime_restarts` was considered and rejected: it starts at zero
1731    /// (line 640), successful initial/operator spawns in `set_running` do not
1732    /// increment it (lines 5264-5274), and crash/deliberate retry bookkeeping
1733    /// increments before a successful replacement exists (lines 604, 3846,
1734    /// and 3921), so a failed spawn can consume it. This counter moves only
1735    /// when a live PID is accepted below.
1736    spawn_generation: u64,
1737    swap_outcome: Option<SwapOutcome>,
1738    pid: Option<u32>,
1739    #[cfg(target_os = "macos")]
1740    report_ready: Option<Arc<OnceLock<()>>>,
1741    /// Last reaped child, retained after current process facts are cleared.
1742    reaped_pid: Option<u32>,
1743    /// Whether a replacement has already been scheduled for the current process.
1744    respawn_pending: bool,
1745    /// A second restart is waiting for the replacement already scheduled.
1746    coalesced_restart_pending: bool,
1747    spawned_at_ms: Option<u64>,
1748    spawned_from: Option<PathBuf>,
1749    launch_spec_digest: Option<LaunchSpecDigest>,
1750    spawned_file_identity: Option<SpawnedFileIdentity>,
1751    process_start_time: Option<u64>,
1752    deliberate_severance: Option<ProcessIdentity>,
1753    last_exit: Option<ExitReport>,
1754    /// Diagnostic attached to the next drain's terminal record, if any.
1755    drain_disposition_detail: Option<String>,
1756    health: ModuleHealthStatus,
1757    last_probe_evidence: Option<HealthProbeEvidence>,
1758    /// Whether the current process was started as a swap candidate and so
1759    /// lives in the module's alternate cgroup. The next swap's candidate takes
1760    /// the other one, so the two processes of a swap never share a cgroup. A
1761    /// plain spawn always uses the primary cgroup.
1762    in_alternate_slot: bool,
1763    /// Whether the current `Draining` state ends in a replacement process
1764    /// (restart, reload, health restart) rather than a stop. Only meaningful
1765    /// while `state` is `Draining`; every entry into that state rewrites it.
1766    /// It is what lets route.open answer the retryable `module_reloading` to a
1767    /// consumer that reaches a still-registered process mid-restart, instead of
1768    /// the `supervisor_not_live` a stop or disable deserves.
1769    draining_to_replace: bool,
1770    /// Whether a configuration update has been applied since the current
1771    /// process was spawned, so that process runs an older spec than the one
1772    /// the supervisor now holds. A queued restart is only coalesced into a
1773    /// fresher process when this is false: a restart requested to pick up a
1774    /// new configuration must not be satisfied by a process that predates it.
1775    configuration_updated_since_spawn: bool,
1776}
1777
1778impl SupervisorSnapshot {
1779    /// The pid that status, provenance and resource readings may report. While
1780    /// the launch trampoline still runs in the pid, reading its executable or
1781    /// resource use would describe `ck-subc`, not the module, so none is
1782    /// reported until the exec acknowledgement confirms the module image.
1783    fn reported_pid(&self) -> Option<u32> {
1784        #[cfg(target_os = "macos")]
1785        if self
1786            .report_ready
1787            .as_ref()
1788            .is_some_and(|ready| ready.get().is_none())
1789        {
1790            return None;
1791        }
1792        self.pid
1793    }
1794
1795    fn starting() -> Self {
1796        Self::new(ModuleState::Starting, true)
1797    }
1798
1799    fn disabled() -> Self {
1800        Self::new(ModuleState::Disabled, false)
1801    }
1802
1803    /// Crash restarts still inside `window`, having dropped the ones that are
1804    /// not. Pruning on read is what makes the budget a rate: an instant older
1805    /// than the window stops holding a slot the moment anybody counts.
1806    fn crash_restarts_in_window(&mut self, window: Duration, now: Instant) -> u32 {
1807        while let Some(oldest) = self.crash_restarts.front() {
1808            if now.duration_since(*oldest) > window {
1809                self.crash_restarts.pop_front();
1810            } else {
1811                break;
1812            }
1813        }
1814        u32::try_from(self.crash_restarts.len()).unwrap_or(u32::MAX)
1815    }
1816
1817    /// Spend one unit of the crash budget and record the restart in the ledger.
1818    ///
1819    /// The ring is bounded by the cap because more than `max_restarts` in-window
1820    /// instants can never be reached (the caller refuses the restart first), so
1821    /// anything beyond that is an unbounded queue waiting to happen.
1822    fn record_crash_restart(&mut self, policy: &RestartPolicy, now: Instant) {
1823        self.crash_restarts.push_back(now);
1824        while self.crash_restarts.len() > policy.max_restarts as usize {
1825            self.crash_restarts.pop_front();
1826        }
1827        self.lifetime_restarts += 1;
1828    }
1829
1830    /// Reserve one crash-restart slot and calculate the delay before respawning.
1831    /// The count is captured before recording this restart, so the first retry
1832    /// uses the base delay and each later in-window retry escalates once.
1833    fn next_crash_restart(
1834        &mut self,
1835        policy: &RestartPolicy,
1836        now: Instant,
1837    ) -> Option<CrashRestartSchedule> {
1838        let restart_in_window = self.crash_restarts_in_window(policy.window, now);
1839        if restart_in_window >= policy.max_restarts {
1840            return None;
1841        }
1842        self.record_crash_restart(policy, now);
1843        Some(CrashRestartSchedule {
1844            restart_in_window,
1845            delay: policy.delay_for_restart(restart_in_window),
1846        })
1847    }
1848
1849    /// Give the module its full budget back, as an operator restart, reload, or
1850    /// re-enable does. `lifetime_restarts` deliberately does not move: it is the
1851    /// ledger of what actually happened, and an operator action does not unmake
1852    /// the crashes.
1853    fn clear_crash_restarts(&mut self) {
1854        self.crash_restarts.clear();
1855    }
1856
1857    fn new(state: ModuleState, enabled: bool) -> Self {
1858        Self {
1859            admission_refused: None,
1860            config_hold_parked: false,
1861            config_hold_daemon_initiated: false,
1862            config_hold_approval: None,
1863            approved_start_failure: None,
1864            legacy_registration_spawn: false,
1865            registration_declaration: None,
1866            stop_reason: None,
1867            config_exit_failed_approval: None,
1868            subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
1869            failed_retry: FailedRetry::default(),
1870            exec_outcome: None,
1871            #[cfg(test)]
1872            actor_turns: 0,
1873            #[cfg(test)]
1874            actor_select: None,
1875            state,
1876            enabled,
1877            process_alive: false,
1878            #[cfg(windows)]
1879            pipe_consumed: None,
1880            spawned_protocol: None,
1881            spawn_failure: None,
1882            waiting_for_previous_pid: None,
1883            waiting_for_previous_detail: None,
1884            crash_restarts: VecDeque::new(),
1885            lifetime_restarts: 0,
1886            spawn_generation: 0,
1887            swap_outcome: None,
1888            pid: None,
1889            #[cfg(target_os = "macos")]
1890            report_ready: None,
1891            reaped_pid: None,
1892            respawn_pending: false,
1893            coalesced_restart_pending: false,
1894            spawned_at_ms: None,
1895            spawned_from: None,
1896            launch_spec_digest: None,
1897            spawned_file_identity: None,
1898            process_start_time: None,
1899            deliberate_severance: None,
1900            last_exit: None,
1901            drain_disposition_detail: None,
1902            health: ModuleHealthStatus::default(),
1903            last_probe_evidence: None,
1904            in_alternate_slot: false,
1905            draining_to_replace: false,
1906            configuration_updated_since_spawn: false,
1907        }
1908    }
1909}
1910
1911type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
1912
1913type SpawnSubscriberKey = (ConnectionId, u64);
1914
1915#[derive(Debug)]
1916struct SpawnSubscriber {
1917    version: u8,
1918    frames: mpsc::Sender<Frame>,
1919    /// Tells this subscriber's forwarder that it was dropped for lagging, and
1920    /// from which event. The full frame channel cannot carry that news, so it
1921    /// travels beside it; see `SpawnEventFeed::subscribe`.
1922    lagged: Option<oneshot::Sender<SpawnCursor>>,
1923}
1924
1925#[derive(Debug)]
1926struct SpawnEventState {
1927    daemon_incarnation: String,
1928    seq: u64,
1929    capacity: usize,
1930    live: HashMap<String, LiveSpawn>,
1931    generations: HashMap<String, u64>,
1932    events: VecDeque<SpawnEvent>,
1933    subscribers: HashMap<SpawnSubscriberKey, SpawnSubscriber>,
1934    process_changes: HashMap<String, tokio::sync::watch::Sender<u64>>,
1935}
1936
1937impl Default for SpawnEventState {
1938    fn default() -> Self {
1939        Self {
1940            daemon_incarnation: "unconfigured".to_string(),
1941            seq: 0,
1942            capacity: SPAWN_EVENT_RING_CAPACITY,
1943            live: HashMap::new(),
1944            generations: HashMap::new(),
1945            events: VecDeque::new(),
1946            subscribers: HashMap::new(),
1947            process_changes: HashMap::new(),
1948        }
1949    }
1950}
1951
1952#[derive(Debug, Clone, Default)]
1953struct SpawnEventFeed(
1954    Arc<Mutex<SpawnEventState>>,
1955    #[cfg(test)] Arc<Mutex<Option<std::net::TcpStream>>>,
1956);
1957
1958#[derive(Debug, Clone, PartialEq, Eq)]
1959pub(crate) enum SpawnSubscribeRefusal {
1960    ForeignIncarnation { current: String },
1961    TooOld { oldest: SpawnCursor },
1962    Frame(String),
1963}
1964
1965impl SpawnEventFeed {
1966    fn configure_incarnation(&self, daemon_incarnation: String) {
1967        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1968        state.daemon_incarnation = daemon_incarnation;
1969        state.seq = 0;
1970        state.live.clear();
1971        state.generations.clear();
1972        state.events.clear();
1973        state.subscribers.clear();
1974        for changed in state.process_changes.values() {
1975            changed.send_replace(0);
1976        }
1977    }
1978
1979    fn cursor(state: &SpawnEventState) -> SpawnCursor {
1980        SpawnCursor {
1981            daemon_incarnation: state.daemon_incarnation.clone(),
1982            seq: state.seq,
1983        }
1984    }
1985
1986    fn snapshot(&self) -> SpawnSnapshot {
1987        let state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1988        let mut live = state.live.values().cloned().collect::<Vec<_>>();
1989        live.sort_by(|left, right| left.module_id.cmp(&right.module_id));
1990        SpawnSnapshot {
1991            cursor: Self::cursor(&state),
1992            ring_bound: state.capacity as u64,
1993            live,
1994        }
1995    }
1996
1997    fn allocate_generation_locked(state: &mut SpawnEventState, module_id: &str) -> u64 {
1998        let generation = state
1999            .generations
2000            .get(module_id)
2001            .copied()
2002            .unwrap_or(0)
2003            .checked_add(1)
2004            .expect("spawn generation exhausted");
2005        state.generations.insert(module_id.to_string(), generation);
2006        generation
2007    }
2008
2009    /// Allocate the spawn generation of a launch that is about to start, with
2010    /// the daemon incarnation it belongs to. The number names the launch from
2011    /// this moment, before its process runs; a launch that never runs keeps
2012    /// its number, so the generations a subscriber sees may skip.
2013    fn allocate_generation(&self, module_id: &str) -> (String, u64) {
2014        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2015        let generation = Self::allocate_generation_locked(&mut state, module_id);
2016        (state.daemon_incarnation.clone(), generation)
2017    }
2018
2019    /// Publish a running process. `allocated` is the generation its launch
2020    /// was given before it started; a launch without one (a process with no
2021    /// registration channel) is numbered here.
2022    fn emit_spawned(
2023        &self,
2024        module_id: &str,
2025        allocated: Option<u64>,
2026        pid: u32,
2027        spawned_at_ms: u64,
2028    ) -> u64 {
2029        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2030        let generation = match allocated {
2031            Some(generation) => generation,
2032            None => Self::allocate_generation_locked(&mut state, module_id),
2033        };
2034        let live = LiveSpawn {
2035            module_id: module_id.to_string(),
2036            spawn_generation: generation,
2037            pid,
2038            spawned_at_ms,
2039        };
2040        state.live.insert(module_id.to_string(), live);
2041        Self::emit_locked(
2042            &mut state,
2043            SpawnEventKind::Spawned,
2044            module_id.to_string(),
2045            generation,
2046            pid,
2047            None,
2048            None,
2049        );
2050        generation
2051    }
2052
2053    fn emit_exited(&self, module_id: &str, exit_code: Option<i32>, exit_signal: Option<i32>) {
2054        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2055        let Some(live) = state.live.remove(module_id) else {
2056            warn!(
2057                module_id,
2058                "terminal record had no live spawn event identity"
2059            );
2060            return;
2061        };
2062        Self::emit_locked(
2063            &mut state,
2064            SpawnEventKind::Exited,
2065            module_id.to_string(),
2066            live.spawn_generation,
2067            live.pid,
2068            exit_code,
2069            exit_signal,
2070        );
2071    }
2072
2073    /// Report the exit of a process that a swap has already replaced.
2074    ///
2075    /// `emit_exited` removes the module's live entry, which after a swap's
2076    /// cutover describes the promoted candidate, not the old process now
2077    /// exiting. This emits the old generation's exit and leaves the live entry
2078    /// alone unless it still names that generation.
2079    fn emit_superseded_exited(
2080        &self,
2081        module_id: &str,
2082        spawn_generation: u64,
2083        pid: u32,
2084        exit_code: Option<i32>,
2085        exit_signal: Option<i32>,
2086    ) {
2087        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2088        if state
2089            .live
2090            .get(module_id)
2091            .is_some_and(|live| live.spawn_generation == spawn_generation)
2092        {
2093            state.live.remove(module_id);
2094        }
2095        Self::emit_locked(
2096            &mut state,
2097            SpawnEventKind::Exited,
2098            module_id.to_string(),
2099            spawn_generation,
2100            pid,
2101            exit_code,
2102            exit_signal,
2103        );
2104    }
2105
2106    #[allow(clippy::too_many_arguments)]
2107    fn emit_locked(
2108        state: &mut SpawnEventState,
2109        kind: SpawnEventKind,
2110        module_id: String,
2111        spawn_generation: u64,
2112        pid: u32,
2113        exit_code: Option<i32>,
2114        exit_signal: Option<i32>,
2115    ) {
2116        state.seq = state
2117            .seq
2118            .checked_add(1)
2119            .expect("spawn event sequence exhausted");
2120        let event = SpawnEvent {
2121            cursor: Self::cursor(state),
2122            kind,
2123            module_id,
2124            spawn_generation,
2125            pid,
2126            exit_code,
2127            exit_signal,
2128        };
2129        state
2130            .process_changes
2131            .retain(|_, changed| changed.receiver_count() > 0);
2132        if let Some(changed) = state.process_changes.get(&event.module_id) {
2133            changed.send_replace(state.seq);
2134        }
2135        state.events.push_back(event.clone());
2136        while state.events.len() > state.capacity {
2137            state.events.pop_front();
2138        }
2139        let body = match serde_json::to_vec(&event) {
2140            Ok(body) => body,
2141            Err(error) => {
2142                error!(%error, "failed to serialize supervisor spawn event");
2143                return;
2144            }
2145        };
2146        state.subscribers.retain(|(connection_id, corr), subscriber| {
2147            let frame = Frame::build_with_version(
2148                subscriber.version,
2149                FrameType::StreamData,
2150                control_flags(),
2151                0,
2152                0,
2153                *corr,
2154                body.clone(),
2155            );
2156            match frame {
2157                Ok(frame) => {
2158                    if subscriber.frames.try_send(frame).is_ok() {
2159                        true
2160                    } else {
2161                        warn!(connection_id = connection_id.get(), corr, "dropping lagged supervisor spawn subscriber");
2162                        if let Some(lagged) = subscriber.lagged.take() {
2163                            let _ = lagged.send(event.cursor.clone());
2164                        }
2165                        false
2166                    }
2167                }
2168                Err(error) => {
2169                    warn!(connection_id = connection_id.get(), corr, %error, "dropping supervisor spawn subscriber after frame build failure");
2170                    false
2171                }
2172            }
2173        });
2174    }
2175
2176    fn subscribe(
2177        &self,
2178        connection_id: ConnectionId,
2179        corr: u64,
2180        version: u8,
2181        since: Option<SpawnCursor>,
2182        sink: FrameSink,
2183    ) -> Result<(), SpawnSubscribeRefusal> {
2184        let (frames, mut receiver) = mpsc::channel(SPAWN_SUBSCRIBER_BUFFER);
2185        let (lagged, mut lagged_rx) = oneshot::channel::<SpawnCursor>();
2186        {
2187            let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2188            let replay = if let Some(since) = since {
2189                if since.daemon_incarnation != state.daemon_incarnation {
2190                    return Err(SpawnSubscribeRefusal::ForeignIncarnation {
2191                        current: state.daemon_incarnation.clone(),
2192                    });
2193                }
2194                if let Some(oldest) = state.events.front().map(|event| event.cursor.clone()) {
2195                    if since.seq < oldest.seq.saturating_sub(1) {
2196                        return Err(SpawnSubscribeRefusal::TooOld { oldest });
2197                    }
2198                }
2199                state
2200                    .events
2201                    .iter()
2202                    .filter(|event| event.cursor.seq > since.seq)
2203                    .cloned()
2204                    .collect::<Vec<_>>()
2205            } else {
2206                Vec::new()
2207            };
2208            for event in replay {
2209                let body = serde_json::to_vec(&event)
2210                    .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2211                let frame = Frame::build_with_version(
2212                    version,
2213                    FrameType::StreamData,
2214                    control_flags(),
2215                    0,
2216                    0,
2217                    corr,
2218                    body,
2219                )
2220                .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2221                frames
2222                    .try_send(frame)
2223                    .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2224            }
2225            state.subscribers.insert(
2226                (connection_id, corr),
2227                SpawnSubscriber {
2228                    version,
2229                    frames,
2230                    lagged: Some(lagged),
2231                },
2232            );
2233        }
2234        // The lagged terminal is sent here, by the forwarder, rather than by
2235        // the emitter: at the moment of the drop the subscriber's own channel
2236        // is full, and writing to the connection sink directly from the emitter
2237        // would put the Error AHEAD of the events still queued in that channel
2238        // (and the emitter holds the feed lock, so it cannot await the sink).
2239        // Dropping the subscriber drops the only sender, so `recv` drains every
2240        // queued event and then returns `None`; only then is the Error sent, so
2241        // the client sees each event it can keep, then the reason it was cut.
2242        // Cancel and connection removal drop the oneshot unsent, so they end
2243        // the stream with no Error.
2244        tokio::spawn(async move {
2245            while let Some(frame) = receiver.recv().await {
2246                if sink.send(frame).await.is_err() {
2247                    return;
2248                }
2249            }
2250            let Ok(first_undelivered) = lagged_rx.try_recv() else {
2251                return;
2252            };
2253            match spawn_subscriber_lagged_frame(version, corr, first_undelivered) {
2254                Ok(frame) => {
2255                    let _ = sink.send(frame).await;
2256                }
2257                Err(error) => {
2258                    error!(%error, corr, "failed to build lagged spawn subscriber terminal frame");
2259                }
2260            }
2261        });
2262        Ok(())
2263    }
2264
2265    fn cancel(&self, connection_id: ConnectionId, corr: u64) -> bool {
2266        let Some(subscriber) = self
2267            .0
2268            .lock()
2269            .unwrap_or_else(|p| p.into_inner())
2270            .subscribers
2271            .remove(&(connection_id, corr))
2272        else {
2273            return false;
2274        };
2275        if let Ok(frame) = Frame::build_with_version(
2276            subscriber.version,
2277            FrameType::StreamEnd,
2278            control_flags(),
2279            0,
2280            0,
2281            corr,
2282            Vec::new(),
2283        ) {
2284            tokio::spawn(async move {
2285                let _ = subscriber.frames.send(frame).await;
2286            });
2287        }
2288        true
2289    }
2290
2291    fn remove_connection(&self, connection_id: ConnectionId) {
2292        self.0
2293            .lock()
2294            .unwrap_or_else(|p| p.into_inner())
2295            .subscribers
2296            .retain(|(subscriber_connection, _), _| *subscriber_connection != connection_id);
2297    }
2298
2299    #[cfg(any(test, feature = "test-support"))]
2300    fn set_capacity(&self, capacity: usize) {
2301        self.0.lock().unwrap_or_else(|p| p.into_inner()).capacity = capacity;
2302    }
2303
2304    #[cfg(any(test, feature = "test-support"))]
2305    fn subscriber_count(&self) -> usize {
2306        self.0
2307            .lock()
2308            .unwrap_or_else(|p| p.into_inner())
2309            .subscribers
2310            .len()
2311    }
2312}
2313
2314/// Narrow process-liveness signal published by supervisors and consumed by passive liveness polls.
2315/// The terminal Error a lagged spawn subscriber receives after its queued events.
2316fn spawn_subscriber_lagged_frame(
2317    version: u8,
2318    corr: u64,
2319    first_undelivered: SpawnCursor,
2320) -> Result<Frame, String> {
2321    // The daemon authors this terminal Error, so it carries the daemon-origin bit.
2322    let body = serde_json::to_vec(&subc_protocol::ErrorBody {
2323        code: SPAWN_SUBSCRIBER_LAGGED_CODE.to_string(),
2324        message: "spawn subscriber fell behind and was dropped; resubscribe from the last cursor received"
2325            .to_string(),
2326        detail: Some(serde_json::json!({
2327            "first_undelivered_cursor": first_undelivered
2328        })),
2329    })
2330    .map_err(|error| error.to_string())?;
2331    Frame::build_with_version(
2332        version,
2333        FrameType::Error,
2334        crate::router::daemon_error_flags(),
2335        0,
2336        0,
2337        corr,
2338        body,
2339    )
2340    .map_err(|error| error.to_string())
2341}
2342
2343pub trait ModuleProcessLiveness: Send + Sync {
2344    fn process_live(&self, module_id: &str) -> Option<bool>;
2345
2346    /// Whether the supervisor is replacing this module's process right now: an
2347    /// operator restart or reload, a health restart, or a crash respawn whose
2348    /// backoff is running. A module in that state is not live, but a consumer
2349    /// refused now should retry shortly rather than treat the target as gone.
2350    /// Stopped, failed, and disabled modules are not replacing.
2351    fn process_replacing(&self, _module_id: &str) -> bool {
2352        false
2353    }
2354}
2355
2356/// Shared process-liveness registry keyed by supervised `module_id`.
2357#[derive(Debug, Clone, Default)]
2358pub struct SupervisorProcessLiveness {
2359    snapshots: Arc<Mutex<HashMap<String, SharedSnapshot>>>,
2360}
2361
2362impl SupervisorProcessLiveness {
2363    pub fn new() -> Self {
2364        Self::default()
2365    }
2366
2367    fn track(&self, module_id: String, snapshot: SharedSnapshot) {
2368        let mut snapshots = self
2369            .snapshots
2370            .lock()
2371            .unwrap_or_else(|poisoned| poisoned.into_inner());
2372        snapshots.insert(module_id, snapshot);
2373    }
2374
2375    fn untrack_if_current(&self, module_id: &str, snapshot: &SharedSnapshot) {
2376        let mut snapshots = self
2377            .snapshots
2378            .lock()
2379            .unwrap_or_else(|poisoned| poisoned.into_inner());
2380        let is_current = snapshots
2381            .get(module_id)
2382            .map(|tracked| Arc::ptr_eq(tracked, snapshot))
2383            .unwrap_or(false);
2384        if is_current {
2385            snapshots.remove(module_id);
2386        }
2387    }
2388}
2389
2390impl ModuleProcessLiveness for SupervisorProcessLiveness {
2391    fn process_live(&self, module_id: &str) -> Option<bool> {
2392        let snapshot = {
2393            let snapshots = self
2394                .snapshots
2395                .lock()
2396                .unwrap_or_else(|poisoned| poisoned.into_inner());
2397            snapshots.get(module_id).cloned()
2398        }?;
2399        let snapshot = snapshot
2400            .lock()
2401            .unwrap_or_else(|poisoned| poisoned.into_inner());
2402        Some(snapshot.state == ModuleState::Running && snapshot.process_alive)
2403    }
2404
2405    fn process_replacing(&self, module_id: &str) -> bool {
2406        let Some(snapshot) = self
2407            .snapshots
2408            .lock()
2409            .unwrap_or_else(|poisoned| poisoned.into_inner())
2410            .get(module_id)
2411            .cloned()
2412        else {
2413            return false;
2414        };
2415        let snapshot = snapshot
2416            .lock()
2417            .unwrap_or_else(|poisoned| poisoned.into_inner());
2418        snapshot.enabled
2419            && match snapshot.state {
2420                ModuleState::Restarting => true,
2421                ModuleState::Draining => snapshot.draining_to_replace,
2422                ModuleState::Starting
2423                | ModuleState::Running
2424                | ModuleState::Unresponsive
2425                | ModuleState::Stopped
2426                | ModuleState::Failed
2427                | ModuleState::Disabled => false,
2428            }
2429    }
2430}
2431
2432#[cfg(test)]
2433#[derive(Debug, Default)]
2434struct ReloadExitRecordGate {
2435    reached: tokio::sync::Notify,
2436    resume: tokio::sync::Notify,
2437}
2438
2439#[derive(Debug, Clone, Copy)]
2440enum RespawnKind {
2441    Spawn,
2442    Reload,
2443}
2444
2445#[derive(Debug, Clone)]
2446struct PendingRespawn {
2447    deadline: Instant,
2448    kind: RespawnKind,
2449    daemon_initiated: bool,
2450    approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
2451}
2452
2453impl PendingRespawn {
2454    fn failure_context(&self, runtime: &SupervisorRuntimeConfig) -> FailureContext {
2455        FailureContext {
2456            approval: self.approval.clone(),
2457            ..runtime.failure_context(self.daemon_initiated)
2458        }
2459    }
2460}
2461
2462type ReloadReply = oneshot::Sender<Result<(), SuperviseError>>;
2463
2464#[derive(Debug, Clone)]
2465struct SupervisorRuntimeConfig {
2466    registry: Arc<Registry>,
2467    config_delivery: Option<config_delivery::ConfigDelivery>,
2468    /// Retained across an operation's deferred backoff, until its child starts.
2469    recovery_is_daemon: bool,
2470    start_requester: Option<Principal>,
2471    pending_activity_restart: bool,
2472    provenance_probe: ExecutableIdentityProbe,
2473    /// Restart operations hand their backoff to the loop, which keeps serving commands.
2474    scheduled_respawn: Arc<Mutex<Option<PendingRespawn>>>,
2475    /// A reload acknowledges completion only after its replacement registers.
2476    deferred_reload_reply: Arc<Mutex<Option<ReloadReply>>>,
2477    restart_policy: RestartPolicy,
2478    register_timeout: Duration,
2479    /// This module's RESOLVED drain budget: per-module config when present,
2480    /// else `default_drain_timeout`.
2481    drain_timeout: Duration,
2482    /// Shared with the status handle so the attested value changes atomically
2483    /// when a rescan updates the running drain policy.
2484    effective_drain_timeout: Arc<Mutex<Duration>>,
2485    /// The supervisor-wide fallback, kept so a configuration update that
2486    /// REMOVES the per-module override can re-resolve to it.
2487    default_drain_timeout: Duration,
2488    health: HealthConfig,
2489    host_health: HostHealth,
2490    connection_file_path: Option<PathBuf>,
2491    capture_logs_dir: Option<PathBuf>,
2492    forwarding: Option<Arc<ForwardingTable>>,
2493    /// The shared handle, so every spawn path (initial, restart, reload) records the
2494    /// reserved-module launch nonce the HELLO verifier checks against.
2495    supervisor_handle: Option<SupervisorHandle>,
2496    /// This module's stderr tail, shared with the [`SupervisedModule`] that answers
2497    /// status queries.
2498    ///
2499    /// One ring per module, held across every respawn. The lines explaining an exit
2500    /// are written BEFORE that exit, so a ring recreated per process would be empty
2501    /// exactly when it is asked for.
2502    stderr_ring: Arc<Mutex<StderrRing>>,
2503    terminal_ring: Arc<Mutex<TerminalRing>>,
2504    spawn_events: SpawnEventFeed,
2505    child_roster: ChildRoster,
2506    #[cfg(target_os = "linux")]
2507    cgroup_placement: Option<subc_cgroup::Placement>,
2508    #[cfg(test)]
2509    test_seed_stale_facts_before_enable_spawn: bool,
2510    #[cfg(test)]
2511    test_reload_exit_record_gate: Option<Arc<ReloadExitRecordGate>>,
2512}
2513
2514impl SupervisorRuntimeConfig {
2515    fn failure_context(&self, daemon_initiated: bool) -> FailureContext {
2516        FailureContext {
2517            daemon_initiated,
2518            approval: None,
2519            shutdown: self.child_roster.shutdown_flag(),
2520        }
2521    }
2522}
2523
2524#[derive(Debug, Clone, PartialEq, Eq)]
2525struct SupervisedConfiguration {
2526    spec: ModuleSpec,
2527    enabled: bool,
2528    health: HealthConfig,
2529    register_timeout: Duration,
2530    restart_policy: RestartPolicy,
2531}
2532
2533/// Shared daemon lookup table for supervised module handles.
2534///
2535/// Shared by clone between the [`Supervisor`] (which spawns processes) and the
2536/// channel-0 control handler (which verifies HELLOs and consumer route opens), so
2537/// launch nonces recorded at spawn are checked by the same daemon instance.
2538#[derive(Debug, Clone, Default)]
2539pub struct SupervisorHandle {
2540    #[cfg(test)]
2541    resource_commit_pause: Arc<Mutex<Option<resource_launch::ResourceCommitPause>>>,
2542    #[cfg(test)]
2543    registration_test_channels: CapturedRegistrationChannels,
2544    registration_service: Arc<Mutex<Option<registration::RegistrationService>>>,
2545    registration_connections: Arc<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
2546    registration_launches: Arc<Mutex<Vec<std::sync::Weak<RegistrationSpawn>>>>,
2547    gate_runtime: Arc<Mutex<Option<std::sync::Weak<crate::config_gate::runtime::RuntimeOwner>>>>,
2548    program_bindings: program_binding::ProgramBindings,
2549    #[cfg(test)]
2550    identity_sample_pause: Arc<Mutex<Option<IdentitySamplePause>>>,
2551    #[cfg(all(test, unix))]
2552    plain_identity_policy_pause: Arc<Mutex<Option<(String, IdentitySamplePause)>>>,
2553    host_health: HostHealth,
2554    restart_intent: Arc<Mutex<DaemonRestartIntent>>,
2555    activity: Arc<Mutex<Option<crate::activity::ActivityLedger>>>,
2556    activity_images: Arc<Mutex<HashMap<String, activity::ActivityImage>>>,
2557    modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
2558    /// Module ids the supervisor has taken on. An id is added BEFORE the
2559    /// module's first process is spawned and removed only when the module
2560    /// leaves the roster (see [`Self::retire`]), so it is always a superset of
2561    /// the keys of `modules`.
2562    ///
2563    /// `modules` cannot answer "is this module configured?" on its own: a
2564    /// [`SupervisedModule`] only exists once its process has been spawned, and
2565    /// a fast child can connect, register, sync its scopes and ask about them
2566    /// before the supervisor has inserted it. Answering "not configured" in that
2567    /// gap makes scope admission refuse with the terminal "will never sync"
2568    /// instead of the retryable "has not synced yet".
2569    configured_ids: Arc<Mutex<HashSet<String>>>,
2570    spawn_events: SpawnEventFeed,
2571    /// The current expected launch nonce for each reserved module_id. Set when the
2572    /// supervisor spawns the reserved module; checked when a HELLO claims that id. A
2573    /// non-reserved module never has an entry here and is never nonce-checked.
2574    /// Reserved module ids and the nonce that authorizes their next HELLO.
2575    /// `None` means RESERVED WITH NO LEGITIMATE HOLDER — a reserved module that
2576    /// has never been spawned (e.g. configured `enabled: false`) — and refuses
2577    /// every HELLO. Before this was expressible, a reserved-but-never-spawned id
2578    /// had NO entry and admitted anyone: the reservation protected the nonce
2579    /// holder, not the NAME (found live by CKCRED's canary probe registering
2580    /// against a reserved scratch id).
2581    reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
2582    /// Reservations installed only to prevent HELLO for a protocol:none process.
2583    /// Replacement by a subc process releases them; explicitly reserved ids are
2584    /// never placed in this set and still require an operator release.
2585    implicit_protocol_none: Arc<Mutex<HashSet<String>>>,
2586    /// Module ids removed by an executed rescan and the unix-millisecond removal time.
2587    ///
2588    /// This is deliberately in-memory only: subc is state-free across daemon
2589    /// restarts, and the tombstone only explains the hours-after-removal window
2590    /// while this executing daemon is still alive. Do not persist it in a store.
2591    removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
2592    /// The current launch nonce for every supervised spawn. This is separate from
2593    /// reserved_nonces because consumer route.open attestation applies to all spawned
2594    /// modules, while HELLO id-squatting protection remains opt-in via `reserved`.
2595    spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
2596    /// The launch each live launch nonce was minted for, keyed by nonce, with
2597    /// the launch's module id, so a nonce-attested consumer or registration
2598    /// resolves to that launch's authority record. An entry whose launch has
2599    /// ended stays while its nonce still authorizes, so a nonce whose record
2600    /// is gone is told apart from one that never had a record.
2601    nonce_launches: Arc<Mutex<NonceLaunches>>,
2602    /// Reserved namespace prefixes mapped to the supervised owner module whose
2603    /// current spawn nonce authorizes HELLO claims below the prefix.
2604    ///
2605    /// Per §2.6 this is not a same-user security barrier: a same-user process can
2606    /// read the key file and launch nonce env. Like exact reserved ids, it prevents
2607    /// accidental collisions and lower-trust processes from squatting protected
2608    /// namespaces.
2609    reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
2610    /// Blue/green swaps in progress, by module id. An entry exists from just
2611    /// before the candidate process is spawned until the swap has failed, or
2612    /// has cut over and the old process is gone. While it exists, HELLO for the
2613    /// id is gated on the swap token (see [`Self::swap_hello_admission`]) and
2614    /// consumer attestation accepts both processes' nonces.
2615    swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
2616    /// Told when a swap promotes its candidate; see [`SwapPromotionObserver`].
2617    promotion_observer: PromotionObserverSlot,
2618    /// Serializes module-set reconciliation with operator lifecycle commands. Without
2619    /// this daemon-wide ordering, a rescan could retire or update a module while a
2620    /// concurrent reload still held its old handle and launch specification.
2621    operation_lock: Arc<AsyncMutex<()>>,
2622}
2623
2624#[cfg(test)]
2625#[derive(Debug)]
2626struct IdentitySamplePause {
2627    reached: std::sync::mpsc::Sender<()>,
2628    release: std::sync::mpsc::Receiver<()>,
2629}
2630
2631/// Told when a swap has promoted its candidate to be the module's active
2632/// registration.
2633///
2634/// An ordinary HELLO runs the control plane's registration side effects (the
2635/// capability cache, the deny census, the requirement recompute) as it
2636/// registers. A swap candidate's HELLO does not, because it is not routable;
2637/// promotion is when those must run instead, and promotion happens in the
2638/// supervisor, which has no other way into the control handler.
2639pub(crate) trait SwapPromotionObserver: Send + Sync {
2640    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration);
2641}
2642
2643/// The installed [`SwapPromotionObserver`], held weakly: the observer (the
2644/// control handler) owns this handle, so a strong reference back would be a
2645/// cycle that keeps both alive.
2646#[derive(Clone, Default)]
2647struct PromotionObserverSlot(Arc<Mutex<Option<std::sync::Weak<dyn SwapPromotionObserver>>>>);
2648
2649impl fmt::Debug for PromotionObserverSlot {
2650    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2651        f.write_str("PromotionObserverSlot")
2652    }
2653}
2654
2655/// The nonces of one open swap.
2656#[derive(Debug, Clone)]
2657struct OpenSwap {
2658    /// Legacy candidate token. A gated candidate has an empty lifecycle
2659    /// placeholder instead; only its own channel admits its HELLO.
2660    candidate_nonce: String,
2661    /// Incumbent token accepted before cutover, then cleared by promotion even
2662    /// while the incumbent's process is still draining.
2663    incumbent_nonce: Option<String>,
2664    /// Set once a HELLO has been admitted with the swap token, so the token
2665    /// admits one registration and cannot be replayed after cutover empties
2666    /// the candidate slot.
2667    candidate_admitted: bool,
2668}
2669
2670/// What the swap gate says about a HELLO. See
2671/// [`SupervisorHandle::swap_hello_admission`].
2672#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2673pub(crate) enum SwapHelloAdmission {
2674    /// No swap is open for the id (or the HELLO carries the incumbent's own
2675    /// nonce); the ordinary gates decide.
2676    NotSwapping,
2677    /// The HELLO carries the swap token: register it into the candidate slot.
2678    Candidate,
2679    /// A swap is open and the HELLO carries a nonce the supervisor did not
2680    /// mint for this id, no nonce, or a token already used.
2681    Refused,
2682    /// The id belongs to a supervised `protocol: none` module. Such a module
2683    /// never registers, so no HELLO may claim its id, with or without a nonce.
2684    ProtocolNone,
2685    /// The id is gated. Its supervised child registers only over the
2686    /// registration channel it inherited at launch, never by HELLO alone.
2687    ChannelRequired,
2688}
2689
2690#[derive(Debug, Clone, PartialEq, Eq)]
2691pub(crate) enum ReservedHelloRejection {
2692    Exact {
2693        module_id: String,
2694    },
2695    Prefix {
2696        prefix: String,
2697        owner_module_id: String,
2698    },
2699}
2700
2701/// Identity facts established by the reserved-module policy for one HELLO.
2702#[derive(Debug, Default)]
2703pub(crate) struct ReservedHelloVerification {
2704    pub(crate) nonce_verified: bool,
2705    pub(crate) prefix_owner: Option<String>,
2706}
2707
2708#[derive(Debug)]
2709struct DaemonRestartIntent {
2710    expires: Option<Duration>,
2711    window: Duration,
2712}
2713
2714impl Default for DaemonRestartIntent {
2715    fn default() -> Self {
2716        Self {
2717            expires: None,
2718            window: Duration::from_secs(120),
2719        }
2720    }
2721}
2722
2723impl SupervisorHandle {
2724    pub(crate) fn module_is_gated(&self, module: &str) -> bool {
2725        let runtime = {
2726            let Ok(runtime) = self.gate_runtime.lock() else {
2727                return true;
2728            };
2729            runtime.clone()
2730        };
2731        runtime.is_some_and(|runtime| {
2732            runtime
2733                .upgrade()
2734                .is_none_or(|owner| owner.module_is_gated(module))
2735        })
2736    }
2737    pub(crate) fn announce_daemon_restart(&self) -> u64 {
2738        let mut intent = self
2739            .restart_intent
2740            .lock()
2741            .unwrap_or_else(|p| p.into_inner());
2742        intent.expires = Some(subc_uptime::suspend_inclusive_now() + intent.window);
2743        unix_ms_now().saturating_add(intent.window.as_millis() as u64)
2744    }
2745
2746    #[cfg(feature = "test-support")]
2747    pub(crate) fn set_shutdown_intent_window(&self, window: Duration) {
2748        self.restart_intent
2749            .lock()
2750            .unwrap_or_else(|p| p.into_inner())
2751            .window = window;
2752    }
2753
2754    #[cfg(unix)]
2755    fn take_daemon_shutdown_reason(&self) -> RouteCloseReason {
2756        let expiry = self
2757            .restart_intent
2758            .lock()
2759            .unwrap_or_else(|p| p.into_inner())
2760            .expires
2761            .take();
2762        if expiry.is_some_and(|expiry| subc_uptime::suspend_inclusive_now() < expiry) {
2763            RouteCloseReason::Restart
2764        } else {
2765            RouteCloseReason::Disable
2766        }
2767    }
2768
2769    pub fn new() -> Self {
2770        Self::default()
2771    }
2772
2773    pub(crate) fn spawn_snapshot(&self) -> SpawnSnapshot {
2774        self.spawn_events.snapshot()
2775    }
2776
2777    /// Subscribe before reading the bound process. A coalesced wake is enough:
2778    /// readers compare its exact generation and PID, not the last event kind.
2779    pub(crate) fn subscribe_process_changes(
2780        &self,
2781        module: &str,
2782    ) -> tokio::sync::watch::Receiver<u64> {
2783        let mut state = self
2784            .spawn_events
2785            .0
2786            .lock()
2787            .unwrap_or_else(|p| p.into_inner());
2788        state
2789            .process_changes
2790            .retain(|_, changed| changed.receiver_count() > 0);
2791        let seq = state.seq;
2792        state
2793            .process_changes
2794            .entry(module.into())
2795            .or_insert_with(|| tokio::sync::watch::channel(seq).0)
2796            .subscribe()
2797    }
2798
2799    pub(crate) fn current_spawn(&self, module: &str) -> Option<LiveSpawn> {
2800        self.spawn_events
2801            .0
2802            .lock()
2803            .unwrap_or_else(|p| p.into_inner())
2804            .live
2805            .get(module)
2806            .cloned()
2807    }
2808
2809    pub(crate) fn subscribe_spawns(
2810        &self,
2811        connection_id: ConnectionId,
2812        corr: u64,
2813        version: u8,
2814        since: Option<SpawnCursor>,
2815        sink: FrameSink,
2816    ) -> Result<(), SpawnSubscribeRefusal> {
2817        self.spawn_events
2818            .subscribe(connection_id, corr, version, since, sink)
2819    }
2820
2821    pub(crate) fn cancel_spawn_subscription(&self, connection_id: ConnectionId, corr: u64) -> bool {
2822        self.spawn_events.cancel(connection_id, corr)
2823    }
2824
2825    pub(crate) fn remove_spawn_subscribers(&self, connection_id: ConnectionId) {
2826        self.spawn_events.remove_connection(connection_id);
2827    }
2828
2829    #[cfg(any(test, feature = "test-support"))]
2830    pub fn set_spawn_event_capacity_for_test(&self, capacity: usize) {
2831        assert!(capacity > 0, "spawn event capacity must be non-zero");
2832        self.spawn_events.set_capacity(capacity);
2833    }
2834
2835    #[cfg(any(test, feature = "test-support"))]
2836    pub fn spawn_subscriber_count_for_test(&self) -> usize {
2837        self.spawn_events.subscriber_count()
2838    }
2839
2840    /// Record the launch nonce from a supervised spawn, replacing any prior nonce so
2841    /// a respawn invalidates stale consumer identities.
2842    pub fn set_spawn_nonce(&self, module_id: &str, nonce: String) {
2843        self.spawn_nonces
2844            .lock()
2845            .unwrap_or_else(|poisoned| poisoned.into_inner())
2846            .insert(module_id.to_string(), nonce);
2847        self.refresh_program_binding_nonces(module_id);
2848    }
2849
2850    /// Record the launch nonce expected from the next HELLO for a reserved module,
2851    /// replacing any prior nonce (a respawn invalidates the previous one).
2852    pub fn set_reserved_nonce(&self, module_id: &str, nonce: String) {
2853        {
2854            let mut reserved = self
2855                .reserved_nonces
2856                .lock()
2857                .unwrap_or_else(|p| p.into_inner());
2858            self.implicit_protocol_none
2859                .lock()
2860                .unwrap_or_else(|p| p.into_inner())
2861                .remove(module_id);
2862            reserved.insert(module_id.to_string(), Some(nonce));
2863        }
2864        self.refresh_program_binding_nonces(module_id);
2865    }
2866
2867    /// Record namespace prefixes owned by a supervised module.
2868    pub fn set_reserved_prefixes(&self, owner_module_id: &str, prefixes: &[String]) {
2869        let mut owners = self
2870            .reserved_prefix_owners
2871            .lock()
2872            .unwrap_or_else(|poisoned| poisoned.into_inner());
2873        owners.retain(|_, owner| owner != owner_module_id);
2874        for prefix in prefixes {
2875            owners.insert(prefix.clone(), owner_module_id.to_string());
2876        }
2877    }
2878
2879    /// The launch nonce most recently minted for a module's spawn, if any.
2880    pub(crate) fn spawn_nonce(&self, module_id: &str) -> Option<String> {
2881        if self.module_is_gated(module_id) {
2882            return None;
2883        }
2884        self.spawn_nonces
2885            .lock()
2886            .unwrap_or_else(|poisoned| poisoned.into_inner())
2887            .get(module_id)
2888            .cloned()
2889    }
2890
2891    #[cfg(all(test, unix))]
2892    pub(crate) fn legacy_nonce_present_for_test(&self, module: &str) -> bool {
2893        self.spawn_nonces.lock().unwrap().contains_key(module)
2894    }
2895
2896    pub(crate) fn apply_identity_configuration(&self, spec: &ModuleSpec) {
2897        // Prefix ownership follows staged configuration, not the running
2898        // child's launch settings. A respawn may still carry an older spec.
2899        self.set_reserved_prefixes(&spec.module_id, &spec.reserved_prefixes);
2900        let protocol = self
2901            .get(&spec.module_id)
2902            .and_then(|module| {
2903                let snapshot = module.inner.snapshot.lock().ok()?;
2904                snapshot
2905                    .process_alive
2906                    .then_some(snapshot.spawned_protocol.unwrap_or(spec.protocol))
2907            })
2908            .unwrap_or(spec.protocol);
2909        self.apply_identity_policy(spec, protocol);
2910    }
2911
2912    #[cfg(all(test, unix))]
2913    pub(crate) fn pause_plain_identity_policy_for_test(
2914        &self,
2915        module: &str,
2916    ) -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
2917        let (reached, waiting) = std::sync::mpsc::channel();
2918        let (release, paused) = std::sync::mpsc::channel();
2919        *self.plain_identity_policy_pause.lock().unwrap() = Some((
2920            module.to_owned(),
2921            IdentitySamplePause {
2922                reached,
2923                release: paused,
2924            },
2925        ));
2926        (waiting, release)
2927    }
2928
2929    fn apply_identity_policy(&self, spec: &ModuleSpec, protocol: ModuleProtocol) {
2930        let channel_only = self.module_is_gated(&spec.module_id);
2931        let mut current_nonces = self
2932            .spawn_nonces
2933            .lock()
2934            .unwrap_or_else(|poisoned| poisoned.into_inner());
2935        if protocol == ModuleProtocol::None || channel_only {
2936            current_nonces.remove(&spec.module_id);
2937        }
2938        let spawn_nonce = current_nonces.get(&spec.module_id).cloned();
2939        #[cfg(test)]
2940        if let Some(pause) = self.identity_sample_pause.lock().unwrap().take() {
2941            pause.reached.send(()).unwrap();
2942            pause.release.recv().unwrap();
2943        }
2944        let mut reserved_nonces = self
2945            .reserved_nonces
2946            .lock()
2947            .unwrap_or_else(|poisoned| poisoned.into_inner());
2948        let mut implicit = self
2949            .implicit_protocol_none
2950            .lock()
2951            .unwrap_or_else(|p| p.into_inner());
2952        if spec.reserved {
2953            implicit.remove(&spec.module_id);
2954        } else if protocol == ModuleProtocol::None {
2955            if !reserved_nonces.contains_key(&spec.module_id) {
2956                implicit.insert(spec.module_id.clone());
2957            }
2958        } else if implicit.remove(&spec.module_id) {
2959            reserved_nonces.remove(&spec.module_id);
2960        }
2961        if spec.reserved || protocol == ModuleProtocol::None {
2962            // `None` (no spawn nonce minted) is INSERTED, not skipped: a
2963            // reserved name whose module has never spawned has no legitimate
2964            // holder, and the entry's absence is what used to leave the name
2965            // open to the first claimant.
2966            reserved_nonces.insert(spec.module_id.clone(), spawn_nonce);
2967        }
2968        drop(implicit);
2969        drop(reserved_nonces);
2970        drop(current_nonces);
2971        self.refresh_program_binding_nonces(&spec.module_id);
2972        // A later unreserved declaration must not silently unreserve an id that
2973        // was retained after its reserved configuration was removed. The explicit
2974        // release ceremony is the only operation that retires that gate.
2975        self.removal_tombstones
2976            .lock()
2977            .unwrap_or_else(|poisoned| poisoned.into_inner())
2978            .remove(&spec.module_id);
2979    }
2980
2981    /// Whether a HELLO claiming `module_id` is authorized. An exact reserved id is
2982    /// authorized only by its expected nonce; otherwise a matching reserved prefix
2983    /// is authorized by the owner module's current spawn nonce. Non-reserved ids
2984    /// with no matching prefix are always authorized.
2985    pub fn reserved_hello_authorized(&self, module_id: &str, presented: Option<&str>) -> bool {
2986        self.reserved_hello_verification(module_id, presented)
2987            .is_ok()
2988    }
2989
2990    /// Whether HELLO passed a nonce check that was actually required by reserved
2991    /// module policy, or the refusal explaining why a required check failed.
2992    pub(crate) fn reserved_hello_verification(
2993        &self,
2994        module_id: &str,
2995        presented: Option<&str>,
2996    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
2997        if self.module_is_gated(module_id) {
2998            return Err(ReservedHelloRejection::Exact {
2999                module_id: module_id.into(),
3000            });
3001        }
3002        self.hello_verification(module_id, presented, false)
3003    }
3004
3005    pub(crate) fn channel_hello_verification(
3006        &self,
3007        module_id: &str,
3008    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
3009        if self
3010            .get(module_id)
3011            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
3012        {
3013            return Err(ReservedHelloRejection::Exact {
3014                module_id: module_id.into(),
3015            });
3016        }
3017        let mut verification = self.hello_verification(module_id, None, true)?;
3018        verification.nonce_verified = true;
3019        Ok(verification)
3020    }
3021
3022    pub(crate) fn prefix_claim_authorized(&self, owner: &str, module_id: &str) -> bool {
3023        self.prefix_claim_publication(owner, module_id).is_some()
3024    }
3025
3026    #[cfg(all(test, unix))]
3027    pub(crate) fn prefix_publication_locked_for_test(&self) -> bool {
3028        matches!(
3029            self.reserved_prefix_owners.try_lock(),
3030            Err(std::sync::TryLockError::WouldBlock)
3031        )
3032    }
3033
3034    // Keep this guard through registry/forwarding publication. Rescans replace
3035    // prefix owners without stopping their launches, so the spawn guard alone
3036    // cannot fence a reservation transfer.
3037    pub(crate) fn prefix_claim_publication(
3038        &self,
3039        owner: &str,
3040        module_id: &str,
3041    ) -> Option<std::sync::MutexGuard<'_, HashMap<String, String>>> {
3042        if subc_protocol::manifest::validate_module_id(module_id).is_err()
3043            || self.module_is_gated(module_id)
3044            || self
3045                .reserved_nonces
3046                .lock()
3047                .unwrap_or_else(|p| p.into_inner())
3048                .contains_key(module_id)
3049        {
3050            return None;
3051        }
3052        let owners = self
3053            .reserved_prefix_owners
3054            .lock()
3055            .unwrap_or_else(|p| p.into_inner());
3056        let authorized = owners
3057            .iter()
3058            .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
3059            .max_by_key(|(prefix, _)| prefix.len())
3060            .is_some_and(|(prefix, holder)| holder == owner && module_id.len() > prefix.len());
3061        authorized.then_some(owners)
3062    }
3063
3064    fn hello_verification(
3065        &self,
3066        module_id: &str,
3067        presented: Option<&str>,
3068        channel: bool,
3069    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
3070        let nonces = self
3071            .reserved_nonces
3072            .lock()
3073            .unwrap_or_else(|poisoned| poisoned.into_inner());
3074        if let Some(expected) = nonces.get(module_id) {
3075            // `None` = reserved with no legitimate holder: refuse every
3076            // presentation, because no process can hold a nonce that was never
3077            // minted. Only a real minted nonce admits, in constant time.
3078            let authorized = channel
3079                || match expected {
3080                    Some(expected) => presented.is_some_and(|p| {
3081                        !p.is_empty() && constant_time_eq(expected.as_bytes(), p.as_bytes())
3082                    }),
3083                    None => false,
3084                };
3085            if authorized {
3086                return Ok(ReservedHelloVerification {
3087                    nonce_verified: true,
3088                    prefix_owner: None,
3089                });
3090            }
3091            return Err(ReservedHelloRejection::Exact {
3092                module_id: module_id.to_string(),
3093            });
3094        }
3095        drop(nonces);
3096
3097        let matched_prefix = self
3098            .reserved_prefix_owners
3099            .lock()
3100            .unwrap_or_else(|poisoned| poisoned.into_inner())
3101            .iter()
3102            .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
3103            .max_by_key(|(prefix, _)| prefix.len())
3104            .map(|(prefix, owner)| (prefix.clone(), owner.clone()));
3105        let Some((prefix, owner_module_id)) = matched_prefix else {
3106            return Ok(ReservedHelloVerification::default());
3107        };
3108
3109        if module_id.len() == prefix.len()
3110            || (!channel
3111                && (self.module_is_gated(&owner_module_id) || self.protocol_none(&owner_module_id)))
3112        {
3113            return Err(ReservedHelloRejection::Prefix {
3114                prefix,
3115                owner_module_id,
3116            });
3117        }
3118
3119        let authorized = if channel {
3120            owner_module_id == module_id
3121        } else {
3122            presented.is_some_and(|presented| {
3123                self.spawn_nonces
3124                .lock()
3125                .unwrap_or_else(|poisoned| poisoned.into_inner())
3126                .get(&owner_module_id)
3127                .is_some_and(|expected| !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes()))
3128                // While the owner is being swapped, children started by
3129                // either of its two processes hold that process's nonce.
3130                || self.swap_nonce_matches(&owner_module_id, presented)
3131            })
3132        };
3133        if authorized {
3134            Ok(ReservedHelloVerification {
3135                nonce_verified: true,
3136                prefix_owner: (owner_module_id != module_id).then_some(owner_module_id),
3137            })
3138        } else {
3139            Err(ReservedHelloRejection::Prefix {
3140                prefix,
3141                owner_module_id,
3142            })
3143        }
3144    }
3145
3146    /// Whether a consumer connection proved it came from a daemon-spawned module.
3147    ///
3148    /// Absence of an expected spawn nonce is a hard failure: consumer_identity is
3149    /// accepted only for module ids the supervisor has spawned.
3150    pub fn spawned_consumer_authorized(&self, module_id: &str, presented: &str) -> bool {
3151        if self.module_is_gated(module_id) || self.protocol_none(module_id) {
3152            return false;
3153        }
3154        let nonces = self
3155            .spawn_nonces
3156            .lock()
3157            .unwrap_or_else(|poisoned| poisoned.into_inner());
3158        let current = nonces.get(module_id).is_some_and(|expected| {
3159            !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes())
3160        });
3161        drop(nonces);
3162        // Before cutover both launches may attest. Promotion removes the
3163        // incumbent's token even if its process still needs time to drain.
3164        current || self.swap_nonce_matches(module_id, presented)
3165    }
3166
3167    /// Whether `presented` is either nonce of an open swap for `module_id`.
3168    fn swap_nonce_matches(&self, module_id: &str, presented: &str) -> bool {
3169        if self.module_is_gated(module_id) || self.protocol_none(module_id) || presented.is_empty()
3170        {
3171            return false;
3172        }
3173        let swaps = self
3174            .swaps
3175            .lock()
3176            .unwrap_or_else(|poisoned| poisoned.into_inner());
3177        swaps.get(module_id).is_some_and(|swap| {
3178            constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes())
3179                || swap.incumbent_nonce.as_deref().is_some_and(|incumbent| {
3180                    constant_time_eq(incumbent.as_bytes(), presented.as_bytes())
3181                })
3182        })
3183    }
3184
3185    /// Open a swap for `module_id` with the candidate's freshly minted nonce.
3186    /// Called before the candidate process exists.
3187    pub(crate) fn open_swap(&self, module_id: &str, candidate_nonce: String) {
3188        let incumbent_nonce = self
3189            .spawn_nonces
3190            .lock()
3191            .unwrap_or_else(|poisoned| poisoned.into_inner())
3192            .get(module_id)
3193            .cloned();
3194        self.swaps
3195            .lock()
3196            .unwrap_or_else(|poisoned| poisoned.into_inner())
3197            .insert(
3198                module_id.to_string(),
3199                OpenSwap {
3200                    candidate_nonce,
3201                    incumbent_nonce,
3202                    candidate_admitted: false,
3203                },
3204            );
3205        self.refresh_program_binding_nonces(module_id);
3206    }
3207
3208    /// Close the swap for `module_id`, releasing whichever nonce is no longer
3209    /// the module's recorded one.
3210    pub(crate) fn close_swap(&self, module_id: &str) {
3211        self.swaps
3212            .lock()
3213            .unwrap_or_else(|poisoned| poisoned.into_inner())
3214            .remove(module_id);
3215        self.refresh_program_binding_nonces(module_id);
3216    }
3217
3218    /// Install the observer told about swap promotions, replacing any earlier
3219    /// one.
3220    pub(crate) fn set_swap_promotion_observer(
3221        &self,
3222        observer: std::sync::Weak<dyn SwapPromotionObserver>,
3223    ) {
3224        *self
3225            .promotion_observer
3226            .0
3227            .lock()
3228            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer);
3229    }
3230
3231    /// Tell the installed observer, if it is still alive, that a swap promoted
3232    /// `registration`.
3233    fn notify_swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
3234        let observer = self
3235            .promotion_observer
3236            .0
3237            .lock()
3238            .unwrap_or_else(|poisoned| poisoned.into_inner())
3239            .as_ref()
3240            .and_then(std::sync::Weak::upgrade);
3241        if let Some(observer) = observer {
3242            observer.swap_promoted(registration);
3243        }
3244    }
3245
3246    /// Whether a swap is open for `module_id`.
3247    pub(crate) fn swap_open(&self, module_id: &str) -> bool {
3248        self.swaps
3249            .lock()
3250            .unwrap_or_else(|poisoned| poisoned.into_inner())
3251            .contains_key(module_id)
3252    }
3253
3254    /// Make the candidate's nonce the module's recorded spawn nonce, as a plain
3255    /// respawn would, once cutover has made the candidate the module's process.
3256    /// Promotion revokes the incumbent's tokens; the swap record stays open
3257    /// only for lifecycle cleanup while the old process drains.
3258    fn promote_swap_nonce(&self, module_id: &str, reserved: bool) {
3259        let candidate_nonce = self
3260            .swaps
3261            .lock()
3262            .unwrap_or_else(|poisoned| poisoned.into_inner())
3263            .get_mut(module_id)
3264            .map(|swap| {
3265                swap.incumbent_nonce = None;
3266                swap.candidate_nonce.clone()
3267            });
3268        self.spawn_nonces
3269            .lock()
3270            .unwrap_or_else(|p| p.into_inner())
3271            .remove(module_id);
3272        {
3273            let mut nonces = self
3274                .reserved_nonces
3275                .lock()
3276                .unwrap_or_else(|p| p.into_inner());
3277            if reserved || nonces.contains_key(module_id) {
3278                nonces.insert(module_id.into(), None);
3279            }
3280        }
3281        if self.module_is_gated(module_id) {
3282            return;
3283        }
3284        let Some(nonce) = candidate_nonce.filter(|nonce| !nonce.is_empty()) else {
3285            return;
3286        };
3287        self.set_spawn_nonce(module_id, nonce.clone());
3288        if reserved {
3289            self.set_reserved_nonce(module_id, nonce);
3290        }
3291    }
3292
3293    /// The swap gate for a HELLO claiming `module_id`.
3294    ///
3295    /// This runs BEFORE the reserved-module gate. A reserved module's candidate
3296    /// presents the candidate nonce, which the reserved gate (holding the
3297    /// incumbent's nonce) would refuse as `reserved_module` before swap
3298    /// admission was ever reached. And it applies to unreserved ids too: for an
3299    /// unreserved id the only thing that ever stopped a second process claiming
3300    /// a live id was the `duplicate_module_id` refusal, which is exactly the
3301    /// refusal a swap lifts for its candidate.
3302    ///
3303    /// The incumbent's own nonce falls through to the ordinary gates, which
3304    /// treat it as they always have (a live incumbent is refused as a
3305    /// duplicate). Anything else while a swap is open is refused, including an
3306    /// absent nonce.
3307    pub(crate) fn swap_hello_admission(
3308        &self,
3309        module_id: &str,
3310        presented: Option<&str>,
3311    ) -> SwapHelloAdmission {
3312        if self.protocol_none(module_id) {
3313            return SwapHelloAdmission::ProtocolNone;
3314        }
3315        if self.module_is_gated(module_id) {
3316            return SwapHelloAdmission::ChannelRequired;
3317        }
3318        let swaps = self
3319            .swaps
3320            .lock()
3321            .unwrap_or_else(|poisoned| poisoned.into_inner());
3322        let Some(swap) = swaps.get(module_id) else {
3323            return SwapHelloAdmission::NotSwapping;
3324        };
3325        let Some(presented) = presented.filter(|nonce| !nonce.is_empty()) else {
3326            return SwapHelloAdmission::Refused;
3327        };
3328        if constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes()) {
3329            return if swap.candidate_admitted {
3330                SwapHelloAdmission::Refused
3331            } else {
3332                SwapHelloAdmission::Candidate
3333            };
3334        }
3335        if swap
3336            .incumbent_nonce
3337            .as_deref()
3338            .is_some_and(|incumbent| constant_time_eq(incumbent.as_bytes(), presented.as_bytes()))
3339        {
3340            return SwapHelloAdmission::NotSwapping;
3341        }
3342        SwapHelloAdmission::Refused
3343    }
3344
3345    fn protocol_none(&self, module: &str) -> bool {
3346        self.get(module)
3347            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
3348    }
3349
3350    /// Exclude swap closure through the short, synchronous candidate publication.
3351    pub(crate) fn with_swap_candidate_admission<T>(
3352        &self,
3353        module_id: &str,
3354        publish: impl FnOnce() -> (T, bool),
3355    ) -> Option<T> {
3356        let mut swaps = self.swaps.lock().unwrap_or_else(|p| p.into_inner());
3357        let swap = swaps
3358            .get_mut(module_id)
3359            .filter(|swap| !swap.candidate_admitted)?;
3360        let (result, admitted) = publish();
3361        swap.candidate_admitted = admitted;
3362        Some(result)
3363    }
3364
3365    /// Test/support lookup for the current launch nonce of a supervised spawn.
3366    pub fn spawn_launch_nonce_for(&self, module_id: &str) -> Option<String> {
3367        self.spawn_nonce(module_id)
3368    }
3369
3370    /// Test/support lookup for the HELLO-gating nonce of a reserved module.
3371    pub fn reserved_launch_nonce_for(&self, module_id: &str) -> Option<String> {
3372        if self.module_is_gated(module_id) {
3373            return None;
3374        }
3375        self.reserved_nonces
3376            .lock()
3377            .unwrap_or_else(|poisoned| poisoned.into_inner())
3378            .get(module_id)
3379            .cloned()
3380            .flatten()
3381    }
3382
3383    pub fn insert(&self, module: SupervisedModule) -> Option<SupervisedModule> {
3384        // Normally already marked before the process was spawned; marking here
3385        // too keeps `configured_ids` a superset of the roster for any caller
3386        // that inserts a module directly.
3387        self.mark_configured(module.module_id());
3388        let mut modules = self
3389            .modules
3390            .lock()
3391            .unwrap_or_else(|poisoned| poisoned.into_inner());
3392        modules.insert(module.module_id().to_string(), module)
3393    }
3394
3395    /// Record that the supervisor has taken on `module_id`. Called before the
3396    /// module's first process is spawned, so that by the time that process can
3397    /// register, [`Self::is_configured`] already answers true.
3398    fn mark_configured(&self, module_id: &str) {
3399        self.update_configured_ids(|ids| {
3400            ids.insert(module_id.to_string());
3401        });
3402    }
3403
3404    fn publish_configured_ids(&self, ids: Option<&HashSet<String>>) {
3405        let owner = self
3406            .gate_runtime
3407            .lock()
3408            .unwrap_or_else(|p| p.into_inner())
3409            .clone()
3410            .and_then(|owner| owner.upgrade());
3411        if let Some(owner) = owner {
3412            owner.observe_supervisor_configured_ids(ids, Arc::downgrade(&self.configured_ids));
3413        }
3414    }
3415
3416    fn update_configured_ids(&self, update: impl FnOnce(&mut HashSet<String>)) {
3417        match self.configured_ids.lock() {
3418            Ok(mut ids) => {
3419                update(&mut ids);
3420                // Publish while this roster mutation is serialized, so an
3421                // older snapshot can never overwrite a later configured id.
3422                self.publish_configured_ids(Some(&ids));
3423            }
3424            Err(poisoned) => {
3425                update(&mut poisoned.into_inner());
3426                self.publish_configured_ids(None);
3427            }
3428        }
3429    }
3430
3431    /// Undo [`Self::mark_configured`] for a module whose first spawn failed
3432    /// before it was ever put on the roster. A module already on the roster
3433    /// keeps its mark: only [`Self::retire`] takes a rostered module off.
3434    fn unmark_configured_unless_rostered(&self, module_id: &str) {
3435        let modules = self
3436            .modules
3437            .lock()
3438            .unwrap_or_else(|poisoned| poisoned.into_inner());
3439        if !modules.contains_key(module_id) {
3440            self.update_configured_ids(|ids| {
3441                ids.remove(module_id);
3442            });
3443        }
3444    }
3445
3446    /// Whether `module_id` is a module this daemon supervises: on the roster,
3447    /// or about to be (its process is being spawned right now).
3448    ///
3449    /// This, not `get(..).is_some()`, is what "the owner is configured" means
3450    /// for scopes: a supervised module's process can register and sync before
3451    /// [`Self::get`] can return it, and in that window it is still a module
3452    /// that will sync, not one that never will.
3453    pub(crate) fn is_configured(&self, module_id: &str) -> bool {
3454        self.configured_ids
3455            .lock()
3456            .unwrap_or_else(|poisoned| poisoned.into_inner())
3457            .contains(module_id)
3458    }
3459
3460    pub fn get(&self, module_id: &str) -> Option<SupervisedModule> {
3461        let modules = self
3462            .modules
3463            .lock()
3464            .unwrap_or_else(|poisoned| poisoned.into_inner());
3465        modules.get(module_id).cloned()
3466    }
3467
3468    pub(crate) fn record_late_health_answer(
3469        &self,
3470        module_id: &str,
3471        latency_ms: u64,
3472    ) -> Result<bool, SuperviseError> {
3473        let Some(module) = self.get(module_id) else {
3474            return Ok(false);
3475        };
3476        self.host_health.record_late_module(module_id);
3477        update_snapshot(&module.inner.snapshot, Some(module_id), |state| {
3478            state.health.late_answer_count = state.health.late_answer_count.saturating_add(1);
3479            state.health.last_late_answer_latency_ms = Some(latency_ms);
3480            // A late answer is an answer: the module served the probe, just past
3481            // the deadline. Leaving the miss streak in place while logging
3482            // "proves the module is alive" is how a CPU-starved module that
3483            // answers every probe a few seconds late still marches to the
3484            // threshold and gets killed — the exact kill class `NoAnswer` is
3485            // excluded from `is_proof_of_death` to prevent. Slow-but-answering
3486            // is degradation, and degradation reports; it does not restart.
3487            state.health.consecutive_failures = 0;
3488        })?;
3489        Ok(true)
3490    }
3491
3492    pub(crate) fn spawn_host_health_monitor(&self) -> JoinHandle<()> {
3493        self.host_health.spawn_monitor()
3494    }
3495
3496    /// Arm the one-shot marker for the module process that this caller
3497    /// deliberately initiated severance against. Generic connection teardown
3498    /// must not call this:
3499    /// a surviving process would otherwise retain an exemption for a later
3500    /// genuine crash.
3501    pub fn record_deliberate_severance(&self, module_id: &str) -> Result<bool, SuperviseError> {
3502        let Some(module) = self.get(module_id) else {
3503            return Ok(false);
3504        };
3505        let snapshot = lock_snapshot(&module.inner.snapshot)?;
3506        let Some((pid, start_time)) = snapshot.pid.zip(snapshot.process_start_time) else {
3507            return Ok(false);
3508        };
3509        drop(snapshot);
3510        module.record_deliberate_severance(ProcessIdentity { pid, start_time })
3511    }
3512
3513    pub fn list(&self) -> Vec<SupervisedModule> {
3514        let modules = self
3515            .modules
3516            .lock()
3517            .unwrap_or_else(|poisoned| poisoned.into_inner());
3518        let mut modules = modules.values().cloned().collect::<Vec<_>>();
3519        modules.sort_by(|left, right| left.module_id().cmp(right.module_id()));
3520        modules
3521    }
3522
3523    pub(crate) fn retire(&self, module_id: &str) -> Option<SupervisedModule> {
3524        self.activity_images
3525            .lock()
3526            .unwrap_or_else(|p| p.into_inner())
3527            .remove(module_id);
3528        self.spawn_nonces
3529            .lock()
3530            .unwrap_or_else(|poisoned| poisoned.into_inner())
3531            .remove(module_id);
3532        self.close_swap(module_id);
3533        let mut reserved_nonces = self
3534            .reserved_nonces
3535            .lock()
3536            .unwrap_or_else(|poisoned| poisoned.into_inner());
3537        if reserved_nonces.contains_key(module_id) {
3538            // The old nonce must die with the removed process, but the exact-id
3539            // gate remains until an operator explicitly releases it.
3540            reserved_nonces.insert(module_id.to_string(), None);
3541        }
3542        drop(reserved_nonces);
3543        self.reserved_prefix_owners
3544            .lock()
3545            .unwrap_or_else(|poisoned| poisoned.into_inner())
3546            .retain(|_, owner| owner != module_id);
3547        let removed = self
3548            .modules
3549            .lock()
3550            .unwrap_or_else(|poisoned| poisoned.into_inner())
3551            .remove(module_id);
3552        self.update_configured_ids(|ids| {
3553            ids.remove(module_id);
3554        });
3555        self.remove_program_binding_records(module_id);
3556        removed
3557    }
3558
3559    /// Remember a module removed by a non-preview rescan so route.open can
3560    /// distinguish that intentional removal from an unknown id.
3561    pub(crate) fn record_rescan_removal(&self, module_id: &str) {
3562        self.removal_tombstones
3563            .lock()
3564            .unwrap_or_else(|poisoned| poisoned.into_inner())
3565            .insert(module_id.to_string(), unix_ms_now());
3566    }
3567
3568    /// Return how long ago a rescan removed this module in milliseconds.
3569    pub(crate) fn removal_tombstone_age_ms(&self, module_id: &str) -> Option<u64> {
3570        self.removal_tombstones
3571            .lock()
3572            .unwrap_or_else(|poisoned| poisoned.into_inner())
3573            .get(module_id)
3574            .copied()
3575            .map(|removed_at_ms| unix_ms_now().saturating_sub(removed_at_ms))
3576    }
3577
3578    /// Retire a reserved-id gate only after its module has left supervision.
3579    ///
3580    /// A retained gate has no live nonce (`None`), so releasing any other entry
3581    /// would weaken a currently configured or otherwise active reservation.
3582    pub(crate) fn release_retained_reserved_gate(&self, module_id: &str) -> bool {
3583        if self.get(module_id).is_some() {
3584            return false;
3585        }
3586        let mut reserved_nonces = self
3587            .reserved_nonces
3588            .lock()
3589            .unwrap_or_else(|poisoned| poisoned.into_inner());
3590        if !matches!(reserved_nonces.get(module_id), Some(None)) {
3591            return false;
3592        }
3593        reserved_nonces.remove(module_id);
3594        self.implicit_protocol_none
3595            .lock()
3596            .unwrap_or_else(|p| p.into_inner())
3597            .remove(module_id);
3598        true
3599    }
3600
3601    pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
3602        Arc::clone(&self.operation_lock)
3603    }
3604}
3605
3606/// Process supervisor for subc-owned singleton modules.
3607#[derive(Debug, Clone)]
3608pub struct Supervisor {
3609    registry: Arc<Registry>,
3610    config_delivery: Option<config_delivery::ConfigDelivery>,
3611    restart_policy: RestartPolicy,
3612    drain_timeout: Duration,
3613    connection_file_path: Option<PathBuf>,
3614    capture_logs_dir: Option<PathBuf>,
3615    forwarding: Option<Arc<ForwardingTable>>,
3616    process_liveness: Arc<SupervisorProcessLiveness>,
3617    supervisor_handle: Option<SupervisorHandle>,
3618    health: HealthConfig,
3619    host_health: HostHealth,
3620    daemon_start_clock: crate::clock::StartClock,
3621    terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
3622    spawn_events: SpawnEventFeed,
3623    provenance_probe: ExecutableIdentityProbe,
3624    /// Every process spawned through this supervisor (and its clones) and not
3625    /// yet reaped, so daemon shutdown can end them.
3626    child_roster: ChildRoster,
3627    #[cfg(target_os = "linux")]
3628    cgroup_placement: Option<subc_cgroup::Placement>,
3629    #[cfg(test)]
3630    test_after_first_spawn: AfterFirstSpawnHook,
3631}
3632
3633/// A roster entry whose monitor and first process have not started yet.
3634/// Keeping the command receiver here lets discovery serve status immediately
3635/// while start/stop requests wait until bootstrap has published the connection file.
3636pub(crate) struct RegisteredConfiguredModule {
3637    spec: ModuleSpec,
3638    runtime: SupervisorRuntimeConfig,
3639    module: SupervisedModule,
3640    commands: mpsc::Receiver<SupervisorCommand>,
3641}
3642
3643/// Test-only hook run on the path that takes on a new module, right after its
3644/// first `spawn_child` returns (the process exists and could already be
3645/// registering) and before that process is handed to the module's supervise
3646/// loop and put on the roster. Lets a test observe what a fast child would see
3647/// in that window without racing a real one.
3648#[cfg(test)]
3649#[derive(Clone, Default)]
3650struct AfterFirstSpawnHook(Option<AfterFirstSpawnFn>);
3651
3652#[cfg(test)]
3653type AfterFirstSpawnFn = Arc<dyn Fn(&str) + Send + Sync>;
3654
3655#[cfg(test)]
3656impl fmt::Debug for AfterFirstSpawnHook {
3657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3658        f.write_str("AfterFirstSpawnHook")
3659    }
3660}
3661
3662#[cfg(test)]
3663impl AfterFirstSpawnHook {
3664    fn run(&self, module_id: &str) {
3665        if let Some(hook) = &self.0 {
3666            hook(module_id);
3667        }
3668    }
3669}
3670
3671impl Supervisor {
3672    #[cfg(all(test, target_os = "linux"))]
3673    pub(crate) fn set_admission_hook_for_test(
3674        &self,
3675        hook: impl Fn(&str, &'static str, Option<u32>) -> bool + Send + Sync + 'static,
3676    ) {
3677        self.child_roster.set_admission_hook_for_test(hook);
3678    }
3679
3680    #[cfg(test)]
3681    pub(crate) fn new_for_test(registry: Arc<Registry>, policy: RestartPolicy) -> Self {
3682        let supervisor = Self::new(registry, policy);
3683        #[cfg(target_os = "macos")]
3684        let supervisor = supervisor.with_privacy_trampoline(test_privacy_trampoline());
3685        supervisor
3686    }
3687    /// Verify the trampoline once when configured. Missing private OS support
3688    /// refuses every macOS launch by name but does not stop the daemon's control
3689    /// server. Embedders must explicitly provide a binary with the subc-os hidden
3690    /// entry point; the library must not exec an arbitrary hosting program.
3691    pub fn with_privacy_trampoline(self, path: impl Into<PathBuf>) -> Self {
3692        let path = path.into();
3693        #[cfg(target_os = "macos")]
3694        {
3695            let result = probe_privacy_trampoline(&path).map(|()| path);
3696            if let Err(cause) = &result {
3697                error!(%cause, "macOS privacy identity unavailable; supervised launches will refuse");
3698            }
3699            self.child_roster.set_privacy_trampoline(result);
3700        }
3701        #[cfg(not(target_os = "macos"))]
3702        let _ = path;
3703        self
3704    }
3705    /// The flag [`Self::begin_daemon_shutdown`] sets, for the control handler's
3706    /// capability-requirement log to read.
3707    pub(crate) fn daemon_shutdown_flag(&self) -> crate::child_roster::DaemonShutdownFlag {
3708        self.child_roster.shutdown_flag()
3709    }
3710
3711    /// The first step of an announced daemon shutdown, before the notice and
3712    /// before any connection is closed.
3713    ///
3714    /// Sets the daemon-shutdown flag first: from here on no module is
3715    /// respawned (crash restart, operator restart, or swap), and every child
3716    /// exit is recorded as `daemon_shutdown` rather than as a crash, whether
3717    /// the module exits on the EOF this shutdown gives it or is signalled by a
3718    /// service manager that kills the whole cgroup. Then writes the journal's
3719    /// shutdown marker, which records the instant and closes this daemon
3720    /// incarnation's stretch of the journal.
3721    #[cfg(unix)]
3722    pub(crate) fn begin_daemon_shutdown(&self) {
3723        self.child_roster.close();
3724        if let Some(journal) = &self.terminal_journal {
3725            journal.stamp_shutdown();
3726        }
3727    }
3728
3729    /// Announce a cut while established connections can still carry replies.
3730    /// These budgets bound the attempt to deliver notices and the wait for
3731    /// routes to drain; neither guarantees delivery or child completion, and
3732    /// they are local policy, not an estimate of launchd's unknown kill ceiling.
3733    #[cfg(unix)]
3734    pub(crate) async fn drain_for_daemon_shutdown(&self) -> Result<(), SuperviseError> {
3735        const NOTICE_BUDGET: Duration = Duration::from_millis(500);
3736        const DRAIN_BUDGET: Duration = Duration::from_secs(2);
3737        let Some(forwarding) = &self.forwarding else {
3738            return Ok(());
3739        };
3740        let notice_started = Instant::now();
3741        let modules = forwarding
3742            .begin_daemon_drain()
3743            .map_err(SuperviseError::Forwarding)?;
3744        let deadline_ms =
3745            unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
3746        let shutdown_reason = self
3747            .supervisor_handle
3748            .as_ref()
3749            .map(SupervisorHandle::take_daemon_shutdown_reason)
3750            .unwrap_or(RouteCloseReason::Disable);
3751        let mut modules_told = 0;
3752        let mut notices = tokio::task::JoinSet::new();
3753        let mut drains = Vec::new();
3754        for connection in forwarding
3755            .module_connections()
3756            .map_err(SuperviseError::Forwarding)?
3757        {
3758            let target = ModuleDrainTarget {
3759                endpoint: connection.endpoint,
3760                sink: connection.sink,
3761                negotiated_ver: connection.negotiated_ver,
3762                abandoned_bindings: Vec::new(),
3763                excluded_subscriptions: 0,
3764            };
3765            notices.spawn(async move {
3766                (
3767                    true,
3768                    send_module_draining(
3769                        &connection.module_id,
3770                        shutdown_reason,
3771                        deadline_ms,
3772                        &target,
3773                        true,
3774                    )
3775                    .await,
3776                )
3777            });
3778        }
3779        for (module_id, endpoint) in modules {
3780            let Some(target) = forwarding
3781                .begin_endpoint_drain(endpoint, RouteCloseReason::Restart)
3782                .map_err(SuperviseError::Forwarding)?
3783            else {
3784                continue;
3785            };
3786            let routes = forwarding
3787                .endpoint_routes(target.endpoint)
3788                .map_err(SuperviseError::Forwarding)?;
3789            // Only an announced restart promises that modules are coming back.
3790            // Client route notices retain their existing reconnect semantics.
3791            let mut recipients = Vec::new();
3792            let mut clients: Vec<(crate::forwarding::GoodbyeTarget, Vec<u16>)> = Vec::new();
3793            for route in routes {
3794                let client = route.goodbye_target;
3795                if let Some((_, channels)) = clients
3796                    .iter_mut()
3797                    .find(|(existing, _)| existing.connection_id == client.connection_id)
3798                {
3799                    channels.push(client.channel);
3800                } else {
3801                    let channel = client.channel;
3802                    clients.push((client, vec![channel]));
3803                }
3804            }
3805            for (client, mut channels) in clients {
3806                channels.sort_unstable();
3807                channels.dedup();
3808                let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
3809                    module_id: module_id.clone(),
3810                    channels,
3811                    reason: RouteCloseReason::Restart,
3812                })
3813                .expect("route closing serializes");
3814                recipients.push((client.sink, client.negotiated_ver, closing));
3815            }
3816            for (sink, version, body) in recipients {
3817                notices.spawn(async move {
3818                    let frame = Frame::build_with_version(
3819                        version,
3820                        FrameType::Push,
3821                        control_flags(),
3822                        0,
3823                        0,
3824                        0,
3825                        body,
3826                    )
3827                    .expect("bounded lifecycle notice frame builds");
3828                    (false, sink.send_flushed(frame).await.is_ok())
3829                });
3830            }
3831            let gauges = declared_busy_gauges(&self.registry, &module_id)?;
3832            drains.push((module_id, target.endpoint, gauges));
3833        }
3834        // A quiet forwarding table is not proof that queued notices reached the
3835        // socket. Wait for writer flush acknowledgements before testing quiescence.
3836        let notice_deadline = Instant::now() + NOTICE_BUDGET;
3837        while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
3838            match result {
3839                Ok((true, true)) => modules_told += 1,
3840                Ok((false, true)) => {}
3841                result => warn!(?result, "daemon shutdown notice delivery failed"),
3842            }
3843        }
3844        notices.abort_all();
3845        info!(
3846            ?shutdown_reason,
3847            modules_told, "daemon shutdown module notices delivered"
3848        );
3849        let notice_elapsed = notice_started.elapsed();
3850        let drain_started = Instant::now();
3851        let deadline = drain_started + DRAIN_BUDGET;
3852        let mut waits = tokio::task::JoinSet::new();
3853        for (module_id, endpoint, gauges) in drains {
3854            let forwarding = Arc::clone(forwarding);
3855            let mut runtime = self.runtime_config();
3856            runtime.health.cadence = Duration::from_millis(100);
3857            waits.spawn(async move {
3858                let wait_result = wait_for_forwarding_quiescence(
3859                    &forwarding,
3860                    &module_id,
3861                    &runtime,
3862                    endpoint,
3863                    deadline,
3864                    &gauges,
3865                    DrainScope::Endpoint(endpoint),
3866                    &mut DrainGaugeTrace::new(&gauges),
3867                )
3868                .await;
3869                // Store the measurement before the task returns: quiescence
3870                // may be reached just as the deadline stops the join loop from
3871                // collecting results. Unfinished or failed waits report false.
3872                forwarding
3873                    .record_daemon_drain_result(
3874                        endpoint,
3875                        drained_after_quiescence_wait(&wait_result),
3876                    )
3877                    .map_err(SuperviseError::Forwarding)?;
3878                wait_result
3879            });
3880        }
3881        while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
3882            if !matches!(result, Ok(Ok(true))) {
3883                warn!(?result, "daemon shutdown drain did not reach quiescence");
3884            }
3885        }
3886        // Measure only the forwarding drain, not child teardown or the caller's
3887        // signal delivery and process-reaping delays.
3888        info!(
3889            notice_elapsed_ms = notice_elapsed.as_millis() as u64,
3890            drain_elapsed_ms = drain_started.elapsed().as_millis() as u64,
3891            "daemon shutdown forwarding drain complete"
3892        );
3893        Ok(())
3894    }
3895
3896    /// The last step of a graceful daemon shutdown, after the notice and the
3897    /// drain: send every registered module a module GOODBYE, the same planned
3898    /// stop signal `ck module stop` gives, then close every connection so each
3899    /// subc module sees EOF and starts its own teardown, then end every
3900    /// supervised child that has not exited
3901    /// by its own deadline (its drain budget, capped). Modules lead their own
3902    /// process groups, so a
3903    /// service manager's group kill no longer reaches them; without this a
3904    /// child that does not stop on EOF (every `protocol: "none"` child, which
3905    /// has no connection) would outlive the daemon. Every wait is bounded (see
3906    /// `child_roster`), and `escalate` resolving (a second SIGTERM) cuts them.
3907    #[cfg(unix)]
3908    pub(crate) async fn end_children_for_daemon_shutdown(
3909        &self,
3910        already_escalated: bool,
3911        escalate: impl std::future::Future<Output = ()>,
3912    ) {
3913        tokio::pin!(escalate);
3914        let mut escalated = already_escalated;
3915        if let Some(forwarding) = &self.forwarding {
3916            let reason = CloseReason::new(
3917                "daemon_shutdown",
3918                "the daemon is exiting after its shutdown notice and drain",
3919            );
3920            if escalated {
3921                // The operator asked to stop waiting: queue the GOODBYEs but
3922                // do not wait for them to be written.
3923                send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, false).await;
3924            } else {
3925                tokio::select! {
3926                    biased;
3927                    _ = escalate.as_mut() => {
3928                        info!("second SIGTERM: abandoning module GOODBYE delivery");
3929                        escalated = true;
3930                    }
3931                    _ = send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, true) => {}
3932                }
3933            }
3934            let closed = forwarding.close_all_connections(&reason);
3935            debug!(closed, "closed established connections for daemon shutdown");
3936        }
3937        // If the second SIGTERM arrived during GOODBYE delivery, `escalate` has
3938        // already completed and must not be polled again; the child shutdown
3939        // wait is told it is escalated and gets a future that never fires.
3940        let escalated_here = escalated && !already_escalated;
3941        let remaining_escalate = async move {
3942            if escalated_here {
3943                std::future::pending::<()>().await;
3944            } else {
3945                escalate.await;
3946            }
3947        };
3948        crate::child_roster::end_children_for_daemon_shutdown(
3949            &self.child_roster,
3950            escalated,
3951            remaining_escalate,
3952        )
3953        .await;
3954    }
3955
3956    pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
3957        Self {
3958            registry,
3959            config_delivery: None,
3960            restart_policy,
3961            drain_timeout: DEFAULT_DRAIN_TIMEOUT,
3962            connection_file_path: None,
3963            capture_logs_dir: None,
3964            forwarding: None,
3965            process_liveness: Arc::new(SupervisorProcessLiveness::default()),
3966            supervisor_handle: None,
3967            health: HealthConfig::default(),
3968            host_health: HostHealth::default(),
3969            daemon_start_clock: crate::clock::StartClock::capture(),
3970            terminal_journal: None,
3971            spawn_events: SpawnEventFeed::default(),
3972            provenance_probe: ExecutableIdentityProbe::default(),
3973            child_roster: ChildRoster::default(),
3974            #[cfg(target_os = "linux")]
3975            cgroup_placement: None,
3976            #[cfg(test)]
3977            test_after_first_spawn: AfterFirstSpawnHook::default(),
3978        }
3979    }
3980
3981    pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
3982        self.drain_timeout = drain_timeout;
3983        self
3984    }
3985
3986    /// The drain budget a module gets when its config entry sets none.
3987    pub(crate) fn default_drain_timeout(&self) -> Duration {
3988        self.drain_timeout
3989    }
3990
3991    pub fn with_process_liveness(
3992        mut self,
3993        process_liveness: Arc<SupervisorProcessLiveness>,
3994    ) -> Self {
3995        self.process_liveness = process_liveness;
3996        self
3997    }
3998
3999    /// Connect configuration delivery to observed process lifecycle events.
4000    pub fn with_config_runtime(
4001        mut self,
4002        owner: Arc<crate::config_gate::runtime::RuntimeOwner>,
4003    ) -> Self {
4004        if let Some(handle) = &self.supervisor_handle {
4005            handle.install_binding_retirement(&owner);
4006        }
4007        self.config_delivery = Some(config_delivery::ConfigDelivery(owner));
4008        self
4009    }
4010
4011    pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
4012        self.connection_file_path = Some(connection_file_path.into());
4013        self
4014    }
4015
4016    /// Enables daemon-owned capture files for supervised stdout and stderr.
4017    pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
4018        self.capture_logs_dir = Some(logs_dir.into());
4019        self
4020    }
4021
4022    /// Names this daemon lifetime in spawn events, independently of whether a
4023    /// terminal journal is configured.
4024    pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
4025        // A millisecond start stamp can repeat after clock rollback or a rapid
4026        // restart. Use the connection file's random daemon_id instead: it already
4027        // identifies this daemon lifetime independently of the wall clock.
4028        self.spawn_events.configure_incarnation(daemon_incarnation);
4029        self
4030    }
4031
4032    /// Enables best-effort history shared by every supervised module. Without
4033    /// it, terminal history is kept only in each module's in-memory ring.
4034    pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
4035        let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
4036        this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
4037            path,
4038            daemon_incarnation,
4039        )));
4040        this
4041    }
4042
4043    pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
4044        self.child_roster.counters = forwarding.counters();
4045        self.forwarding = Some(forwarding);
4046        self
4047    }
4048
4049    pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
4050        if let Some(delivery) = &self.config_delivery {
4051            supervisor_handle.install_binding_retirement(&delivery.0);
4052        }
4053        self.host_health = supervisor_handle.host_health.clone();
4054        self.spawn_events = supervisor_handle.spawn_events.clone();
4055        self.supervisor_handle = Some(supervisor_handle);
4056        self
4057    }
4058
4059    pub fn with_health_config(mut self, health: HealthConfig) -> Self {
4060        self.health = health;
4061        self
4062    }
4063
4064    /// Keeps a record of every live child at `path`, rewritten on each spawn and
4065    /// reap, for the orphan sweep a later daemon runs at boot. Without it no
4066    /// record is kept.
4067    pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
4068        self.child_roster.record_to(path.into());
4069        self
4070    }
4071
4072    #[cfg(target_os = "linux")]
4073    pub fn with_cgroup_placement(
4074        mut self,
4075        cgroup_placement: Option<subc_cgroup::Placement>,
4076    ) -> Self {
4077        self.child_roster
4078            .set_cgroup_placement(cgroup_placement.clone());
4079        self.cgroup_placement = cgroup_placement;
4080        self
4081    }
4082
4083    /// Spawn `spec.program` and start monitoring it.
4084    ///
4085    /// The child is expected to parse `--subc <connection-file-path>`, read the
4086    /// TCP+key connection file, authenticate to the already-running listener, and
4087    /// register with channel-0 `HELLO` using `spec.module_id` as its manifest id.
4088    ///
4089    /// This synchronous embedder API blocks on launch admission and store I/O.
4090    /// Do not call it on an async runtime thread; use [`Self::spawn_async`].
4091    pub fn spawn(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
4092        validate_spec(&spec)?;
4093        self.establish_identity(&spec);
4094
4095        let runtime = self.runtime_config();
4096        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
4097        let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4098        let registration_watch = watch_registration(&self.registry, &spec);
4099        let spawned = spawn_child(
4100            &spec,
4101            runtime.connection_file_path.as_deref(),
4102            self.supervisor_handle.as_ref(),
4103            &runtime.stderr_ring,
4104            runtime.capture_logs_dir.as_deref(),
4105            &runtime.child_roster,
4106            runtime.spawn_delivery(),
4107            #[cfg(target_os = "linux")]
4108            runtime.cgroup_placement.as_ref(),
4109            runtime.register_timeout,
4110        );
4111        #[cfg(test)]
4112        self.test_after_first_spawn.run(&spec.module_id);
4113        let mut child = match spawned {
4114            Ok(child) => child,
4115            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4116                defer_config_spawn(
4117                    &spec,
4118                    &runtime,
4119                    &snapshot,
4120                    RespawnKind::Spawn,
4121                    &runtime.failure_context(runtime.recovery_is_daemon),
4122                )?;
4123                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4124            }
4125            Err(SuperviseError::ConfigHeld { .. }) => {
4126                hold_config_spawn(
4127                    &spec,
4128                    &runtime,
4129                    &snapshot,
4130                    &runtime.failure_context(runtime.recovery_is_daemon),
4131                )?;
4132                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4133            }
4134            Err(err) => {
4135                // Unlike the configured paths, a failed `spawn` leaves nothing
4136                // on the roster, so the module must not stay marked configured.
4137                self.abandon_unrostered(&spec.module_id);
4138                return Err(err);
4139            }
4140        };
4141        arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
4142        self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
4143        if let Some(spawn) = activity_spawn {
4144            spawn.complete(&snapshot);
4145        }
4146
4147        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
4148    }
4149
4150    /// Spawn without running configuration integrity or keychain checks on the
4151    /// runtime thread. Cancellation during preparation cannot create a child.
4152    pub async fn spawn_async(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
4153        validate_spec(&spec)?;
4154        self.establish_identity(&spec);
4155        let mut identity = AsyncInitialIdentity {
4156            supervisor: self,
4157            module: spec.module_id.clone(),
4158            committed: false,
4159        };
4160        let runtime = self.runtime_config();
4161        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
4162        let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4163        let registration_watch = watch_registration(&self.registry, &spec);
4164        let spawned = spawn_child_async(&spec, &runtime).await;
4165        #[cfg(test)]
4166        self.test_after_first_spawn.run(&spec.module_id);
4167        let mut child = match spawned {
4168            Ok(child) => child,
4169            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4170                defer_config_spawn(
4171                    &spec,
4172                    &runtime,
4173                    &snapshot,
4174                    RespawnKind::Spawn,
4175                    &runtime.failure_context(runtime.recovery_is_daemon),
4176                )?;
4177                identity.committed = true;
4178                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4179            }
4180            Err(SuperviseError::ConfigHeld { .. }) => {
4181                hold_config_spawn(
4182                    &spec,
4183                    &runtime,
4184                    &snapshot,
4185                    &runtime.failure_context(runtime.recovery_is_daemon),
4186                )?;
4187                identity.committed = true;
4188                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4189            }
4190            Err(err) => {
4191                self.abandon_unrostered(&spec.module_id);
4192                return Err(err);
4193            }
4194        };
4195        arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
4196        self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
4197        if let Some(spawn) = activity_spawn {
4198            spawn.complete(&snapshot);
4199        }
4200        identity.committed = true;
4201        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
4202    }
4203
4204    /// Make `spec`'s module count as configured, with its identity gates
4205    /// (reserved id, reserved prefixes) in place, BEFORE any process of it
4206    /// exists.
4207    ///
4208    /// Every path that takes on a new module calls this before `spawn_child`.
4209    /// The order is the point: the child can connect, register, sync its
4210    /// scopes and ask about them as soon as it is spawned, and the module is
4211    /// only put on the roster after `spawn_child` returns. Were the mark set
4212    /// with the roster entry, a fast child would see its own owner reported
4213    /// as not configured, and a scoped `route.open` in that window would be
4214    /// refused as terminal `scope_not_live` ("will never sync") instead of
4215    /// retryable `scope_not_synced`.
4216    fn establish_identity(&self, spec: &ModuleSpec) {
4217        if let Some(supervisor_handle) = &self.supervisor_handle {
4218            supervisor_handle.apply_identity_configuration(spec);
4219            supervisor_handle.mark_configured(&spec.module_id);
4220        }
4221    }
4222
4223    /// Take back [`Self::establish_identity`]'s configured mark when the
4224    /// module will not be put on the roster after all.
4225    fn abandon_unrostered(&self, module_id: &str) {
4226        if let Some(supervisor_handle) = &self.supervisor_handle {
4227            supervisor_handle.unmark_configured_unless_rostered(module_id);
4228        }
4229    }
4230
4231    /// Record a freshly spawned first process as running. On failure the
4232    /// module never reaches the roster, so its configured mark is taken back.
4233    fn mark_first_process_running(
4234        &self,
4235        spec: &ModuleSpec,
4236        runtime: &SupervisorRuntimeConfig,
4237        snapshot: &SharedSnapshot,
4238        child: &mut SupervisedChild,
4239    ) -> Result<(), SuperviseError> {
4240        if let Err(err) = set_running(snapshot, child, &spec.module_id, &runtime.spawn_events) {
4241            containment::terminate_blocking(&runtime.child_roster.containment);
4242            self.abandon_unrostered(&spec.module_id);
4243            return Err(err);
4244        }
4245        self.process_liveness
4246            .track(spec.module_id.clone(), Arc::clone(snapshot));
4247        Ok(())
4248    }
4249
4250    /// Start supervising a module declared in daemon configuration.
4251    ///
4252    /// Unlike [`Self::spawn`], this records disabled modules and immediate spawn
4253    /// failures in the supervisor handle so operator-facing `supervisor.list`
4254    /// reflects every configured module while daemon startup continues.
4255    pub fn supervise_configured(
4256        &self,
4257        spec: ModuleSpec,
4258        enabled: bool,
4259    ) -> Result<SupervisedModule, SuperviseError> {
4260        self.supervise_configured_requested(
4261            spec,
4262            enabled,
4263            self.health.clone(),
4264            None,
4265            self.restart_policy,
4266            DEFAULT_REGISTER_TIMEOUT,
4267            None,
4268        )
4269    }
4270
4271    /// Supervise a configured module with its own health, drain, and crash
4272    /// budget. The restart policy is per-module because the config file is:
4273    /// `modules.<id>.restart` resolves to a full policy at parse time, and a
4274    /// module that is expensive to restart should not be forced onto the same
4275    /// budget as one that is cheap.
4276    pub fn supervise_configured_with_health(
4277        &self,
4278        spec: ModuleSpec,
4279        enabled: bool,
4280        health: HealthConfig,
4281        drain_timeout_ms: Option<u64>,
4282        restart_policy: RestartPolicy,
4283    ) -> Result<SupervisedModule, SuperviseError> {
4284        self.supervise_configured_requested(
4285            spec,
4286            enabled,
4287            health,
4288            drain_timeout_ms,
4289            restart_policy,
4290            DEFAULT_REGISTER_TIMEOUT,
4291            None,
4292        )
4293    }
4294
4295    #[allow(clippy::too_many_arguments)]
4296    pub(crate) fn supervise_configured_requested(
4297        &self,
4298        spec: ModuleSpec,
4299        enabled: bool,
4300        health: HealthConfig,
4301        drain_timeout_ms: Option<u64>,
4302        restart_policy: RestartPolicy,
4303        register_timeout: Duration,
4304        requester: Option<Principal>,
4305    ) -> Result<SupervisedModule, SuperviseError> {
4306        let registered = self.register_configured_with_health(
4307            spec,
4308            enabled,
4309            health,
4310            drain_timeout_ms,
4311            restart_policy,
4312            register_timeout,
4313        )?;
4314        let daemon_initiated = requester.is_none();
4315        self.start_registered_configured(registered, requester, daemon_initiated)
4316    }
4317
4318    #[allow(clippy::too_many_arguments)]
4319    pub(crate) async fn supervise_configured_requested_async(
4320        &self,
4321        spec: ModuleSpec,
4322        enabled: bool,
4323        health: HealthConfig,
4324        drain_timeout_ms: Option<u64>,
4325        restart_policy: RestartPolicy,
4326        register_timeout: Duration,
4327        requester: Option<Principal>,
4328    ) -> Result<SupervisedModule, SuperviseError> {
4329        let registered = self.register_configured_with_health(
4330            spec,
4331            enabled,
4332            health,
4333            drain_timeout_ms,
4334            restart_policy,
4335            register_timeout,
4336        )?;
4337        let daemon_initiated = requester.is_none();
4338        self.start_registered_configured_async(registered, requester, daemon_initiated)
4339            .await
4340    }
4341
4342    /// Record a configured module as starting or disabled, without launching a
4343    /// process or running its monitor. Bootstrap registers the entire roster
4344    /// before publishing discovery, then activates it once children can read
4345    /// the connection file passed in their `--subc` argument.
4346    pub(crate) fn register_configured_with_health(
4347        &self,
4348        spec: ModuleSpec,
4349        enabled: bool,
4350        health: HealthConfig,
4351        drain_timeout_ms: Option<u64>,
4352        restart_policy: RestartPolicy,
4353        register_timeout: Duration,
4354    ) -> Result<RegisteredConfiguredModule, SuperviseError> {
4355        validate_spec(&spec)?;
4356        self.establish_identity(&spec);
4357
4358        let mut runtime = self.runtime_config();
4359        runtime.health = health;
4360        runtime.restart_policy = restart_policy;
4361        runtime.register_timeout = register_timeout;
4362        if let Some(ms) = drain_timeout_ms {
4363            runtime.drain_timeout = Duration::from_millis(ms);
4364            *runtime
4365                .effective_drain_timeout
4366                .lock()
4367                .unwrap_or_else(|poisoned| poisoned.into_inner()) = runtime.drain_timeout;
4368        }
4369        let snapshot = if enabled {
4370            SupervisorSnapshot::starting()
4371        } else {
4372            SupervisorSnapshot::disabled()
4373        };
4374        let snapshot = {
4375            let mut snapshot = snapshot;
4376            if enabled {
4377                if let Some((pid, reason)) = runtime.child_roster.previous_instance(&spec.module_id)
4378                {
4379                    snapshot.waiting_for_previous_pid = Some(pid);
4380                    snapshot.waiting_for_previous_detail = Some(reason.waiting_message(pid));
4381                }
4382            }
4383            snapshot
4384        };
4385        let (module, commands) =
4386            self.register_module(&spec, &runtime, Arc::new(Mutex::new(snapshot)));
4387        Ok(RegisteredConfiguredModule {
4388            spec,
4389            runtime,
4390            module,
4391            commands,
4392        })
4393    }
4394
4395    /// Activate a previously registered module. Queued control requests are
4396    /// served by the monitor after the initial configured spawn has settled.
4397    pub(crate) fn start_registered_configured(
4398        &self,
4399        registered: RegisteredConfiguredModule,
4400        requester: Option<Principal>,
4401        daemon_initiated: bool,
4402    ) -> Result<SupervisedModule, SuperviseError> {
4403        let RegisteredConfiguredModule {
4404            spec,
4405            mut runtime,
4406            module,
4407            commands,
4408        } = registered;
4409        runtime.start_requester = requester;
4410        runtime.recovery_is_daemon = daemon_initiated;
4411        let snapshot = &module.inner.snapshot;
4412        let should_spawn = {
4413            let state = lock_snapshot(snapshot)?;
4414            state.enabled && state.waiting_for_previous_pid.is_none()
4415        };
4416        let child = if should_spawn {
4417            let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4418            let registration_watch = watch_registration(&self.registry, &spec);
4419            let spawned = spawn_child(
4420                &spec,
4421                runtime.connection_file_path.as_deref(),
4422                self.supervisor_handle.as_ref(),
4423                &runtime.stderr_ring,
4424                runtime.capture_logs_dir.as_deref(),
4425                &runtime.child_roster,
4426                runtime.spawn_delivery(),
4427                #[cfg(target_os = "linux")]
4428                runtime.cgroup_placement.as_ref(),
4429                runtime.register_timeout,
4430            );
4431            #[cfg(test)]
4432            self.test_after_first_spawn.run(&spec.module_id);
4433            match spawned {
4434                Ok(mut child) => {
4435                    arm_registration_deadline(
4436                        &mut child,
4437                        runtime.register_timeout,
4438                        registration_watch,
4439                    );
4440                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
4441                    if let Some(spawn) = activity_spawn {
4442                        spawn.complete(snapshot);
4443                    }
4444                    Some(child)
4445                }
4446                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4447                    defer_config_spawn(
4448                        &spec,
4449                        &runtime,
4450                        snapshot,
4451                        RespawnKind::Spawn,
4452                        &runtime.failure_context(daemon_initiated),
4453                    )?;
4454                    None
4455                }
4456                Err(mut err) => {
4457                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
4458                        match hold_config_spawn(
4459                            &spec,
4460                            &runtime,
4461                            snapshot,
4462                            &runtime.failure_context(daemon_initiated),
4463                        ) {
4464                            Ok(()) => {
4465                                self.start_monitor(spec, runtime, &module, None, commands);
4466                                return Ok(module);
4467                            }
4468                            Err(parking_error) => err = parking_error,
4469                        }
4470                    }
4471                    if runtime.health.critical {
4472                        error!(
4473                            module_id = %spec.module_id,
4474                            program = %spec.program.display(),
4475                            error = %err,
4476                            "critical configured module failed to spawn; marking failed and alerting"
4477                        );
4478                    } else {
4479                        error!(
4480                            module_id = %spec.module_id,
4481                            program = %spec.program.display(),
4482                            error = %err,
4483                            "configured module failed to spawn; marking failed and continuing"
4484                        );
4485                    }
4486                    fail_snapshot(
4487                        snapshot,
4488                        Some(&spec.module_id),
4489                        None,
4490                        &runtime.failure_context(daemon_initiated),
4491                    );
4492                    None
4493                }
4494            }
4495        } else {
4496            None
4497        };
4498        self.start_monitor(spec, runtime, &module, child, commands);
4499        Ok(module)
4500    }
4501
4502    pub(crate) async fn start_registered_configured_async(
4503        &self,
4504        registered: RegisteredConfiguredModule,
4505        requester: Option<Principal>,
4506        daemon_initiated: bool,
4507    ) -> Result<SupervisedModule, SuperviseError> {
4508        self.start_registered_with_failure_policy(registered, requester, daemon_initiated, None)
4509            .await
4510    }
4511
4512    pub(crate) async fn start_registered_approved_async(
4513        &self,
4514        registered: RegisteredConfiguredModule,
4515        requester: Principal,
4516        generation: crate::config_gate::runtime::ApprovalIdentity,
4517    ) -> Result<SupervisedModule, SuperviseError> {
4518        self.start_registered_with_failure_policy(
4519            registered,
4520            Some(requester),
4521            false,
4522            Some(generation),
4523        )
4524        .await
4525    }
4526
4527    async fn start_registered_with_failure_policy(
4528        &self,
4529        registered: RegisteredConfiguredModule,
4530        requester: Option<Principal>,
4531        daemon_initiated: bool,
4532        approved_generation: Option<crate::config_gate::runtime::ApprovalIdentity>,
4533    ) -> Result<SupervisedModule, SuperviseError> {
4534        let RegisteredConfiguredModule {
4535            spec,
4536            mut runtime,
4537            module,
4538            commands,
4539        } = registered;
4540        runtime.start_requester = requester;
4541        runtime.recovery_is_daemon = daemon_initiated;
4542        let snapshot = &module.inner.snapshot;
4543        let mut startup_error = None;
4544        let failure = FailureContext {
4545            approval: approved_generation.clone(),
4546            ..runtime.failure_context(daemon_initiated)
4547        };
4548        let should_spawn = {
4549            let state = lock_snapshot(snapshot)?;
4550            state.enabled && state.waiting_for_previous_pid.is_none()
4551        };
4552        let child = if should_spawn {
4553            let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4554            let registration_watch = watch_registration(&self.registry, &spec);
4555            let spawned = spawn_child_async(&spec, &runtime).await;
4556            #[cfg(test)]
4557            self.test_after_first_spawn.run(&spec.module_id);
4558            match spawned {
4559                Ok(mut child) => {
4560                    arm_registration_deadline(
4561                        &mut child,
4562                        runtime.register_timeout,
4563                        registration_watch,
4564                    );
4565                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
4566                    if let Some(spawn) = activity_spawn {
4567                        spawn.complete(snapshot);
4568                    }
4569                    Some(child)
4570                }
4571                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4572                    defer_config_spawn(&spec, &runtime, snapshot, RespawnKind::Spawn, &failure)?;
4573                    None
4574                }
4575                Err(mut err) => {
4576                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
4577                        match hold_config_spawn(&spec, &runtime, snapshot, &failure) {
4578                            Ok(()) => {
4579                                self.start_monitor(spec, runtime, &module, None, commands);
4580                                return Ok(module);
4581                            }
4582                            Err(parking_error) => err = parking_error,
4583                        }
4584                    }
4585                    if runtime.health.critical {
4586                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
4587                            "critical configured module failed to spawn; marking failed and alerting");
4588                    } else {
4589                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
4590                            "configured module failed to spawn; marking failed and continuing");
4591                    }
4592                    fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
4593                    if let Some(generation) = approved_generation {
4594                        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
4595                            state.approved_start_failure = Some((generation, err.to_string()));
4596                        });
4597                        startup_error = Some(err);
4598                    }
4599                    None
4600                }
4601            }
4602        } else {
4603            None
4604        };
4605        self.start_monitor(spec, runtime, &module, child, commands);
4606        // Applying an operator-approved configuration must report a spawn error
4607        // without removing the failed module or its monitor. Bootstrap instead
4608        // tolerates failed starts so other configured modules can still run.
4609        startup_error.map_or(Ok(module), Err)
4610    }
4611
4612    fn runtime_config(&self) -> SupervisorRuntimeConfig {
4613        let effective_drain_timeout = Arc::new(Mutex::new(self.drain_timeout));
4614        SupervisorRuntimeConfig {
4615            registry: self.registry.clone(),
4616            config_delivery: self.config_delivery.clone(),
4617            recovery_is_daemon: true,
4618            start_requester: None,
4619            pending_activity_restart: false,
4620            provenance_probe: self.provenance_probe.clone(),
4621            scheduled_respawn: Arc::default(),
4622            deferred_reload_reply: Arc::default(),
4623            restart_policy: self.restart_policy,
4624            register_timeout: DEFAULT_REGISTER_TIMEOUT,
4625            drain_timeout: self.drain_timeout,
4626            // Shared with this module's roster copy: daemon shutdown waits on
4627            // each child for the module's own drain budget, as resolved now.
4628            child_roster: self
4629                .child_roster
4630                .for_module(Arc::clone(&effective_drain_timeout)),
4631            effective_drain_timeout,
4632            default_drain_timeout: self.drain_timeout,
4633            health: self.health.clone(),
4634            host_health: self.host_health.clone(),
4635            connection_file_path: self.connection_file_path.clone(),
4636            capture_logs_dir: self.capture_logs_dir.clone(),
4637            forwarding: self.forwarding.clone(),
4638            supervisor_handle: self.supervisor_handle.clone(),
4639            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
4640            terminal_ring: Arc::new(Mutex::new(
4641                TerminalRing::new(
4642                    TerminalRingConfig::default(),
4643                    self.daemon_start_clock.started_at_ms(),
4644                )
4645                .with_start_clock(self.daemon_start_clock)
4646                .with_journal(self.terminal_journal.clone())
4647                .with_daemon_shutdown(self.child_roster.shutdown_flag()),
4648            )),
4649            spawn_events: self.spawn_events.clone(),
4650            #[cfg(target_os = "linux")]
4651            cgroup_placement: self.cgroup_placement.clone(),
4652            #[cfg(test)]
4653            test_seed_stale_facts_before_enable_spawn: false,
4654            #[cfg(test)]
4655            test_reload_exit_record_gate: None,
4656        }
4657    }
4658
4659    fn supervised_module(
4660        &self,
4661        spec: ModuleSpec,
4662        runtime: SupervisorRuntimeConfig,
4663        snapshot: SharedSnapshot,
4664        child: Option<SupervisedChild>,
4665    ) -> SupervisedModule {
4666        let (module, commands) = self.register_module(&spec, &runtime, snapshot);
4667        self.start_monitor(spec, runtime, &module, child, commands);
4668        module
4669    }
4670
4671    fn register_module(
4672        &self,
4673        spec: &ModuleSpec,
4674        runtime: &SupervisorRuntimeConfig,
4675        snapshot: SharedSnapshot,
4676    ) -> (SupervisedModule, mpsc::Receiver<SupervisorCommand>) {
4677        runtime.host_health.track(spec, &snapshot);
4678        let configuration = Arc::new(Mutex::new(SupervisedConfiguration {
4679            spec: spec.clone(),
4680            enabled: snapshot.lock().unwrap_or_else(|p| p.into_inner()).enabled,
4681            health: runtime.health.clone(),
4682            register_timeout: runtime.register_timeout,
4683            restart_policy: runtime.restart_policy,
4684        }));
4685        let stderr_ring = Arc::clone(&runtime.stderr_ring);
4686        let terminal_ring = Arc::clone(&runtime.terminal_ring);
4687        let effective_drain_timeout = Arc::clone(&runtime.effective_drain_timeout);
4688        let (tx, rx) = mpsc::channel(4);
4689        let module_id = spec.module_id.clone();
4690        let module = SupervisedModule {
4691            inner: Arc::new(SupervisedModuleInner {
4692                module_id: module_id.clone(),
4693                registry: Arc::clone(&self.registry),
4694                snapshot,
4695                configuration,
4696                stderr_ring,
4697                terminal_ring,
4698                commands: tx,
4699                monitor: Mutex::new(None),
4700                effective_drain_timeout,
4701                provenance_probe: self.provenance_probe.clone(),
4702                retained: runtime.child_roster.retained_view(),
4703            }),
4704        };
4705        // Identity gates and the configured mark must precede the roster entry,
4706        // so a client never sees a module without its admission policy.
4707        if let Some(supervisor_handle) = &self.supervisor_handle {
4708            supervisor_handle.insert(module.clone());
4709        }
4710        (module, rx)
4711    }
4712
4713    fn start_monitor(
4714        &self,
4715        spec: ModuleSpec,
4716        runtime: SupervisorRuntimeConfig,
4717        module: &SupervisedModule,
4718        child: Option<SupervisedChild>,
4719        commands: mpsc::Receiver<SupervisorCommand>,
4720    ) {
4721        let monitor = tokio::spawn(supervise_loop(
4722            spec,
4723            runtime,
4724            Arc::clone(&self.registry),
4725            Arc::clone(&self.process_liveness),
4726            Arc::clone(&module.inner.snapshot),
4727            child,
4728            commands,
4729        ));
4730        *module
4731            .inner
4732            .monitor
4733            .lock()
4734            .unwrap_or_else(|p| p.into_inner()) = Some(monitor);
4735    }
4736}
4737
4738impl Default for Supervisor {
4739    fn default() -> Self {
4740        Self::new(Arc::new(Registry::default()), RestartPolicy::default())
4741    }
4742}
4743
4744/// Handle to one supervised child process.
4745#[derive(Clone)]
4746pub struct SupervisedModule {
4747    inner: Arc<SupervisedModuleInner>,
4748}
4749
4750struct SupervisedModuleInner {
4751    retained: crate::child_roster::RetainedView,
4752    module_id: String,
4753    registry: Arc<Registry>,
4754    snapshot: SharedSnapshot,
4755    configuration: Arc<Mutex<SupervisedConfiguration>>,
4756    stderr_ring: Arc<Mutex<StderrRing>>,
4757    terminal_ring: Arc<Mutex<TerminalRing>>,
4758    commands: mpsc::Sender<SupervisorCommand>,
4759    monitor: Mutex<Option<JoinHandle<()>>>,
4760    effective_drain_timeout: Arc<Mutex<Duration>>,
4761    provenance_probe: ExecutableIdentityProbe,
4762}
4763
4764impl fmt::Debug for SupervisedModule {
4765    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4766        f.debug_struct("SupervisedModule")
4767            .field("module_id", &self.inner.module_id)
4768            .field("status", &self.status())
4769            .finish_non_exhaustive()
4770    }
4771}
4772
4773impl SupervisedModule {
4774    pub(crate) fn check_approved_start_failure(
4775        &self,
4776        generation: &crate::config_gate::runtime::ApprovalIdentity,
4777    ) -> Result<bool, SuperviseError> {
4778        let state = lock_snapshot(&self.inner.snapshot)?;
4779        if let Some((failed_generation, detail)) = &state.approved_start_failure {
4780            if failed_generation == generation {
4781                return Err(SuperviseError::ReloadFailed {
4782                    module_id: self.inner.module_id.clone(),
4783                    reason: detail.clone(),
4784                });
4785            }
4786        }
4787        Ok(state.approved_start_failure.is_some())
4788    }
4789
4790    pub(crate) fn has_approved_start_failure(
4791        &self,
4792        identity: &crate::config_gate::runtime::ApprovalIdentity,
4793    ) -> bool {
4794        lock_snapshot(&self.inner.snapshot).is_ok_and(|state| {
4795            state
4796                .approved_start_failure
4797                .as_ref()
4798                .is_some_and(|(failed, _)| failed == identity)
4799        })
4800    }
4801
4802    pub(crate) fn needs_approved_gate_restart(
4803        &self,
4804        approval: &crate::config_gate::runtime::ApprovalIdentity,
4805    ) -> bool {
4806        lock_snapshot(&self.inner.snapshot)
4807            .is_ok_and(|state| state.needs_approved_gate_restart(approval))
4808    }
4809
4810    #[cfg(all(test, unix))]
4811    pub(crate) fn config_hold_origin_for_test(
4812        &self,
4813    ) -> (bool, Option<crate::config_gate::runtime::ApprovalIdentity>) {
4814        let state = lock_snapshot(&self.inner.snapshot).unwrap();
4815        (
4816            state.config_hold_daemon_initiated,
4817            state.config_hold_approval.clone(),
4818        )
4819    }
4820
4821    pub(crate) async fn config_policy_probe(
4822        &self,
4823        connection: crate::ConnectionId,
4824        generation: u64,
4825        attempt: u64,
4826    ) -> Result<(), SuperviseError> {
4827        self.inner
4828            .commands
4829            .send(SupervisorCommand::ConfigPolicyProbe {
4830                connection,
4831                generation,
4832                attempt,
4833            })
4834            .await
4835            .map_err(|_| SuperviseError::CommandClosed {
4836                module_id: self.inner.module_id.clone(),
4837            })
4838    }
4839    pub(crate) async fn config_exit_hold(&self) -> Result<(), SuperviseError> {
4840        let (reply, result) = oneshot::channel();
4841        self.inner
4842            .commands
4843            .send(SupervisorCommand::ConfigExitHold { reply })
4844            .await
4845            .map_err(|_| SuperviseError::CommandClosed {
4846                module_id: self.module_id().to_string(),
4847            })?;
4848        result.await.map_err(|_| SuperviseError::CommandClosed {
4849            module_id: self.module_id().to_string(),
4850        })?
4851    }
4852    pub(crate) async fn config_delivery_failed(
4853        &self,
4854        connection: crate::ConnectionId,
4855        hold: bool,
4856    ) -> Result<(), SuperviseError> {
4857        self.inner
4858            .commands
4859            .send(SupervisorCommand::ConfigDeliveryFailed { connection, hold })
4860            .await
4861            .map_err(|_| SuperviseError::CommandClosed {
4862                module_id: self.module_id().to_string(),
4863            })
4864    }
4865
4866    pub(crate) async fn config_apply_restart(&self, generation: u64) -> Result<(), SuperviseError> {
4867        self.inner
4868            .commands
4869            .send(SupervisorCommand::ConfigApplyRestart {
4870                generation,
4871                supersedes_swap: false,
4872            })
4873            .await
4874            .map_err(|_| SuperviseError::CommandClosed {
4875                module_id: self.inner.module_id.clone(),
4876            })
4877    }
4878    pub fn module_id(&self) -> &str {
4879        &self.inner.module_id
4880    }
4881
4882    /// Test-only: put one probe miss on the streak, the way
4883    /// `handle_health_probe_failure` does, so tests can assert what a later
4884    /// event does to the streak without driving the whole probe loop.
4885    #[cfg(test)]
4886    pub(crate) fn record_health_probe_failure_for_test(
4887        &self,
4888        detail: &str,
4889    ) -> Result<(), SuperviseError> {
4890        update_snapshot(&self.inner.snapshot, Some(&self.inner.module_id), |state| {
4891            state.health.consecutive_failures = state.health.consecutive_failures.saturating_add(1);
4892            state.health.detail = Some(detail.to_string());
4893        })
4894    }
4895
4896    pub fn state(&self) -> Result<ModuleState, SuperviseError> {
4897        Ok(lock_snapshot(&self.inner.snapshot)?.state)
4898    }
4899
4900    pub(crate) fn registration_end_reason(
4901        &self,
4902    ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
4903        let snapshot = lock_snapshot(&self.inner.snapshot)?;
4904        Ok(match snapshot.state {
4905            ModuleState::Draining if snapshot.draining_to_replace => {
4906                Some(RegistrationEndReason::SupervisorRestart)
4907            }
4908            ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
4909            ModuleState::Restarting if snapshot.draining_to_replace => {
4910                Some(RegistrationEndReason::SupervisorRestart)
4911            }
4912            _ => None,
4913        })
4914    }
4915
4916    /// The module's retained stderr, newest lines last.
4917    ///
4918    /// Deliberately NOT on [`Self::status`]: a bounded tail is kilobytes per
4919    /// module, `supervisor.list` renders every module, and putting it in the
4920    /// shared snapshot would make each status read carry a payload almost nobody
4921    /// asked for. Callers that want the text ask for it.
4922    pub fn stderr_tail(
4923        &self,
4924        max_lines: Option<usize>,
4925        max_bytes: Option<usize>,
4926    ) -> StderrTailSnapshot {
4927        self.inner
4928            .stderr_ring
4929            .lock()
4930            .unwrap_or_else(|poisoned| poisoned.into_inner())
4931            .snapshot(max_lines, max_bytes)
4932    }
4933
4934    /// The module's bounded terminal history, oldest retained exit first.
4935    ///
4936    /// The daemon-start stamp distinguishes a quiet supervisor from a replacement
4937    /// daemon whose in-memory history was necessarily reset.
4938    pub fn terminal_history(&self) -> TerminalHistorySnapshot {
4939        self.inner
4940            .terminal_ring
4941            .lock()
4942            .unwrap_or_else(|poisoned| poisoned.into_inner())
4943            .snapshot()
4944    }
4945
4946    /// Retained observations from the current ring and all journal generations.
4947    ///
4948    /// Blocking: this reads the journal files. Async callers use
4949    /// `Self::read_durable_terminal_history`.
4950    pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
4951        durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
4952    }
4953
4954    /// [`Self::durable_terminal_history`] on a blocking thread, so the journal
4955    /// read (up to every retained generation) never occupies a runtime worker.
4956    /// Fails only if the blocking task could not finish (runtime shutdown or a
4957    /// panic in the read).
4958    pub(crate) async fn read_durable_terminal_history(
4959        &self,
4960    ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
4961        let terminal_ring = Arc::clone(&self.inner.terminal_ring);
4962        let module_id = self.inner.module_id.clone();
4963        tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
4964            .await
4965    }
4966
4967    pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
4968        self.status_with_snapshot_lock(&self.inner.snapshot, None)
4969            .map(|(status, _)| status)
4970    }
4971
4972    pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
4973        let state = lock_snapshot(&self.inner.snapshot)?;
4974        Ok(state
4975            .failed_retry
4976            .pending
4977            .filter(|_| state.state == ModuleState::Failed && state.enabled)
4978            .map(|retry| {
4979                unix_ms_now().saturating_add(
4980                    u64::try_from(
4981                        retry
4982                            .deadline
4983                            .saturating_duration_since(Instant::now())
4984                            .as_millis(),
4985                    )
4986                    .unwrap_or(u64::MAX),
4987                )
4988            }))
4989    }
4990
4991    #[cfg(all(test, unix))]
4992    pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
4993        lock_snapshot(&self.inner.snapshot)
4994            .unwrap()
4995            .failed_retry
4996            .pending
4997            .map(|retry| retry.deadline)
4998    }
4999
5000    pub(crate) fn record_deliberate_severance(
5001        &self,
5002        identity: ProcessIdentity,
5003    ) -> Result<bool, SuperviseError> {
5004        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
5005        if snapshot.pid != Some(identity.pid)
5006            || snapshot.process_start_time != Some(identity.start_time)
5007        {
5008            return Ok(false);
5009        }
5010        snapshot.deliberate_severance = Some(identity);
5011        Ok(true)
5012    }
5013
5014    /// Read status for a channel-0 renderer and report a contended snapshot lock.
5015    ///
5016    /// Internal supervision callers use [`Self::status`] so writer-side machinery
5017    /// does not produce reader-observability logs.
5018    pub(crate) fn status_for_control(
5019        &self,
5020        caller: &'static str,
5021    ) -> Result<ModuleStatus, SuperviseError> {
5022        self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
5023            .map(|(status, _)| status)
5024    }
5025
5026    fn status_with_snapshot_lock(
5027        &self,
5028        snapshot: &SharedSnapshot,
5029        caller: Option<&'static str>,
5030    ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
5031        let restart_policy = self
5032            .inner
5033            .configuration
5034            .lock()
5035            .map_err(|_| SuperviseError::StatePoisoned {
5036                module_id: Some(self.inner.module_id.clone()),
5037            })?
5038            .restart_policy;
5039        let mut guard = match caller {
5040            Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
5041            None => lock_snapshot(snapshot)?,
5042        };
5043        // Read the budget through the pruning path so a reader sees the same
5044        // in-window count the restart decision would use, not a stale total.
5045        let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
5046        let snapshot = guard.clone();
5047        drop(guard);
5048        let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
5049            SuperviseError::StatePoisoned {
5050                module_id: Some(self.inner.module_id.clone()),
5051            }
5052        })?;
5053        let registration_active = self
5054            .inner
5055            .registry
5056            .get_module(&self.inner.module_id)
5057            .map_err(SuperviseError::Registry)?
5058            .is_some();
5059        let protocol = snapshot
5060            .spawned_protocol
5061            .unwrap_or(self.declared_protocol()?);
5062        let running_process =
5063            snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
5064        // Registration is the difference between the two protocols and the only
5065        // one: a subc module that has not registered cannot serve a request even
5066        // though its process is up, and a `none` module never registers at all,
5067        // so requiring it there would pin `live` to false for the whole life of
5068        // a perfectly healthy process.
5069        let live = match protocol {
5070            ModuleProtocol::Subc => running_process && registration_active,
5071            ModuleProtocol::None => running_process,
5072        };
5073        // Read only the retained cache: a status read must not resend signals,
5074        // rewrite the record, or keep the containment resource alive.
5075        let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
5076        let carry_configured = self
5077            .inner
5078            .configuration
5079            .lock()
5080            .map_err(|_| SuperviseError::StatePoisoned {
5081                module_id: Some(self.inner.module_id.clone()),
5082            })?
5083            .spec
5084            .carry_containment;
5085        let recovery_block = carries_containment(
5086            carry_configured,
5087            self.inner
5088                .retained
5089                .has_carried_container(&self.inner.module_id),
5090        )
5091        .then(|| self.inner.retained.recovery_block())
5092        .flatten();
5093        let launch_nonce_source = observed_launch_nonce_source(&snapshot);
5094        let pid = snapshot.reported_pid();
5095        let mut health = snapshot.health;
5096        if let Some(detail) = recovery_block
5097            .as_ref()
5098            .or_else(|| retained.as_ref().map(|(_, detail)| detail))
5099        {
5100            health.detail = Some(match health.detail {
5101                Some(previous) => format!("{previous}; {detail}"),
5102                None => detail.clone(),
5103            });
5104        }
5105
5106        Ok((
5107            ModuleStatus {
5108                admission_refused: snapshot.admission_refused,
5109                legacy_registration_spawn: snapshot.legacy_registration_spawn,
5110                registration_declaration: snapshot.registration_declaration.clone(),
5111                stop_reason: snapshot.stop_reason,
5112                waiting_for_previous_pid: retained
5113                    .as_ref()
5114                    .map(|(pid, _)| *pid)
5115                    .filter(|pid| *pid > 0)
5116                    .or(snapshot.waiting_for_previous_pid),
5117                waiting_for_previous_detail: recovery_block
5118                    .or_else(|| retained.map(|(_, detail)| detail))
5119                    .or(snapshot.waiting_for_previous_detail),
5120                module_id: self.inner.module_id.clone(),
5121                launch_nonce_source,
5122                state: snapshot.state,
5123                enabled: snapshot.enabled,
5124                process_alive: snapshot.process_alive,
5125                registration_active,
5126                protocol,
5127                live,
5128                restart_count,
5129                lifetime_restarts: snapshot.lifetime_restarts,
5130                spawn_generation: snapshot.spawn_generation,
5131                swap_outcome: snapshot.swap_outcome,
5132                max_restarts: restart_policy.max_restarts,
5133                restart_window: restart_policy.window,
5134                drain_timeout,
5135                restart_backoff: restart_policy.backoff,
5136                restart_max_backoff: restart_policy.max_backoff,
5137                pid,
5138                spawned_at_ms: snapshot.spawned_at_ms,
5139                spawned_from: snapshot.spawned_from,
5140                launch_spec_digest: snapshot.launch_spec_digest,
5141                process_start_time: snapshot.process_start_time,
5142                last_exit: snapshot.last_exit,
5143                health,
5144            },
5145            snapshot.spawned_file_identity.clone(),
5146        ))
5147    }
5148
5149    #[cfg(test)]
5150    pub(crate) fn hold_snapshot_for_test(
5151        &self,
5152        acquired: std::sync::mpsc::Sender<()>,
5153        hold: Duration,
5154    ) -> std::thread::JoinHandle<()> {
5155        let snapshot = Arc::clone(&self.inner.snapshot);
5156        std::thread::spawn(move || {
5157            let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
5158            acquired
5159                .send(())
5160                .expect("test receiver waits for snapshot lock");
5161            std::thread::sleep(hold);
5162        })
5163    }
5164
5165    /// The status and the running-image check for `supervisor.provenance`,
5166    /// taken from one status read. The exec acknowledgement can land between
5167    /// two separate reads, and the reply would then pair "no pid yet" with an
5168    /// image observed after the module started, which describes no single
5169    /// moment.
5170    pub(crate) async fn status_and_running_image_agreement(
5171        &self,
5172    ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
5173        let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
5174        let image = self
5175            .inner
5176            .provenance_probe
5177            .observe(
5178                status.pid,
5179                status.spawned_from.as_deref(),
5180                identity,
5181                status.process_start_time,
5182            )
5183            .await;
5184        Ok((status, image))
5185    }
5186
5187    pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
5188        let snapshot = match lock_snapshot(&self.inner.snapshot) {
5189            Ok(snapshot) => snapshot.clone(),
5190            Err(_) => {
5191                return subc_control::RunningImageAgreement::Unavailable {
5192                    reason: subc_control::RunningImageUnavailableReason::NotRunning,
5193                };
5194            }
5195        };
5196        self.inner
5197            .provenance_probe
5198            .observe(
5199                snapshot.reported_pid(),
5200                snapshot.spawned_from.as_deref(),
5201                snapshot.spawned_file_identity.clone(),
5202                snapshot.process_start_time,
5203            )
5204            .await
5205    }
5206
5207    /// Memory and CPU time of the module's current process, read now. Only the
5208    /// process the supervisor spawned is read, not processes it has started.
5209    pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
5210        #[cfg(windows)]
5211        {
5212            let image = lock_snapshot(&self.inner.snapshot)
5213                .ok()
5214                .and_then(|snapshot| {
5215                    snapshot
5216                        .spawned_file_identity
5217                        .as_ref()
5218                        .and_then(|identity| identity.windows_image.clone())
5219                });
5220            match image {
5221                Some(image) => {
5222                    crate::child_resources::read_windows_handle(image.process(), image.start_time())
5223                }
5224                None => subc_control::ChildResourceUsage::Unavailable {
5225                    reason: subc_control::ChildResourceUnavailableReason::NotRunning,
5226                },
5227            }
5228        }
5229        #[cfg(not(windows))]
5230        {
5231            let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
5232                Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
5233                Err(_) => {
5234                    return subc_control::ChildResourceUsage::Unavailable {
5235                        reason: subc_control::ChildResourceUnavailableReason::Unreadable,
5236                    }
5237                }
5238            };
5239            crate::child_resources::read(pid, start_time)
5240        }
5241    }
5242
5243    #[cfg(all(test, any(target_os = "linux", windows)))]
5244    pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
5245        self.inner
5246            .snapshot
5247            .try_lock()
5248            .map(|snapshot| snapshot.subtree_target.clone())
5249            .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
5250    }
5251
5252    #[cfg(test)]
5253    pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
5254        self.inner.snapshot.lock().unwrap().subtree_target = target;
5255    }
5256
5257    pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
5258        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
5259        Ok(match snapshot.state {
5260            ModuleState::Restarting => true,
5261            ModuleState::Failed | ModuleState::Disabled => false,
5262            _ if snapshot.enabled && snapshot.respawn_pending => true,
5263            _ => daemon_will_restart(
5264                &mut snapshot,
5265                &self
5266                    .inner
5267                    .configuration
5268                    .lock()
5269                    .map_err(|_| SuperviseError::StatePoisoned {
5270                        module_id: Some(self.inner.module_id.clone()),
5271                    })?
5272                    .restart_policy,
5273                Instant::now(),
5274            ),
5275        })
5276    }
5277
5278    #[cfg(test)]
5279    pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
5280        self.is_warming_with_snapshot_lock(None)
5281    }
5282
5283    pub(crate) fn is_warming_for_control(
5284        &self,
5285        caller: &'static str,
5286    ) -> Result<bool, SuperviseError> {
5287        self.is_warming_with_snapshot_lock(Some(caller))
5288    }
5289
5290    fn is_warming_with_snapshot_lock(
5291        &self,
5292        caller: Option<&'static str>,
5293    ) -> Result<bool, SuperviseError> {
5294        let snapshot = match caller {
5295            Some(caller) => {
5296                lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
5297            }
5298            None => lock_snapshot(&self.inner.snapshot)?,
5299        }
5300        .clone();
5301        Ok(matches!(
5302            snapshot.state,
5303            ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
5304        ))
5305    }
5306
5307    /// Drain the module and stop monitoring it.
5308    pub async fn drain(&self) -> Result<(), SuperviseError> {
5309        self.stop().await
5310    }
5311
5312    pub(crate) async fn retire_requested(
5313        &self,
5314        requester: Option<Principal>,
5315    ) -> Result<(), SuperviseError> {
5316        match self.state()? {
5317            ModuleState::Stopped => return Ok(()),
5318            ModuleState::Failed
5319                if lock_snapshot(&self.inner.snapshot)?
5320                    .failed_retry
5321                    .pending
5322                    .is_none() =>
5323            {
5324                return Ok(())
5325            }
5326            ModuleState::Failed
5327            | ModuleState::Starting
5328            | ModuleState::Running
5329            | ModuleState::Unresponsive
5330            | ModuleState::Restarting
5331            | ModuleState::Draining
5332            | ModuleState::Disabled => {}
5333        }
5334
5335        let (reply_tx, reply_rx) = oneshot::channel();
5336        self.inner
5337            .commands
5338            .send(SupervisorCommand::Retire {
5339                requester,
5340                reply: reply_tx,
5341            })
5342            .await
5343            .map_err(|_| SuperviseError::CommandClosed {
5344                module_id: self.inner.module_id.clone(),
5345            })?;
5346        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5347            module_id: self.inner.module_id.clone(),
5348        })?
5349    }
5350
5351    pub async fn stop(&self) -> Result<(), SuperviseError> {
5352        self.stop_requested(None).await
5353    }
5354
5355    pub(crate) async fn stop_requested(
5356        &self,
5357        requester: Option<Principal>,
5358    ) -> Result<(), SuperviseError> {
5359        match self.state()? {
5360            ModuleState::Stopped => return Ok(()),
5361            ModuleState::Failed
5362                if lock_snapshot(&self.inner.snapshot)?
5363                    .failed_retry
5364                    .pending
5365                    .is_none() =>
5366            {
5367                return Ok(())
5368            }
5369            ModuleState::Failed
5370            | ModuleState::Starting
5371            | ModuleState::Running
5372            | ModuleState::Unresponsive
5373            | ModuleState::Restarting
5374            | ModuleState::Draining
5375            | ModuleState::Disabled => {}
5376        }
5377
5378        let (reply_tx, reply_rx) = oneshot::channel();
5379        self.inner
5380            .commands
5381            .send(SupervisorCommand::Drain {
5382                requester,
5383                reply: reply_tx,
5384            })
5385            .await
5386            .map_err(|_| SuperviseError::CommandClosed {
5387                module_id: self.inner.module_id.clone(),
5388            })?;
5389        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5390            module_id: self.inner.module_id.clone(),
5391        })?
5392    }
5393
5394    pub async fn restart(&self, drain_timeout_ms: Option<u64>) -> Result<(), SuperviseError> {
5395        self.restart_requested(drain_timeout_ms, None).await
5396    }
5397
5398    pub(crate) async fn restart_requested(
5399        &self,
5400        drain_timeout_ms: Option<u64>,
5401        requester: Option<Principal>,
5402    ) -> Result<(), SuperviseError> {
5403        let queued_at = Instant::now();
5404        let received_at_generation = lock_snapshot(&self.inner.snapshot)?.spawn_generation;
5405        let (reply_tx, reply_rx) = oneshot::channel();
5406        self.inner
5407            .commands
5408            .send(SupervisorCommand::Restart {
5409                requester,
5410                drain_timeout_ms,
5411                received_at_generation,
5412                queued_at,
5413                reply: reply_tx,
5414            })
5415            .await
5416            .map_err(|_| SuperviseError::CommandClosed {
5417                module_id: self.inner.module_id.clone(),
5418            })?;
5419        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5420            module_id: self.inner.module_id.clone(),
5421        })?
5422    }
5423
5424    /// Blue/green restart: see `SupervisorCommand::Swap` and the
5425    /// `supervisor_swap` module. Returns once the swap has cut over (the old
5426    /// process then drains in the background of the supervise loop), has been
5427    /// superseded by an approved configuration restart, or has failed. Both
5428    /// supersession and failure leave the old process serving until replacement.
5429    pub async fn swap(
5430        &self,
5431        ready_timeout: Option<Duration>,
5432    ) -> Result<SwapOutcome, SuperviseError> {
5433        self.swap_requested(ready_timeout, None).await
5434    }
5435
5436    pub(crate) async fn swap_requested(
5437        &self,
5438        ready_timeout: Option<Duration>,
5439        requester: Option<Principal>,
5440    ) -> Result<SwapOutcome, SuperviseError> {
5441        let (reply_tx, reply_rx) = oneshot::channel();
5442        self.inner
5443            .commands
5444            .send(SupervisorCommand::Swap {
5445                requester,
5446                ready_timeout,
5447                reply: reply_tx,
5448            })
5449            .await
5450            .map_err(|_| SuperviseError::CommandClosed {
5451                module_id: self.inner.module_id.clone(),
5452            })?;
5453        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5454            module_id: self.inner.module_id.clone(),
5455        })?
5456    }
5457
5458    pub async fn reload(&self) -> Result<(), SuperviseError> {
5459        self.reload_requested(None).await
5460    }
5461
5462    pub(crate) async fn reload_requested(
5463        &self,
5464        requester: Option<Principal>,
5465    ) -> Result<(), SuperviseError> {
5466        let (reply_tx, reply_rx) = oneshot::channel();
5467        self.inner
5468            .commands
5469            .send(SupervisorCommand::Reload {
5470                requester,
5471                reply: reply_tx,
5472            })
5473            .await
5474            .map_err(|_| SuperviseError::CommandClosed {
5475                module_id: self.inner.module_id.clone(),
5476            })?;
5477        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5478            module_id: self.inner.module_id.clone(),
5479        })?
5480    }
5481
5482    pub async fn set_enabled(&self, enabled: bool) -> Result<bool, SuperviseError> {
5483        self.set_enabled_requested(enabled, None).await
5484    }
5485
5486    pub(crate) async fn set_enabled_requested(
5487        &self,
5488        enabled: bool,
5489        requester: Option<Principal>,
5490    ) -> Result<bool, SuperviseError> {
5491        self.set_enabled_with_budget_policy(enabled, requester, true)
5492            .await
5493    }
5494
5495    pub(crate) async fn release_config_hold(&self) -> Result<bool, SuperviseError> {
5496        self.set_enabled_with_budget_policy(true, None, false).await
5497    }
5498
5499    #[cfg(all(test, unix))]
5500    pub(crate) fn seed_crash_budget_for_test(&self, count: u32) {
5501        let policy = self.inner.configuration.lock().unwrap().restart_policy;
5502        let mut state = self.inner.snapshot.lock().unwrap();
5503        for _ in 0..count {
5504            state.record_crash_restart(&policy, Instant::now());
5505        }
5506    }
5507
5508    async fn set_enabled_with_budget_policy(
5509        &self,
5510        enabled: bool,
5511        requester: Option<Principal>,
5512        reset_budget: bool,
5513    ) -> Result<bool, SuperviseError> {
5514        let (reply_tx, reply_rx) = oneshot::channel();
5515        self.inner
5516            .commands
5517            .send(SupervisorCommand::SetEnabled {
5518                requester,
5519                enabled,
5520                reset_budget,
5521                reply: reply_tx,
5522            })
5523            .await
5524            .map_err(|_| SuperviseError::CommandClosed {
5525                module_id: self.inner.module_id.clone(),
5526            })?;
5527        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5528            module_id: self.inner.module_id.clone(),
5529        })?
5530    }
5531
5532    /// The current process's protocol, or the configured protocol when down.
5533    /// A rescan stores the next launch spec without changing how an existing
5534    /// process registers, serves routes, is probed, or exits.
5535    pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
5536        let configured = self
5537            .inner
5538            .configuration
5539            .lock()
5540            .map_err(|_| SuperviseError::StatePoisoned {
5541                module_id: Some(self.inner.module_id.clone()),
5542            })?
5543            .spec
5544            .protocol;
5545        let state = lock_snapshot(&self.inner.snapshot)?;
5546        Ok(state.spawned_protocol.unwrap_or(configured))
5547    }
5548
5549    pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
5550        let configuration =
5551            self.inner
5552                .configuration
5553                .lock()
5554                .map_err(|_| SuperviseError::StatePoisoned {
5555                    module_id: Some(self.inner.module_id.clone()),
5556                })?;
5557        Ok((configuration.spec.clone(), configuration.health.clone()))
5558    }
5559
5560    pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
5561        self.inner
5562            .configuration
5563            .lock()
5564            .map(|configuration| configuration.register_timeout)
5565            .map_err(|_| SuperviseError::StatePoisoned {
5566                module_id: Some(self.inner.module_id.clone()),
5567            })
5568    }
5569
5570    pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
5571        self.inner
5572            .configuration
5573            .lock()
5574            .map(|configuration| configuration.enabled)
5575            .map_err(|_| SuperviseError::StatePoisoned {
5576                module_id: Some(self.inner.module_id.clone()),
5577            })
5578    }
5579
5580    /// Replace this module's launch spec, keeping its health and drain policy,
5581    /// the way a rescan does for a changed config entry. The running process is
5582    /// untouched; the next spawn (a restart, or a swap's candidate) uses it.
5583    #[cfg(any(test, feature = "test-support"))]
5584    pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
5585        let (_, health) = self.configuration()?;
5586        let drain_timeout_ms = u64::try_from(
5587            self.inner
5588                .effective_drain_timeout
5589                .lock()
5590                .unwrap_or_else(|poisoned| poisoned.into_inner())
5591                .as_millis(),
5592        )
5593        .ok();
5594        self.update_configuration(spec, health, drain_timeout_ms)
5595            .await
5596    }
5597
5598    pub(crate) async fn reconcile_approved_configuration(
5599        &self,
5600        approved: crate::config_gate::runtime::ApprovedDaemonConfiguration,
5601    ) -> Result<(), SuperviseError> {
5602        let entry = approved
5603            .module_entry(&self.inner.module_id)
5604            .map_err(|error| SuperviseError::InvalidSpec {
5605                reason: error.to_string(),
5606            })?;
5607        validate_spec(&entry.module_spec())?;
5608        let (reply, received) = oneshot::channel();
5609        self.inner
5610            .commands
5611            .send(SupervisorCommand::ApprovedConfiguration { approved, reply })
5612            .await
5613            .map_err(|_| SuperviseError::CommandClosed {
5614                module_id: self.inner.module_id.clone(),
5615            })?;
5616        received.await.map_err(|_| SuperviseError::CommandClosed {
5617            module_id: self.inner.module_id.clone(),
5618        })??;
5619        let mut configuration =
5620            self.inner
5621                .configuration
5622                .lock()
5623                .map_err(|_| SuperviseError::StatePoisoned {
5624                    module_id: Some(self.inner.module_id.clone()),
5625                })?;
5626        configuration.spec = entry.module_spec();
5627        configuration.enabled = entry.enabled;
5628        configuration.health = entry.health;
5629        configuration.register_timeout = entry.register_timeout;
5630        configuration.restart_policy = entry.restart;
5631        Ok(())
5632    }
5633
5634    pub(crate) async fn update_configuration(
5635        &self,
5636        spec: ModuleSpec,
5637        health: HealthConfig,
5638        drain_timeout_ms: Option<u64>,
5639    ) -> Result<(), SuperviseError> {
5640        if spec.module_id != self.inner.module_id {
5641            return Err(SuperviseError::InvalidSpec {
5642                reason: "a supervised module's module_id cannot be changed".to_string(),
5643            });
5644        }
5645        validate_spec(&spec)?;
5646        let (reply_tx, reply_rx) = oneshot::channel();
5647        self.inner
5648            .commands
5649            .send(SupervisorCommand::UpdateConfiguration {
5650                spec: spec.clone(),
5651                health: health.clone(),
5652                drain_timeout_ms,
5653                reply: reply_tx,
5654            })
5655            .await
5656            .map_err(|_| SuperviseError::CommandClosed {
5657                module_id: self.inner.module_id.clone(),
5658            })?;
5659        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5660            module_id: self.inner.module_id.clone(),
5661        })??;
5662        let mut configuration =
5663            self.inner
5664                .configuration
5665                .lock()
5666                .map_err(|_| SuperviseError::StatePoisoned {
5667                    module_id: Some(self.inner.module_id.clone()),
5668                })?;
5669        configuration.spec = spec;
5670        configuration.health = health;
5671        Ok(())
5672    }
5673}
5674
5675impl Drop for SupervisedModuleInner {
5676    fn drop(&mut self) {
5677        let Ok(mut monitor) = self.monitor.lock() else {
5678            return;
5679        };
5680        if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
5681            let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
5682                state.state = ModuleState::Stopped;
5683                clear_current_process_facts(state);
5684            });
5685            monitor.abort();
5686        }
5687        let _ = monitor.take();
5688    }
5689}
5690
5691#[derive(Debug)]
5692enum SupervisorCommand {
5693    ApprovedConfiguration {
5694        approved: crate::config_gate::runtime::ApprovedDaemonConfiguration,
5695        reply: oneshot::Sender<Result<(), SuperviseError>>,
5696    },
5697    ConfigPolicyProbe {
5698        connection: crate::ConnectionId,
5699        generation: u64,
5700        attempt: u64,
5701    },
5702    ConfigApplyRestart {
5703        generation: u64,
5704        supersedes_swap: bool,
5705    },
5706    ConfigExitHold {
5707        reply: oneshot::Sender<Result<(), SuperviseError>>,
5708    },
5709    ConfigDeliveryFailed {
5710        connection: crate::ConnectionId,
5711        hold: bool,
5712    },
5713    Drain {
5714        requester: Option<Principal>,
5715        reply: oneshot::Sender<Result<(), SuperviseError>>,
5716    },
5717    Retire {
5718        requester: Option<Principal>,
5719        reply: oneshot::Sender<Result<(), SuperviseError>>,
5720    },
5721    Restart {
5722        requester: Option<Principal>,
5723        /// Operator override for this one restart's drain budget, in ms. `None`
5724        /// uses the module's configured/default budget; `Some(0)` cuts
5725        /// immediately (wedge bounce: a stuck request never settles, so
5726        /// waiting only delays recovery).
5727        drain_timeout_ms: Option<u64>,
5728        /// The module's `spawn_generation` when the request was received, before
5729        /// it waited in the command queue. A queued restart whose module has
5730        /// since spawned a newer process is already satisfied (see the handler).
5731        received_at_generation: u64,
5732        /// When the request entered the command queue, so the handler can log
5733        /// how long it waited behind the loop's other work.
5734        queued_at: Instant,
5735        reply: oneshot::Sender<Result<(), SuperviseError>>,
5736    },
5737    Reload {
5738        requester: Option<Principal>,
5739        reply: oneshot::Sender<Result<(), SuperviseError>>,
5740    },
5741    SetEnabled {
5742        reset_budget: bool,
5743        requester: Option<Principal>,
5744        enabled: bool,
5745        reply: oneshot::Sender<Result<bool, SuperviseError>>,
5746    },
5747    UpdateConfiguration {
5748        spec: ModuleSpec,
5749        health: HealthConfig,
5750        /// Per-module drain override from the new config; `None` re-resolves to
5751        /// the supervisor-wide default.
5752        drain_timeout_ms: Option<u64>,
5753        reply: oneshot::Sender<Result<(), SuperviseError>>,
5754    },
5755    Swap {
5756        requester: Option<Principal>,
5757        /// How long the candidate may take to register and declare itself
5758        /// ready. `None` uses [`DEFAULT_SWAP_READY_TIMEOUT`].
5759        ready_timeout: Option<Duration>,
5760        /// Answered at cutover or failure; the incumbent's drain follows.
5761        reply: oneshot::Sender<Result<SwapOutcome, SuperviseError>>,
5762    },
5763}
5764
5765/// Successful daemon-local swap disposition. Supersession leaves the incumbent
5766/// serving until an approved replacement starts with the latest configured
5767/// command; the legacy control acknowledgment does not carry this disposition.
5768#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5769pub enum SwapOutcome {
5770    Cutover,
5771    SupersededByConfigRestart,
5772}
5773
5774impl SwapOutcome {
5775    pub fn as_str(self) -> &'static str {
5776        match self {
5777            Self::Cutover => "cutover",
5778            Self::SupersededByConfigRestart => "superseded_by_config_restart",
5779        }
5780    }
5781}
5782
5783#[derive(Debug)]
5784pub enum SuperviseError {
5785    ConfigHeld {
5786        module_id: String,
5787        code: String,
5788        detail: String,
5789    },
5790    ConfigDeliveryDeferred {
5791        module_id: String,
5792    },
5793    InvalidSpec {
5794        reason: String,
5795    },
5796    Spawn {
5797        program: PathBuf,
5798        source: io::Error,
5799        cgroup_path: Option<PathBuf>,
5800    },
5801    Cgroup {
5802        module_id: String,
5803        source: io::Error,
5804    },
5805    /// CSPRNG failure generating a reserved module's launch nonce. Fail loud rather
5806    /// than spawn a reserved module without its identity binding.
5807    LaunchNonce {
5808        reason: String,
5809    },
5810    Wait {
5811        module_id: String,
5812        source: io::Error,
5813    },
5814    Kill {
5815        module_id: String,
5816        source: io::Error,
5817    },
5818    Forwarding(ForwardingError),
5819    Registry(RegistryError),
5820    ReloadUnavailable {
5821        module_id: String,
5822        reason: String,
5823    },
5824    /// An operator restart/reload was requested for a module that is currently
5825    /// disabled. Restart/reload cycle a *running* module; a disabled module must
5826    /// be explicitly re-enabled (set_enabled(true)) rather than silently started
5827    /// by a restart, so these commands are rejected instead of re-enabling it.
5828    Disabled {
5829        module_id: String,
5830    },
5831    ReloadFailed {
5832        module_id: String,
5833        reason: String,
5834    },
5835    RegistrationStillActive {
5836        module_id: String,
5837        waited: Duration,
5838    },
5839    StatePoisoned {
5840        module_id: Option<String>,
5841    },
5842    CommandClosed {
5843        module_id: String,
5844    },
5845    /// A restart or reload arrived while a swap's candidate was warming. The
5846    /// swap owns the module until it cuts over or fails; a stop or disable
5847    /// would have aborted it instead.
5848    SwapInProgress {
5849        module_id: String,
5850    },
5851    /// A swap was refused before anything was spawned.
5852    SwapRefused {
5853        module_id: String,
5854        reason: SwapRefusal,
5855    },
5856    /// A swap spawned a candidate and gave up on it. The candidate has been
5857    /// killed and its slot freed; the incumbent was left serving and was never
5858    /// drained, except in the one `CutoverLost` case described on that arm.
5859    SwapFailed {
5860        module_id: String,
5861        arm: SwapFailureArm,
5862        detail: String,
5863        /// How the candidate exited, when it exited on its own before the
5864        /// supervisor gave up on it.
5865        candidate_exit: Option<ExitReport>,
5866    },
5867}
5868
5869/// Why a swap was refused before a candidate was spawned.
5870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5871pub enum SwapRefusal {
5872    /// The module's config does not declare `overlap: "safe"`.
5873    OverlapExclusive,
5874    /// The module is not registered, so there is no incumbent to keep serving
5875    /// and nothing a swap would improve on; a plain restart is the tool.
5876    NotRegistered,
5877    /// The module does not speak the subc wire, so a candidate could never
5878    /// register or declare itself ready.
5879    ProtocolNone,
5880    /// The supervisor lacks the forwarding table (to cut routes over) or the
5881    /// shared handle (to admit the candidate's HELLO) that a swap needs.
5882    NotConfigured,
5883    /// A swap is already open for this module.
5884    AlreadySwapping,
5885}
5886
5887impl SwapRefusal {
5888    pub fn as_str(self) -> &'static str {
5889        match self {
5890            Self::OverlapExclusive => "overlap_exclusive",
5891            Self::NotRegistered => "not_registered",
5892            Self::ProtocolNone => "protocol_none",
5893            Self::NotConfigured => "not_configured",
5894            Self::AlreadySwapping => "already_swapping",
5895        }
5896    }
5897}
5898
5899/// Which failure arm ended a swap. Every arm but one leaves the incumbent
5900/// serving and undrained; see `CutoverLost`.
5901#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5902pub enum SwapFailureArm {
5903    /// The candidate process could not be started.
5904    SpawnFailed,
5905    /// The candidate did not register within the readiness budget.
5906    NeverRegistered,
5907    /// The candidate registered but did not declare itself ready in time.
5908    NeverReady,
5909    /// The candidate exited before cutover.
5910    CandidateExited,
5911    /// The candidate declared itself ready but failed its health probe.
5912    CandidateUnhealthy,
5913    /// An operator stop, disable or retire arrived while the candidate warmed.
5914    /// The candidate was killed and the operator's command then carried out on
5915    /// the incumbent.
5916    Interrupted,
5917    /// The candidate's connection closed at the moment of cutover. If it
5918    /// closed before forwarding moved, the incumbent is untouched. If it closed
5919    /// between the forwarding and registry halves of cutover, forwarding can no
5920    /// longer route to the incumbent, so the module is restarted plainly.
5921    CutoverLost,
5922}
5923
5924impl SwapFailureArm {
5925    pub fn as_str(self) -> &'static str {
5926        match self {
5927            Self::SpawnFailed => "spawn_failed",
5928            Self::NeverRegistered => "never_registered",
5929            Self::NeverReady => "never_ready",
5930            Self::CandidateExited => "candidate_exited",
5931            Self::CandidateUnhealthy => "candidate_unhealthy",
5932            Self::Interrupted => "interrupted",
5933            Self::CutoverLost => "cutover_lost",
5934        }
5935    }
5936}
5937
5938impl SuperviseError {
5939    pub(crate) fn is_config_gate_error(&self) -> bool {
5940        match self {
5941            Self::ConfigHeld { .. } => true,
5942            Self::Spawn { source, .. } => source
5943                .get_ref()
5944                .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
5945            _ => false,
5946        }
5947    }
5948}
5949
5950impl fmt::Display for SuperviseError {
5951    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5952        match self {
5953            Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
5954            Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
5955            Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
5956            Self::Spawn {
5957                program,
5958                source,
5959                cgroup_path: Some(cgroup_path),
5960            } => write!(
5961                f,
5962                "failed to place module in cgroup '{}' while spawning '{}': {source}",
5963                cgroup_path.display(),
5964                program.display()
5965            ),
5966            Self::Spawn {
5967                program,
5968                source,
5969                cgroup_path: None,
5970            } => write!(
5971                f,
5972                "failed to spawn module '{}': {source}",
5973                program.display()
5974            ),
5975            Self::Cgroup { module_id, source } => {
5976                write!(
5977                    f,
5978                    "failed to prepare cgroup for module '{module_id}': {source}"
5979                )
5980            }
5981            Self::LaunchNonce { reason } => {
5982                write!(
5983                    f,
5984                    "failed to generate reserved-module launch nonce: {reason}"
5985                )
5986            }
5987            Self::Wait { module_id, source } => {
5988                write!(f, "failed to wait for module '{module_id}': {source}")
5989            }
5990            Self::Kill { module_id, source } => {
5991                write!(f, "failed to kill module '{module_id}': {source}")
5992            }
5993            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
5994            Self::Registry(err) => write!(f, "registry error: {err}"),
5995            Self::ReloadUnavailable { module_id, reason } => {
5996                write!(f, "reload unavailable for module '{module_id}': {reason}")
5997            }
5998            Self::Disabled { module_id } => {
5999                write!(
6000                    f,
6001                    "module '{module_id}' is disabled; enable it before restart or reload"
6002                )
6003            }
6004            Self::ReloadFailed { module_id, reason } => {
6005                write!(f, "reload failed for module '{module_id}': {reason}")
6006            }
6007            Self::RegistrationStillActive { module_id, waited } => write!(
6008                f,
6009                "module '{module_id}' registration remained active after waiting {waited:?}"
6010            ),
6011            Self::StatePoisoned { module_id } => match module_id {
6012                Some(module_id) => {
6013                    write!(f, "supervisor state for module '{module_id}' was poisoned")
6014                }
6015                None => write!(f, "supervisor state was poisoned"),
6016            },
6017            Self::CommandClosed { module_id } => {
6018                write!(
6019                    f,
6020                    "supervisor command channel for module '{module_id}' is closed"
6021                )
6022            }
6023            Self::SwapInProgress { module_id } => write!(
6024                f,
6025                "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
6026            ),
6027            Self::SwapRefused { module_id, reason } => match reason {
6028                SwapRefusal::OverlapExclusive => write!(
6029                    f,
6030                    "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"
6031                ),
6032                SwapRefusal::NotRegistered => write!(
6033                    f,
6034                    "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
6035                ),
6036                SwapRefusal::ProtocolNone => write!(
6037                    f,
6038                    "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
6039                ),
6040                SwapRefusal::NotConfigured => write!(
6041                    f,
6042                    "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
6043                ),
6044                SwapRefusal::AlreadySwapping => {
6045                    write!(f, "module '{module_id}' is already being swapped")
6046                }
6047            },
6048            Self::SwapFailed {
6049                module_id,
6050                arm,
6051                detail,
6052                ..
6053            } => write!(
6054                f,
6055                "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
6056                arm.as_str()
6057            ),
6058        }
6059    }
6060}
6061
6062impl Error for SuperviseError {
6063    fn source(&self) -> Option<&(dyn Error + 'static)> {
6064        match self {
6065            Self::Spawn { source, .. }
6066            | Self::Cgroup { source, .. }
6067            | Self::Wait { source, .. }
6068            | Self::Kill { source, .. } => Some(source),
6069            Self::Forwarding(err) => Some(err),
6070            Self::Registry(err) => Some(err),
6071            Self::LaunchNonce { .. }
6072            | Self::ConfigDeliveryDeferred { .. }
6073            | Self::ConfigHeld { .. }
6074            | Self::InvalidSpec { .. }
6075            | Self::ReloadUnavailable { .. }
6076            | Self::Disabled { .. }
6077            | Self::ReloadFailed { .. }
6078            | Self::RegistrationStillActive { .. }
6079            | Self::StatePoisoned { .. }
6080            | Self::CommandClosed { .. }
6081            | Self::SwapInProgress { .. }
6082            | Self::SwapRefused { .. }
6083            | Self::SwapFailed { .. } => None,
6084        }
6085    }
6086}
6087
6088pub(crate) fn validate_spec(spec: &ModuleSpec) -> Result<(), SuperviseError> {
6089    if spec.carry_containment && spec.overlap == ModuleOverlap::Safe {
6090        return Err(SuperviseError::InvalidSpec {
6091            reason: "carry_containment cannot be combined with overlap: safe".to_owned(),
6092        });
6093    }
6094    if spec.module_id.trim().is_empty() {
6095        return Err(SuperviseError::InvalidSpec {
6096            reason: "module_id must not be empty".to_string(),
6097        });
6098    }
6099
6100    Ok(())
6101}
6102
6103#[derive(Debug, Default)]
6104struct HealthProbeRuntime {
6105    spawn_generation: Option<u64>,
6106    configured_health: Option<HealthConfig>,
6107    registered_connection: Option<crate::ConnectionId>,
6108    advertised: bool,
6109    next_probe_at: Option<Instant>,
6110    probe_index: u64,
6111}
6112
6113fn running_protocol(spec: &ModuleSpec, snapshot: &SharedSnapshot) -> ModuleProtocol {
6114    lock_snapshot(snapshot)
6115        .ok()
6116        .and_then(|state| state.spawned_protocol)
6117        .unwrap_or(spec.protocol)
6118}
6119
6120impl HealthProbeRuntime {
6121    fn refresh_registration(
6122        &mut self,
6123        spec: &ModuleSpec,
6124        runtime: &SupervisorRuntimeConfig,
6125        registry: &Registry,
6126        snapshot: &SharedSnapshot,
6127    ) {
6128        let generation = lock_snapshot(snapshot)
6129            .ok()
6130            .map(|state| state.spawn_generation);
6131        if self.spawn_generation != generation {
6132            // A replacement cannot reuse a deadline that is already due for its
6133            // predecessor. HTTP children get a full cadence to start; wire
6134            // children still wait for their own health-advertising HELLO.
6135            *self = Self {
6136                spawn_generation: generation,
6137                ..Self::default()
6138            };
6139        }
6140        if self.configured_health.as_ref() != Some(&runtime.health) {
6141            self.configured_health = Some(runtime.health.clone());
6142            self.next_probe_at = None;
6143            self.registered_connection = None;
6144            self.probe_index = 0;
6145        }
6146        // A non-wire process never registers. Only an explicitly configured
6147        // HTTP endpoint can arm its health probe; an absent HELLO is not a
6148        // health failure for that kind of process.
6149        if running_protocol(spec, snapshot) == ModuleProtocol::None {
6150            self.registered_connection = None;
6151            self.advertised = runtime.health.http.is_some();
6152            if !self.advertised {
6153                self.next_probe_at = None;
6154                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6155                    let unknown = ModuleHealthStatus::default();
6156                    if state.health != unknown {
6157                        state.health = unknown;
6158                        state.last_probe_evidence = None;
6159                    }
6160                });
6161            } else if self.next_probe_at.is_none() {
6162                self.next_probe_at = Some(
6163                    Instant::now()
6164                        + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
6165                );
6166            }
6167            return;
6168        }
6169
6170        let registration = match registry.get_module(&spec.module_id) {
6171            Ok(registration) => registration,
6172            Err(err) => {
6173                warn!(module_id = %spec.module_id, error = %err, "health prober could not read registry");
6174                self.advertised = false;
6175                self.next_probe_at = None;
6176                return;
6177            }
6178        };
6179
6180        let Some(registration) = registration else {
6181            self.registered_connection = None;
6182            self.advertised = false;
6183            self.next_probe_at = None;
6184            return;
6185        };
6186
6187        let advertised = registration
6188            .control_ops
6189            .iter()
6190            .any(|op| op == MODULE_CONTROL_OP_HEALTH_CHECK);
6191        if !advertised {
6192            self.registered_connection = Some(registration.connection_id);
6193            self.advertised = false;
6194            self.next_probe_at = None;
6195            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6196                if state.health.status != SupervisorHealthStatus::Unknown
6197                    || state.health.consecutive_failures != 0
6198                    || state.health.last_probe_ms.is_some()
6199                    || state.health.detail.is_some()
6200                    || state.health.metrics.is_some()
6201                {
6202                    state.health.status = SupervisorHealthStatus::Unknown;
6203                    state.last_probe_evidence = None;
6204                    state.health.consecutive_failures = 0;
6205                    state.health.last_probe_ms = None;
6206                    state.health.detail = None;
6207                    state.health.metrics = None;
6208                }
6209            });
6210            return;
6211        }
6212
6213        let reregistered = self.registered_connection != Some(registration.connection_id);
6214        self.registered_connection = Some(registration.connection_id);
6215        self.advertised = true;
6216        if reregistered || self.next_probe_at.is_none() {
6217            self.probe_index = 0;
6218            self.next_probe_at = Some(
6219                Instant::now() + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
6220            );
6221            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6222                state.health.status = SupervisorHealthStatus::Unknown;
6223                state.last_probe_evidence = None;
6224                state.health.consecutive_failures = 0;
6225                state.health.detail = None;
6226                state.health.metrics = None;
6227            });
6228        }
6229    }
6230
6231    fn wake_at(&self) -> Option<Instant> {
6232        if !self.advertised {
6233            return None;
6234        }
6235        self.next_probe_at
6236    }
6237
6238    fn due(&self) -> bool {
6239        self.advertised
6240            && self
6241                .next_probe_at
6242                .is_some_and(|next| Instant::now() >= next)
6243    }
6244
6245    fn schedule_next(&mut self, spec: &ModuleSpec, cadence: Duration) {
6246        self.probe_index = self.probe_index.wrapping_add(1);
6247        self.next_probe_at = Some(
6248            Instant::now() + jittered_health_delay(&spec.module_id, self.probe_index, cadence),
6249        );
6250    }
6251}
6252
6253/// Evidence is separate from diagnostic prose so host starvation can hold only
6254/// silence-based restarts. A missing lane is still actionable during overload;
6255/// a timeout can instead mean the host has not scheduled a healthy module.
6256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6257enum HealthProbeEvidence {
6258    /// The module's control lane is gone. Proof of death.
6259    LaneDead,
6260    /// No reply within the deadline. Proves nothing about the module's state.
6261    NoAnswer,
6262    /// The module replied, but not with a usable health report. Proves it is alive.
6263    BadAnswer,
6264    /// The daemon could not ask. Says nothing about the module.
6265    Misconfigured,
6266}
6267
6268#[derive(Debug)]
6269struct HealthProbeError {
6270    evidence: HealthProbeEvidence,
6271    message: String,
6272}
6273
6274impl HealthProbeError {
6275    fn lane_dead(message: impl Into<String>) -> Self {
6276        Self::with(HealthProbeEvidence::LaneDead, message)
6277    }
6278
6279    fn no_answer(message: impl Into<String>) -> Self {
6280        Self::with(HealthProbeEvidence::NoAnswer, message)
6281    }
6282
6283    fn bad_answer(message: impl Into<String>) -> Self {
6284        Self::with(HealthProbeEvidence::BadAnswer, message)
6285    }
6286
6287    fn misconfigured(message: impl Into<String>) -> Self {
6288        Self::with(HealthProbeEvidence::Misconfigured, message)
6289    }
6290
6291    fn with(evidence: HealthProbeEvidence, message: impl Into<String>) -> Self {
6292        Self {
6293            evidence,
6294            message: message.into(),
6295        }
6296    }
6297
6298    /// Whether this observation is proof the module cannot serve.
6299    ///
6300    /// Only `LaneDead` qualifies. `NoAnswer` is deliberately excluded: it is the
6301    /// variant that fires under CPU starvation, and treating it as proof is the
6302    /// defect this enum exists to make impossible to reintroduce silently.
6303    ///
6304    /// Outside a host-overload hold, silence still reaches the normal failure
6305    /// threshold so an isolated, genuinely wedged module can recover.
6306    #[allow(dead_code)]
6307    fn is_proof_of_death(&self) -> bool {
6308        matches!(self.evidence, HealthProbeEvidence::LaneDead)
6309    }
6310
6311    /// Short stable label for logs and the health snapshot.
6312    ///
6313    /// An operator reading `ck health` currently cannot tell "the module is gone"
6314    /// from "the module did not answer in five seconds", because both render as
6315    /// prose in the same field. These labels are what make the two
6316    /// distinguishable at a glance, and they are what a later restart-policy
6317    /// change will be argued from.
6318    fn label(&self) -> &'static str {
6319        match self.evidence {
6320            HealthProbeEvidence::LaneDead => "lane-dead",
6321            HealthProbeEvidence::NoAnswer => "no-answer",
6322            HealthProbeEvidence::BadAnswer => "bad-answer",
6323            HealthProbeEvidence::Misconfigured => "daemon-misconfigured",
6324        }
6325    }
6326}
6327
6328impl fmt::Display for HealthProbeError {
6329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6330        f.write_str(&self.message)
6331    }
6332}
6333
6334async fn run_health_probe_cycle(
6335    spec: &ModuleSpec,
6336    runtime: &SupervisorRuntimeConfig,
6337    registry: &Registry,
6338    process_liveness: &SupervisorProcessLiveness,
6339    snapshot: &SharedSnapshot,
6340    child: &mut Option<SupervisedChild>,
6341) {
6342    let now_ms = unix_ms_now();
6343    let delivery_probe = match &runtime.config_delivery {
6344        Some(delivery) => {
6345            delivery
6346                .health_probe(&spec.module_id, runtime.forwarding.as_deref(), registry)
6347                .await
6348        }
6349        None => None,
6350    };
6351    let http = (running_protocol(spec, snapshot) == ModuleProtocol::None)
6352        .then_some(runtime.health.http.as_deref())
6353        .flatten();
6354    let result = match http {
6355        Some(url) => probe_http_health(url, runtime.health.deadline)
6356            .await
6357            .map(|report| (report, None)),
6358        None => probe_module_health_from(&spec.module_id, runtime, None)
6359            .await
6360            .map(|(report, probed)| (report, Some(probed))),
6361    };
6362    match result {
6363        Ok((report, probed)) => {
6364            handle_health_report(
6365                spec,
6366                runtime,
6367                registry,
6368                process_liveness,
6369                snapshot,
6370                child,
6371                report,
6372                now_ms,
6373                delivery_probe,
6374                probed,
6375            )
6376            .await;
6377        }
6378        Err(err) => {
6379            if http.is_some() {
6380                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6381                    state.health.status = SupervisorHealthStatus::Failing;
6382                });
6383            }
6384            handle_health_probe_failure(
6385                spec,
6386                runtime,
6387                registry,
6388                process_liveness,
6389                snapshot,
6390                child,
6391                err,
6392                now_ms,
6393                delivery_probe,
6394            )
6395            .await;
6396        }
6397    }
6398}
6399
6400pub(crate) struct HttpProbeTarget<'a> {
6401    address: std::net::SocketAddr,
6402    localhost: bool,
6403    authority: &'a str,
6404    path: String,
6405}
6406
6407/// Resolve only literal loopback endpoints, without DNS, redirects, proxies,
6408/// or TLS. A URL cannot turn a local health check into an outbound connection.
6409pub(crate) fn parse_http_probe_url(url: &str) -> Result<HttpProbeTarget<'_>, String> {
6410    if url.bytes().any(|b| b <= b' ' || b == 127) || url.contains('#') {
6411        return Err("must not contain whitespace, controls, or a fragment".into());
6412    }
6413    let rest = url
6414        .strip_prefix("http://")
6415        .ok_or("must use plain http://")?;
6416    let split = rest.find(['/', '?']).unwrap_or(rest.len());
6417    let (authority, suffix) = rest.split_at(split);
6418    let (host, port) = if let Some(rest) = authority.strip_prefix("[::1]") {
6419        ("::1", rest)
6420    } else {
6421        let split = authority.find(':').unwrap_or(authority.len());
6422        authority.split_at(split)
6423    };
6424    let ip: std::net::IpAddr = match host {
6425        "127.0.0.1" | "localhost" => std::net::Ipv4Addr::LOCALHOST.into(),
6426        "::1" => std::net::Ipv6Addr::LOCALHOST.into(),
6427        _ => return Err("host must be 127.0.0.1, [::1], or localhost".into()),
6428    };
6429    let port = if port.is_empty() {
6430        80
6431    } else {
6432        port.strip_prefix(':')
6433            .and_then(|p| p.parse::<u16>().ok())
6434            .filter(|p| *p > 0)
6435            .ok_or("must have a valid nonzero TCP port")?
6436    };
6437    let path = if suffix.is_empty() {
6438        "/".into()
6439    } else if suffix.starts_with('?') {
6440        format!("/{suffix}")
6441    } else {
6442        suffix.into()
6443    };
6444    Ok(HttpProbeTarget {
6445        address: std::net::SocketAddr::new(ip, port),
6446        localhost: host == "localhost",
6447        authority,
6448        path,
6449    })
6450}
6451
6452async fn probe_http_health(
6453    url: &str,
6454    deadline: Duration,
6455) -> Result<HealthReport, HealthProbeError> {
6456    use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
6457    let target = parse_http_probe_url(url).map_err(HealthProbeError::misconfigured)?;
6458    // Keep partial diagnostics outside the timed future so cancellation does
6459    // not discard a status line or body bytes already received.
6460    let mut response_status = String::new();
6461    let mut body = Vec::new();
6462    let probe = async {
6463        // Resolve localhost ourselves so a hosts-file override cannot turn
6464        // this into an outbound request, while IPv6-only local servers work.
6465        let connection = match tokio::net::TcpStream::connect(target.address).await {
6466            Err(_) if target.localhost => {
6467                tokio::net::TcpStream::connect((
6468                    std::net::Ipv6Addr::LOCALHOST,
6469                    target.address.port(),
6470                ))
6471                .await
6472            }
6473            result => result,
6474        };
6475        let mut stream = connection.map_err(|error| {
6476            HealthProbeError::no_answer(format!("HTTP connect failed: {error}"))
6477        })?;
6478        stream.write_all(format!("GET {} HTTP/1.1\r\nHost: {}\r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n", target.path, target.authority).as_bytes()).await
6479            .map_err(|error| HealthProbeError::no_answer(format!("HTTP write failed: {error}")))?;
6480        let mut reader = BufReader::new(stream);
6481        let mut budget = 16 * 1024;
6482        let status = http_line(&mut reader, &mut budget).await?;
6483        let mut words = status.split_ascii_whitespace();
6484        let version = words.next();
6485        let code = words
6486            .next()
6487            .filter(|word| word.len() == 3)
6488            .and_then(|word| word.parse::<u16>().ok());
6489        if !matches!(version, Some("HTTP/1.1" | "HTTP/1.0"))
6490            || !code.is_some_and(|code| (100..600).contains(&code))
6491        {
6492            return Err(HealthProbeError::bad_answer(format!(
6493                "invalid HTTP status: {status}"
6494            )));
6495        }
6496        let code = code.expect("validated status code");
6497        response_status = status.clone();
6498        let mut length = None;
6499        let mut chunked = false;
6500        loop {
6501            let line = http_line(&mut reader, &mut budget).await?;
6502            if line.is_empty() {
6503                break;
6504            }
6505            if let Some((name, value)) = line.split_once(':') {
6506                if name.eq_ignore_ascii_case("content-length") {
6507                    length = Some(value.trim().parse::<u64>().map_err(|_| {
6508                        HealthProbeError::bad_answer("invalid HTTP Content-Length")
6509                    })?);
6510                } else if name.eq_ignore_ascii_case("transfer-encoding") {
6511                    chunked = value.trim().eq_ignore_ascii_case("chunked");
6512                }
6513            }
6514        }
6515        if chunked {
6516            while body.len() < 200 {
6517                let line = http_line(&mut reader, &mut budget).await?;
6518                let size = u64::from_str_radix(line.split(';').next().unwrap_or("").trim(), 16)
6519                    .map_err(|_| HealthProbeError::bad_answer("invalid HTTP chunk size"))?;
6520                if size == 0 {
6521                    break;
6522                }
6523                let count = size.min((200 - body.len()) as u64) as usize;
6524                let start = body.len();
6525                (&mut reader)
6526                    .take(count as u64)
6527                    .read_to_end(&mut body)
6528                    .await
6529                    .map_err(|error| {
6530                        HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
6531                    })?;
6532                if body.len() - start != count {
6533                    return Err(HealthProbeError::bad_answer("truncated HTTP chunk"));
6534                }
6535                if size > count as u64 || body.len() == 200 {
6536                    break;
6537                }
6538                if !http_line(&mut reader, &mut budget).await?.is_empty() {
6539                    return Err(HealthProbeError::bad_answer("invalid HTTP chunk delimiter"));
6540                }
6541            }
6542        } else {
6543            reader
6544                .take(length.unwrap_or(200).min(200))
6545                .read_to_end(&mut body)
6546                .await
6547                .map_err(|error| {
6548                    HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
6549                })?;
6550        }
6551        if (200..300).contains(&code) {
6552            Ok(HealthReport::ok())
6553        } else {
6554            Err(HealthProbeError::bad_answer(
6555                "HTTP health endpoint returned non-2xx",
6556            ))
6557        }
6558    };
6559    let mut result = timeout(deadline, probe).await.unwrap_or_else(|_| {
6560        Err(HealthProbeError::no_answer(format!(
6561            "HTTP probe timed out after {deadline:?}"
6562        )))
6563    });
6564    if let Err(error) = &mut result {
6565        if !response_status.is_empty() {
6566            error.message = format!(
6567                "{}; {response_status}: {}",
6568                error.message,
6569                String::from_utf8_lossy(&body)
6570            );
6571        }
6572    }
6573    result
6574}
6575
6576async fn http_line(
6577    reader: &mut tokio::io::BufReader<tokio::net::TcpStream>,
6578    remaining: &mut usize,
6579) -> Result<String, HealthProbeError> {
6580    use tokio::io::{AsyncBufReadExt, AsyncReadExt};
6581    let mut line = Vec::new();
6582    (&mut *reader)
6583        .take(*remaining as u64)
6584        .read_until(b'\n', &mut line)
6585        .await
6586        .map_err(|error| {
6587            HealthProbeError::no_answer(format!("HTTP header read failed: {error}"))
6588        })?;
6589    *remaining -= line.len();
6590    if !line.ends_with(b"\r\n") {
6591        return Err(HealthProbeError::bad_answer(
6592            "HTTP headers are incomplete or exceed 16 KiB",
6593        ));
6594    }
6595    line.truncate(line.len() - 2);
6596    String::from_utf8(line).map_err(|_| HealthProbeError::bad_answer("HTTP header is not UTF-8"))
6597}
6598
6599async fn probe_module_health(
6600    module_id: &str,
6601    runtime: &SupervisorRuntimeConfig,
6602    drain_deadline: Option<Instant>,
6603) -> Result<HealthReport, HealthProbeError> {
6604    probe_module_health_from(module_id, runtime, drain_deadline)
6605        .await
6606        .map(|(report, _)| report)
6607}
6608
6609/// [`probe_module_health`], also returning the connection whose registration
6610/// answered, so its answer is credited to that registration and no other.
6611async fn probe_module_health_from(
6612    module_id: &str,
6613    runtime: &SupervisorRuntimeConfig,
6614    drain_deadline: Option<Instant>,
6615) -> Result<(HealthReport, ConnectionId), HealthProbeError> {
6616    let Some(forwarding) = runtime.forwarding.as_ref() else {
6617        return Err(HealthProbeError::misconfigured(
6618            "supervisor was not configured with a forwarding table",
6619        ));
6620    };
6621    let probe_started_at = Instant::now();
6622    let mut deadline = probe_started_at + runtime.health.deadline;
6623    if let Some(drain_deadline) = drain_deadline {
6624        deadline = deadline.min(drain_deadline);
6625    }
6626    let pending = if drain_deadline.is_some() {
6627        forwarding.begin_drain_health_probe_rpc_for(
6628            module_id,
6629            MODULE_CONTROL_OP_HEALTH_CHECK,
6630            probe_started_at,
6631            deadline,
6632        )
6633    } else {
6634        forwarding.begin_health_probe_rpc_for(
6635            module_id,
6636            MODULE_CONTROL_OP_HEALTH_CHECK,
6637            probe_started_at,
6638            deadline,
6639        )
6640    }
6641    .map_err(|err| {
6642        // The endpoint is not registered, so there is no live control lane to
6643        // ask. That is the module being absent, not slow.
6644        HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
6645    })?;
6646    let probed = pending.endpoint.connection_id;
6647    await_health_probe(forwarding, pending, deadline, runtime.health.deadline)
6648        .await
6649        .map(|report| (report, probed))
6650}
6651
6652/// [`probe_module_health`] for one endpoint rather than the id's active one.
6653///
6654/// A swap probes two processes that no by-id lookup reaches: its candidate
6655/// before cutover, and its superseded incumbent (for busy gauges) while the
6656/// incumbent drains. `deadline_cap` bounds the probe the way a drain deadline
6657/// bounds the by-id drain probe.
6658async fn probe_endpoint_health(
6659    endpoint: crate::ModuleEndpointId,
6660    runtime: &SupervisorRuntimeConfig,
6661    deadline_cap: Option<Instant>,
6662) -> Result<HealthReport, HealthProbeError> {
6663    let Some(forwarding) = runtime.forwarding.as_ref() else {
6664        return Err(HealthProbeError::misconfigured(
6665            "supervisor was not configured with a forwarding table",
6666        ));
6667    };
6668    let probe_started_at = Instant::now();
6669    let mut deadline = probe_started_at + runtime.health.deadline;
6670    if let Some(cap) = deadline_cap {
6671        deadline = deadline.min(cap);
6672    }
6673    let pending = forwarding
6674        .begin_endpoint_health_probe_rpc_for(
6675            endpoint,
6676            MODULE_CONTROL_OP_HEALTH_CHECK,
6677            probe_started_at,
6678            deadline,
6679        )
6680        .map_err(|err| {
6681            HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
6682        })?;
6683    await_health_probe(forwarding, pending, deadline, runtime.health.deadline).await
6684}
6685
6686/// Send a begun health probe and classify its answer.
6687async fn await_health_probe(
6688    forwarding: &ForwardingTable,
6689    pending: PendingModuleControlRpc,
6690    deadline: Instant,
6691    probe_budget: Duration,
6692) -> Result<HealthReport, HealthProbeError> {
6693    let PendingModuleControlRpc {
6694        endpoint,
6695        module_sink,
6696        negotiated_ver,
6697        corr,
6698        receiver,
6699    } = pending;
6700    let body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).map_err(|err| {
6701        HealthProbeError::misconfigured(format!("failed to encode health.check: {err}"))
6702    })?;
6703    let frame = Frame::build_with_version(
6704        negotiated_ver,
6705        FrameType::Request,
6706        control_flags(),
6707        0,
6708        0,
6709        corr,
6710        body,
6711    )
6712    .map_err(|err| {
6713        HealthProbeError::misconfigured(format!("failed to build health.check frame: {err}"))
6714    })?;
6715
6716    // The enqueue itself must be bounded by the probe deadline: FrameSink.send
6717    // blocks waiting for capacity when the module's egress queue is full, and an
6718    // unbounded await here freezes the whole supervision actor (it stops polling
6719    // Child::wait and supervisor commands), making the module unrecoverable
6720    // in-band. On timeout the probe fails like any transport failure.
6721    match timeout_at(deadline, module_sink.send(frame)).await {
6722        Ok(Ok(())) => {}
6723        Ok(Err(err)) => {
6724            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
6725            // A closed sink means the module's egress channel is gone -- the
6726            // receiving half is dropped when its connection tears down. Proof.
6727            return Err(HealthProbeError::lane_dead(format!(
6728                "failed to send health.check: {err}"
6729            )));
6730        }
6731        Err(_elapsed) => {
6732            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
6733            // A full egress queue means the module is not draining its socket, which
6734            // is consistent with a wedged module AND with one whose reader is merely
6735            // starved. Silence, not proof.
6736            return Err(HealthProbeError::no_answer(
6737                "health.check send timed out before enqueue (module egress full)",
6738            ));
6739        }
6740    }
6741
6742    match timeout_at(deadline, receiver).await {
6743        Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => Err(HealthProbeError::bad_answer(
6744            "health.check returned an unexpected config response",
6745        )),
6746        // Each arm records WHAT WAS OBSERVED. Four of them are the module
6747        // demonstrably answering -- rejected, non-health, malformed, wrong op --
6748        // and those prove it is alive even though the probe failed.
6749        Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
6750            response.health_report().ok_or_else(|| {
6751                HealthProbeError::bad_answer("health.check RPC returned a non-health response")
6752            })
6753        }
6754        Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => Err(HealthProbeError::bad_answer(
6755            format!("health.check rejected: {}", body.message),
6756        )),
6757        Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
6758            Err(HealthProbeError::lane_dead(message))
6759        }
6760        Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
6761            Err(HealthProbeError::bad_answer(message))
6762        }
6763        Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
6764            Err(HealthProbeError::bad_answer(format!(
6765                "expected module-control op '{expected}', got '{actual}'"
6766            )))
6767        }
6768        // A reply that crosses the deadline before this waiter observes it is
6769        // still proof of life. The forwarding path records its end-to-end latency
6770        // before delivering this classification.
6771        Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => Err(HealthProbeError::bad_answer(
6772            "module answered health.check after its daemon deadline",
6773        )),
6774        Ok(Err(_)) => Err(HealthProbeError::misconfigured(
6775            "health.check waiter was canceled before the module responded",
6776        )),
6777        Err(_) => {
6778            let _ = forwarding.tombstone_health_probe_rpc(endpoint, corr);
6779            Err(HealthProbeError::no_answer(format!(
6780                "module did not answer health.check within {probe_budget:?}"
6781            )))
6782        }
6783    }
6784}
6785
6786/// Act on a health probe's answer. `probed` is the connection whose
6787/// registration answered (`None` for an HTTP probe, which reaches no
6788/// registration); only that registration's spawn is credited with readiness.
6789#[allow(clippy::too_many_arguments)]
6790async fn handle_health_report(
6791    spec: &ModuleSpec,
6792    runtime: &SupervisorRuntimeConfig,
6793    registry: &Registry,
6794    process_liveness: &SupervisorProcessLiveness,
6795    snapshot: &SharedSnapshot,
6796    child: &mut Option<SupervisedChild>,
6797    report: HealthReport,
6798    now_ms: u64,
6799    delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
6800    probed: Option<ConnectionId>,
6801) {
6802    let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
6803        (Some(delivery), Some(probe)) => {
6804            delivery
6805                .health_result(
6806                    &spec.module_id,
6807                    runtime.forwarding.as_deref(),
6808                    registry,
6809                    probe,
6810                    report.status == HealthStatus::Ok,
6811                )
6812                .await
6813        }
6814        _ => false,
6815    };
6816    if let (Some(delivery), Some(spawn)) = (
6817        &runtime.config_delivery,
6818        child
6819            .as_ref()
6820            .and_then(|child| child.config_delivery.as_ref()),
6821    ) {
6822        delivery
6823            .mark_readiness(
6824                &spec.module_id,
6825                runtime.forwarding.as_deref(),
6826                probed,
6827                spawn,
6828                report.status == HealthStatus::Ok,
6829            )
6830            .await;
6831    }
6832    let status = supervisor_health_status(report.status);
6833    let detail = report.detail.clone();
6834    let metrics = truncate_health_metrics(report.metrics);
6835    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6836        state.health.status = status;
6837        state.last_probe_evidence = None;
6838        state.health.last_probe_ms = Some(now_ms);
6839        state.health.detail = detail.clone();
6840        state.health.metrics = metrics.clone();
6841        state.health.consecutive_failures = 0;
6842        state.failed_retry.observe_health(
6843            report.status == HealthStatus::Ok,
6844            runtime.restart_policy.window,
6845        );
6846    });
6847
6848    if delivery_failed {
6849        return;
6850    }
6851    let action = match report.status {
6852        HealthStatus::Ok => return,
6853        HealthStatus::Degraded => runtime.health.on_degraded,
6854        HealthStatus::Failing => runtime.health.on_failing,
6855    };
6856    apply_l3_health_action(
6857        spec,
6858        runtime,
6859        registry,
6860        process_liveness,
6861        snapshot,
6862        child,
6863        status,
6864        detail.as_deref(),
6865        action,
6866        now_ms,
6867    )
6868    .await;
6869}
6870
6871#[allow(clippy::too_many_arguments)]
6872async fn handle_health_probe_failure(
6873    spec: &ModuleSpec,
6874    runtime: &SupervisorRuntimeConfig,
6875    registry: &Registry,
6876    process_liveness: &SupervisorProcessLiveness,
6877    snapshot: &SharedSnapshot,
6878    child: &mut Option<SupervisedChild>,
6879    err: HealthProbeError,
6880    now_ms: u64,
6881    delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
6882) {
6883    let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
6884        (Some(delivery), Some(probe)) => {
6885            delivery
6886                .health_result(
6887                    &spec.module_id,
6888                    runtime.forwarding.as_deref(),
6889                    registry,
6890                    probe,
6891                    false,
6892                )
6893                .await
6894        }
6895        _ => false,
6896    };
6897    let threshold = runtime.health.failure_threshold.max(1);
6898    let held = if err.evidence == HealthProbeEvidence::NoAnswer {
6899        runtime.host_health.record_late_module(&spec.module_id)
6900    } else {
6901        false
6902    };
6903    let mut failures = 0;
6904    // Carry the evidence class into the operator-visible detail. Without it,
6905    // "module did not answer within 5s" and "the control lane is gone" are two
6906    // prose strings in the same field, and the reader has to know the codebase to
6907    // tell which one is proof of anything.
6908    let detail = if held {
6909        format!("[{}] {err}; host overloaded", err.label())
6910    } else {
6911        format!("[{}] {err}", err.label())
6912    };
6913    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6914        state.last_probe_evidence = Some(err.evidence);
6915        state
6916            .failed_retry
6917            .observe_health(false, runtime.restart_policy.window);
6918        // A failed wire probe invalidates the last report, even before the
6919        // restart threshold. HTTP probes already mark failures as Failing.
6920        if held {
6921            state.health.status = SupervisorHealthStatus::Degraded;
6922        } else if state.spawned_protocol.unwrap_or(spec.protocol) == ModuleProtocol::Subc {
6923            state.health.status = SupervisorHealthStatus::Unknown;
6924        }
6925        state.health.last_probe_ms = Some(now_ms);
6926        // Held silence breaks the streak: after the host recovers, only new
6927        // failures count. Replaying pre-overload misses would restart immediately.
6928        state.health.consecutive_failures = if held {
6929            0
6930        } else {
6931            state.health.consecutive_failures.saturating_add(1)
6932        };
6933        state.health.detail = Some(detail.clone());
6934        state.health.metrics = None;
6935        failures = state.health.consecutive_failures;
6936    });
6937
6938    if delivery_failed {
6939        return;
6940    }
6941    if held || failures < threshold {
6942        warn!(
6943            module_id = %spec.module_id,
6944            consecutive_failures = failures,
6945            threshold,
6946            evidence = err.label(),
6947            detail = %detail,
6948            "health.check probe failed"
6949        );
6950        return;
6951    }
6952
6953    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6954        state.state = ModuleState::Unresponsive;
6955        state.health.status = SupervisorHealthStatus::Unresponsive;
6956    });
6957    // The evidence class is logged at the kill site because this is the line an
6958    // operator reads after an unexplained restart. A streak of `no-answer` under
6959    // machine load is the known false-positive shape; a `lane-dead` is not.
6960    if runtime.health.critical {
6961        error!(
6962            module_id = %spec.module_id,
6963            status = "unresponsive",
6964            evidence = err.label(),
6965            detail = %detail,
6966            "critical module health alert"
6967        );
6968    } else {
6969        warn!(
6970            module_id = %spec.module_id,
6971            status = "unresponsive",
6972            evidence = err.label(),
6973            detail = %detail,
6974            "module health threshold breached"
6975        );
6976    }
6977    if let Err(err) = health_restart_child(
6978        spec,
6979        runtime,
6980        registry,
6981        process_liveness,
6982        snapshot,
6983        child,
6984        SupervisorHealthStatus::Unresponsive,
6985        Some(&detail),
6986        now_ms,
6987    )
6988    .await
6989    {
6990        error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
6991    }
6992}
6993
6994#[allow(clippy::too_many_arguments)]
6995async fn apply_l3_health_action(
6996    spec: &ModuleSpec,
6997    runtime: &SupervisorRuntimeConfig,
6998    registry: &Registry,
6999    process_liveness: &SupervisorProcessLiveness,
7000    snapshot: &SharedSnapshot,
7001    child: &mut Option<SupervisedChild>,
7002    status: SupervisorHealthStatus,
7003    detail: Option<&str>,
7004    action: HealthAction,
7005    now_ms: u64,
7006) {
7007    record_health_action(snapshot, &spec.module_id, action.to_string(), now_ms);
7008    match action {
7009        HealthAction::Report => {
7010            info!(
7011                module_id = %spec.module_id,
7012                status = ?status,
7013                detail,
7014                "module reported non-ok health"
7015            );
7016        }
7017        HealthAction::Alert => {
7018            error!(
7019                module_id = %spec.module_id,
7020                status = ?status,
7021                detail,
7022                "module health alert"
7023            );
7024        }
7025        HealthAction::Restart => {
7026            if let Err(err) = health_restart_child(
7027                spec,
7028                runtime,
7029                registry,
7030                process_liveness,
7031                snapshot,
7032                child,
7033                status,
7034                detail,
7035                now_ms,
7036            )
7037            .await
7038            {
7039                error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
7040            }
7041        }
7042    }
7043}
7044
7045#[allow(clippy::too_many_arguments)]
7046async fn health_restart_child(
7047    spec: &ModuleSpec,
7048    runtime: &SupervisorRuntimeConfig,
7049    registry: &Registry,
7050    process_liveness: &SupervisorProcessLiveness,
7051    snapshot: &SharedSnapshot,
7052    child: &mut Option<SupervisedChild>,
7053    status: SupervisorHealthStatus,
7054    detail: Option<&str>,
7055    now_ms: u64,
7056) -> Result<(), SuperviseError> {
7057    budgeted_restart_child(
7058        spec,
7059        runtime,
7060        registry,
7061        process_liveness,
7062        snapshot,
7063        child,
7064        status,
7065        detail,
7066        now_ms,
7067        true,
7068    )
7069    .await
7070}
7071
7072#[allow(clippy::too_many_arguments)]
7073async fn budgeted_restart_child(
7074    spec: &ModuleSpec,
7075    runtime: &SupervisorRuntimeConfig,
7076    registry: &Registry,
7077    process_liveness: &SupervisorProcessLiveness,
7078    snapshot: &SharedSnapshot,
7079    child: &mut Option<SupervisedChild>,
7080    status: SupervisorHealthStatus,
7081    detail: Option<&str>,
7082    now_ms: u64,
7083    health_failure: bool,
7084) -> Result<(), SuperviseError> {
7085    if let Some(error) = runtime
7086        .config_delivery
7087        .as_ref()
7088        .and_then(|delivery| delivery.0.check_module_hold(&spec.module_id).err())
7089        .filter(|error| error.code != "config_delivery_deferred")
7090    {
7091        return Err(config_delivery::gate_hold_error(
7092            spec,
7093            error,
7094            runtime.config_delivery.as_ref(),
7095        ));
7096    }
7097    let recovery_reason = if health_failure {
7098        "health_check"
7099    } else {
7100        "configuration_delivery"
7101    };
7102    let (enabled, schedule) = {
7103        let mut state = lock_snapshot(snapshot)?;
7104        let enabled = state.enabled;
7105        let schedule = if enabled {
7106            state.next_crash_restart(&runtime.restart_policy, Instant::now())
7107        } else {
7108            None
7109        };
7110        (enabled, schedule)
7111    };
7112
7113    if !enabled {
7114        return Err(SuperviseError::Disabled {
7115            module_id: spec.module_id.clone(),
7116        });
7117    }
7118
7119    if schedule.is_none() {
7120        if health_failure {
7121            record_health_action(snapshot, &spec.module_id, "failed".to_string(), now_ms);
7122        }
7123        error!(
7124            module_id = %spec.module_id,
7125            status = ?status,
7126            detail,
7127            max_restarts = runtime.restart_policy.max_restarts,
7128            window_secs = runtime.restart_policy.window.as_secs(),
7129            reason = %runtime.restart_policy.budget_exhausted_detail(),
7130            recovery_reason,
7131            "automatic restart budget exhausted; marking module failed"
7132        );
7133        let stop_notice = begin_forwarding_drain_if_configured(
7134            spec,
7135            runtime,
7136            registry,
7137            snapshot,
7138            Some(true),
7139            RouteCloseReason::Disable,
7140        )
7141        .await?;
7142        update_snapshot(snapshot, Some(&spec.module_id), |state| {
7143            state.drain_disposition_detail = Some(runtime.restart_policy.budget_exhausted_detail());
7144        })?;
7145        let result = drain_optional_child(
7146            &spec.module_id,
7147            spec.protocol,
7148            stop_notice,
7149            registry,
7150            runtime.forwarding.as_deref(),
7151            snapshot,
7152            &runtime.terminal_ring,
7153            &runtime.spawn_events,
7154            child,
7155            runtime.drain_timeout,
7156            ModuleState::Failed,
7157            Some(true),
7158            &runtime.failure_context(true),
7159        )
7160        .await;
7161        update_snapshot(snapshot, Some(&spec.module_id), |state| {
7162            if state.state == ModuleState::Failed && !runtime.child_roster.is_closed() {
7163                state.failed_retry.schedule(&spec.module_id);
7164            }
7165        })?;
7166        result?;
7167        process_liveness.untrack_if_current(&spec.module_id, snapshot);
7168        return Ok(());
7169    }
7170
7171    let schedule = schedule.expect("a health restart must have a crash-restart schedule");
7172    let mut restart_count = 0;
7173    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7174        restart_count = state.crash_restarts.len();
7175        state.state = ModuleState::Unresponsive;
7176        if health_failure {
7177            state.health.status = status;
7178            state.health.last_action = Some(HealthAction::Restart.to_string());
7179            state.health.last_action_ms = Some(now_ms);
7180        }
7181    })?;
7182    warn!(
7183        module_id = %spec.module_id,
7184        status = ?status,
7185        detail,
7186        restart_count,
7187        restart_in_window = schedule.restart_in_window,
7188        delay_ms = schedule.delay.as_millis() as u64,
7189        recovery_reason,
7190        "automatic module restart"
7191    );
7192
7193    let stop_notice = begin_forwarding_drain_if_configured(
7194        spec,
7195        runtime,
7196        registry,
7197        snapshot,
7198        Some(true),
7199        RouteCloseReason::Restart,
7200    )
7201    .await?;
7202    drain_optional_child(
7203        &spec.module_id,
7204        spec.protocol,
7205        stop_notice,
7206        registry,
7207        runtime.forwarding.as_deref(),
7208        snapshot,
7209        &runtime.terminal_ring,
7210        &runtime.spawn_events,
7211        child,
7212        runtime.drain_timeout,
7213        ModuleState::Restarting,
7214        Some(true),
7215        &runtime.failure_context(true),
7216    )
7217    .await?;
7218    schedule_respawn(
7219        runtime,
7220        snapshot,
7221        &spec.module_id,
7222        schedule.delay,
7223        RespawnKind::Spawn,
7224        true,
7225    )
7226}
7227
7228fn cancel_deferred_reload(runtime: &SupervisorRuntimeConfig, module_id: &str, reason: &str) {
7229    if let Some(reply) = runtime
7230        .deferred_reload_reply
7231        .lock()
7232        .unwrap_or_else(|p| p.into_inner())
7233        .take()
7234    {
7235        let _ = reply.send(Err(SuperviseError::ReloadFailed {
7236            module_id: module_id.to_string(),
7237            reason: reason.to_string(),
7238        }));
7239    }
7240}
7241
7242fn park_config_spawn(
7243    spec: &ModuleSpec,
7244    runtime: &SupervisorRuntimeConfig,
7245    snapshot: &SharedSnapshot,
7246    failure: &FailureContext,
7247    admission_refused: Option<String>,
7248) -> Result<(), SuperviseError> {
7249    *runtime
7250        .scheduled_respawn
7251        .lock()
7252        .unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
7253    if let Some(reply) = runtime
7254        .deferred_reload_reply
7255        .lock()
7256        .unwrap_or_else(|poisoned| poisoned.into_inner())
7257        .take()
7258    {
7259        let _ = reply.send(Err(SuperviseError::ConfigHeld {
7260            module_id: spec.module_id.clone(),
7261            code: "config_gated".into(),
7262            detail: "module is held by configuration admission".into(),
7263        }));
7264    }
7265    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7266        state.admission_refused = admission_refused;
7267        state.config_hold_daemon_initiated = failure.daemon_initiated;
7268        state.config_hold_approval = failure.approval.clone();
7269        state.config_hold_parked = true;
7270        state.state = ModuleState::Stopped;
7271        state.respawn_pending = false;
7272        state.failed_retry.pending = None;
7273        // Parking ends this attempt and discards its failure timestamp. If a
7274        // later release fails, its retry delay starts at that new failure.
7275        state.failed_retry.failed_at = None;
7276        clear_current_process_facts(state);
7277    })
7278}
7279
7280fn try_park_config_attempt(
7281    spec: &ModuleSpec,
7282    runtime: &SupervisorRuntimeConfig,
7283    snapshot: &SharedSnapshot,
7284    failure: &FailureContext,
7285    program_base: Option<&subc_config::Digest>,
7286) -> Result<bool, SuperviseError> {
7287    let result = (|| {
7288        if !lock_snapshot(snapshot)?.enabled {
7289            return Ok(false);
7290        }
7291        #[cfg(test)]
7292        if let Some(delivery) = &runtime.config_delivery {
7293            delivery.0.pause_before_config_park_for_test();
7294        }
7295        let Some(delivery) = &runtime.config_delivery else {
7296            return Ok(false);
7297        };
7298        let parked = delivery
7299            .0
7300            .with_recorded_admission_hold(&spec.module_id, program_base, |refusal| {
7301                park_config_spawn(spec, runtime, snapshot, failure, refusal)
7302            })
7303            .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(delivery)))?;
7304        if let Some(result) = parked {
7305            result?;
7306            Ok(true)
7307        } else {
7308            Ok(false)
7309        }
7310    })();
7311    if let Err(error) = &result {
7312        // A failed park still belongs to the attempt that tried to park. Mark it
7313        // Failed here, before the monitor can use a daemon/operator origin saved
7314        // for a different attempt to decide whether to schedule a slow retry.
7315        fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
7316        record_approved_attempt_failure(spec, snapshot, failure, error);
7317    }
7318    result
7319}
7320
7321fn record_approved_attempt_failure(
7322    spec: &ModuleSpec,
7323    snapshot: &SharedSnapshot,
7324    failure: &FailureContext,
7325    error: &SuperviseError,
7326) {
7327    let Some(approval) = &failure.approval else {
7328        return;
7329    };
7330    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
7331        if state.enabled
7332            && state.state == ModuleState::Failed
7333            && state
7334                .approved_start_failure
7335                .as_ref()
7336                .is_none_or(|(identity, _)| identity != approval)
7337        {
7338            state.approved_start_failure = Some((approval.clone(), error.to_string()));
7339        }
7340    });
7341}
7342
7343fn hold_config_spawn(
7344    spec: &ModuleSpec,
7345    runtime: &SupervisorRuntimeConfig,
7346    snapshot: &SharedSnapshot,
7347    failure: &FailureContext,
7348) -> Result<(), SuperviseError> {
7349    if !lock_snapshot(snapshot)?.enabled {
7350        return Ok(());
7351    }
7352    if !try_park_config_attempt(spec, runtime, snapshot, failure, None)? {
7353        // This caller consumed an actual start attempt. If its hold ended before
7354        // parking, retain that attempt instead of waiting for a lost release.
7355        defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
7356    }
7357    Ok(())
7358}
7359
7360fn schedule_respawn(
7361    runtime: &SupervisorRuntimeConfig,
7362    snapshot: &SharedSnapshot,
7363    module_id: &str,
7364    delay: Duration,
7365    kind: RespawnKind,
7366    daemon_initiated: bool,
7367) -> Result<(), SuperviseError> {
7368    cancel_deferred_reload(runtime, module_id, "respawn superseded by another restart");
7369    update_snapshot(snapshot, Some(module_id), |state| {
7370        state.respawn_pending = true
7371    })?;
7372    *runtime
7373        .scheduled_respawn
7374        .lock()
7375        .unwrap_or_else(|p| p.into_inner()) = Some(PendingRespawn {
7376        deadline: Instant::now() + delay,
7377        kind,
7378        daemon_initiated,
7379        approval: None,
7380    });
7381    Ok(())
7382}
7383
7384const CONFIG_ADMISSION_RETRY_DELAY: Duration = Duration::from_millis(100);
7385
7386fn defer_config_spawn(
7387    spec: &ModuleSpec,
7388    runtime: &SupervisorRuntimeConfig,
7389    snapshot: &SharedSnapshot,
7390    kind: RespawnKind,
7391    failure: &FailureContext,
7392) -> Result<(), SuperviseError> {
7393    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7394        state.state = ModuleState::Restarting;
7395        state.respawn_pending = true;
7396        clear_current_process_facts(state);
7397    })?;
7398    *runtime
7399        .scheduled_respawn
7400        .lock()
7401        .unwrap_or_else(|p| p.into_inner()) = Some(PendingRespawn {
7402        deadline: Instant::now() + CONFIG_ADMISSION_RETRY_DELAY,
7403        kind,
7404        daemon_initiated: failure.daemon_initiated,
7405        approval: failure.approval.clone(),
7406    });
7407    Ok(())
7408}
7409
7410fn record_health_action(snapshot: &SharedSnapshot, module_id: &str, action: String, now_ms: u64) {
7411    let _ = update_snapshot(snapshot, Some(module_id), |state| {
7412        state.health.last_action = Some(action);
7413        state.health.last_action_ms = Some(now_ms);
7414    });
7415}
7416
7417fn supervisor_health_status(status: HealthStatus) -> SupervisorHealthStatus {
7418    match status {
7419        HealthStatus::Ok => SupervisorHealthStatus::Ok,
7420        HealthStatus::Degraded => SupervisorHealthStatus::Degraded,
7421        HealthStatus::Failing => SupervisorHealthStatus::Failing,
7422    }
7423}
7424
7425/// Caps the metrics blob stored in the cached supervisor snapshot, which is
7426/// returned to every `supervisor.list` and `supervisor.health` caller.
7427///
7428/// This cap is deliberately NOT applied on the one-shot `supervisor.health_probe`
7429/// path: that request exists to return a module's complete metrics object, and
7430/// `ck health <module-id>` documents it as the way to see what the cached view
7431/// truncates. The asymmetry is the feature.
7432///
7433/// So a new caller must decide which side it is on rather than assume the cap is
7434/// universal. Reaching for it on a fresh-probe path would silently reintroduce
7435/// the truncation that path exists to avoid.
7436fn truncate_health_metrics(metrics: Option<Value>) -> Option<Value> {
7437    let metrics = metrics?;
7438    match serde_json::to_vec(&metrics) {
7439        Ok(encoded) if encoded.len() > MAX_HEALTH_METRICS_BYTES => Some(serde_json::json!({
7440            "truncated": true,
7441            "original_bytes": encoded.len(),
7442        })),
7443        Ok(_) | Err(_) => Some(metrics),
7444    }
7445}
7446
7447/// Spread health probes so a fleet-wide restart does not converge them.
7448///
7449/// The delay is derived from the module id and probe index rather than a random
7450/// source, so it is deterministic per module: a module keeps its own offset
7451/// across daemon restarts instead of re-rolling into a collision.
7452fn jittered_health_delay(module_id: &str, probe_index: u64, cadence: Duration) -> Duration {
7453    if cadence.is_zero() {
7454        return Duration::ZERO;
7455    }
7456    let cadence_ms = cadence.as_millis() as u64;
7457    // This early return is REDUNDANT, deliberately, and a mutation run will show
7458    // it surviving removal. Recording why here so the next person to notice does
7459    // not have to re-derive it:
7460    //
7461    // - It is unreachable in practice. `positive_millis` in daemon_config rejects
7462    //   a zero cadence and builds the Duration from whole milliseconds, so a
7463    //   sub-millisecond cadence cannot come from config.
7464    // - Even if reached it changes no answer. The `.max(1)` below makes the span
7465    //   1, and `hash % 1` is 0, so the fall-through returns `cadence` unchanged
7466    //   -- exactly what this returns.
7467    //
7468    // Kept as a guard against a future widening of the config parser (accepting
7469    // microseconds, say), which would make the sub-millisecond case reachable.
7470    // The `.max(1)` is the load-bearing half TODAY: remove it and the modulo
7471    // divides by zero. Remove this and nothing changes.
7472    if cadence_ms == 0 {
7473        return cadence;
7474    }
7475    // Note that this never returns less than one cadence, including for the FIRST
7476    // probe. So a freshly registered module reports health `unknown` for a full
7477    // cadence plus jitter -- 30-33s at the default -- no matter how quickly it is
7478    // ready to answer.
7479    //
7480    // That is a property of the supervisor's schedule, not of any module: an
7481    // operator watching a restart sees `unknown` and cannot tell it from a module
7482    // that is slow to warm. Measured on two unrelated modules, both flipping to
7483    // `ok` between 22s and 32s after restart.
7484    //
7485    // Left as-is because spreading the first probe is what keeps a fleet-wide
7486    // restart from firing fourteen simultaneous probes into a cold machine. The
7487    // alternative -- probe at t+0 and jitter only from the second onward -- trades
7488    // that thundering herd for a faster first reading.
7489    let jitter_span = (cadence_ms / 10).max(1);
7490    let hash = module_id.as_bytes().iter().fold(
7491        probe_index.wrapping_mul(0x9E37_79B9_7F4A_7C15),
7492        |acc, byte| {
7493            acc.wrapping_mul(1099511628211)
7494                .wrapping_add(u64::from(*byte))
7495        },
7496    );
7497    cadence + Duration::from_millis(hash % jitter_span)
7498}
7499
7500#[cfg(test)]
7501mod tests {
7502    use super::*;
7503
7504    #[test]
7505    fn registration_retirement_self_prefixed_owner_is_not_a_prefix_submodule() {
7506        let handle = SupervisorHandle::new();
7507        handle.set_spawn_nonce("prefix:owner", "owner-nonce".into());
7508        handle.set_reserved_prefixes("prefix:owner", &["prefix:".into()]);
7509        let owner = handle
7510            .reserved_hello_verification("prefix:owner", Some("owner-nonce"))
7511            .unwrap();
7512        assert!(owner.nonce_verified);
7513        assert!(
7514            owner.prefix_owner.is_none(),
7515            "an unreserved programmatic owner is not its own prefix child"
7516        );
7517        let child = handle
7518            .reserved_hello_verification("prefix:child", Some("owner-nonce"))
7519            .unwrap();
7520        assert!(child.nonce_verified);
7521        assert_eq!(child.prefix_owner.as_deref(), Some("prefix:owner"));
7522    }
7523
7524    #[test]
7525    fn readding_a_module_clears_its_rescan_removal_tombstone() {
7526        let handle = SupervisorHandle::new();
7527        let module_id = "readded-tombstone";
7528        handle.record_rescan_removal(module_id);
7529        assert!(handle.removal_tombstone_age_ms(module_id).is_some());
7530
7531        handle.apply_identity_configuration(&ModuleSpec {
7532            script: None,
7533            module_id: module_id.to_string(),
7534            program: PathBuf::from("/test/module"),
7535            args: Vec::new(),
7536            env: Vec::new(),
7537            reserved: false,
7538            reserved_prefixes: Vec::new(),
7539            protocol: ModuleProtocol::Subc,
7540            overlap: Default::default(),
7541            carry_containment: false,
7542        });
7543
7544        assert!(
7545            handle.removal_tombstone_age_ms(module_id).is_none(),
7546            "a re-added module must not retain a stale removal tombstone"
7547        );
7548    }
7549
7550    /// What one module's owner looked like from the control plane at the
7551    /// instant after its first process was spawned.
7552    #[derive(Debug, PartialEq, Eq)]
7553    struct OwnerInSpawnWindow {
7554        module_id: String,
7555        configured: bool,
7556        on_roster: bool,
7557        admission_refusal: Option<&'static str>,
7558    }
7559
7560    /// A supervised module's process can connect, register, sync its scopes
7561    /// and describe them as soon as it is spawned. A plain `spawn` does not put
7562    /// the module on the roster until afterward; configured supervision does
7563    /// so before spawning. In both cases the owner must
7564    /// already read as configured, so a scoped `route.open` against it is
7565    /// refused as retryable `scope_not_synced` and not as terminal
7566    /// `scope_not_live` ("will never sync").
7567    ///
7568    /// The hook runs just after each initial spawn attempt, before returning to
7569    /// the caller, so no race with a real child's registration is needed.
7570    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7571    async fn a_new_module_is_configured_before_its_first_process_can_register() {
7572        use crate::scopes::ScopeTable;
7573        use subc_protocol::{error_codes, scope::ScopeSelector, Principal};
7574
7575        let dir = cortexkit_test_support::ScratchDir::new("configured-before-spawn");
7576        let stub = |module_id: &str, program: PathBuf| ModuleSpec {
7577            script: None,
7578            module_id: module_id.to_string(),
7579            program,
7580            args: Vec::new(),
7581            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7582                .into_iter()
7583                .map(|key| (key.to_string(), dir.path().display().to_string()))
7584                .chain([("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())])
7585                .collect(),
7586            reserved: false,
7587            reserved_prefixes: Vec::new(),
7588            protocol: ModuleProtocol::Subc,
7589            overlap: Default::default(),
7590            carry_containment: false,
7591        };
7592        let live = super::terminal_history_tests::fake_aft_stub_path();
7593        let missing = dir.path().join("definitely-missing-module");
7594
7595        let handle = SupervisorHandle::new();
7596        let mut supervisor =
7597            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7598                .with_handle(handle.clone());
7599        let observed = Arc::new(Mutex::new(Vec::<OwnerInSpawnWindow>::new()));
7600        let hook_handle = handle.clone();
7601        let hook_observed = Arc::clone(&observed);
7602        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |module_id| {
7603            // Exactly what the control plane computes for a scoped route.open
7604            // naming this module as the owner of a scope it has not synced.
7605            let configured = hook_handle.is_configured(module_id);
7606            let selector = ScopeSelector::new(
7607                Principal::Reserved {
7608                    module_id: module_id.to_string(),
7609                },
7610                "s".to_string(),
7611                Some(1),
7612            );
7613            let carrier = Principal::Reserved {
7614                module_id: "carrier".to_string(),
7615            };
7616            let admission_refusal = match ScopeTable::new(Vec::<String>::new())
7617                .admit(&carrier, module_id, &selector, configured)
7618            {
7619                Ok(_) => None,
7620                Err(refusal) => Some(refusal.code),
7621            };
7622            hook_observed.lock().unwrap().push(OwnerInSpawnWindow {
7623                module_id: module_id.to_string(),
7624                configured,
7625                on_roster: hook_handle.get(module_id).is_some(),
7626                admission_refusal,
7627            });
7628        })));
7629
7630        let plain = supervisor.spawn(stub("plain", live.clone())).unwrap();
7631        let configured = supervisor
7632            .supervise_configured(stub("configured", live.clone()), true)
7633            .unwrap();
7634        let with_health = supervisor
7635            .supervise_configured_with_health(
7636                stub("with-health", live.clone()),
7637                true,
7638                HealthConfig::default(),
7639                None,
7640                RestartPolicy::default(),
7641            )
7642            .unwrap();
7643        // The failed-spawn path still puts the module on the roster (as
7644        // failed), so it is configured throughout.
7645        let failed = supervisor
7646            .supervise_configured_with_health(
7647                stub("failed-spawn", missing.clone()),
7648                true,
7649                HealthConfig::default(),
7650                None,
7651                RestartPolicy::default(),
7652            )
7653            .unwrap();
7654        // A failed plain `spawn` puts nothing on the roster, so its mark is
7655        // taken back once the spawn has failed.
7656        assert!(supervisor.spawn(stub("spawn-error", missing)).is_err());
7657
7658        let expected = [
7659            "plain",
7660            "configured",
7661            "with-health",
7662            "failed-spawn",
7663            "spawn-error",
7664        ]
7665        .into_iter()
7666        .map(|module_id| OwnerInSpawnWindow {
7667            module_id: module_id.to_string(),
7668            configured: true,
7669            on_roster: !matches!(module_id, "plain" | "spawn-error"),
7670            admission_refusal: Some(error_codes::SCOPE_NOT_SYNCED),
7671        })
7672        .collect::<Vec<_>>();
7673        assert_eq!(*observed.lock().unwrap(), expected);
7674
7675        for module_id in ["plain", "configured", "with-health", "failed-spawn"] {
7676            assert!(
7677                handle.get(module_id).is_some(),
7678                "{module_id} is on the roster"
7679            );
7680            assert!(
7681                handle.is_configured(module_id),
7682                "{module_id} stays configured"
7683            );
7684        }
7685        assert!(handle.get("spawn-error").is_none());
7686        assert!(
7687            !handle.is_configured("spawn-error"),
7688            "a plain spawn that failed must not leave its module marked configured"
7689        );
7690
7691        // Leaving the roster clears the mark with it.
7692        handle.retire("failed-spawn");
7693        assert!(!handle.is_configured("failed-spawn"));
7694
7695        for module in [plain, configured, with_health] {
7696            module.stop().await.unwrap();
7697        }
7698        drop(failed);
7699    }
7700
7701    /// A configured module reads as starting until the supervisor has admitted
7702    /// its first process (exec confirmed, identity durably recorded), even
7703    /// though that process is already running by then and can register over
7704    /// HELLO, which is what lists it in catalog.list. So a client that needs
7705    /// the supervisor state must wait for that state; seeing the module in
7706    /// the catalog does not mean supervisor.list already says running.
7707    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7708    async fn a_configured_module_reads_starting_while_its_first_process_already_runs() {
7709        let dir = cortexkit_test_support::ScratchDir::new("starting-while-spawned");
7710        let spec = ModuleSpec {
7711            script: None,
7712            module_id: "spawned-not-admitted".to_string(),
7713            program: super::terminal_history_tests::fake_aft_stub_path(),
7714            args: Vec::new(),
7715            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7716                .into_iter()
7717                .map(|key| (key.to_string(), dir.path().display().to_string()))
7718                .chain([("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())])
7719                .collect(),
7720            reserved: false,
7721            reserved_prefixes: Vec::new(),
7722            protocol: ModuleProtocol::Subc,
7723            overlap: Default::default(),
7724            carry_containment: false,
7725        };
7726        let handle = SupervisorHandle::new();
7727        let mut supervisor =
7728            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7729                .with_handle(handle.clone());
7730        let observed = Arc::new(Mutex::new(None));
7731        let hook_handle = handle.clone();
7732        let hook_observed = Arc::clone(&observed);
7733        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |module_id| {
7734            let state = hook_handle
7735                .get(module_id)
7736                .expect("a configured module is on the roster before it is spawned")
7737                .state()
7738                .unwrap();
7739            *hook_observed.lock().unwrap() = Some(state);
7740        })));
7741
7742        let module = supervisor.supervise_configured(spec, true).unwrap();
7743        assert_eq!(
7744            *observed.lock().unwrap(),
7745            Some(ModuleState::Starting),
7746            "between the spawn and its admission the supervisor still reports starting"
7747        );
7748        assert_eq!(module.state().unwrap(), ModuleState::Running);
7749        module.stop().await.unwrap();
7750    }
7751
7752    fn stale_process_snapshot(state: ModuleState, enabled: bool) -> SharedSnapshot {
7753        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(state, enabled)));
7754        update_snapshot(&snapshot, Some("stale-process-facts"), |snapshot| {
7755            snapshot.process_alive = true;
7756            snapshot.pid = Some(41);
7757            snapshot.spawned_at_ms = Some(42);
7758            snapshot.spawned_from = Some(PathBuf::from("/spawned/module"));
7759            snapshot.launch_spec_digest = Some(LaunchSpecDigest([0xA5; 32]));
7760            snapshot.spawned_file_identity = Some(SpawnedFileIdentity {
7761                device: 43,
7762                inode: 44,
7763                #[cfg(windows)]
7764                windows_image: None,
7765            });
7766        })
7767        .unwrap();
7768        snapshot
7769    }
7770
7771    fn assert_snapshot_process_facts_cleared(snapshot: &SharedSnapshot) {
7772        let snapshot = lock_snapshot(snapshot).unwrap();
7773        assert!(!snapshot.process_alive);
7774        assert_eq!(snapshot.pid, None);
7775        assert_eq!(snapshot.spawned_at_ms, None);
7776        assert_eq!(snapshot.spawned_from, None);
7777        assert_eq!(snapshot.launch_spec_digest, None);
7778        assert_eq!(snapshot.spawned_file_identity, None);
7779    }
7780
7781    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7782    async fn failed_enable_spawn_clears_preexisting_current_process_facts() {
7783        let supervisor =
7784            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7785        let mut runtime = supervisor.runtime_config();
7786        runtime.test_seed_stale_facts_before_enable_spawn = true;
7787        let snapshot = stale_process_snapshot(ModuleState::Disabled, false);
7788        let mut child = None;
7789        let spec = ModuleSpec {
7790            script: None,
7791            module_id: "failed-enable-clears-facts".to_string(),
7792            program: PathBuf::from("/definitely/missing/failed-enable-module"),
7793            args: Vec::new(),
7794            env: Vec::new(),
7795            reserved: false,
7796            reserved_prefixes: Vec::new(),
7797            protocol: ModuleProtocol::Subc,
7798            overlap: Default::default(),
7799            carry_containment: false,
7800        };
7801
7802        let result = set_child_enabled(
7803            &spec,
7804            &runtime,
7805            &supervisor.registry,
7806            &supervisor.process_liveness,
7807            &snapshot,
7808            &mut child,
7809            true,
7810            &runtime.failure_context(false),
7811        )
7812        .await;
7813
7814        assert!(matches!(result, Err(SuperviseError::Spawn { .. })));
7815        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
7816        assert_snapshot_process_facts_cleared(&snapshot);
7817    }
7818
7819    #[tokio::test]
7820    async fn start_revives_stranded_restarting_but_not_pending_backoff() {
7821        let supervisor =
7822            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7823        let runtime = supervisor.runtime_config();
7824        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
7825            ModuleState::Restarting,
7826            true,
7827        )));
7828        let spec = ModuleSpec {
7829            script: None,
7830            module_id: "start-stranded-restarting".to_string(),
7831            program: super::terminal_history_tests::fake_aft_stub_path(),
7832            args: Vec::new(),
7833            env: vec![("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())],
7834            reserved: false,
7835            reserved_prefixes: Vec::new(),
7836            protocol: ModuleProtocol::None,
7837            overlap: Default::default(),
7838            carry_containment: false,
7839        };
7840        let mut child = None;
7841        lock_snapshot(&snapshot).unwrap().respawn_pending = true;
7842        assert!(!super::set_child_enabled(
7843            &spec,
7844            &runtime,
7845            &Registry::default(),
7846            &supervisor.process_liveness,
7847            &snapshot,
7848            &mut child,
7849            true,
7850            &runtime.failure_context(false),
7851        )
7852        .await
7853        .unwrap());
7854        assert!(child.is_none());
7855        lock_snapshot(&snapshot).unwrap().respawn_pending = false;
7856        assert!(super::set_child_enabled(
7857            &spec,
7858            &runtime,
7859            &Registry::default(),
7860            &supervisor.process_liveness,
7861            &snapshot,
7862            &mut child,
7863            true,
7864            &runtime.failure_context(false),
7865        )
7866        .await
7867        .unwrap());
7868        assert_eq!(
7869            lock_snapshot(&snapshot).unwrap().state,
7870            ModuleState::Running
7871        );
7872        let mut child = child.unwrap();
7873        child.start_kill().unwrap();
7874        child.wait().await.unwrap();
7875    }
7876
7877    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7878    async fn failed_reload_spawn_clears_current_process_facts() {
7879        let supervisor =
7880            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7881        let mut runtime = supervisor.runtime_config();
7882        runtime.restart_policy = RestartPolicy::new(0, Duration::ZERO);
7883        let snapshot = stale_process_snapshot(ModuleState::Running, true);
7884        let mut child = None;
7885        let spec = ModuleSpec {
7886            script: None,
7887            module_id: "failed-reload-clears-facts".to_string(),
7888            program: PathBuf::from("/unused/failed-reload-module"),
7889            args: Vec::new(),
7890            env: Vec::new(),
7891            reserved: false,
7892            reserved_prefixes: Vec::new(),
7893            protocol: ModuleProtocol::Subc,
7894            overlap: Default::default(),
7895            carry_containment: false,
7896        };
7897
7898        let result = handle_reload_spawn_failure(
7899            &spec,
7900            &runtime,
7901            &supervisor.process_liveness,
7902            &snapshot,
7903            &mut child,
7904            "forced reload spawn failure".to_string(),
7905        )
7906        .await;
7907
7908        assert!(matches!(result, Err(SuperviseError::ReloadFailed { .. })));
7909        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
7910        assert_snapshot_process_facts_cleared(&snapshot);
7911    }
7912
7913    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7914    async fn dropping_a_module_with_an_active_monitor_clears_current_process_facts() {
7915        let supervisor =
7916            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7917        let snapshot = stale_process_snapshot(ModuleState::Running, true);
7918        let module = supervisor.supervised_module(
7919            ModuleSpec {
7920                script: None,
7921                module_id: "drop-clears-facts".to_string(),
7922                program: PathBuf::from("/unused/drop-module"),
7923                args: Vec::new(),
7924                env: Vec::new(),
7925                reserved: false,
7926                reserved_prefixes: Vec::new(),
7927                protocol: ModuleProtocol::Subc,
7928                overlap: Default::default(),
7929                carry_containment: false,
7930            },
7931            supervisor.runtime_config(),
7932            Arc::clone(&snapshot),
7933            None,
7934        );
7935        assert!(!module
7936            .inner
7937            .monitor
7938            .lock()
7939            .unwrap()
7940            .as_ref()
7941            .unwrap()
7942            .is_finished());
7943
7944        drop(module);
7945
7946        assert_eq!(
7947            lock_snapshot(&snapshot).unwrap().state,
7948            ModuleState::Stopped
7949        );
7950        assert_snapshot_process_facts_cleared(&snapshot);
7951    }
7952
7953    #[cfg(unix)]
7954    #[tokio::test]
7955    async fn rescan_preserves_running_protocol_until_respawn() {
7956        let dir = cortexkit_test_support::ScratchDir::new("rescan-protocol");
7957        let initial = ModuleSpec {
7958            script: None,
7959            module_id: "rescan-protocol".into(),
7960            program: PathBuf::from("/bin/sleep"),
7961            args: vec!["60".into()],
7962            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7963                .into_iter()
7964                .map(|key| (key.into(), dir.path().to_string_lossy().into_owned()))
7965                .collect(),
7966            reserved: false,
7967            reserved_prefixes: vec![],
7968            protocol: ModuleProtocol::None,
7969            overlap: Default::default(),
7970            carry_containment: false,
7971        };
7972        let supervisor =
7973            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7974        let module = supervisor.spawn(initial.clone()).unwrap();
7975        assert!(module.status().unwrap().live);
7976        let mut next = initial;
7977        next.protocol = ModuleProtocol::Subc;
7978        module
7979            .update_configuration(next.clone(), HealthConfig::default(), None)
7980            .await
7981            .unwrap();
7982        assert!(
7983            module.status().unwrap().live,
7984            "rescan must not require HELLO from the old non-wire process"
7985        );
7986        let runtime = supervisor.runtime_config();
7987        let action = on_child_exit(
7988            &next,
7989            RestartPolicy::default(),
7990            &supervisor.registry,
7991            &module.inner.snapshot,
7992            &runtime.terminal_ring,
7993            &runtime.spawn_events,
7994            &runtime.child_roster,
7995            ExitReport {
7996                kind: ExitKind::Clean,
7997                code: Some(0),
7998                signal: None,
7999                at_ms: unix_ms_now(),
8000            },
8001            true,
8002        )
8003        .await;
8004        assert!(
8005            matches!(action, NextAction::Restart { .. }),
8006            "the old non-wire process's clean exit must restart"
8007        );
8008        module.drain().await.unwrap();
8009    }
8010
8011    #[cfg(unix)]
8012    #[tokio::test]
8013    async fn orphan_identity_matches_path_names_and_shebang_interpreters() {
8014        use std::os::unix::fs::PermissionsExt;
8015        let dir = cortexkit_test_support::ScratchDir::new("spawn-image-identity");
8016        let script = dir.join("module.sh");
8017        std::fs::write(&script, "#!/bin/sh\nwhile :; do sleep 0.1; done\n").unwrap();
8018        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
8019        let record_path = dir.join("live-children.json");
8020        let supervisor =
8021            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8022                .with_live_children_record(&record_path);
8023        for (program, args) in [
8024            (PathBuf::from("sleep"), vec!["60".into()]),
8025            (script, vec![]),
8026        ] {
8027            let spec = ModuleSpec {
8028                script: None,
8029                module_id: "image-identity".into(),
8030                program: program.clone(),
8031                args,
8032                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
8033                    .into_iter()
8034                    .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
8035                    .collect(),
8036                reserved: false,
8037                reserved_prefixes: vec![],
8038                protocol: ModuleProtocol::None,
8039                overlap: Default::default(),
8040                carry_containment: false,
8041            };
8042            let module = supervisor.spawn(spec).unwrap();
8043            #[cfg(target_os = "macos")]
8044            {
8045                // SETEXEC confirmation is asynchronous; the orphan record must
8046                // identify the final image, never the intermediate trampoline.
8047                let deadline = Instant::now() + Duration::from_secs(5);
8048                while crate::live_children::read_record(&record_path)
8049                    .unwrap()
8050                    .iter()
8051                    .all(|entry| entry.executable.is_none())
8052                {
8053                    assert!(Instant::now() < deadline, "module image was not confirmed");
8054                    tokio::time::sleep(Duration::from_millis(5)).await;
8055                }
8056            }
8057            let entry = crate::live_children::read_record(&record_path)
8058                .unwrap()
8059                .pop()
8060                .unwrap();
8061            let observed = subc_os::Process::open(entry.pid)
8062                .unwrap()
8063                .unwrap()
8064                .observe()
8065                .unwrap();
8066            let verdict = crate::live_children::identity_verdict(&entry, entry.pid, &observed);
8067            module.drain().await.unwrap();
8068            assert_eq!(
8069                verdict,
8070                crate::live_children::IdentityVerdict::Matches,
8071                "program {program:?}: recorded {entry:?}, observed {observed:?}"
8072            );
8073        }
8074    }
8075
8076    #[cfg(unix)]
8077    fn http_fixture(
8078        dir: &std::path::Path,
8079        url: &str,
8080        threshold: u32,
8081    ) -> crate::daemon_config::ConfiguredModule {
8082        let path = dir.join("subc.jsonc");
8083        std::fs::write(&path, serde_json::json!({"version": 1, "modules": {"http-process": {
8084            "program": "/bin/sleep", "args": ["60"], "protocol": "none",
8085            "env": {"XDG_DATA_HOME":dir,"XDG_RUNTIME_DIR":dir,"XDG_CONFIG_HOME":dir},
8086            "health": {"http":url,"cadence_ms":20,"deadline_ms":200,"failure_threshold":threshold},
8087            "restart": {"backoff_ms":1,"max_backoff_ms":1}, "drain_timeout_ms":10
8088        }}}).to_string()).unwrap();
8089        crate::daemon_config::load(&path)
8090            .unwrap()
8091            .unwrap()
8092            .modules
8093            .pop()
8094            .unwrap()
8095    }
8096
8097    #[cfg(unix)]
8098    async fn wait_http_health(module: &SupervisedModule, status: SupervisorHealthStatus) {
8099        timeout(Duration::from_secs(5), async {
8100            loop {
8101                if module.status().unwrap().health.status == status {
8102                    break;
8103                }
8104                sleep(Duration::from_millis(5)).await;
8105            }
8106        })
8107        .await
8108        .unwrap_or_else(|_| {
8109            panic!(
8110                "expected {status:?}, got {:?}",
8111                module.status().unwrap().health
8112            )
8113        });
8114    }
8115
8116    #[cfg(unix)]
8117    #[tokio::test]
8118    async fn http_health_status_flips_ok_failing_ok() {
8119        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8120        let dir = cortexkit_test_support::ScratchDir::new("http-status-flips");
8121        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8122        let status = Arc::new(std::sync::atomic::AtomicU16::new(200));
8123        let serving_status = status.clone();
8124        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8125        let server = tokio::spawn(async move {
8126            loop {
8127                let (mut stream, _) = listener.accept().await.unwrap();
8128                let mut request = [0u8; 2048];
8129                let count = stream.read(&mut request).await.unwrap();
8130                assert!(count > 0, "a probe must send an HTTP request");
8131                let code = serving_status.load(std::sync::atomic::Ordering::SeqCst);
8132                let body = if code == 200 {
8133                    "ready"
8134                } else {
8135                    "{\"status\":\"unavailable\",\"error\":\"scratch failure\"}"
8136                };
8137                let response = format!("HTTP/1.1 {code} scratch\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
8138                let _ = stream.write_all(response.as_bytes()).await;
8139            }
8140        });
8141        let configured = http_fixture(&dir, &url, 1000);
8142        let module =
8143            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8144                .supervise_configured_with_health(
8145                    configured.module_spec(),
8146                    true,
8147                    configured.health,
8148                    configured.drain_timeout_ms,
8149                    configured.restart,
8150                )
8151                .unwrap();
8152        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8153        status.store(503, std::sync::atomic::Ordering::SeqCst);
8154        wait_http_health(&module, SupervisorHealthStatus::Failing).await;
8155        assert!(module
8156            .status()
8157            .unwrap()
8158            .health
8159            .detail
8160            .unwrap()
8161            .contains("scratch failure"));
8162        status.store(200, std::sync::atomic::Ordering::SeqCst);
8163        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8164        assert_eq!(module.status().unwrap().health.consecutive_failures, 0);
8165        let before = module.status().unwrap();
8166        let (spec, mut health) = module.configuration().unwrap();
8167        health.http = None;
8168        module
8169            .update_configuration(spec.clone(), health.clone(), Some(10))
8170            .await
8171            .unwrap();
8172        wait_http_health(&module, SupervisorHealthStatus::Unknown).await;
8173        health.http = Some(url);
8174        module
8175            .update_configuration(spec, health, Some(10))
8176            .await
8177            .unwrap();
8178        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8179        assert_eq!(
8180            module.status().unwrap().pid,
8181            before.pid,
8182            "changing a probe must apply live, not restart its process"
8183        );
8184        let (spec, mut health) = module.configuration().unwrap();
8185        health.failure_threshold = 2;
8186        module
8187            .update_configuration(spec, health, Some(10))
8188            .await
8189            .unwrap();
8190        status.store(503, std::sync::atomic::Ordering::SeqCst);
8191        timeout(Duration::from_secs(5), async {
8192            while module.status().unwrap().spawn_generation == before.spawn_generation {
8193                sleep(Duration::from_millis(5)).await;
8194            }
8195        })
8196        .await
8197        .expect("sustained HTTP 503 responses must trigger the health restart policy");
8198        module.drain().await.unwrap();
8199        server.abort();
8200    }
8201
8202    #[cfg(unix)]
8203    #[tokio::test]
8204    async fn http_health_replacement_recovers_after_one_restart() {
8205        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8206        let dir = cortexkit_test_support::ScratchDir::new("http-replacement-recovers");
8207        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8208        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8209        let mut configured = http_fixture(&dir, &url, 2);
8210        configured.restart.max_restarts = 2;
8211        let module =
8212            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8213                .supervise_configured_with_health(
8214                    configured.module_spec(),
8215                    true,
8216                    configured.health,
8217                    configured.drain_timeout_ms,
8218                    configured.restart,
8219                )
8220                .unwrap();
8221        let first_generation = module.status().unwrap().spawn_generation;
8222        let observed = module.clone();
8223        let (healthy_tx, mut healthy_rx) = mpsc::channel(8);
8224        let server = tokio::spawn(async move {
8225            let mut generation = first_generation;
8226            let mut probes = 0;
8227            loop {
8228                let (mut stream, _) = listener.accept().await.unwrap();
8229                let mut request = [0; 2048];
8230                assert!(stream.read(&mut request).await.unwrap() > 0);
8231                let current = observed.status().unwrap().spawn_generation;
8232                if current != generation {
8233                    generation = current;
8234                    probes = 0;
8235                }
8236                probes += 1;
8237                // The original process never recovers. Each replacement has one
8238                // transient miss, then answers successfully for its remaining life.
8239                let healthy = generation != first_generation && probes > 1;
8240                let code = if healthy { 200 } else { 503 };
8241                let response = format!(
8242                    "HTTP/1.1 {code} scratch\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
8243                );
8244                let _ = stream.write_all(response.as_bytes()).await;
8245                if healthy {
8246                    healthy_tx.send(()).await.unwrap();
8247                }
8248            }
8249        });
8250        timeout(Duration::from_secs(5), async {
8251            let mut healthy_probes = 0;
8252            loop {
8253                if module.state().unwrap() == ModuleState::Failed {
8254                    break;
8255                }
8256                while healthy_rx.try_recv().is_ok() {
8257                    healthy_probes += 1;
8258                }
8259                if healthy_probes >= 3
8260                    && module.status().unwrap().health.status == SupervisorHealthStatus::Ok
8261                {
8262                    break;
8263                }
8264                sleep(Duration::from_millis(5)).await;
8265            }
8266        })
8267        .await
8268        .expect("the replacement must settle healthy without exhausting its restart budget");
8269        let status = module.status().unwrap();
8270        module.drain().await.unwrap();
8271        server.abort();
8272        assert_eq!(status.state, ModuleState::Running);
8273        assert_eq!(status.health.status, SupervisorHealthStatus::Ok);
8274        assert_eq!(status.health.consecutive_failures, 0);
8275        assert_eq!(status.lifetime_restarts, 1);
8276        assert_eq!(status.restart_count, 1);
8277    }
8278
8279    #[cfg(unix)]
8280    #[tokio::test]
8281    async fn http_health_sustained_failure_exhausts_restart_budget() {
8282        use std::collections::BTreeMap;
8283        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8284        let dir = cortexkit_test_support::ScratchDir::new("http-health-budget");
8285        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8286        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8287        let mut configured = http_fixture(&dir, &url, 2);
8288        configured.restart.max_restarts = 2;
8289        let module =
8290            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8291                .supervise_configured_with_health(
8292                    configured.module_spec(),
8293                    true,
8294                    configured.health,
8295                    configured.drain_timeout_ms,
8296                    configured.restart,
8297                )
8298                .unwrap();
8299        let observed = module.clone();
8300        let probes = Arc::new(Mutex::new(BTreeMap::<u64, u32>::new()));
8301        let served = probes.clone();
8302        let server = tokio::spawn(async move {
8303            loop {
8304                let (mut stream, _) = listener.accept().await.unwrap();
8305                let mut request = [0; 2048];
8306                assert!(stream.read(&mut request).await.unwrap() > 0);
8307                *served
8308                    .lock()
8309                    .unwrap()
8310                    .entry(observed.status().unwrap().spawn_generation)
8311                    .or_default() += 1;
8312                let _ = stream
8313                    .write_all(b"HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
8314                    .await;
8315            }
8316        });
8317        timeout(Duration::from_secs(5), async {
8318            while module.state().unwrap() != ModuleState::Failed {
8319                sleep(Duration::from_millis(5)).await;
8320            }
8321        })
8322        .await
8323        .expect("sustained failures must still exhaust the health restart budget");
8324        let status = module.status().unwrap();
8325        server.abort();
8326        assert_eq!(status.restart_count, 2);
8327        assert_eq!(status.lifetime_restarts, 2);
8328        assert!(!status.process_alive);
8329        assert_eq!(
8330            probes.lock().unwrap().values().copied().collect::<Vec<_>>(),
8331            vec![2, 2, 2]
8332        );
8333    }
8334
8335    #[cfg(unix)]
8336    #[tokio::test]
8337    async fn spawn_clears_the_previous_process_health() {
8338        let dir = cortexkit_test_support::ScratchDir::new("spawn-fresh-health");
8339        let mut configured = http_fixture(&dir, "http://127.0.0.1:1/healthz", 2);
8340        configured.health.cadence = Duration::from_secs(3600);
8341        let module =
8342            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8343                .supervise_configured_with_health(
8344                    configured.module_spec(),
8345                    false,
8346                    configured.health,
8347                    configured.drain_timeout_ms,
8348                    configured.restart,
8349                )
8350                .unwrap();
8351        update_snapshot(&module.inner.snapshot, Some(module.module_id()), |state| {
8352            state.health.status = SupervisorHealthStatus::Unresponsive;
8353            state.health.consecutive_failures = 3;
8354            state.health.detail = Some("old process refused connections".into());
8355            state.health.metrics = Some(serde_json::json!({"old": true}));
8356            state.health.last_probe_ms = Some(123);
8357            state.health.last_action = Some("restart".into());
8358            state.health.last_action_ms = Some(124);
8359        })
8360        .unwrap();
8361        module.set_enabled(true).await.unwrap();
8362        let health = module.status().unwrap().health;
8363        module.drain().await.unwrap();
8364        assert_eq!(health.consecutive_failures, 0);
8365        assert_eq!(health.status, SupervisorHealthStatus::Unknown);
8366        assert_eq!(health.detail, None);
8367        assert_eq!(health.metrics, None);
8368        assert_eq!(health.last_probe_ms, None);
8369        assert_eq!(health.last_action.as_deref(), Some("restart"));
8370        assert_eq!(health.last_action_ms, Some(124));
8371    }
8372
8373    #[cfg(unix)]
8374    #[tokio::test]
8375    async fn http_health_no_listener_restarts_after_consecutive_failures() {
8376        let dir = cortexkit_test_support::ScratchDir::new("http-refused");
8377        let unused = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8378        let url = format!("http://{}/healthz", unused.local_addr().unwrap());
8379        drop(unused);
8380        let configured = http_fixture(&dir, &url, 2);
8381        let module =
8382            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8383                .supervise_configured_with_health(
8384                    configured.module_spec(),
8385                    true,
8386                    configured.health,
8387                    configured.drain_timeout_ms,
8388                    configured.restart,
8389                )
8390                .unwrap();
8391        let before = module.status().unwrap().spawn_generation;
8392        timeout(Duration::from_secs(5), async {
8393            loop {
8394                let status = module.status().unwrap();
8395                if status.spawn_generation > before {
8396                    assert!(status.lifetime_restarts > 0);
8397                    break;
8398                }
8399                sleep(Duration::from_millis(5)).await;
8400            }
8401        })
8402        .await
8403        .expect("sustained HTTP refusal must trigger the health restart policy");
8404        module.drain().await.unwrap();
8405    }
8406
8407    #[cfg(unix)]
8408    #[tokio::test]
8409    async fn http_health_timeout_honours_deadline() {
8410        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8411        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8412        let server = tokio::spawn(async move {
8413            let _held = listener.accept().await.unwrap();
8414            std::future::pending::<()>().await;
8415        });
8416        let error = timeout(
8417            Duration::from_secs(1),
8418            probe_http_health(&url, Duration::from_millis(10)),
8419        )
8420        .await
8421        .expect("the probe must enforce its own deadline")
8422        .unwrap_err();
8423        server.abort();
8424        assert!(error.to_string().contains("timed out"));
8425    }
8426
8427    #[cfg(unix)]
8428    #[tokio::test]
8429    async fn http_health_localhost_reaches_an_ipv6_only_listener() {
8430        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8431        let listener = tokio::net::TcpListener::bind("[::1]:0").await.unwrap();
8432        let url = format!(
8433            "http://localhost:{}/healthz",
8434            listener.local_addr().unwrap().port()
8435        );
8436        let server = tokio::spawn(async move {
8437            let (mut stream, _) = listener.accept().await.unwrap();
8438            let mut request = [0u8; 2048];
8439            assert!(stream.read(&mut request).await.unwrap() > 0);
8440            stream
8441                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
8442                .await
8443                .unwrap();
8444        });
8445        // The deadline only bounds a hang. A probe that never tried the IPv6
8446        // address would be refused on 127.0.0.1 and fail at once, so a longer
8447        // deadline does not weaken the assertion; one second timed out under a
8448        // loaded parallel test run.
8449        assert_eq!(
8450            probe_http_health(&url, Duration::from_secs(10))
8451                .await
8452                .unwrap()
8453                .status,
8454            HealthStatus::Ok
8455        );
8456        server.await.unwrap();
8457    }
8458
8459    #[cfg(unix)]
8460    #[tokio::test]
8461    async fn http_health_timeout_keeps_partial_status_and_body() {
8462        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8463        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8464        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8465        let server = tokio::spawn(async move {
8466            let (mut stream, _) = listener.accept().await.unwrap();
8467            let mut request = [0u8; 2048];
8468            assert!(stream.read(&mut request).await.unwrap() > 0);
8469            stream
8470                .write_all(
8471                    b"HTTP/1.1 503 Unavailable\r\nContent-Length: 100\r\n\r\npartial diagnostic",
8472                )
8473                .await
8474                .unwrap();
8475            std::future::pending::<()>().await;
8476        });
8477        let error = probe_http_health(&url, Duration::from_secs(1))
8478            .await
8479            .unwrap_err()
8480            .to_string();
8481        server.abort();
8482        assert!(
8483            error.contains("timed out")
8484                && error.contains("503 Unavailable")
8485                && error.contains("partial diagnostic"),
8486            "{error}"
8487        );
8488    }
8489
8490    #[cfg(unix)]
8491    #[tokio::test]
8492    async fn http_health_diagnostic_body_is_bounded_to_200_bytes() {
8493        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8494        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8495        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8496        let server = tokio::spawn(async move {
8497            let (mut stream, _) = listener.accept().await.unwrap();
8498            let mut request = [0u8; 2048];
8499            assert!(stream.read(&mut request).await.unwrap() > 0);
8500            let body = format!("{}not-in-diagnostic", "x".repeat(400));
8501            let response = format!(
8502                "HTTP/1.1 503 Unavailable\r\nContent-Length: {}\r\n\r\n{body}",
8503                body.len()
8504            );
8505            stream.write_all(response.as_bytes()).await.unwrap();
8506        });
8507        let error = probe_http_health(&url, Duration::from_secs(1))
8508            .await
8509            .unwrap_err()
8510            .to_string();
8511        server.await.unwrap();
8512        assert!(error.ends_with(&"x".repeat(200)), "{error}");
8513        assert_eq!(error.split(": ").last().unwrap().len(), 200);
8514        assert!(!error.contains("not-in-diagnostic"));
8515    }
8516
8517    #[cfg(unix)]
8518    #[tokio::test]
8519    async fn http_health_real_nats_server_monitoring() {
8520        if std::process::Command::new("nats-server")
8521            .arg("--version")
8522            .env("XDG_DATA_HOME", std::env::temp_dir())
8523            .env("XDG_RUNTIME_DIR", std::env::temp_dir())
8524            .env("XDG_CONFIG_HOME", std::env::temp_dir())
8525            .output()
8526            .is_err()
8527        {
8528            eprintln!(
8529                "skipped: http_health_real_nats_server_monitoring (nats-server is not on PATH)"
8530            );
8531            return;
8532        }
8533        let dir = cortexkit_test_support::ScratchDir::new("nats-http-monitoring");
8534        let monitor = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8535        let port = monitor.local_addr().unwrap().port();
8536        let client = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8537        let client_port = client.local_addr().unwrap().port();
8538        let config = dir.join("server.conf");
8539        std::fs::write(&config, format!("listen: 127.0.0.1:{client_port}\nhttp: 127.0.0.1:{port}\njetstream {{ store_dir: \"{}\" }}\n", dir.join("jetstream").display())).unwrap();
8540        let mut configured = http_fixture(&dir, &format!("http://127.0.0.1:{port}/healthz"), 1000);
8541        configured.program = PathBuf::from("nats-server");
8542        configured.args = vec!["-c".into(), config.to_string_lossy().into_owned()];
8543        drop(monitor);
8544        drop(client);
8545        let module =
8546            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8547                .supervise_configured_with_health(
8548                    configured.module_spec(),
8549                    true,
8550                    configured.health,
8551                    configured.drain_timeout_ms,
8552                    configured.restart,
8553                )
8554                .unwrap();
8555        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8556        module.drain().await.unwrap();
8557    }
8558
8559    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8560    async fn configuration_update_does_not_replace_captured_running_process_facts() {
8561        let supervisor =
8562            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
8563        let snapshot = stale_process_snapshot(ModuleState::Running, true);
8564        let initial = ModuleSpec {
8565            script: None,
8566            module_id: "rescan-preserves-spawn-facts".to_string(),
8567            program: PathBuf::from("/spawned/module"),
8568            args: Vec::new(),
8569            env: Vec::new(),
8570            reserved: false,
8571            reserved_prefixes: Vec::new(),
8572            protocol: ModuleProtocol::Subc,
8573            overlap: Default::default(),
8574            carry_containment: false,
8575        };
8576        let module = supervisor.supervised_module(
8577            initial.clone(),
8578            supervisor.runtime_config(),
8579            snapshot,
8580            None,
8581        );
8582        let before = module.status().unwrap();
8583        let mut replacement = initial;
8584        replacement.program = PathBuf::from("/rescanned/replacement-module");
8585
8586        module
8587            .update_configuration(replacement, HealthConfig::default(), None)
8588            .await
8589            .unwrap();
8590
8591        let after = module.status().unwrap();
8592        assert_eq!(after.pid, before.pid);
8593        assert_eq!(after.spawned_at_ms, before.spawned_at_ms);
8594        assert_eq!(after.spawned_from, before.spawned_from);
8595        drop(module);
8596    }
8597}
8598
8599fn unix_ms_now() -> u64 {
8600    SystemTime::now()
8601        .duration_since(UNIX_EPOCH)
8602        .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
8603        .unwrap_or(0)
8604}
8605
8606async fn supervise_loop(
8607    mut spec: ModuleSpec,
8608    mut runtime: SupervisorRuntimeConfig,
8609    registry: Arc<Registry>,
8610    process_liveness: Arc<SupervisorProcessLiveness>,
8611    snapshot: SharedSnapshot,
8612    mut child: Option<SupervisedChild>,
8613    mut commands: mpsc::Receiver<SupervisorCommand>,
8614) {
8615    let mut health_probe = HealthProbeRuntime::default();
8616    // Registry writes (including embedded callers) notify this module only.
8617    // Subscribe before the first refresh; watch retains changes that arrive
8618    // while commands or probes are running. No polling fallback is needed.
8619    let mut registration_changes = match registry.subscribe_module_changes(&spec.module_id) {
8620        Ok(changes) => Some(changes),
8621        Err(err) => {
8622            // A poisoned registry cannot accept further writes, so it cannot
8623            // recover via a timer. Keep exit and command handling alive.
8624            warn!(module_id = %spec.module_id, error = %err, "health prober could not subscribe to registry");
8625            None
8626        }
8627    };
8628    // All restart backoffs run here, including health and operator requests.
8629    // While one is pending the loop serves commands, so disable or drain can
8630    // cancel the replacement without spawning a process just to stop it.
8631    let mut pending_respawn: Option<PendingRespawn> = None;
8632    // Commands a swap handed back to run next (see `swap::SwapEnd`). Served
8633    // before anything else so a stop that interrupted a swap runs at once.
8634    let mut requeued: VecDeque<SupervisorCommand> = VecDeque::new();
8635    let mut previous_instance_recheck = tokio::time::interval_at(
8636        Instant::now() + Duration::from_secs(5),
8637        Duration::from_secs(5),
8638    );
8639    previous_instance_recheck.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
8640    'supervision: loop {
8641        #[cfg(test)]
8642        {
8643            lock_snapshot(&snapshot).unwrap().actor_select = None;
8644        }
8645        #[cfg(target_os = "macos")]
8646        if let Some(active) = child.as_mut() {
8647            active.confirm_privacy_exec().await;
8648        }
8649        if let Some(scheduled) = runtime
8650            .scheduled_respawn
8651            .lock()
8652            .unwrap_or_else(|p| p.into_inner())
8653            .take()
8654        {
8655            runtime.recovery_is_daemon = scheduled.daemon_initiated;
8656            pending_respawn = Some(scheduled);
8657        }
8658        if pending_respawn.is_some() && (child.is_some() || !respawn_still_pending(&snapshot)) {
8659            pending_respawn = None;
8660            cancel_deferred_reload(
8661                &runtime,
8662                &spec.module_id,
8663                "respawn cancelled by a supervisor command",
8664            );
8665        }
8666        if child.is_none()
8667            && pending_respawn.is_none()
8668            && lock_snapshot(&snapshot).is_ok_and(|state| state.waiting_for_previous_pid.is_none())
8669        {
8670            cancel_deferred_reload(
8671                &runtime,
8672                &spec.module_id,
8673                "respawn cancelled before a replacement was spawned",
8674            );
8675            let mut stranded = false;
8676            let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8677                state.respawn_pending = false;
8678                state.coalesced_restart_pending = false;
8679                if matches!(
8680                    state.state,
8681                    ModuleState::Restarting
8682                        | ModuleState::Starting
8683                        | ModuleState::Draining
8684                        | ModuleState::Unresponsive
8685                ) {
8686                    error!(module_id = %spec.module_id, state = ?state.state,
8687                        "supervision operation ended without a child or pending respawn; marking failed so start can retry");
8688                    stranded = true;
8689                }
8690            });
8691            if stranded {
8692                fail_snapshot(
8693                    &snapshot,
8694                    Some(&spec.module_id),
8695                    None,
8696                    &runtime.failure_context(runtime.recovery_is_daemon),
8697                );
8698            }
8699        }
8700        if child.is_none()
8701            && (runtime.child_roster.is_closed()
8702                || pending_respawn.is_none()
8703                || !lock_snapshot(&snapshot)
8704                    .is_ok_and(|state| state.enabled && state.state == ModuleState::Restarting))
8705        {
8706            containment::terminate(&runtime.child_roster.containment).await;
8707        }
8708        if let Some(command) = requeued.pop_front() {
8709            if !handle_supervisor_command(
8710                command,
8711                &mut spec,
8712                &mut runtime,
8713                &registry,
8714                &process_liveness,
8715                &snapshot,
8716                &mut child,
8717                &mut commands,
8718                &mut requeued,
8719            )
8720            .await
8721            {
8722                containment::terminate(&runtime.child_roster.containment).await;
8723                return;
8724            }
8725            if child.is_some() || !respawn_still_pending(&snapshot) {
8726                pending_respawn = None;
8727                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8728                    state.respawn_pending = false
8729                });
8730            }
8731            continue;
8732        }
8733        if child.is_some() {
8734            runtime.recovery_is_daemon = true;
8735            #[cfg(test)]
8736            {
8737                lock_snapshot(&snapshot).unwrap().actor_turns += 1;
8738            }
8739            health_probe.refresh_registration(&spec, &runtime, &registry, &snapshot);
8740            let active = child.as_mut().expect("child checked above");
8741            if active.registered_since_spawn() {
8742                if let Some(delivery) = &runtime.config_delivery {
8743                    delivery.queue_registered(
8744                        &spec.module_id,
8745                        runtime.forwarding.as_ref(),
8746                        &registry,
8747                        active,
8748                    );
8749                }
8750            }
8751            if runtime.child_roster.is_closed() || !active.awaiting_registration() {
8752                active.registration_deadline = None;
8753            }
8754            let registration_deadline = active.registration_deadline;
8755            let no_checks = runtime.health.http.is_none()
8756                && (running_protocol(&spec, &snapshot) == ModuleProtocol::None
8757                    || (health_probe.registered_connection.is_some() && !health_probe.advertised));
8758            let uptime_reset = lock_snapshot(&snapshot).ok().and_then(|mut state| {
8759                state
8760                    .failed_retry
8761                    .uptime_reset_at(no_checks, runtime.restart_policy.window)
8762            });
8763            let wake_at = match (health_probe.wake_at(), uptime_reset) {
8764                (probe, Some(reset)) => Some(probe.map_or(reset, |probe| probe.min(reset))),
8765                (probe, None) => probe,
8766            };
8767            let wake_at = match (wake_at, registration_deadline) {
8768                (Some(wake), Some(register)) => Some(wake.min(register)),
8769                (wake, register) => wake.or(register),
8770            };
8771            #[cfg(test)]
8772            let wake_after = wake_at.map(|at| at.saturating_duration_since(Instant::now()));
8773            let probe_sleep = supervisor_sleep(wake_at);
8774            tokio::pin!(probe_sleep);
8775            // A `protocol: "none"` child (a plain process that never registers
8776            // over the subc wire, such as nats-server) with no HTTP health
8777            // check has nothing to probe, so it waits only for its exit or a
8778            // supervisor command. A rescan that adds an HTTP check is a command.
8779            let wire_child = running_protocol(&spec, &snapshot) == ModuleProtocol::Subc;
8780            #[cfg(test)]
8781            {
8782                let registration_pending = wire_child
8783                    && registration_changes
8784                        .as_ref()
8785                        .is_some_and(|changes| changes.has_changed().unwrap());
8786                let mut state = lock_snapshot(&snapshot).unwrap();
8787                state.actor_select = (!registration_pending).then_some(ActorSelectCheckpoint {
8788                    generation: state.spawn_generation,
8789                    turn: state.actor_turns,
8790                    registered_connection: health_probe.registered_connection,
8791                    next_probe_at: health_probe.next_probe_at,
8792                    wake_after,
8793                });
8794            }
8795            let registration = active
8796                .awaiting_registration()
8797                .then(|| active.registration_spawn.clone())
8798                .flatten();
8799            #[cfg(all(test, target_os = "linux"))]
8800            let registration_before_exit = !runtime.child_roster.admission_event_for_test(
8801                &spec.module_id,
8802                "observe_registration_before_exit",
8803                Some(active.pid),
8804            ) && registration.is_some();
8805            #[cfg(not(all(test, target_os = "linux")))]
8806            let registration_before_exit = false;
8807            #[cfg(all(test, target_os = "linux"))]
8808            let registration_child_is_running = |child: &mut SupervisedChild| {
8809                // Model the interval after SIGKILL is accepted but before the
8810                // child becomes waitable, without delaying the actual kill.
8811                registration_before_exit || registration_child_is_running(child)
8812            };
8813            let registration_failed = async {
8814                match &registration {
8815                    Some(spawn) => spawn.wait_registration_failure().await,
8816                    None => std::future::pending().await,
8817                }
8818            };
8819            let active_child = child.as_mut().expect("child checked above");
8820            tokio::select! {
8821                _ = registration_failed => {
8822                    if !active_child.registered_since_spawn() && registration_child_is_running(active_child) {
8823                        active_child.registration_deadline = None;
8824                        active_child.spawn_failure = Some("registration_channel_closed".into());
8825                        if let Err(error) = stop_unregistered_child(active_child).await {
8826                            fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
8827                                &runtime.spawn_events, format!("registration_channel_closed: {error}"),
8828                                &runtime.failure_context(true));
8829                            child = None;
8830                        }
8831                    }
8832                    continue;
8833                }
8834                wait_result = active_child.wait(), if !registration_before_exit => {
8835                    if let Ok(mut state) = lock_snapshot(&snapshot) {
8836                        state.failed_retry.uptime_reset_at(no_checks, runtime.restart_policy.window);
8837                    }
8838                    #[cfg(test)]
8839                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8840                    // Every arm below that gives up on the CHILD must keep the
8841                    // supervision task itself alive (child = None, loop
8842                    // continues into command-serving mode). Returning here
8843                    // closes the command channel, which makes the module
8844                    // permanently unrestartable in-band: a clean child exit
8845                    // of an enabled module once wedged the fleet this way
8846                    // ('supervisor command channel is closed') and required a
8847                    // full daemon restart to recover.
8848                    let exit_report = match wait_result {
8849                        Ok(status) => classify_reaped_child_exit(&snapshot, active_child, &status),
8850                        Err(err) => {
8851                            active_child.drain_stderr(&spec.module_id).await;
8852                            fail_after_wait_error(
8853                                &spec.module_id,
8854                                &snapshot,
8855                                &runtime.terminal_ring,
8856                                &runtime.spawn_events,
8857                                format!("failed to wait for supervised module: {err}"),
8858                            &runtime.failure_context(true),
8859                            );
8860                            untrack_if_registration_released(
8861                                &process_liveness,
8862                                &registry,
8863                                &spec.module_id,
8864                                &snapshot,
8865                            );
8866                            error!(module_id = %spec.module_id, error = %err, "failed to wait for supervised module");
8867                            child = None;
8868                            continue;
8869                        }
8870                    };
8871                    active_child.drain_stderr(&spec.module_id).await;
8872
8873                    let delivery=runtime.config_delivery.clone();
8874                    let exited_spawn=active_child.spawned_at;
8875                    let spawn=active_child.config_delivery.clone();
8876                    let refusal=active_child.spawn_failure.as_deref().filter(|detail|detail.starts_with("program_refused:") && !active_child.live_program_binding.as_ref().is_some_and(|binding|binding.is_refused())).zip(active_child.admission_base.clone()).map(|(detail,base)|(base,subc_config::raw_digest(detail.as_bytes())));
8877                    let module_id=spec.module_id.clone();
8878                    // Publication may own the store mutex for local durable I/O.
8879                    // Keep commands selectable until the child's exit is recorded;
8880                    // no respawn disposition is chosen before that observation.
8881                    let observed=async move {
8882                        if let Some(delivery)=delivery {
8883                            delivery.0.on_blocking(move |owner| {
8884                                if let Some(spawn)=spawn { owner.delivery_child_exited(&spawn)?; }
8885                                if let Some((base,identity))=refusal {owner.record_program_refusal(&module_id,&base,identity)?;}
8886                                Ok(())
8887                            }).await
8888                        } else {Ok(())}
8889                    };
8890                    tokio::pin!(observed);
8891                    loop {
8892                        tokio::select! {
8893                            result=&mut observed=>{
8894                                if let Err(error)=result {warn!(module_id=%spec.module_id,%error,"configuration exit observation failed");}
8895                                break;
8896                            }
8897                            command=commands.recv()=>{
8898                                let Some(command)=command else {containment::terminate(&runtime.child_roster.containment).await;return;};
8899                                let deferred=||SuperviseError::ConfigDeliveryDeferred {module_id:spec.module_id.clone()};
8900                                let command=match command {
8901                                    SupervisorCommand::Restart {reply,..}|SupervisorCommand::Reload {reply,..}=>{let _=reply.send(Err(deferred()));continue;}
8902                                    SupervisorCommand::Swap {reply,..}=>{let _=reply.send(Err(deferred()));continue;}
8903                                    command @ (SupervisorCommand::ConfigApplyRestart {..}|SupervisorCommand::ConfigPolicyProbe {..}|SupervisorCommand::ConfigDeliveryFailed {..})=>{requeued.push_back(command);continue;}
8904                                    command=>command,
8905                                };
8906                                if !handle_supervisor_command(command,&mut spec,&mut runtime,&registry,&process_liveness,&snapshot,&mut child,&mut commands,&mut requeued).await {
8907                                    containment::terminate(&runtime.child_roster.containment).await;return;
8908                                }
8909                                if child.as_ref().is_none_or(|current|current.spawned_at!=exited_spawn) {continue 'supervision;}
8910                            }
8911                        }
8912                    }
8913                    let active_child=child.as_mut().expect("exit observation retained its child");
8914                    // An unavailable image can race the program's own exit.
8915                    // Only the admission kill is budget-free; another exit must
8916                    // retain its ordinary crash/clean-exit accounting.
8917                    let admission_kill = admission_exit::is_admission_kill(active_child.admission_kill_sent, &exit_report);
8918                    let deferred_spawn=admission_kill && active_child.spawn_failure.as_deref().is_some_and(|detail|detail.starts_with("config_delivery_deferred:"));
8919                    let refused_program = active_child.live_program_binding.as_ref().is_some_and(|binding| binding.is_refused());
8920                    let exit_held = !deferred_spawn && (refused_program || runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.exit_is_held(&spec.module_id)));
8921                    let parked = exit_held && (!refused_program || active_child.admission_base.is_some())
8922                        && try_park_config_attempt(&spec, &runtime, &snapshot, &runtime.failure_context(true),
8923                            if refused_program { active_child.admission_base.as_ref() } else { None })
8924                            .unwrap_or_else(|error| { warn!(module_id=%spec.module_id, %error, "exit hold could not be recorded; using ordinary exit accounting"); false });
8925                    let next = if deferred_spawn {
8926                        record_terminal_with_detail(&spec.module_id,&runtime.terminal_ring,&runtime.spawn_events,&exit_report,TerminalDisposition::Restarting,active_child.spawn_failure.clone());
8927                        let _=update_snapshot(&snapshot,Some(&spec.module_id),|state| {
8928                            state.state=ModuleState::Restarting;
8929                            clear_current_process_facts(state);
8930                            state.last_exit=Some(exit_report.clone());
8931                        });
8932                        NextAction::Restart {schedule:None}
8933                    } else if parked {
8934                        record_terminal_with_detail(&spec.module_id, &runtime.terminal_ring, &runtime.spawn_events, &exit_report, TerminalDisposition::Stopped, active_child.spawn_failure.clone().or_else(|| Some("config_gated".into())));
8935                        NextAction::Stop { registration_released: registry.get_module(&spec.module_id).ok().flatten().is_none() }
8936                    } else { on_child_exit(
8937                        &spec,
8938                        runtime.restart_policy,
8939                        &registry,
8940                        &snapshot,
8941                        &runtime.terminal_ring,
8942                        &runtime.spawn_events,
8943                        &runtime.child_roster,
8944                        exit_report,
8945                        true,
8946                    ).await };
8947                    runtime.start_requester = None;
8948                    runtime.pending_activity_restart = false;
8949                    // The exit is recorded, so a daemon shutdown may stop
8950                    // waiting for this child (see `SupervisedChild::wait`).
8951                    let carry = matches!(next, NextAction::Restart { .. })
8952                        && active_child.spawn_failure.is_none()
8953                        && !runtime.child_roster.is_closed();
8954                    if let Err(error) = active_child.finish_exit(carry).await {
8955                        containment::terminate(&runtime.child_roster.containment).await;
8956                        fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
8957                            &runtime.spawn_events, format!("failed to reap classified exit: {error}"),
8958                            &runtime.failure_context(true));
8959                        child = None;
8960                        continue;
8961                    }
8962                    match next {
8963                        NextAction::Stop { registration_released } => {
8964                            if registration_released {
8965                                process_liveness.untrack_if_current(&spec.module_id, &snapshot);
8966                            }
8967                            child = None;
8968                        }
8969                        NextAction::Restart { schedule } => {
8970                            let delay = if deferred_spawn {CONFIG_ADMISSION_RETRY_DELAY} else {schedule.map_or(
8971                                runtime.restart_policy.delay_for_restart(0),
8972                                |schedule| schedule.delay,
8973                            )};
8974                            if let Some(schedule) = schedule {
8975                                log_crash_respawn(&spec.module_id, schedule);
8976                            }
8977                            // The exited child is fully recorded at this point,
8978                            // so release it and count the backoff down in the
8979                            // command-serving branch below rather than sleeping
8980                            // here: commands cannot be received from inside this
8981                            // select arm, and an operator disable or drain that
8982                            // arrives during the backoff must cancel the pending
8983                            // respawn instead of waiting for it to spawn first.
8984                            child = None;
8985                            pending_respawn = Some(PendingRespawn { deadline: Instant::now() + delay, kind: RespawnKind::Spawn, daemon_initiated: true, approval: None });
8986                             let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = true);
8987                        }
8988                    }
8989                }
8990                command = commands.recv() => {
8991                    #[cfg(test)]
8992                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8993                    let Some(command) = command else {
8994                        containment::terminate(&runtime.child_roster.containment).await;
8995                        return;
8996                    };
8997                    if !handle_supervisor_command(
8998                        command,
8999                        &mut spec,
9000                        &mut runtime,
9001                        &registry,
9002                        &process_liveness,
9003                        &snapshot,
9004                        &mut child,
9005                        &mut commands,
9006                        &mut requeued,
9007                    ).await {
9008                        containment::terminate(&runtime.child_roster.containment).await;
9009                        return;
9010                    }
9011                }
9012                _ = async {
9013                    match registration_changes.as_mut() {
9014                        Some(changes) => { let _ = changes.changed().await; }
9015                        None => std::future::pending().await,
9016                    }
9017                }, if wire_child => {
9018                    #[cfg(test)]
9019                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
9020                }
9021                _ = &mut probe_sleep => {
9022                    #[cfg(test)]
9023                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
9024                    if registration_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
9025                        // Recheck after the wake: HELLO, exit or shutdown may
9026                        // have become ready in the same executor tick.
9027                        active_child.registration_deadline = None;
9028                        if !runtime.child_roster.is_closed()
9029                            && !active_child.registered_since_spawn()
9030                            && registration_child_is_running(active_child)
9031                        {
9032                            warn!(module_id = %spec.module_id, pid = active_child.pid,
9033                                wait_secs = runtime.register_timeout.as_secs(),
9034                                "supervised module registration_timeout: first HELLO deadline expired; stopping child");
9035                            active_child.spawn_failure = Some("registration_timeout".into());
9036                            if let Err(error) = stop_unregistered_child(active_child).await {
9037                                error!(module_id = %spec.module_id, %error, "failed to stop unregistered child");
9038                                fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
9039                                    &runtime.spawn_events, format!("registration_timeout: {error}"),
9040                                    &runtime.failure_context(true));
9041                                child = None;
9042                            }
9043                            // The ordinary exit handler records the child's exit,
9044                            // spends crash budget, and schedules recovery.
9045                            continue;
9046                        }
9047                    }
9048                    if health_probe.due() {
9049                        run_health_probe_cycle(
9050                            &spec,
9051                            &runtime,
9052                            &registry,
9053                            &process_liveness,
9054                            &snapshot,
9055                            &mut child,
9056                        ).await;
9057                        if child.is_none() {
9058                            runtime.start_requester = None;
9059                            runtime.pending_activity_restart = false;
9060                        }
9061                        if child.is_some() {
9062                            health_probe.schedule_next(&spec, runtime.health.cadence);
9063                        }
9064                    }
9065                }
9066            }
9067        } else if let Some(pending) = pending_respawn.clone() {
9068            tokio::select! {
9069                _ = runtime.child_roster.closed() => {
9070                    pending_respawn = None;
9071                    let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9072                        state.state = ModuleState::Stopped;
9073                        state.respawn_pending = false;
9074                    });
9075                    containment::terminate(&runtime.child_roster.containment).await;
9076                }
9077                _ = async {
9078                    sleep_until(pending.deadline).await;
9079                    if let Some(delivery) = &runtime.config_delivery {
9080                        delivery.unfenced(&spec.module_id).await;
9081                    }
9082                } => {
9083                    pending_respawn = None;
9084                    let failure = pending.failure_context(&runtime);
9085                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = false);
9086                    // A command handled below while the backoff elapsed may
9087                    // have stopped the module; never respawn past an operator's
9088                    // disable or drain.
9089                    if !respawn_still_pending(&snapshot) {
9090                        continue;
9091                    }
9092                    // The daemon began shutting down during the backoff: the
9093                    // spawn would be refused anyway, and refusing it here
9094                    // leaves the module stopped instead of reporting a
9095                    // failed restart.
9096                    if runtime.child_roster.is_closed() {
9097                        let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9098                            state.state = ModuleState::Stopped;
9099                        });
9100                        debug!(module_id = %spec.module_id, "crash respawn cancelled by daemon shutdown");
9101                        continue;
9102                    }
9103                    if let Err(err) = release_dead_registration(
9104                        &registry,
9105                        runtime.forwarding.as_deref(),
9106                        &snapshot,
9107                        &spec.module_id,
9108                        &failure,
9109                    ).await {
9110                        record_approved_attempt_failure(&spec, &snapshot, &failure, &err);
9111                        error!(module_id = %spec.module_id, error = %err, "registration did not release before restart");
9112                        continue;
9113                    }
9114
9115                    if matches!(pending.kind, RespawnKind::Reload) {
9116                        let reply = runtime.deferred_reload_reply.lock().unwrap_or_else(|p| p.into_inner()).take();
9117                        let result = finish_reload_child(&spec, &runtime, &registry, &process_liveness, &snapshot, &mut child).await;
9118                        if matches!(result, Err(SuperviseError::ConfigDeliveryDeferred { .. })) {
9119                            *runtime.deferred_reload_reply.lock().unwrap_or_else(|p| p.into_inner()) = reply;
9120                            continue;
9121                        }
9122                        if result.is_ok() && runtime.pending_activity_restart {
9123                            runtime.record_activity_transition("subc.module_restarted", &spec.module_id, runtime.start_requester.clone());
9124                        }
9125                        runtime.pending_activity_restart = false;
9126                        if let Some(reply) = reply { let _ = reply.send(result); }
9127                        continue;
9128                    }
9129                    process_liveness.track(spec.module_id.clone(), Arc::clone(&snapshot));
9130                    match spawn_and_mark_running_async(&spec, &runtime, &snapshot).await {
9131                        Ok(next_child) => {
9132                            child = Some(next_child);
9133                            if runtime.pending_activity_restart {
9134                                runtime.record_activity_transition("subc.module_restarted", &spec.module_id, runtime.start_requester.clone());
9135                                runtime.pending_activity_restart = false;
9136                            }
9137                            debug!(module_id = %spec.module_id, "supervised module restarted after crash");
9138                        }
9139                        Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9140                            pending_respawn = Some(PendingRespawn { deadline:Instant::now()+CONFIG_ADMISSION_RETRY_DELAY, ..pending });
9141                            let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = true);
9142                        }
9143                        Err(SuperviseError::ConfigHeld { .. }) => {
9144                            let _ = hold_config_spawn(&spec, &runtime, &snapshot, &failure);
9145                            runtime.pending_activity_restart = false;
9146                            process_liveness.untrack_if_current(&spec.module_id, &snapshot);
9147                        }
9148                        Err(err) => {
9149                            fail_snapshot(&snapshot, Some(&spec.module_id), None, &failure);
9150                            record_approved_attempt_failure(&spec, &snapshot, &failure, &err);
9151                            process_liveness.untrack_if_current(&spec.module_id, &snapshot);
9152                            error!(module_id = %spec.module_id, error = %err, "failed to restart supervised module");
9153                        }
9154                    }
9155                }
9156                command = commands.recv() => {
9157                    let Some(command) = command else {
9158                        containment::terminate(&runtime.child_roster.containment).await;
9159                        return;
9160                    };
9161                    if !handle_supervisor_command(
9162                        command,
9163                        &mut spec,
9164                        &mut runtime,
9165                        &registry,
9166                        &process_liveness,
9167                        &snapshot,
9168                        &mut child,
9169                        &mut commands,
9170                        &mut requeued,
9171                    ).await {
9172                        containment::terminate(&runtime.child_roster.containment).await;
9173                        return;
9174                    }
9175                    // Reconcile the pending respawn with what the command did:
9176                    // a start may already have spawned a fresh child,
9177                    // while a disable or drain moved the snapshot out of the
9178                    // state the respawn was counting down from.
9179                    if child.is_some() || !respawn_still_pending(&snapshot) {
9180                        pending_respawn = None;
9181                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = false);
9182                    }
9183                }
9184            }
9185        } else {
9186            let slow_retry = lock_snapshot(&snapshot).ok().and_then(|state| {
9187                (state.enabled && state.state == ModuleState::Failed)
9188                    .then_some(state.failed_retry.pending)
9189                    .flatten()
9190            });
9191            let command = if lock_snapshot(&snapshot)
9192                .is_ok_and(|state| state.waiting_for_previous_pid.is_some())
9193            {
9194                tokio::select! {
9195                    command = commands.recv() => command,
9196                    _ = previous_instance_recheck.tick() => {
9197                        if runtime.child_roster.previous_instance_pid(&spec.module_id).is_none() {
9198                            let enabled = lock_snapshot(&snapshot).is_ok_and(|state| state.enabled);
9199                            if enabled && !runtime.child_roster.is_closed() {
9200                                process_liveness.track(spec.module_id.clone(), Arc::clone(&snapshot));
9201                                match spawn_and_mark_running_async(&spec, &runtime, &snapshot).await {
9202                                    Ok(next_child) => child = Some(next_child),
9203                                    Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9204                                        let _ = defer_config_spawn(&spec, &runtime, &snapshot, RespawnKind::Spawn, &runtime.failure_context(true));
9205                                    }
9206                                    Err(SuperviseError::ConfigHeld { .. }) => {
9207                                        let _ = hold_config_spawn(&spec, &runtime, &snapshot, &runtime.failure_context(true));
9208                                    }
9209                                    Err(error) => {
9210                                        fail_snapshot(&snapshot, Some(&spec.module_id), None, &runtime.failure_context(true));
9211                                        error!(module_id = %spec.module_id, %error, "failed to start module after its previous instance exited");
9212                                    }
9213                                }
9214                            } else {
9215                                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9216                                    state.waiting_for_previous_pid = None;
9217                                    state.waiting_for_previous_detail = None;
9218                                });
9219                            }
9220                        }
9221                        continue;
9222                    }
9223                }
9224            } else {
9225                tokio::select! {
9226                    biased;
9227                    command = commands.recv() => command,
9228                    _ = async {
9229                        match slow_retry {
9230                            Some(retry) => sleep_until(retry.deadline).await,
9231                            None => std::future::pending().await,
9232                        }
9233                    } => {
9234                        let retry = slow_retry.expect("only a scheduled slow retry can wake");
9235                        let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9236                            state.failed_retry.pending = None;
9237                        });
9238                        if runtime.child_roster.is_closed() {
9239                            continue;
9240                        }
9241                        info!(module_id = %spec.module_id, attempt = retry.attempt,
9242                            delay_secs = retry.delay.as_secs(), "starting failed module retry");
9243                        if let Err(error) = set_child_enabled(
9244                            &spec, &runtime, &registry, &process_liveness, &snapshot, &mut child, true,
9245                            &runtime.failure_context(true),
9246                        ).await {
9247                            error!(module_id = %spec.module_id, %error, "failed module retry could not start");
9248                        }
9249                        continue;
9250                    }
9251                }
9252            };
9253            let Some(command) = command else {
9254                containment::terminate(&runtime.child_roster.containment).await;
9255                return;
9256            };
9257            if !handle_supervisor_command(
9258                command,
9259                &mut spec,
9260                &mut runtime,
9261                &registry,
9262                &process_liveness,
9263                &snapshot,
9264                &mut child,
9265                &mut commands,
9266                &mut requeued,
9267            )
9268            .await
9269            {
9270                containment::terminate(&runtime.child_roster.containment).await;
9271                return;
9272            }
9273        }
9274    }
9275}
9276
9277// Preserve the deadline until the future is polled. Starting a relative sleep
9278// after the executor yields would restart part of the countdown.
9279async fn supervisor_sleep(wake_at: Option<Instant>) {
9280    match wake_at {
9281        Some(deadline) => sleep_until(deadline).await,
9282        None => std::future::pending().await,
9283    }
9284}
9285
9286fn log_crash_respawn(module_id: &str, schedule: CrashRestartSchedule) {
9287    info!(
9288        module_id,
9289        restart_in_window = schedule.restart_in_window,
9290        delay_ms = schedule.delay.as_millis() as u64,
9291        "respawning after crash"
9292    );
9293}
9294
9295/// Whether the respawn a backoff was counting down to is still wanted. A
9296/// disable or drain handled while the backoff elapsed moves the snapshot out
9297/// of `Restarting`, and the operator's stop must win over the pending respawn,
9298/// so every sleep-then-spawn path re-validates against the live snapshot
9299/// instead of assuming the state it left behind still holds.
9300fn respawn_still_pending(snapshot: &SharedSnapshot) -> bool {
9301    matches!(
9302        lock_snapshot(snapshot),
9303        Ok(state) if state.enabled && state.state == ModuleState::Restarting
9304    )
9305}
9306
9307enum NextAction {
9308    Stop {
9309        registration_released: bool,
9310    },
9311    Restart {
9312        schedule: Option<CrashRestartSchedule>,
9313    },
9314}
9315
9316#[allow(clippy::too_many_arguments)]
9317async fn handle_supervisor_command(
9318    command: SupervisorCommand,
9319    spec: &mut ModuleSpec,
9320    runtime: &mut SupervisorRuntimeConfig,
9321    registry: &Arc<Registry>,
9322    process_liveness: &SupervisorProcessLiveness,
9323    snapshot: &SharedSnapshot,
9324    child: &mut Option<SupervisedChild>,
9325    commands: &mut mpsc::Receiver<SupervisorCommand>,
9326    requeued: &mut VecDeque<SupervisorCommand>,
9327) -> bool {
9328    if let SupervisorCommand::SetEnabled {
9329        enabled: true,
9330        reset_budget: false,
9331        reply,
9332        ..
9333    } = command
9334    {
9335        let parked = lock_snapshot(snapshot).ok().and_then(|state| {
9336            (state.config_hold_parked
9337                && state.enabled
9338                && !state.process_alive
9339                && child.is_none()
9340                && state.state == ModuleState::Stopped)
9341                .then(|| {
9342                    (
9343                        state.config_hold_daemon_initiated,
9344                        state.config_hold_approval.clone(),
9345                    )
9346                })
9347        });
9348        // Clearing a configuration-delivery block must not restart a child that
9349        // exited on its own or exhausted its crash budget. Resume only an actor
9350        // stopped by a configuration hold; otherwise leave its slow retry alone.
9351        let result = if let Some((daemon_initiated, approval)) = parked {
9352            runtime.recovery_is_daemon = daemon_initiated;
9353            let failure = FailureContext {
9354                approval,
9355                ..runtime.failure_context(daemon_initiated)
9356            };
9357            let result = set_child_enabled_with_budget_policy(
9358                spec,
9359                runtime,
9360                registry,
9361                process_liveness,
9362                snapshot,
9363                child,
9364                true,
9365                &failure,
9366                false,
9367            )
9368            .await;
9369            if let Err(error) = &result {
9370                record_approved_attempt_failure(spec, snapshot, &failure, error);
9371            }
9372            result
9373        } else {
9374            Ok(false)
9375        };
9376        let _ = reply.send(result);
9377        return true;
9378    }
9379    let blocked = runtime
9380        .config_delivery
9381        .as_ref()
9382        .and_then(|delivery| delivery.0.check_module_hold(&spec.module_id).err())
9383        .filter(|error| error.code != "config_delivery_deferred")
9384        .map(|error| {
9385            config_delivery::gate_hold_error(spec, error, runtime.config_delivery.as_ref())
9386        })
9387        .or_else(|| recovery_block_error(spec, &runtime.child_roster))
9388        .or_else(|| {
9389            runtime
9390                .child_roster
9391                .previous_instance(&spec.module_id)
9392                .map(|(pid, reason)| previous_instance_error(spec, pid, reason))
9393        });
9394    let command = if let Some(error) = blocked {
9395        match command {
9396            SupervisorCommand::Restart { reply, .. } | SupervisorCommand::Reload { reply, .. } => {
9397                let _ = reply.send(Err(error));
9398                return true;
9399            }
9400            SupervisorCommand::Swap { reply, .. } => {
9401                let _ = reply.send(Err(error));
9402                return true;
9403            }
9404            SupervisorCommand::ConfigApplyRestart { .. } => return true,
9405            SupervisorCommand::SetEnabled {
9406                enabled: true,
9407                requester,
9408                reply,
9409                ..
9410            } => {
9411                if matches!(error, SuperviseError::ConfigHeld { .. })
9412                    && lock_snapshot(snapshot).is_ok_and(|state| !state.enabled)
9413                    && runtime
9414                        .config_delivery
9415                        .as_ref()
9416                        .is_some_and(|delivery| delivery.0.can_stage_unstamp_enable())
9417                {
9418                    // Stage only the pending unstamp's desired state. A stamped
9419                    // unapproved actor stays refused; admission release starts
9420                    // an unstamped actor only after reconciliation completes.
9421                    let mut changed = false;
9422                    let result = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9423                        changed = !state.enabled;
9424                        state.enabled = true;
9425                        if child.is_none() && state.waiting_for_previous_pid.is_none() {
9426                            state.state = ModuleState::Starting;
9427                            state.failed_retry.cancel();
9428                        }
9429                    })
9430                    .and_then(|_| {
9431                        if child.is_none()
9432                            && lock_snapshot(snapshot)?.waiting_for_previous_pid.is_none()
9433                        {
9434                            hold_config_spawn(
9435                                spec,
9436                                runtime,
9437                                snapshot,
9438                                &runtime.failure_context(false),
9439                            )?;
9440                        }
9441                        Ok(changed)
9442                    });
9443                    if result.is_ok() && changed {
9444                        runtime.start_requester = requester;
9445                    }
9446                    let _ = reply.send(result);
9447                    return true;
9448                }
9449                let _ = reply.send(Err(error));
9450                return true;
9451            }
9452            other => other,
9453        }
9454    } else {
9455        command
9456    };
9457    // A refused start or restart leaves the Failed actor's existing recovery
9458    // deadline intact. Cancel only after the command passes admission.
9459    if matches!(
9460        command,
9461        SupervisorCommand::Drain { .. }
9462            | SupervisorCommand::Retire { .. }
9463            | SupervisorCommand::SetEnabled { .. }
9464            | SupervisorCommand::Restart { .. }
9465    ) {
9466        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9467            state.failed_retry.cancel();
9468        });
9469    }
9470    match command {
9471        SupervisorCommand::ApprovedConfiguration { approved, reply } => {
9472            let result = async {
9473                let next = approved.module_entry(&spec.module_id).map_err(|error| {
9474                    SuperviseError::InvalidSpec { reason: error.to_string() }
9475                })?;
9476                let retry_approved_failure = {
9477                    let mut state = lock_snapshot(snapshot)?;
9478                    if let Some((generation, detail)) = &state.approved_start_failure {
9479                        if *generation == approved.identity() && next.enabled {
9480                            return Err(SuperviseError::Spawn {
9481                                program: spec.program.clone(),
9482                                source: std::io::Error::other(detail.clone()),
9483                                cgroup_path: None,
9484                            });
9485                        }
9486                    }
9487                    let retry = state.approved_start_failure.is_some();
9488                    state.approved_start_failure = None;
9489                    retry
9490                };
9491                stage_supervisor_configuration(
9492                    spec, runtime, snapshot, next.module_spec(), next.health,
9493                    next.drain_timeout_ms,
9494                );
9495                runtime.restart_policy = next.restart;
9496                runtime.register_timeout = next.register_timeout;
9497                if let Some(active) = child.as_mut()
9498                    .filter(|child| child.registration_deadline.is_some())
9499                {
9500                    active.registration_deadline = Some(active.spawned_at + next.register_timeout);
9501                }
9502                let enabled = lock_snapshot(snapshot)?.enabled;
9503                // An approval retries a changed failed entry or its own earlier
9504                // failed start, not an unrelated crash-budget failure. For an
9505                // unchanged entry, reconciled means the approved configuration
9506                // is effective; it does not claim the process has recovered.
9507                // A terminal gate stop is different: a new approval owns its
9508                // recovery even when the daemon entry itself did not change.
9509                let retry_gate_stopped = lock_snapshot(snapshot)?
9510                    .needs_approved_gate_restart(&approved.identity());
9511                let retry_failed = enabled && child.is_none()
9512                    && ((lock_snapshot(snapshot)?.state == ModuleState::Failed
9513                        && (retry_approved_failure || approved.changes_entry(&spec.module_id)))
9514                        || retry_gate_stopped);
9515                if retry_failed {
9516                    // This approval owns a new start, so the failed attempt's
9517                    // daemon retry must not survive either result of that start.
9518                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
9519                        state.failed_retry.cancel();
9520                        if retry_gate_stopped {
9521                            state.stop_reason = None;
9522                            state.config_exit_failed_approval = None;
9523                        }
9524                    })?;
9525                }
9526                if enabled != next.enabled || retry_failed {
9527                    let failure = FailureContext {
9528                        approval: next.enabled.then(|| approved.identity()),
9529                        ..runtime.failure_context(false)
9530                    };
9531                    let held = next.enabled && runtime.config_delivery.as_ref()
9532                        .is_some_and(|delivery| delivery.0.has_recorded_admission_hold(&spec.module_id)
9533                            || delivery.0.check_module_hold(&spec.module_id).is_err_and(|error| error.code == "config_delivery_deferred"));
9534                    if held {
9535                        // Preserve module-delivery failure/recovery holds. The
9536                        // admission release starts the actor when its own hold ends.
9537                        reset_restart_count(snapshot, &spec.module_id)?;
9538                        update_snapshot(snapshot, Some(&spec.module_id), |state| {
9539                            state.enabled = true;
9540                            if child.is_none() && state.waiting_for_previous_pid.is_none() {
9541                                state.state = ModuleState::Starting;
9542                            }
9543                        })?;
9544                        if child.is_none() && lock_snapshot(snapshot)?.waiting_for_previous_pid.is_none() {
9545                            hold_config_spawn(spec, runtime, snapshot, &failure)?;
9546                        }
9547                    } else {
9548                        match set_child_enabled_with_budget_policy(
9549                            spec, runtime, registry, process_liveness, snapshot, child,
9550                            next.enabled, &failure, true,
9551                        ).await {
9552                            Ok(_) => {},
9553                            Err(SuperviseError::ConfigHeld { .. }) if next.enabled => {},
9554                            Err(error) => return Err(error),
9555                        }
9556                        if !next.enabled {
9557                            containment::terminate(&runtime.child_roster.containment).await;
9558                        }
9559                    }
9560                }
9561                if (child.as_ref().is_some_and(|child| child.registration_spawn.is_some() && child.admission_base.is_none())
9562                        || (child.is_none() && lock_snapshot(snapshot)?.state == ModuleState::Restarting
9563                            && runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.stamp_channel_cutover_pending())))
9564                    && runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.module_is_gated(&spec.module_id))
9565                {
9566                    let failure = FailureContext {
9567                        approval: Some(approved.identity()),
9568                        ..runtime.failure_context(false)
9569                    };
9570                    // A stamp cannot adopt an unverified legacy process, even
9571                    // when its approved replacement no longer speaks subc.
9572                    // Stopping that process spends no crash restart budget.
9573                    if child.is_some() {
9574                        restart_child_with_budget_policy(spec, runtime, registry,
9575                            process_liveness, snapshot, child, runtime.drain_timeout, false).await?;
9576                    }
9577                    // The stamp is already committed. A deferred or held launch
9578                    // belongs to the normal retry/hold loop, not a failed apply.
9579                    update_snapshot(snapshot, Some(&spec.module_id), |state| state.respawn_pending = false)?;
9580                    match spawn_and_mark_running_async(spec, runtime, snapshot).await {
9581                        Ok(replacement) => *child = Some(replacement),
9582                        Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9583                            defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, &failure)?;
9584                        }
9585                        Err(SuperviseError::ConfigHeld { .. }) => hold_config_spawn(spec, runtime, snapshot, &failure)?,
9586                        Err(error) => {
9587                            fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
9588                            return Err(error);
9589                        }
9590                    }
9591                }
9592                info!(module_id=%spec.module_id, config_generation=approved.generation(), "approved daemon entry reconciled");
9593                Ok(())
9594            }
9595            .await;
9596            if let Err(error) = &result {
9597                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9598                    if state.enabled
9599                        && state.state == ModuleState::Failed
9600                        && state
9601                            .approved_start_failure
9602                            .as_ref()
9603                            .is_none_or(|(generation, _)| *generation != approved.identity())
9604                    {
9605                        state.approved_start_failure =
9606                            Some((approved.identity(), error.to_string()));
9607                    }
9608                });
9609            }
9610            let _ = reply.send(result);
9611            true
9612        }
9613        SupervisorCommand::ConfigPolicyProbe {
9614            connection,
9615            generation,
9616            attempt,
9617        } => {
9618            let Some(delivery) = &runtime.config_delivery else {
9619                return true;
9620            };
9621            let Ok(gate) = delivery.0.module_gate(&spec.module_id) else {
9622                return true;
9623            };
9624            let guard = gate.lock().await;
9625            let pending = delivery
9626                .0
9627                .on_blocking(move |owner| {
9628                    owner.policy_probe_pending(connection, generation, attempt)
9629                })
9630                .await
9631                .unwrap_or(false)
9632                && child.is_some()
9633                && registry
9634                    .get_module(&spec.module_id)
9635                    .ok()
9636                    .flatten()
9637                    .is_some_and(|registration| registration.connection_id == connection);
9638            drop(guard);
9639            if pending {
9640                run_health_probe_cycle(spec, runtime, registry, process_liveness, snapshot, child)
9641                    .await;
9642            }
9643            true
9644        }
9645        SupervisorCommand::ConfigApplyRestart {
9646            generation,
9647            supersedes_swap,
9648        } => {
9649            let Some(owner) = runtime
9650                .config_delivery
9651                .as_ref()
9652                .map(|delivery| delivery.0.clone())
9653            else {
9654                return true;
9655            };
9656            let Ok(gate) = owner.module_gate(&spec.module_id) else {
9657                return true;
9658            };
9659            let _guard = gate.lock().await;
9660            let spawn = child
9661                .as_ref()
9662                .and_then(|child| child.config_delivery.clone());
9663            let module = spec.module_id.clone();
9664            let current = owner
9665                .on_blocking(move |owner| {
9666                    Ok((supersedes_swap
9667                        || owner
9668                            .pending_config_restarts()?
9669                            .contains(&(module.clone(), generation)))
9670                        && owner.requires_fresher_spawn(&module, spawn.as_ref())?
9671                            == Some(generation))
9672                })
9673                .await
9674                .unwrap_or(false);
9675            if !current
9676                || !lock_snapshot(snapshot).is_ok_and(|state| {
9677                    state.enabled && !state.respawn_pending && state.process_alive
9678                })
9679            {
9680                return true;
9681            }
9682            drop(_guard);
9683            info!(module_id=%spec.module_id, config_generation=generation, "approved configuration restart preserves the crash budget");
9684            if let Err(error) = restart_child_with_budget_policy(
9685                spec,
9686                runtime,
9687                registry,
9688                process_liveness,
9689                snapshot,
9690                child,
9691                runtime.drain_timeout,
9692                false,
9693            )
9694            .await
9695            {
9696                warn!(module_id=%spec.module_id, %error, "approved configuration restart could not be scheduled");
9697            }
9698            true
9699        }
9700        SupervisorCommand::ConfigExitHold { reply } => {
9701            // A notification owns no start, backoff, reload reply or previous-
9702            // instance wait. Only an idle, registered initial start has no work
9703            // to preserve; its initialized startup context can be parked here.
9704            let idle_start = child.is_none()
9705                && lock_snapshot(snapshot).is_ok_and(|state| {
9706                    state.enabled
9707                        && state.state == ModuleState::Starting
9708                        && !state.process_alive
9709                        && !state.respawn_pending
9710                        && state.waiting_for_previous_pid.is_none()
9711                        && state.waiting_for_previous_detail.is_none()
9712                        && state.failed_retry.pending.is_none()
9713                })
9714                && runtime
9715                    .scheduled_respawn
9716                    .lock()
9717                    .unwrap_or_else(|p| p.into_inner())
9718                    .is_none()
9719                && runtime
9720                    .deferred_reload_reply
9721                    .lock()
9722                    .unwrap_or_else(|p| p.into_inner())
9723                    .is_none();
9724            let result = if idle_start {
9725                try_park_config_attempt(
9726                    spec,
9727                    runtime,
9728                    snapshot,
9729                    &runtime.failure_context(runtime.recovery_is_daemon),
9730                    None,
9731                )
9732                .map(|_| ())
9733            } else {
9734                Ok(())
9735            };
9736            let _ = reply.send(result);
9737            true
9738        }
9739        SupervisorCommand::ConfigDeliveryFailed { connection, hold } => {
9740            if registry
9741                .get_module(&spec.module_id)
9742                .ok()
9743                .flatten()
9744                .is_none_or(|registration| registration.connection_id != connection)
9745            {
9746                return true;
9747            }
9748            runtime.recovery_is_daemon = true;
9749            // With a recoverable generation, delivery-failure recovery spends
9750            // one crash-budget entry: the module rejected its configuration.
9751            // Approved configuration restarts spend none.
9752            if hold {
9753                let notice = begin_forwarding_drain_if_configured(
9754                    spec,
9755                    runtime,
9756                    registry,
9757                    snapshot,
9758                    Some(true),
9759                    RouteCloseReason::Disable,
9760                )
9761                .await;
9762                if let Ok(notice) = notice {
9763                    let drained = drain_optional_child(
9764                        &spec.module_id,
9765                        spec.protocol,
9766                        notice,
9767                        registry,
9768                        runtime.forwarding.as_deref(),
9769                        snapshot,
9770                        &runtime.terminal_ring,
9771                        &runtime.spawn_events,
9772                        child,
9773                        runtime.drain_timeout,
9774                        ModuleState::Failed,
9775                        Some(true),
9776                        &runtime.failure_context(true),
9777                    )
9778                    .await;
9779                    if drained.is_ok() {
9780                        match try_park_config_attempt(
9781                            spec,
9782                            runtime,
9783                            snapshot,
9784                            &runtime.failure_context(true),
9785                            None,
9786                        ) {
9787                            Ok(true) => {}
9788                            Ok(false) => {
9789                                if let Err(error) = budgeted_restart_child(
9790                                    spec,
9791                                    runtime,
9792                                    registry,
9793                                    process_liveness,
9794                                    snapshot,
9795                                    child,
9796                                    SupervisorHealthStatus::Unknown,
9797                                    Some("configuration delivery failed after its hold ended"),
9798                                    unix_ms_now(),
9799                                    false,
9800                                )
9801                                .await
9802                                {
9803                                    warn!(module_id=%spec.module_id, %error, "configuration failure restart could not be scheduled");
9804                                }
9805                            }
9806                            Err(error) => {
9807                                warn!(module_id=%spec.module_id, %error, "configuration failure could not be parked")
9808                            }
9809                        }
9810                    }
9811                }
9812            } else if let Err(error) = budgeted_restart_child(
9813                spec,
9814                runtime,
9815                registry,
9816                process_liveness,
9817                snapshot,
9818                child,
9819                SupervisorHealthStatus::Unknown,
9820                Some("configuration delivery failed"),
9821                unix_ms_now(),
9822                false,
9823            )
9824            .await
9825            {
9826                warn!(module_id=%spec.module_id, %error, "configuration failure restart could not be scheduled");
9827            }
9828            true
9829        }
9830        SupervisorCommand::Drain { requester, reply } => {
9831            // A plain stop runs no forwarding drain, so nothing reaches the
9832            // module over its connection before the wait: ask by signal.
9833            let result = drain_optional_child(
9834                &spec.module_id,
9835                spec.protocol,
9836                StopNotice::NotSent,
9837                registry,
9838                runtime.forwarding.as_deref(),
9839                snapshot,
9840                &runtime.terminal_ring,
9841                &runtime.spawn_events,
9842                child,
9843                runtime.drain_timeout,
9844                ModuleState::Stopped,
9845                None,
9846                &FailureContext::operator(),
9847            )
9848            .await;
9849            containment::terminate(&runtime.child_roster.containment).await;
9850            let registration_released = result.is_ok();
9851            if registration_released {
9852                runtime.record_activity_transition(
9853                    "subc.module_stopped",
9854                    &spec.module_id,
9855                    requester,
9856                );
9857            }
9858            let _ = reply.send(result);
9859            if registration_released {
9860                process_liveness.untrack_if_current(&spec.module_id, snapshot);
9861            }
9862            false
9863        }
9864        SupervisorCommand::Retire { requester, reply } => {
9865            let result = async {
9866                let stop_notice = begin_forwarding_drain_if_configured(
9867                    spec,
9868                    runtime,
9869                    registry,
9870                    snapshot,
9871                    None,
9872                    RouteCloseReason::Disable,
9873                )
9874                .await?;
9875                drain_optional_child(
9876                    &spec.module_id,
9877                    spec.protocol,
9878                    stop_notice,
9879                    registry,
9880                    runtime.forwarding.as_deref(),
9881                    snapshot,
9882                    &runtime.terminal_ring,
9883                    &runtime.spawn_events,
9884                    child,
9885                    runtime.drain_timeout,
9886                    ModuleState::Stopped,
9887                    None,
9888                    &FailureContext::operator(),
9889                )
9890                .await
9891            }
9892            .await;
9893            containment::terminate(&runtime.child_roster.containment).await;
9894            let registration_released = result.is_ok();
9895            if registration_released {
9896                runtime.record_activity_transition(
9897                    "subc.module_stopped",
9898                    &spec.module_id,
9899                    requester,
9900                );
9901            }
9902            let _ = reply.send(result);
9903            if registration_released {
9904                process_liveness.untrack_if_current(&spec.module_id, snapshot);
9905            }
9906            false
9907        }
9908        SupervisorCommand::Restart {
9909            requester,
9910            drain_timeout_ms,
9911            received_at_generation,
9912            queued_at,
9913            reply,
9914        } => {
9915            // Without this line a restart that waited in the queue (behind a
9916            // health probe cycle or another command) was invisible: the log
9917            // showed only the drain timing out, minutes after the operator's call.
9918            info!(
9919                module_id = %spec.module_id,
9920                queued_ms = u64::try_from(queued_at.elapsed().as_millis()).unwrap_or(u64::MAX),
9921                "restart command dequeued"
9922            );
9923            // ACK AT INITIATION, not completion. The blocking form deadlocked any
9924            // caller whose own request lane rides the module being restarted: the
9925            // caller's in-flight request keeps the drain from quiescing, the drain
9926            // keeps the restart from completing, and the completion keeps the reply
9927            // from releasing the caller — so the drain always timed out and cut the
9928            // initiator with a GOODBYE, even on a healthy module. Replying once the
9929            // restart is validated lets a self-lane caller settle, which is exactly
9930            // what makes the drain succeed. Completion is observable via
9931            // supervisor.list / module status; a post-ack failure lands the module
9932            // in a visible terminal state below rather than in a reply nobody can
9933            // receive.
9934            let validation = match lock_snapshot(snapshot) {
9935                Ok(state) if !state.enabled => Err(SuperviseError::Disabled {
9936                    module_id: spec.module_id.clone(),
9937                }),
9938                Ok(_) => Ok(()),
9939                Err(err) => Err(err),
9940            };
9941            let initiated = validation.is_ok();
9942            let _ = reply.send(validation);
9943            // A restart asks for a fresh process. Commands run one at a time,
9944            // so a restart queued behind another restart (two operator calls
9945            // in quick succession) is dequeued the moment the first one has
9946            // spawned its replacement -- before that process has sent HELLO.
9947            // Running it would drain and kill the process the first restart
9948            // just produced, which is the opposite of what both callers asked
9949            // for. If a process spawned after this request was received is
9950            // still supervised, the request is already satisfied. Not when the
9951            // configuration changed since that spawn: then the newer process
9952            // predates the spec this restart may exist to apply.
9953            // Generation publication can lag a child that is already serving
9954            // while its identity is recorded. Only process creation after request
9955            // receipt satisfies a restart, not publication after receipt.
9956            let satisfied_by_generation = if initiated
9957                && child
9958                    .as_ref()
9959                    .is_some_and(|child| child.spawned_at > queued_at)
9960            {
9961                lock_snapshot(snapshot).ok().and_then(|state| {
9962                    (!state.configuration_updated_since_spawn).then_some(state.spawn_generation)
9963                })
9964            } else {
9965                None
9966            };
9967            let satisfied_by_pending = initiated
9968                && child.is_none()
9969                && lock_snapshot(snapshot).ok().is_some_and(|mut state| {
9970                    // No child exists yet, so this replacement will necessarily
9971                    // be created after the queued request, unlike a published
9972                    // generation whose process may already have been serving.
9973                    let pending = state.respawn_pending && !state.configuration_updated_since_spawn;
9974                    if pending {
9975                        state.coalesced_restart_pending = true;
9976                    }
9977                    pending
9978                });
9979            if satisfied_by_pending {
9980                debug!(module_id = %spec.module_id, "restart coalesced into the pending replacement");
9981            } else if let Some(generation) = satisfied_by_generation {
9982                info!(
9983                    module_id = %spec.module_id,
9984                    received_at_generation,
9985                    "restart already satisfied by generation {generation}; not restarting again"
9986                );
9987            } else if initiated {
9988                // Precedence: this restart's operator override, else the module's
9989                // configured budget (already resolved into the runtime).
9990                let drain_timeout = drain_timeout_ms
9991                    .map(Duration::from_millis)
9992                    .unwrap_or(runtime.drain_timeout);
9993                if let Err(err) = restart_child(
9994                    spec,
9995                    runtime,
9996                    registry,
9997                    process_liveness,
9998                    snapshot,
9999                    child,
10000                    drain_timeout,
10001                )
10002                .await
10003                {
10004                    warn!(
10005                        module_id = %spec.module_id,
10006                        error = %err,
10007                        "operator restart failed after initiation ack; module state carries the outcome"
10008                    );
10009                    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10010                        state.state = ModuleState::Failed;
10011                        clear_current_process_facts(state);
10012                    });
10013                } else {
10014                    runtime.start_requester = requester;
10015                    runtime.pending_activity_restart = true;
10016                }
10017            }
10018            true
10019        }
10020        SupervisorCommand::Reload { requester, reply } => {
10021            let result =
10022                reload_child(spec, runtime, registry, process_liveness, snapshot, child).await;
10023            if result.is_ok() {
10024                runtime.start_requester = requester;
10025                runtime.pending_activity_restart = true;
10026            }
10027            if result.is_ok()
10028                && runtime
10029                    .scheduled_respawn
10030                    .lock()
10031                    .unwrap_or_else(|p| p.into_inner())
10032                    .as_ref()
10033                    .is_some_and(|pending| matches!(pending.kind, RespawnKind::Reload))
10034            {
10035                *runtime
10036                    .deferred_reload_reply
10037                    .lock()
10038                    .unwrap_or_else(|p| p.into_inner()) = Some(reply);
10039            } else {
10040                let _ = reply.send(result);
10041            }
10042            true
10043        }
10044        SupervisorCommand::SetEnabled {
10045            enabled,
10046            requester,
10047            reply,
10048            reset_budget,
10049        } => {
10050            let previous_requester = runtime.start_requester.clone();
10051            if enabled {
10052                runtime.start_requester = requester.clone();
10053            }
10054            let result = set_child_enabled_with_budget_policy(
10055                spec,
10056                runtime,
10057                registry,
10058                process_liveness,
10059                snapshot,
10060                child,
10061                enabled,
10062                &runtime.failure_context(false),
10063                reset_budget,
10064            )
10065            .await;
10066            if !enabled {
10067                containment::terminate(&runtime.child_roster.containment).await;
10068            }
10069            if matches!(result, Ok(true)) {
10070                runtime.pending_activity_restart = false;
10071                if enabled {
10072                    runtime.start_requester = requester;
10073                } else {
10074                    runtime.start_requester = None;
10075                    runtime.record_activity_transition(
10076                        "subc.module_disabled",
10077                        &spec.module_id,
10078                        requester,
10079                    );
10080                }
10081            } else {
10082                runtime.start_requester = previous_requester;
10083            }
10084            let _ = reply.send(result);
10085            true
10086        }
10087        SupervisorCommand::UpdateConfiguration {
10088            spec: next_spec,
10089            health,
10090            drain_timeout_ms,
10091            reply,
10092        } => {
10093            if runtime
10094                .config_delivery
10095                .as_ref()
10096                .is_some_and(|delivery| delivery.0.file_configuration_is_gated(&spec.module_id))
10097            {
10098                let _ = reply.send(Err(SuperviseError::ConfigHeld {
10099                    module_id: spec.module_id.clone(),
10100                    code: "config_gated".into(),
10101                    detail: "live file reconfiguration cannot replace stamped authority".into(),
10102                }));
10103                return true;
10104            }
10105            stage_supervisor_configuration(
10106                spec,
10107                runtime,
10108                snapshot,
10109                next_spec,
10110                health,
10111                drain_timeout_ms,
10112            );
10113            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10114                state.configuration_updated_since_spawn = true;
10115            });
10116            let _ = reply.send(Ok(()));
10117            true
10118        }
10119        SupervisorCommand::Swap {
10120            requester,
10121            ready_timeout,
10122            reply,
10123        } => {
10124            if spec.carry_containment
10125                || containment::current(&runtime.child_roster.containment).is_some()
10126            {
10127                let _ = reply.send(Err(SuperviseError::InvalidSpec {
10128                    reason: "a carried container cannot overlap a swap candidate".to_owned(),
10129                }));
10130                return true;
10131            }
10132            let mut swap_runtime = runtime.clone();
10133            swap_runtime.start_requester = requester;
10134            let before = lock_snapshot(snapshot)
10135                .ok()
10136                .map(|state| state.spawn_generation);
10137            let end = swap::run_swap(
10138                spec,
10139                &swap_runtime,
10140                registry,
10141                process_liveness,
10142                snapshot,
10143                child,
10144                commands,
10145                ready_timeout.unwrap_or(DEFAULT_SWAP_READY_TIMEOUT),
10146                reply,
10147            )
10148            .await;
10149            if before
10150                != lock_snapshot(snapshot)
10151                    .ok()
10152                    .map(|state| state.spawn_generation)
10153            {
10154                runtime.start_requester = swap_runtime.start_requester;
10155            }
10156            requeued.extend(end.requeue);
10157            true
10158        }
10159    }
10160}
10161
10162fn stage_supervisor_configuration(
10163    spec: &mut ModuleSpec,
10164    runtime: &mut SupervisorRuntimeConfig,
10165    snapshot: &SharedSnapshot,
10166    next_spec: ModuleSpec,
10167    health: HealthConfig,
10168    drain_timeout_ms: Option<u64>,
10169) {
10170    if let Some(handle) = &runtime.supervisor_handle {
10171        handle.apply_identity_configuration(&next_spec);
10172    }
10173    let launch_changed = *spec != next_spec;
10174    *spec = next_spec;
10175    if launch_changed {
10176        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10177            state.configuration_updated_since_spawn = true
10178        });
10179    }
10180    let health_changed = runtime.health != health;
10181    runtime.health = health;
10182    // Reset the cadence and old endpoint's failure streak on a live
10183    // health-policy change rather than waiting for its old deadline.
10184    if health_changed {
10185        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10186            state.health = ModuleHealthStatus::default();
10187            state.last_probe_evidence = None;
10188        });
10189    }
10190    runtime.drain_timeout = drain_timeout_ms
10191        .map(Duration::from_millis)
10192        .unwrap_or(runtime.default_drain_timeout);
10193    *runtime
10194        .effective_drain_timeout
10195        .lock()
10196        .unwrap_or_else(|p| p.into_inner()) = runtime.drain_timeout;
10197}
10198
10199async fn restart_child(
10200    spec: &ModuleSpec,
10201    runtime: &SupervisorRuntimeConfig,
10202    registry: &Registry,
10203    process_liveness: &SupervisorProcessLiveness,
10204    snapshot: &SharedSnapshot,
10205    child: &mut Option<SupervisedChild>,
10206    drain_timeout: Duration,
10207) -> Result<(), SuperviseError> {
10208    restart_child_with_budget_policy(
10209        spec,
10210        runtime,
10211        registry,
10212        process_liveness,
10213        snapshot,
10214        child,
10215        drain_timeout,
10216        true,
10217    )
10218    .await
10219}
10220
10221#[allow(clippy::too_many_arguments)]
10222async fn restart_child_with_budget_policy(
10223    spec: &ModuleSpec,
10224    runtime: &SupervisorRuntimeConfig,
10225    registry: &Registry,
10226    process_liveness: &SupervisorProcessLiveness,
10227    snapshot: &SharedSnapshot,
10228    child: &mut Option<SupervisedChild>,
10229    drain_timeout: Duration,
10230    reset_budget: bool,
10231) -> Result<(), SuperviseError> {
10232    // Restart cycles a running module; it must not silently start a disabled one.
10233    if !lock_snapshot(snapshot)?.enabled {
10234        return Err(SuperviseError::Disabled {
10235            module_id: spec.module_id.clone(),
10236        });
10237    }
10238    let stop_notice = begin_forwarding_drain_with_timeout(
10239        spec,
10240        runtime,
10241        registry,
10242        snapshot,
10243        None,
10244        RouteCloseReason::Restart,
10245        drain_timeout,
10246    )
10247    .await?;
10248
10249    if child.is_some() {
10250        drain_optional_child(
10251            &spec.module_id,
10252            spec.protocol,
10253            stop_notice,
10254            registry,
10255            runtime.forwarding.as_deref(),
10256            snapshot,
10257            &runtime.terminal_ring,
10258            &runtime.spawn_events,
10259            child,
10260            drain_timeout,
10261            ModuleState::Restarting,
10262            Some(true),
10263            &FailureContext::operator(),
10264        )
10265        .await?;
10266    } else {
10267        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10268            state.enabled = true;
10269            state.state = ModuleState::Restarting;
10270            clear_current_process_facts(state);
10271        })?;
10272        release_dead_registration(
10273            registry,
10274            runtime.forwarding.as_deref(),
10275            snapshot,
10276            &spec.module_id,
10277            &runtime.failure_context(false),
10278        )
10279        .await?;
10280    }
10281
10282    if reset_budget {
10283        reset_restart_count(snapshot, &spec.module_id)?;
10284    }
10285    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10286    schedule_respawn(
10287        runtime,
10288        snapshot,
10289        &spec.module_id,
10290        runtime.restart_policy.backoff,
10291        RespawnKind::Spawn,
10292        false,
10293    )
10294}
10295
10296async fn reload_child(
10297    spec: &ModuleSpec,
10298    runtime: &SupervisorRuntimeConfig,
10299    registry: &Registry,
10300    process_liveness: &SupervisorProcessLiveness,
10301    snapshot: &SharedSnapshot,
10302    child: &mut Option<SupervisedChild>,
10303) -> Result<(), SuperviseError> {
10304    // Reload cycles a running module; it must not silently start a disabled one.
10305    if !lock_snapshot(snapshot)?.enabled {
10306        return Err(SuperviseError::Disabled {
10307            module_id: spec.module_id.clone(),
10308        });
10309    }
10310    let stop_notice = begin_forwarding_drain(
10311        spec,
10312        runtime,
10313        registry,
10314        snapshot,
10315        Some(true),
10316        RouteCloseReason::Reload,
10317    )
10318    .await?;
10319
10320    if child.is_some() {
10321        drain_optional_child(
10322            &spec.module_id,
10323            spec.protocol,
10324            stop_notice,
10325            registry,
10326            runtime.forwarding.as_deref(),
10327            snapshot,
10328            &runtime.terminal_ring,
10329            &runtime.spawn_events,
10330            child,
10331            runtime.drain_timeout,
10332            ModuleState::Restarting,
10333            Some(true),
10334            &FailureContext::operator(),
10335        )
10336        .await?;
10337    } else {
10338        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10339            state.enabled = true;
10340            state.state = ModuleState::Restarting;
10341            clear_current_process_facts(state);
10342        })?;
10343        release_dead_registration(
10344            registry,
10345            runtime.forwarding.as_deref(),
10346            snapshot,
10347            &spec.module_id,
10348            &runtime.failure_context(false),
10349        )
10350        .await?;
10351    }
10352
10353    reset_restart_count(snapshot, &spec.module_id)?;
10354    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10355    schedule_respawn(
10356        runtime,
10357        snapshot,
10358        &spec.module_id,
10359        runtime.restart_policy.backoff,
10360        RespawnKind::Reload,
10361        false,
10362    )
10363}
10364
10365async fn finish_reload_child(
10366    spec: &ModuleSpec,
10367    runtime: &SupervisorRuntimeConfig,
10368    registry: &Registry,
10369    process_liveness: &SupervisorProcessLiveness,
10370    snapshot: &SharedSnapshot,
10371    child: &mut Option<SupervisedChild>,
10372) -> Result<(), SuperviseError> {
10373    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10374    let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
10375        Ok(next_child) => next_child,
10376        Err(error @ SuperviseError::ConfigDeliveryDeferred { .. }) => {
10377            defer_config_spawn(
10378                spec,
10379                runtime,
10380                snapshot,
10381                RespawnKind::Reload,
10382                &runtime.failure_context(runtime.recovery_is_daemon),
10383            )?;
10384            return Err(error);
10385        }
10386        Err(error @ SuperviseError::ConfigHeld { .. }) => {
10387            let failure = runtime.failure_context(runtime.recovery_is_daemon);
10388            if try_park_config_attempt(spec, runtime, snapshot, &failure, None)? {
10389                return Err(error);
10390            }
10391            defer_config_spawn(spec, runtime, snapshot, RespawnKind::Reload, &failure)?;
10392            return Err(SuperviseError::ConfigDeliveryDeferred {
10393                module_id: spec.module_id.clone(),
10394            });
10395        }
10396        Err(err) => {
10397            return handle_reload_spawn_failure(
10398                spec,
10399                runtime,
10400                process_liveness,
10401                snapshot,
10402                child,
10403                format!("new child failed to spawn: {err}"),
10404            )
10405            .await;
10406        }
10407    };
10408    *child = Some(next_child);
10409
10410    let wait_outcome = {
10411        let active_child = child.as_mut().expect("new reload child was just stored");
10412        wait_for_registration_after_reload(
10413            registry,
10414            &spec.module_id,
10415            snapshot,
10416            active_child,
10417            REGISTRY_RELEASE_TIMEOUT,
10418        )
10419        .await?
10420    };
10421
10422    match wait_outcome {
10423        RegistrationWaitOutcome::Registered => {
10424            child
10425                .as_mut()
10426                .expect("registered reload child")
10427                .registration_deadline = None;
10428            debug!(module_id = %spec.module_id, "supervised module reloaded and registered");
10429            Ok(())
10430        }
10431        RegistrationWaitOutcome::Exited(exit_report) => {
10432            if let Some(active_child) = child.as_mut() {
10433                active_child.drain_stderr(&spec.module_id).await;
10434            }
10435            // Keep the exited child's roster guard until its terminal is written.
10436            // Shutdown waits on that guard, not on the child Option used for respawn.
10437            let mut exited_child = child.take().expect("exited reload child is still stored");
10438            #[cfg(test)]
10439            if let Some(gate) = &runtime.test_reload_exit_record_gate {
10440                gate.reached.notify_one();
10441                gate.resume.notified().await;
10442            }
10443            let result = handle_reload_child_registration_failure(
10444                spec,
10445                runtime,
10446                registry,
10447                process_liveness,
10448                snapshot,
10449                child,
10450                ReloadRegistrationFailure {
10451                    exit_report: registration_failure_exit_report(exit_report),
10452                    reason: exited_child
10453                        .spawn_failure
10454                        .clone()
10455                        .unwrap_or_else(|| "new child exited before registering".to_string()),
10456                },
10457            )
10458            .await;
10459            exited_child
10460                .finish_exit(false)
10461                .await
10462                .map_err(|source| SuperviseError::Wait {
10463                    module_id: spec.module_id.clone(),
10464                    source,
10465                })?;
10466            result
10467        }
10468        RegistrationWaitOutcome::TimedOut => {
10469            let mut timed_out_child = child
10470                .take()
10471                .expect("timed-out reload child is still running");
10472            timed_out_child
10473                .start_kill()
10474                .map_err(|source| SuperviseError::Kill {
10475                    module_id: spec.module_id.clone(),
10476                    source,
10477                })?;
10478            let status = timed_out_child
10479                .wait()
10480                .await
10481                .map_err(|source| SuperviseError::Wait {
10482                    module_id: spec.module_id.clone(),
10483                    source,
10484                })?;
10485            timed_out_child.drain_stderr(&spec.module_id).await;
10486            let result = handle_reload_child_registration_failure(
10487                spec,
10488                runtime,
10489                registry,
10490                process_liveness,
10491                snapshot,
10492                child,
10493                ReloadRegistrationFailure {
10494                    exit_report: registration_failure_exit_report(classify_reaped_child_exit(
10495                        snapshot,
10496                        &timed_out_child,
10497                        &status,
10498                    )),
10499                    reason: format!(
10500                        "new child did not register within {:?}",
10501                        REGISTRY_RELEASE_TIMEOUT
10502                    ),
10503                },
10504            )
10505            .await;
10506            timed_out_child
10507                .finish_exit(false)
10508                .await
10509                .map_err(|source| SuperviseError::Wait {
10510                    module_id: spec.module_id.clone(),
10511                    source,
10512                })?;
10513            result
10514        }
10515    }
10516}
10517
10518#[allow(clippy::too_many_arguments)]
10519async fn set_child_enabled(
10520    spec: &ModuleSpec,
10521    runtime: &SupervisorRuntimeConfig,
10522    registry: &Registry,
10523    process_liveness: &SupervisorProcessLiveness,
10524    snapshot: &SharedSnapshot,
10525    child: &mut Option<SupervisedChild>,
10526    enabled: bool,
10527    failure: &FailureContext,
10528) -> Result<bool, SuperviseError> {
10529    set_child_enabled_with_budget_policy(
10530        spec,
10531        runtime,
10532        registry,
10533        process_liveness,
10534        snapshot,
10535        child,
10536        enabled,
10537        failure,
10538        true,
10539    )
10540    .await
10541}
10542
10543#[allow(clippy::too_many_arguments)]
10544async fn set_child_enabled_with_budget_policy(
10545    spec: &ModuleSpec,
10546    runtime: &SupervisorRuntimeConfig,
10547    registry: &Registry,
10548    process_liveness: &SupervisorProcessLiveness,
10549    snapshot: &SharedSnapshot,
10550    child: &mut Option<SupervisedChild>,
10551    enabled: bool,
10552    failure: &FailureContext,
10553    reset_budget: bool,
10554) -> Result<bool, SuperviseError> {
10555    let (current_enabled, current_state, respawn_pending) = {
10556        let state = lock_snapshot(snapshot)?;
10557        (state.enabled, state.state, state.respawn_pending)
10558    };
10559    // `start` (enable on an already-enabled module) heals TERMINAL states instead
10560    // of no-op'ing: a module whose restart budget exhausted (Failed) or that exited
10561    // clean (Stopped) has no live process and no other in-band recovery — the
10562    // operator's start is the explicit recovery act and resets the budget. Without
10563    // this arm the only revival was subc-probe --supervisor-restart in a terminal,
10564    // which the 2026-07-14 aft outage proved is a trap when the failed module is
10565    // the one providing every agent's shell.
10566    let revive_terminal = enabled
10567        && current_enabled
10568        && child.is_none()
10569        && (matches!(current_state, ModuleState::Failed | ModuleState::Stopped)
10570            || (current_state == ModuleState::Restarting && !respawn_pending));
10571    if current_enabled == enabled && !revive_terminal {
10572        return Ok(false);
10573    }
10574
10575    if enabled {
10576        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10577            state.enabled = true;
10578            state.state = ModuleState::Starting;
10579            clear_current_process_facts(state);
10580        })?;
10581        #[cfg(test)]
10582        if runtime.test_seed_stale_facts_before_enable_spawn {
10583            update_snapshot(snapshot, Some(&spec.module_id), |state| {
10584                state.process_alive = true;
10585                state.pid = Some(41);
10586                state.spawned_at_ms = Some(42);
10587                state.spawned_from = Some(PathBuf::from("/spawned/module"));
10588                state.spawned_file_identity = Some(SpawnedFileIdentity {
10589                    device: 43,
10590                    inode: 44,
10591                    #[cfg(windows)]
10592                    windows_image: None,
10593                });
10594            })?;
10595        }
10596        release_dead_registration(
10597            registry,
10598            runtime.forwarding.as_deref(),
10599            snapshot,
10600            &spec.module_id,
10601            failure,
10602        )
10603        .await?;
10604        if reset_budget {
10605            reset_restart_count(snapshot, &spec.module_id)?;
10606        }
10607        process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10608        let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
10609            Ok(next_child) => next_child,
10610            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
10611                defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
10612                return Ok(true);
10613            }
10614            Err(error @ SuperviseError::ConfigHeld { .. }) => {
10615                if let Err(parking_error) = hold_config_spawn(spec, runtime, snapshot, failure) {
10616                    process_liveness.untrack_if_current(&spec.module_id, snapshot);
10617                    return Err(parking_error);
10618                }
10619                return Err(error);
10620            }
10621            Err(err) => {
10622                fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
10623                process_liveness.untrack_if_current(&spec.module_id, snapshot);
10624                return Err(err);
10625            }
10626        };
10627        *child = Some(next_child);
10628        debug!(module_id = %spec.module_id, "supervised module enabled");
10629        Ok(true)
10630    } else {
10631        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10632            state.config_hold_parked = false;
10633            state.config_hold_daemon_initiated = false;
10634            state.config_hold_approval = None;
10635        })?;
10636        let stop_notice = begin_forwarding_drain_if_configured(
10637            spec,
10638            runtime,
10639            registry,
10640            snapshot,
10641            Some(false),
10642            RouteCloseReason::Disable,
10643        )
10644        .await?;
10645        drain_optional_child(
10646            &spec.module_id,
10647            spec.protocol,
10648            stop_notice,
10649            registry,
10650            runtime.forwarding.as_deref(),
10651            snapshot,
10652            &runtime.terminal_ring,
10653            &runtime.spawn_events,
10654            child,
10655            runtime.drain_timeout,
10656            ModuleState::Disabled,
10657            Some(false),
10658            failure,
10659        )
10660        .await?;
10661        debug!(module_id = %spec.module_id, "supervised module disabled");
10662        Ok(true)
10663    }
10664}
10665
10666#[allow(clippy::too_many_arguments)]
10667async fn on_child_exit(
10668    spec: &ModuleSpec,
10669    policy: RestartPolicy,
10670    registry: &Registry,
10671    snapshot: &SharedSnapshot,
10672    terminal_ring: &Arc<Mutex<TerminalRing>>,
10673    spawn_events: &SpawnEventFeed,
10674    roster: &ChildRoster,
10675    exit_report: ExitReport,
10676    daemon_initiated: bool,
10677) -> NextAction {
10678    // Once the daemon has begun shutting down, no exit is a crash to recover
10679    // from: the module is exiting because the daemon is going away (EOF on its
10680    // connection, or a service manager signalling the whole cgroup). Record it
10681    // as such and never schedule a respawn, which would only start a process
10682    // for the shutdown to end again.
10683    if roster.is_closed() {
10684        return on_child_exit_during_daemon_shutdown(
10685            spec,
10686            registry,
10687            snapshot,
10688            terminal_ring,
10689            spawn_events,
10690            exit_report,
10691        )
10692        .await;
10693    }
10694    // Deliberate stops the supervisor asks for (operator stop, disable,
10695    // restart, reload, swap, a health restart, a drain that runs out of budget)
10696    // takes the child out of the supervise loop and reaps it in
10697    // `drain_child_to_state`, and daemon shutdown is handled above. So an exit
10698    // that reaches this point is either unrequested or a first-HELLO timeout,
10699    // which is deliberately classified as a crash even after a clean TERM exit.
10700    //
10701    // For a subc-wire module a clean exit is still a stop: those modules are
10702    // written to re-raise SIGTERM, so a stray outside signal already reads as a
10703    // crash, and exiting 0 is a deliberate choice the module made. A
10704    // `protocol: "none"` module is a stock program we cannot change, and many
10705    // of them (nats-server among them) exit 0 on SIGTERM. Treating that as a
10706    // stop would leave the module down for good after any stray signal, so it
10707    // goes through the crash path instead: it spends restart budget, respawns
10708    // with the crash backoff, and ends `failed` when the budget runs out.
10709    let unrequested_clean_exit_of_protocol_none = exit_report.kind == ExitKind::Clean
10710        && running_protocol(spec, snapshot) == ModuleProtocol::None;
10711    match exit_report.kind {
10712        ExitKind::Clean if !unrequested_clean_exit_of_protocol_none => {
10713            info!(
10714                module_id = %spec.module_id,
10715                exit_code = ?exit_report.code,
10716                exit_signal = ?exit_report.signal,
10717                "supervised module exited cleanly"
10718            );
10719            if let Err(err) = publish_after_terminal_record(
10720                &spec.module_id,
10721                || {
10722                    record_terminal(
10723                        &spec.module_id,
10724                        terminal_ring,
10725                        spawn_events,
10726                        &exit_report,
10727                        TerminalDisposition::Stopped,
10728                    )
10729                },
10730                || {
10731                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10732                        state.state = ModuleState::Stopped;
10733                        clear_current_process_facts(state);
10734                        state.last_exit = Some(exit_report.clone());
10735                    })
10736                },
10737            ) {
10738                error!(module_id = %spec.module_id, error = %err, "failed to publish clean module exit");
10739            }
10740            let registration_released = match wait_for_registration_release(
10741                registry,
10742                &spec.module_id,
10743                REGISTRY_RELEASE_TIMEOUT,
10744            )
10745            .await
10746            {
10747                Ok(()) => true,
10748                Err(err) => {
10749                    warn!(module_id = %spec.module_id, error = %err, "registration still active after clean exit");
10750                    false
10751                }
10752            };
10753            NextAction::Stop {
10754                registration_released,
10755            }
10756        }
10757        ExitKind::Clean | ExitKind::Crash => {
10758            if unrequested_clean_exit_of_protocol_none {
10759                warn!(
10760                    module_id = %spec.module_id,
10761                    exit_code = ?exit_report.code,
10762                    exit_signal = ?exit_report.signal,
10763                    "protocol-none module exited cleanly without a stop request; handling it as a crash"
10764                );
10765            } else {
10766                warn!(
10767                    module_id = %spec.module_id,
10768                    exit_code = ?exit_report.code,
10769                    exit_signal = ?exit_report.signal,
10770                    "supervised module exited abnormally (crash)"
10771                );
10772            }
10773            let mut restart_schedule = None;
10774            let mut disposition = TerminalDisposition::Disabled;
10775            let mut final_state = ModuleState::Disabled;
10776            // Set only when the budget is what stopped the module, so the
10777            // terminal record says which limit was hit rather than leaving
10778            // `failed` to be read as "crashed once, badly".
10779            let mut disposition_detail = lock_snapshot(snapshot)
10780                .ok()
10781                .and_then(|mut state| state.spawn_failure.take());
10782            let now = Instant::now();
10783            if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10784                if state.enabled {
10785                    if let Some(schedule) = state.next_crash_restart(&policy, now) {
10786                        // Reserving the last slot exhausts the budget for the
10787                        // replacement, not for this exit. Publish its scheduled
10788                        // recovery atomically with the reservation so connection
10789                        // cleanup sees it while terminal recording still holds
10790                        // the visible state at Running.
10791                        state.respawn_pending = true;
10792                        final_state = ModuleState::Restarting;
10793                        restart_schedule = Some(schedule);
10794                        disposition = TerminalDisposition::Restarting;
10795                    } else {
10796                        final_state = ModuleState::Failed;
10797                        disposition = TerminalDisposition::Failed;
10798                        let budget = policy.budget_exhausted_detail();
10799                        disposition_detail =
10800                            Some(disposition_detail.take().map_or_else(
10801                                || budget.clone(),
10802                                |cause| format!("{cause}; {budget}"),
10803                            ));
10804                    }
10805                } else {
10806                    disposition = TerminalDisposition::Disabled;
10807                }
10808            }) {
10809                error!(module_id = %spec.module_id, error = %err, "failed to record crashed module exit");
10810                return NextAction::Stop {
10811                    registration_released: false,
10812                };
10813            }
10814            if disposition == TerminalDisposition::Failed {
10815                // The window is in the message, not only in the fields: this line
10816                // is read in a scrollback where a bare `max_restarts=3` reads as a
10817                // lifetime cap and sends the operator looking for three crashes
10818                // that never happened together.
10819                error!(
10820                    module_id = %spec.module_id,
10821                    max_restarts = policy.max_restarts,
10822                    window_secs = policy.window.as_secs(),
10823                    "module stopped: {}",
10824                    policy.budget_exhausted_detail()
10825                );
10826            }
10827            if let Err(err) = publish_after_terminal_record(
10828                &spec.module_id,
10829                || {
10830                    record_terminal_with_detail(
10831                        &spec.module_id,
10832                        terminal_ring,
10833                        spawn_events,
10834                        &exit_report,
10835                        disposition,
10836                        disposition_detail,
10837                    )
10838                },
10839                || {
10840                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10841                        state.state = final_state;
10842                        clear_current_process_facts(state);
10843                        if final_state == ModuleState::Failed
10844                            && daemon_initiated
10845                            && !roster.is_closed()
10846                        {
10847                            state.failed_retry.schedule(&spec.module_id);
10848                        }
10849                        state.last_exit = Some(exit_report.clone());
10850                    })
10851                },
10852            ) {
10853                error!(module_id = %spec.module_id, error = %err, "failed to publish crashed module exit");
10854            }
10855
10856            if let Some(schedule) = restart_schedule {
10857                NextAction::Restart {
10858                    schedule: Some(schedule),
10859                }
10860            } else {
10861                let registration_released = match wait_for_registration_release(
10862                    registry,
10863                    &spec.module_id,
10864                    REGISTRY_RELEASE_TIMEOUT,
10865                )
10866                .await
10867                {
10868                    Ok(()) => true,
10869                    Err(err) => {
10870                        warn!(module_id = %spec.module_id, error = %err, "registration still active after failed module");
10871                        false
10872                    }
10873                };
10874                NextAction::Stop {
10875                    registration_released,
10876                }
10877            }
10878        }
10879        ExitKind::DeliberateSeverance => {
10880            warn!(
10881                module_id = %spec.module_id,
10882                exit_code = ?exit_report.code,
10883                exit_signal = ?exit_report.signal,
10884                "supervised module exited after deliberate connection severance"
10885            );
10886            let should_restart = match lock_snapshot(snapshot) {
10887                Ok(state) => state.enabled,
10888                Err(err) => {
10889                    error!(module_id = %spec.module_id, error = %err, "failed to read deliberately severed module state");
10890                    return NextAction::Stop {
10891                        registration_released: false,
10892                    };
10893                }
10894            };
10895            let final_state = if should_restart {
10896                ModuleState::Restarting
10897            } else {
10898                ModuleState::Disabled
10899            };
10900            if let Err(err) = publish_after_terminal_record(
10901                &spec.module_id,
10902                || {
10903                    record_terminal(
10904                        &spec.module_id,
10905                        terminal_ring,
10906                        spawn_events,
10907                        &exit_report,
10908                        terminal_disposition(final_state),
10909                    )
10910                },
10911                || {
10912                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10913                        state.state = final_state;
10914                        clear_current_process_facts(state);
10915                        state.last_exit = Some(exit_report.clone());
10916                        state.lifetime_restarts += 1;
10917                    })
10918                },
10919            ) {
10920                error!(module_id = %spec.module_id, error = %err, "failed to publish deliberately severed module exit");
10921                return NextAction::Stop {
10922                    registration_released: false,
10923                };
10924            }
10925
10926            if should_restart {
10927                NextAction::Restart { schedule: None }
10928            } else {
10929                let registration_released = match wait_for_registration_release(
10930                    registry,
10931                    &spec.module_id,
10932                    REGISTRY_RELEASE_TIMEOUT,
10933                )
10934                .await
10935                {
10936                    Ok(()) => true,
10937                    Err(err) => {
10938                        warn!(module_id = %spec.module_id, error = %err, "registration still active after deliberately severed module exit");
10939                        false
10940                    }
10941                };
10942                NextAction::Stop {
10943                    registration_released,
10944                }
10945            }
10946        }
10947    }
10948}
10949
10950async fn on_child_exit_during_daemon_shutdown(
10951    spec: &ModuleSpec,
10952    registry: &Registry,
10953    snapshot: &SharedSnapshot,
10954    terminal_ring: &Arc<Mutex<TerminalRing>>,
10955    spawn_events: &SpawnEventFeed,
10956    exit_report: ExitReport,
10957) -> NextAction {
10958    info!(
10959        module_id = %spec.module_id,
10960        exit_code = ?exit_report.code,
10961        exit_signal = ?exit_report.signal,
10962        exit_kind = ?exit_report.kind,
10963        "supervised module exited during daemon shutdown; not restarting it"
10964    );
10965    if let Err(err) = publish_after_terminal_record(
10966        &spec.module_id,
10967        || {
10968            record_terminal(
10969                &spec.module_id,
10970                terminal_ring,
10971                spawn_events,
10972                &exit_report,
10973                TerminalDisposition::DaemonShutdown,
10974            )
10975        },
10976        || {
10977            update_snapshot(snapshot, Some(&spec.module_id), |state| {
10978                state.state = ModuleState::Stopped;
10979                clear_current_process_facts(state);
10980                state.last_exit = Some(exit_report.clone());
10981            })
10982        },
10983    ) {
10984        error!(module_id = %spec.module_id, error = %err, "failed to publish module exit during daemon shutdown");
10985    }
10986    let registration_released =
10987        wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT)
10988            .await
10989            .is_ok();
10990    NextAction::Stop {
10991        registration_released,
10992    }
10993}
10994
10995// Keep the status lock out of terminal I/O. Readers may observe the previous
10996// state while recording is in progress, but never a completed exit without its
10997// history. Journal errors are logged by the journal and retained in the ring;
10998// a recording panic still publishes the final state before resuming the unwind.
10999fn publish_after_terminal_record<T>(
11000    module_id: &str,
11001    record: impl FnOnce(),
11002    publish: impl FnOnce() -> T,
11003) -> T {
11004    let recorded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(record));
11005    let published = publish();
11006    if let Err(panic) = recorded {
11007        error!(
11008            module_id,
11009            "terminal recording panicked; published final state before resuming unwind"
11010        );
11011        std::panic::resume_unwind(panic);
11012    }
11013    published
11014}
11015
11016fn fail_after_wait_error(
11017    module_id: &str,
11018    snapshot: &SharedSnapshot,
11019    terminal_ring: &Arc<Mutex<TerminalRing>>,
11020    spawn_events: &SpawnEventFeed,
11021    detail: String,
11022    failure: &FailureContext,
11023) {
11024    let report = wait_error_exit_report();
11025    publish_after_terminal_record(
11026        module_id,
11027        || {
11028            record_terminal_with_detail(
11029                module_id,
11030                terminal_ring,
11031                spawn_events,
11032                &report,
11033                TerminalDisposition::Failed,
11034                Some(detail),
11035            )
11036        },
11037        || fail_snapshot(snapshot, Some(module_id), Some(report.clone()), failure),
11038    );
11039}
11040
11041#[cfg(test)]
11042fn record_wait_error_terminal(
11043    module_id: &str,
11044    terminal_ring: &Arc<Mutex<TerminalRing>>,
11045    spawn_events: &SpawnEventFeed,
11046) {
11047    record_terminal(
11048        module_id,
11049        terminal_ring,
11050        spawn_events,
11051        &wait_error_exit_report(),
11052        TerminalDisposition::Failed,
11053    );
11054}
11055
11056fn record_terminal(
11057    module_id: &str,
11058    terminal_ring: &Arc<Mutex<TerminalRing>>,
11059    spawn_events: &SpawnEventFeed,
11060    exit_report: &ExitReport,
11061    disposition: TerminalDisposition,
11062) {
11063    record_terminal_with_detail(
11064        module_id,
11065        terminal_ring,
11066        spawn_events,
11067        exit_report,
11068        disposition,
11069        None,
11070    );
11071}
11072
11073/// The ring lock is held only to capture the read (see
11074/// `TerminalJournal::capture_read`), so this module's exits keep recording
11075/// while the journal files are read. Blocking: it reads files.
11076fn durable_terminal_history_of(
11077    terminal_ring: &Mutex<TerminalRing>,
11078    module_id: &str,
11079) -> subc_control::TerminalHistory {
11080    let read = terminal_ring
11081        .lock()
11082        .unwrap_or_else(|p| p.into_inner())
11083        .capture_durable_history();
11084    read.read(module_id)
11085}
11086
11087fn record_terminal_with_detail(
11088    module_id: &str,
11089    terminal_ring: &Arc<Mutex<TerminalRing>>,
11090    spawn_events: &SpawnEventFeed,
11091    exit_report: &ExitReport,
11092    disposition: TerminalDisposition,
11093    disposition_detail: Option<String>,
11094) {
11095    #[cfg(test)]
11096    terminal_history_tests::before_terminal_record(spawn_events);
11097    spawn_events.emit_exited(module_id, exit_report.code, exit_report.signal);
11098    let record = TerminalRecord {
11099        exit_code: exit_report.code,
11100        exit_signal: exit_report.signal,
11101        at_ms: exit_report.at_ms,
11102        disposition,
11103        exit_kind: exit_report.kind.into(),
11104        disposition_detail,
11105    };
11106    terminal_ring
11107        .lock()
11108        .unwrap_or_else(|poisoned| poisoned.into_inner())
11109        .record_exit(module_id, record);
11110}
11111
11112fn untrack_if_registration_released(
11113    process_liveness: &SupervisorProcessLiveness,
11114    registry: &Registry,
11115    module_id: &str,
11116    snapshot: &SharedSnapshot,
11117) {
11118    match registry.get_module(module_id) {
11119        Ok(None) => process_liveness.untrack_if_current(module_id, snapshot),
11120        Ok(Some(_)) => {}
11121        Err(err) => {
11122            warn!(module_id, error = %err, "could not determine whether supervisor liveness can be untracked");
11123        }
11124    }
11125}
11126
11127/// The child's environment plan: inherit the parent's, drop ambient `CK_LOG`,
11128/// then apply the module's configured entries minus daemon-private capture keys.
11129///
11130/// Separated from `spawn_child` only so it can be asserted without spawning a
11131/// process — a duplicate of this logic in a test would pass while the real one
11132/// drifted, which is the defect class this function exists to avoid.
11133/// The subc-wire half of a spawn: `--subc <connection file>` and the launch
11134/// nonce. A `protocol: "none"` module gets neither, because it cannot use
11135/// either and the argument would stop a stock binary from starting at all.
11136/// `SUBC_MODULE_ID` is set on every path since an unread variable is inert.
11137///
11138/// The plain-spawn form, kept for the tests that assert its plan; spawns go
11139/// through [`apply_wire_spawn_args_for_admission`].
11140#[cfg(test)]
11141fn apply_wire_spawn_args(
11142    command: &mut Command,
11143    spec: &ModuleSpec,
11144    connection_file_path: Option<&std::path::Path>,
11145    handle: Option<&SupervisorHandle>,
11146) -> Result<Option<NonceHandoff>, SuperviseError> {
11147    apply_wire_spawn_args_for_role(
11148        command,
11149        spec,
11150        connection_file_path,
11151        handle,
11152        SpawnRole::Plain,
11153    )
11154}
11155
11156/// The read end of a spawn's launch-nonce pipe, prepared by
11157/// [`apply_wire_spawn_args_for_admission`] and installed as the child's descriptor 3
11158/// by the last pre-exec step, just before `spawn()`. Windows prepares a named
11159/// server before spawn and authenticates its client after the child exists.
11160#[cfg(unix)]
11161type NonceHandoff = subc_os::LaunchNonceHandoff;
11162#[cfg(windows)]
11163type NonceHandoff = subc_os::LaunchNoncePipeHandoff;
11164#[cfg(not(any(unix, windows)))]
11165type NonceHandoff = std::convert::Infallible;
11166
11167/// Create the launch nonce that a new module process must present when it
11168/// registers or opens a consumer connection, including a replacement process
11169/// started alongside a still-serving module.
11170///
11171/// A plain spawn replaces the module's recorded nonce. A swap candidate records
11172/// a separate candidate token so the still-serving incumbent and its consumers
11173/// keep their nonce. Both records are installed before the process exists, so
11174/// the child's initial HELLO registration cannot arrive ahead of its nonce.
11175///
11176/// On Unix the nonce is delivered only through a pipe. It is written into
11177/// a pipe whose read end the child gets as descriptor 3, named by
11178/// `SUBC_LAUNCH_NONCE_FD=3:<pipe inode>`: unlike the environment, another
11179/// process of the same user cannot read it with `ps eww`. That handoff is
11180/// returned rather than installed here. The combined descriptor placement runs
11181/// after the cgroup callback and placement barrier, so replacing slots 3-5
11182/// cannot close a descriptor either callback still needs.
11183/// Windows keeps SUBC_LAUNCH_NONCE as well until every module reads the named pipe.
11184#[cfg(test)]
11185fn apply_wire_spawn_args_for_role(
11186    command: &mut Command,
11187    spec: &ModuleSpec,
11188    connection_file_path: Option<&std::path::Path>,
11189    handle: Option<&SupervisorHandle>,
11190    role: SpawnRole,
11191) -> Result<Option<NonceHandoff>, SuperviseError> {
11192    apply_wire_spawn_args_for_admission(command, spec, connection_file_path, handle, role, None)
11193}
11194
11195fn apply_wire_spawn_args_for_admission(
11196    command: &mut Command,
11197    spec: &ModuleSpec,
11198    connection_file_path: Option<&std::path::Path>,
11199    handle: Option<&SupervisorHandle>,
11200    role: SpawnRole,
11201    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
11202) -> Result<Option<NonceHandoff>, SuperviseError> {
11203    command.env(SUBC_MODULE_ID_ENV, &spec.module_id);
11204    // SUBC_LAUNCH_NONCE_FD is removed for every child, `protocol: "none"`
11205    // included: a daemon started from a module's process tree inherits it,
11206    // and passing it on would point the child at a descriptor it does not
11207    // have.
11208    command.env_remove(subc_os::LAUNCH_NONCE_FD_ENV);
11209    #[cfg(windows)]
11210    {
11211        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_ENV);
11212        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV);
11213    }
11214    // Remove inherited or configured copies too: withholding must mean absent.
11215    command.env_remove(SUBC_LAUNCH_NONCE_ENV);
11216    command.env_remove(subc_os::registration_channel::REGISTRATION_FD_ENV);
11217    command.env_remove(subc_os::registration_channel::REGISTRATION_PIPE_ENV);
11218    command.env_remove(subc_os::registration_channel::DAEMON_PID_ENV);
11219    if role == SpawnRole::Plain {
11220        if let Some(handle) = handle {
11221            #[cfg(all(test, unix))]
11222            {
11223                let pause = {
11224                    let mut slot = handle.plain_identity_policy_pause.lock().unwrap();
11225                    if slot
11226                        .as_ref()
11227                        .is_some_and(|(module, _)| module == &spec.module_id)
11228                    {
11229                        slot.take().map(|(_, pause)| pause)
11230                    } else {
11231                        None
11232                    }
11233                };
11234                if let Some(pause) = pause {
11235                    pause.reached.send(()).unwrap();
11236                    pause.release.recv().unwrap();
11237                }
11238            }
11239            // A rescan preserves the running child's nonce and reservation.
11240            // Replacement spawn preparation applies the new protocol now,
11241            // before protocol:none can return without minting a nonce.
11242            handle.apply_identity_policy(spec, spec.protocol);
11243        }
11244    }
11245    if spec.protocol == ModuleProtocol::None {
11246        return Ok(None);
11247    }
11248    if let Some(connection_file_path) = connection_file_path {
11249        command.arg(SUBC_ARG).arg(connection_file_path);
11250    }
11251
11252    if admission.is_some_and(|admission| admission.launch.is_some()) {
11253        if let Some(handle) = handle {
11254            match role {
11255                SpawnRole::Plain => {
11256                    handle
11257                        .spawn_nonces
11258                        .lock()
11259                        .unwrap_or_else(|p| p.into_inner())
11260                        .remove(&spec.module_id);
11261                    if spec.reserved {
11262                        handle
11263                            .reserved_nonces
11264                            .lock()
11265                            .unwrap_or_else(|p| p.into_inner())
11266                            .insert(spec.module_id.clone(), None);
11267                    }
11268                }
11269                // Swaps still need their lifecycle record, but the empty value
11270                // is not a bearer token and is never accepted by nonce HELLO.
11271                SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, String::new()),
11272            }
11273        }
11274        return Ok(None);
11275    }
11276    // Every subc-wire spawn receives a fresh one-time launch nonce for consumer
11277    // route.open attestation. Reserved modules additionally use the same nonce
11278    // for HELLO id-squatting protection. A respawn rotates both records.
11279    let nonce = generate_launch_nonce()?;
11280    if let Some(handle) = handle {
11281        match role {
11282            SpawnRole::Plain => {
11283                handle.set_spawn_nonce(&spec.module_id, nonce.clone());
11284                if spec.reserved {
11285                    handle.set_reserved_nonce(&spec.module_id, nonce.clone());
11286                }
11287            }
11288            SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, nonce.clone()),
11289        }
11290    }
11291    #[cfg(unix)]
11292    let handoff = {
11293        let handoff =
11294            subc_os::LaunchNonceHandoff::new(&nonce).map_err(|source| SuperviseError::Spawn {
11295                program: spec.program.clone(),
11296                source,
11297                cgroup_path: None,
11298            })?;
11299        command.env(subc_os::LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
11300        Some(handoff)
11301    };
11302    #[cfg(windows)]
11303    let handoff = prepare_windows_nonce_pipe(command, spec, &nonce);
11304    #[cfg(not(any(unix, windows)))]
11305    let handoff = None;
11306    // Older modules still read SUBC_LAUNCH_NONCE to register. Keep that copy
11307    // until the daemon's per-spawn delivery records show that every running
11308    // Windows module has read its secret from the named pipe.
11309    #[cfg(not(unix))]
11310    command.env(SUBC_LAUNCH_NONCE_ENV, nonce);
11311    Ok(handoff)
11312}
11313
11314pub(crate) fn apply_child_env(command: &mut Command, spec: &ModuleSpec) {
11315    command.env_remove(CK_LOG_ENV);
11316    // The spawn role is the supervisor's to set, and only on a swap candidate
11317    // (see `apply_spawn_role`). Removing it here, rather than just not setting
11318    // it, is what makes it absent on a plain spawn: the daemon's own
11319    // environment could carry it, and so could a spec built outside daemon
11320    // config (config refuses it as an `env` key). A module reading it on a
11321    // plain restart would pick the long swap budget and leave callers waiting.
11322    command.env_remove(SUBC_SPAWN_ROLE_ENV);
11323    for (key, value) in &spec.env {
11324        // cortexkit-log currently exposes retention only as a Rust struct, not
11325        // environment names. These values are daemon-private sink metadata and
11326        // must never become a public child-process contract by being inherited.
11327        if matches!(
11328            key.as_str(),
11329            CAPTURE_MAX_FILE_MB_ENV | CAPTURE_KEEP_ENV | CAPTURE_MAX_AGE_DAYS_ENV
11330        ) || key == SUBC_SPAWN_ROLE_ENV
11331        {
11332            continue;
11333        }
11334        command.env(key, value);
11335    }
11336}
11337
11338#[cfg(windows)]
11339fn prepare_windows_registration_pipe(
11340    command: &mut Command,
11341    spec: &ModuleSpec,
11342) -> Result<Option<SpawnRegistrationChannel>, SuperviseError> {
11343    if spec.protocol == ModuleProtocol::None {
11344        return Ok(None);
11345    }
11346    let pipe = subc_os::registration_channel::RegistrationPipe::new().map_err(|source| {
11347        SuperviseError::Spawn {
11348            program: spec.program.clone(),
11349            source,
11350            cgroup_path: None,
11351        }
11352    })?;
11353    command
11354        .env(
11355            subc_os::registration_channel::REGISTRATION_PIPE_ENV,
11356            pipe.name(),
11357        )
11358        .env(
11359            subc_os::registration_channel::DAEMON_PID_ENV,
11360            std::process::id().to_string(),
11361        );
11362    Ok(Some(pipe))
11363}
11364
11365#[cfg(windows)]
11366fn prepare_windows_nonce_pipe(
11367    command: &mut Command,
11368    spec: &ModuleSpec,
11369    nonce: &str,
11370) -> Option<NonceHandoff> {
11371    match subc_os::LaunchNoncePipeHandoff::new(nonce) {
11372        Ok(handoff) => {
11373            command.env(subc_os::LAUNCH_NONCE_PIPE_ENV, handoff.name());
11374            // Let a failed pipe read use SUBC_LAUNCH_NONCE so the process can
11375            // still register until every module reads the pipe. A reader without
11376            // this variable set to env returns the pipe error instead of using
11377            // an inherited or configured environment copy.
11378            command.env(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV, "env");
11379            Some(handoff)
11380        }
11381        Err(error) => {
11382            warn!(module_id = %spec.module_id, %error, "could not prepare launch nonce pipe; retaining the environment handoff");
11383            None
11384        }
11385    }
11386}
11387
11388#[cfg(windows)]
11389fn start_windows_nonce_pipe(
11390    handoff: Option<NonceHandoff>,
11391    pid: u32,
11392    spec: &ModuleSpec,
11393) -> Option<subc_os::LaunchNoncePipeDelivery> {
11394    // Close an unread pipe after REGISTRY_RELEASE_TIMEOUT (one second), the
11395    // same maximum wait used for registration during a reload. Older modules
11396    // may register using SUBC_LAUNCH_NONCE without ever connecting to the pipe.
11397    handoff.and_then(|handoff| match handoff.serve(pid, REGISTRY_RELEASE_TIMEOUT) {
11398        Ok(delivery) => Some(delivery),
11399        Err(error) => {
11400            warn!(module_id = %spec.module_id, %error, "could not serve launch nonce pipe; retaining the environment handoff");
11401            None
11402        }
11403    })
11404}
11405
11406fn observed_launch_nonce_source(snapshot: &SupervisorSnapshot) -> Option<String> {
11407    #[cfg(windows)]
11408    if snapshot.process_alive && snapshot.spawned_protocol == Some(ModuleProtocol::Subc) {
11409        return Some(
11410            if snapshot
11411                .pipe_consumed
11412                .as_ref()
11413                .is_some_and(|consumed| consumed.get().is_some())
11414            {
11415                "pipe"
11416            } else {
11417                "env"
11418            }
11419            .to_owned(),
11420        );
11421    }
11422    let _ = snapshot;
11423    None
11424}
11425
11426/// Which slot a spawn fills: the module's ordinary one, or the candidate slot
11427/// of a blue/green swap.
11428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11429enum SpawnRole {
11430    Plain,
11431    SwapCandidate,
11432}
11433
11434/// Set the spawn role for a swap candidate. A plain spawn gets nothing here;
11435/// `apply_child_env` has already removed the variable for every spawn.
11436fn apply_spawn_role(command: &mut Command, role: SpawnRole) {
11437    if role == SpawnRole::SwapCandidate {
11438        command.env(SUBC_SPAWN_ROLE_ENV, SPAWN_ROLE_SWAP_CANDIDATE);
11439    }
11440}
11441
11442fn previous_instance_error(
11443    spec: &ModuleSpec,
11444    pid: u32,
11445    reason: crate::live_children::RetainedReason,
11446) -> SuperviseError {
11447    SuperviseError::Spawn {
11448        program: spec.program.clone(),
11449        source: io::Error::new(io::ErrorKind::WouldBlock, reason.waiting_message(pid)),
11450        cgroup_path: None,
11451    }
11452}
11453
11454fn carries_containment(configured: bool, has_container: bool) -> bool {
11455    configured || has_container
11456}
11457
11458fn recovery_block_error(spec: &ModuleSpec, roster: &ChildRoster) -> Option<SuperviseError> {
11459    if !carries_containment(
11460        spec.carry_containment,
11461        containment::current(&roster.containment).is_some(),
11462    ) {
11463        return None;
11464    }
11465    Some(SuperviseError::Spawn {
11466        program: spec.program.clone(),
11467        source: io::Error::new(io::ErrorKind::WouldBlock, roster.recovery_block()?),
11468        cgroup_path: None,
11469    })
11470}
11471
11472#[allow(clippy::too_many_arguments)]
11473fn spawn_child(
11474    spec: &ModuleSpec,
11475    connection_file_path: Option<&std::path::Path>,
11476    handle: Option<&SupervisorHandle>,
11477    ring: &Arc<Mutex<StderrRing>>,
11478    capture_logs_dir: Option<&std::path::Path>,
11479    roster: &ChildRoster,
11480    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11481    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11482    register_timeout: Duration,
11483) -> Result<SupervisedChild, SuperviseError> {
11484    #[cfg(all(test, unix))]
11485    if let Some(source) = containment_tests::join_failure(spec, roster) {
11486        containment::terminate_blocking(&roster.containment);
11487        return Err(SuperviseError::Spawn {
11488            program: spec.program.clone(),
11489            source,
11490            cgroup_path: None,
11491        });
11492    }
11493    let result = spawn_child_in_slot(
11494        spec,
11495        connection_file_path,
11496        handle,
11497        ring,
11498        capture_logs_dir,
11499        roster,
11500        config_delivery,
11501        #[cfg(target_os = "linux")]
11502        cgroup_placement,
11503        SpawnRole::Plain,
11504        false,
11505        register_timeout,
11506    );
11507    if result
11508        .as_ref()
11509        .is_err_and(|error| !is_launch_deferral(error))
11510    {
11511        if roster.admission_pending(&spec.module_id) {
11512            containment::terminate_deferred(&roster.containment);
11513        } else {
11514            containment::terminate_blocking(&roster.containment);
11515        }
11516    }
11517    result
11518}
11519
11520/// A configuration deferral means the launch never started: the module gate
11521/// or the configuration owner was briefly busy, and every caller schedules
11522/// the same launch again shortly. A carried container stays for that retry,
11523/// as it does across a restart backoff; ending it here would kill the
11524/// module's helpers and give up the group the retry is meant to join.
11525fn is_launch_deferral(error: &SuperviseError) -> bool {
11526    matches!(error, SuperviseError::ConfigDeliveryDeferred { .. })
11527}
11528
11529/// Spawn one process of `spec` into a slot.
11530///
11531/// `alternate_slot` picks the process's cgroup label on Linux (see `swap::cgroup_name`).
11532/// A swap candidate needs a different cgroup from the process it is replacing,
11533/// which is still alive: in the same cgroup the two would be one kill domain,
11534/// and killing a failed candidate could take the incumbent with it.
11535///
11536/// The stderr capture file is `<module_id>.stderr.log` for every process of
11537/// the module, whichever slot it is in, because that is the one file
11538/// `ck module logs` reads. During a swap's overlap both processes append to it;
11539/// the daemon writes whole lines, so the two interleave by line, which is also
11540/// the merged view an operator wants while a swap runs.
11541#[allow(clippy::too_many_arguments)]
11542fn spawn_child_in_slot(
11543    spec: &ModuleSpec,
11544    connection_file_path: Option<&std::path::Path>,
11545    handle: Option<&SupervisorHandle>,
11546    ring: &Arc<Mutex<StderrRing>>,
11547    capture_logs_dir: Option<&std::path::Path>,
11548    roster: &ChildRoster,
11549    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11550    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11551    role: SpawnRole,
11552    alternate_slot: bool,
11553    register_timeout: Duration,
11554) -> Result<SupervisedChild, SuperviseError> {
11555    let prepared = prepare_child_in_slot(
11556        spec,
11557        connection_file_path,
11558        handle,
11559        capture_logs_dir,
11560        roster,
11561        config_delivery,
11562        #[cfg(target_os = "linux")]
11563        cgroup_placement,
11564        role,
11565        alternate_slot,
11566        false,
11567    )?;
11568    let gate = config_delivery
11569        .map(|delivery| delivery.module_gate(spec))
11570        .transpose()?;
11571    let _gate = gate
11572        .as_ref()
11573        .map(|gate| {
11574            gate.try_lock()
11575                .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
11576                    module_id: spec.module_id.clone(),
11577                })
11578        })
11579        .transpose()?;
11580    if let (Some(delivery), Some(admission)) = (config_delivery, &prepared.spawn_admission) {
11581        delivery.check(spec, admission)?;
11582    }
11583    let checked_base = prepared
11584        .spawn_admission
11585        .as_ref()
11586        .and_then(|admission| admission.approved_base())
11587        .cloned();
11588    let mut result = launch_child_in_slot(spec, ring, roster, prepared, register_timeout);
11589    drop(_gate);
11590    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
11591        (config_delivery, &result)
11592    {
11593        if let Some(base) = checked_base.as_ref().filter(|_| code == "program_refused") {
11594            if !delivery.record_refusal(spec, base, detail)? {
11595                result = Err(spawn_plan_stale(spec));
11596            }
11597        }
11598    }
11599    result
11600}
11601
11602struct AsyncInitialIdentity<'a> {
11603    supervisor: &'a Supervisor,
11604    module: String,
11605    committed: bool,
11606}
11607impl Drop for AsyncInitialIdentity<'_> {
11608    fn drop(&mut self) {
11609        if !self.committed {
11610            self.supervisor.abandon_unrostered(&self.module);
11611        }
11612    }
11613}
11614
11615/// Child-free preparation can be abandoned without orphaning a process. After
11616/// this value returns, the async caller validates its launch witness and creates
11617/// and publishes the child without another await.
11618struct PreparedChild {
11619    script_delivery: Option<script::Delivery>,
11620    registration_spawn: Option<Arc<RegistrationSpawn>>,
11621    registration_handle: Option<SupervisorHandle>,
11622    #[cfg(any(unix, windows))]
11623    registration_channel: Option<SpawnRegistrationChannel>,
11624    config_context: Option<config_delivery::ConfigDelivery>,
11625    binding_publication: Option<ProgramBindingPublication>,
11626    launch_spec: ModuleSpec,
11627    spawn_admission: Option<crate::config_gate::runtime::SpawnAdmission>,
11628    command: Command,
11629    carrying: bool,
11630    carried: Option<Arc<containment::CarriedContainment>>,
11631    #[cfg(unix)]
11632    launch_identity: Option<containment::LaunchIdentity>,
11633    #[cfg(unix)]
11634    group_target: containment::GroupTarget,
11635    #[cfg(target_os = "linux")]
11636    cgroup_placement: Option<subc_cgroup::Placement>,
11637    #[cfg(target_os = "linux")]
11638    cgroup_name: String,
11639    #[cfg(target_os = "linux")]
11640    cgroup_cleanup: PreparedCgroup,
11641    cgroup_path: Option<PathBuf>,
11642    #[cfg(unix)]
11643    admission_gate: Option<admission::Gate>,
11644    output_sink: ChildOutputSink,
11645    #[cfg(target_os = "macos")]
11646    privacy_exec: Option<PrivacyExec>,
11647    #[cfg(windows)]
11648    image_capture: subc_os::ExecutableCapture,
11649    #[cfg(windows)]
11650    nonce_handoff: Option<NonceHandoff>,
11651    spawned_at: Instant,
11652    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
11653    delivery_registration: Option<config_delivery::RegistrationGuard>,
11654    program_binding: Option<SpawnProgramBinding>,
11655}
11656
11657#[cfg(target_os = "linux")]
11658struct PreparedCgroup(Option<(subc_cgroup::Placement, String)>);
11659#[cfg(target_os = "linux")]
11660impl Drop for PreparedCgroup {
11661    fn drop(&mut self) {
11662        if let Some((placement, name)) = &self.0 {
11663            remove_module_cgroup(placement, name);
11664        }
11665    }
11666}
11667
11668pub(crate) struct SpawnProgramBinding {
11669    pub(crate) path: PathBuf,
11670    // Keep the inode alive if the configured name is replaced while preparation
11671    // is suspended, so replacement cannot pass through inode reuse.
11672    _file: std::fs::File,
11673    pub(crate) identity: subc_os::RetainedFileIdentity,
11674}
11675
11676impl SpawnProgramBinding {
11677    pub(crate) fn capture(spec: &ModuleSpec) -> Result<Self, SuperviseError> {
11678        Self::capture_after_resolution(spec, |_| {})
11679    }
11680
11681    fn capture_after_resolution(
11682        spec: &ModuleSpec,
11683        before_open: impl FnOnce(&std::path::Path),
11684    ) -> Result<Self, SuperviseError> {
11685        require_program_search_path(spec)?;
11686        #[cfg(windows)]
11687        let windows_capture =
11688            windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
11689                program: spec.program.clone(),
11690                source,
11691                cgroup_path: None,
11692            })?;
11693        #[cfg(windows)]
11694        let path = windows_capture.path().to_path_buf();
11695        #[cfg(not(windows))]
11696        let path = if spec.program.is_absolute() || spec.program.components().count() > 1 {
11697            spec.program.clone()
11698        } else {
11699            let path = spec
11700                .env
11701                .iter()
11702                .rev()
11703                .find(|(key, _)| key == "PATH")
11704                .map(|(_, path)| std::ffi::OsString::from(path))
11705                .or_else(|| std::env::var_os("PATH"))
11706                .unwrap_or_else(|| {
11707                    if cfg!(target_os = "macos") {
11708                        // Match Darwin's spawn search when PATH is absent, not
11709                        // the current-directory search of an explicitly empty PATH.
11710                        "/usr/bin:/bin".into()
11711                    } else {
11712                        Default::default()
11713                    }
11714                });
11715            std::env::split_paths(&path)
11716                .map(|dir| dir.join(&spec.program))
11717                .find(|path| {
11718                    if !path.is_file() {
11719                        return false;
11720                    }
11721                    #[cfg(unix)]
11722                    {
11723                        rustix::fs::accessat(
11724                            rustix::fs::CWD,
11725                            path,
11726                            rustix::fs::Access::EXEC_OK,
11727                            rustix::fs::AtFlags::EACCESS,
11728                        )
11729                        .is_ok()
11730                    }
11731                    #[cfg(not(unix))]
11732                    {
11733                        true
11734                    }
11735                })
11736                .ok_or_else(|| SuperviseError::Spawn {
11737                    program: spec.program.clone(),
11738                    source: io::Error::new(io::ErrorKind::NotFound, "executable not found in PATH"),
11739                    cgroup_path: None,
11740                })?
11741        };
11742        let resolved = std::fs::canonicalize(&path).map_err(|source| SuperviseError::Spawn {
11743            program: spec.program.clone(),
11744            source,
11745            cgroup_path: None,
11746        })?;
11747        before_open(&resolved);
11748        // Resolving links does not open their target. The descriptor open must
11749        // remain nonblocking and no-follow if that resolved name is substituted.
11750        let file =
11751            subc_os::open_regular_nofollow(&resolved).map_err(|source| SuperviseError::Spawn {
11752                program: spec.program.clone(),
11753                source: io::Error::other(source),
11754                cgroup_path: None,
11755            })?;
11756        let identity =
11757            subc_os::retained_file_identity(&file).map_err(|source| SuperviseError::Spawn {
11758                program: spec.program.clone(),
11759                source,
11760                cgroup_path: None,
11761            })?;
11762        Ok(Self {
11763            path,
11764            _file: file,
11765            identity,
11766        })
11767    }
11768    fn current(&self) -> bool {
11769        #[cfg(unix)]
11770        {
11771            subc_os::file_identity(&self.path) == Some(self.identity)
11772        }
11773        #[cfg(windows)]
11774        {
11775            std::fs::canonicalize(&self.path)
11776                .ok()
11777                .and_then(|path| subc_os::open_regular_nofollow(&path).ok())
11778                .and_then(|file| subc_os::retained_file_identity(&file).ok())
11779                == Some(self.identity)
11780        }
11781    }
11782}
11783
11784fn spawn_plan_stale(spec: &ModuleSpec) -> SuperviseError {
11785    SuperviseError::ConfigDeliveryDeferred {
11786        module_id: spec.module_id.clone(),
11787    }
11788}
11789
11790fn require_program_search_path(spec: &ModuleSpec) -> Result<(), SuperviseError> {
11791    if !cfg!(target_os = "macos")
11792        && !spec.program.is_absolute()
11793        && spec.program.components().count() == 1
11794        && !spec.env.iter().any(|(key, _)| {
11795            if cfg!(windows) {
11796                key.eq_ignore_ascii_case("PATH")
11797            } else {
11798                key == "PATH"
11799            }
11800        })
11801        && std::env::var_os("PATH").is_none()
11802    {
11803        // The OS default search is not a current-directory search. Refusing an
11804        // unspecified search path prevents approving a decoy in the current directory.
11805        return Err(SuperviseError::Spawn {
11806            program: spec.program.clone(),
11807            source: io::Error::new(io::ErrorKind::InvalidInput, "bare program requires PATH"),
11808            cgroup_path: None,
11809        });
11810    }
11811    Ok(())
11812}
11813
11814async fn spawn_child_async(
11815    spec: &ModuleSpec,
11816    runtime: &SupervisorRuntimeConfig,
11817) -> Result<SupervisedChild, SuperviseError> {
11818    #[cfg(all(test, unix))]
11819    if let Some(source) = containment_tests::join_failure(spec, &runtime.child_roster) {
11820        containment::terminate_blocking(&runtime.child_roster.containment);
11821        return Err(SuperviseError::Spawn {
11822            program: spec.program.clone(),
11823            source,
11824            cgroup_path: None,
11825        });
11826    }
11827    let result = spawn_child_in_slot_async(spec, runtime, SpawnRole::Plain, false).await;
11828    if result
11829        .as_ref()
11830        .is_err_and(|error| !is_launch_deferral(error))
11831    {
11832        if runtime.child_roster.admission_pending(&spec.module_id) {
11833            containment::terminate_deferred(&runtime.child_roster.containment);
11834        } else {
11835            containment::terminate_blocking(&runtime.child_roster.containment);
11836        }
11837    }
11838    result
11839}
11840
11841async fn spawn_child_in_slot_async(
11842    spec: &ModuleSpec,
11843    runtime: &SupervisorRuntimeConfig,
11844    role: SpawnRole,
11845    alternate_slot: bool,
11846) -> Result<SupervisedChild, SuperviseError> {
11847    let gate = runtime
11848        .config_delivery
11849        .as_ref()
11850        .map(|delivery| delivery.0.module_gate(&spec.module_id))
11851        .transpose()
11852        .map_err(|error| SuperviseError::InvalidSpec {
11853            reason: error.to_string(),
11854        })?;
11855    if gate.as_ref().is_some_and(|gate| gate.try_lock().is_err()) {
11856        return Err(SuperviseError::ConfigDeliveryDeferred {
11857            module_id: spec.module_id.clone(),
11858        });
11859    }
11860    let prepared_spec = spec.clone();
11861    let prepared_runtime = runtime.clone();
11862    let prepared = tokio::task::spawn_blocking(move || {
11863        let prepared = prepare_child_in_slot(
11864            &prepared_spec,
11865            prepared_runtime.connection_file_path.as_deref(),
11866            prepared_runtime.supervisor_handle.as_ref(),
11867            prepared_runtime.capture_logs_dir.as_deref(),
11868            &prepared_runtime.child_roster,
11869            prepared_runtime.spawn_delivery(),
11870            #[cfg(target_os = "linux")]
11871            prepared_runtime.cgroup_placement.as_ref(),
11872            role,
11873            alternate_slot,
11874            true,
11875        );
11876        prepared
11877    })
11878    .await
11879    .map_err(|_| SuperviseError::InvalidSpec {
11880        reason: "configuration launch preparation stopped".into(),
11881    })??;
11882    if let Some(registration) = &prepared.delivery_registration {
11883        if !registration.launch_current()? {
11884            return Err(spawn_plan_stale(spec));
11885        }
11886    }
11887    let _gate = match gate {
11888        Some(gate) => {
11889            Some(
11890                gate.try_lock_owned()
11891                    .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
11892                        module_id: spec.module_id.clone(),
11893                    })?,
11894            )
11895        }
11896        None => None,
11897    };
11898    if let (Some(delivery), Some(admission)) = (runtime.spawn_delivery(), &prepared.spawn_admission)
11899    {
11900        delivery.check(spec, admission)?;
11901    }
11902    if prepared
11903        .spawn_admission
11904        .as_ref()
11905        .is_none_or(|admission| admission.launch.is_none())
11906        && prepared
11907            .program_binding
11908            .as_ref()
11909            .is_some_and(|binding| !binding.current())
11910    {
11911        return Err(spawn_plan_stale(spec));
11912    }
11913    // No await may separate this last identity check from ownership publication.
11914    let checked_base = prepared
11915        .spawn_admission
11916        .as_ref()
11917        .and_then(|admission| admission.approved_base())
11918        .cloned();
11919    let mut result = launch_child_in_slot(
11920        spec,
11921        &runtime.stderr_ring,
11922        &runtime.child_roster,
11923        prepared,
11924        runtime.register_timeout,
11925    );
11926    drop(_gate);
11927    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
11928        (runtime.config_delivery.as_ref(), &result)
11929    {
11930        if let Some(base) = checked_base.filter(|_| code == "program_refused") {
11931            let module = spec.module_id.clone();
11932            let identity = subc_config::raw_digest(detail.as_bytes());
11933            let recorded = delivery
11934                .0
11935                .on_blocking(move |owner| owner.record_program_refusal(&module, &base, identity))
11936                .await;
11937            match recorded {
11938                Ok(true) => {}
11939                Ok(false) => result = Err(spawn_plan_stale(spec)),
11940                Err(error) => {
11941                    result = Err(config_delivery::gate_hold_error(
11942                        spec,
11943                        error,
11944                        Some(delivery),
11945                    ))
11946                }
11947            }
11948        }
11949    }
11950    result
11951}
11952
11953fn validate_spawn_program(
11954    spec: &ModuleSpec,
11955    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
11956    delivery: Option<config_delivery::SpawnDelivery<'_>>,
11957) -> Result<(), SuperviseError> {
11958    if let Some(admission) = admission {
11959        if let Some(program) = &admission.launch {
11960            if let Err(error) = program.validate_for_spawn() {
11961                // A captured unsigned image is a definite refusal. Uncertain
11962                // reads are deferred by validate_for_spawn, not attributed to
11963                // the operator as a changed or unapprovable program.
11964                if let (Some(context), Some(base)) = (delivery, admission.approved_base()) {
11965                    if error.code == "program_refused"
11966                        && !context.record_refusal(spec, base, &error.detail)?
11967                    {
11968                        return Err(spawn_plan_stale(spec));
11969                    }
11970                }
11971                return Err(config_delivery::gate_hold_error(
11972                    spec,
11973                    error,
11974                    delivery.map(|context| context.runtime()).as_ref(),
11975                ));
11976            }
11977        }
11978    }
11979    Ok(())
11980}
11981
11982#[allow(clippy::too_many_arguments)]
11983fn prepare_child_in_slot(
11984    spec: &ModuleSpec,
11985    connection_file_path: Option<&std::path::Path>,
11986    handle: Option<&SupervisorHandle>,
11987    capture_logs_dir: Option<&std::path::Path>,
11988    roster: &ChildRoster,
11989    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11990    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11991    role: SpawnRole,
11992    alternate_slot: bool,
11993    asynchronous: bool,
11994) -> Result<PreparedChild, SuperviseError> {
11995    require_program_search_path(spec)?;
11996    let spawn_admission = config_delivery
11997        .map(|delivery| delivery.prepare(spec))
11998        .transpose()?;
11999    #[cfg(target_os = "macos")]
12000    let gated = spawn_admission
12001        .as_ref()
12002        .is_some_and(|admission| admission.approved_base().is_some());
12003    let mut launch_spec = spawn_admission
12004        .as_ref()
12005        .and_then(|admission| admission.launch.as_ref())
12006        .map(|launch| launch.spec.clone())
12007        .unwrap_or_else(|| spec.clone());
12008    if let Some(script) = &launch_spec.script {
12009        launch_spec.program =
12010            script::runner_path(script.runtime).map_err(|source| SuperviseError::Spawn {
12011                program: launch_spec.program.clone(),
12012                source,
12013                cgroup_path: None,
12014            })?;
12015    }
12016    let script_content = if let Some(entry) = &launch_spec.script {
12017        Some(
12018            spawn_admission
12019                .as_ref()
12020                .and_then(|admission| admission.launch.as_ref())
12021                .and_then(|launch| launch.script.clone())
12022                .map_or_else(|| script::ScriptBytes::read(&entry.path), Ok)
12023                .map_err(|error| config_delivery::gate_hold_error(&launch_spec, error, None))?,
12024        )
12025    } else {
12026        None
12027    };
12028    let spec = &launch_spec;
12029    if let Some(error) = recovery_block_error(spec, roster) {
12030        return Err(error);
12031    }
12032    if let Some((pid, reason)) = roster.previous_instance(&spec.module_id) {
12033        return Err(previous_instance_error(spec, pid, reason));
12034    }
12035    if roster.is_closed() {
12036        return Err(SuperviseError::Spawn {
12037            program: spec.program.clone(),
12038            source: io::Error::other("the daemon is shutting down; not starting a new process"),
12039            cgroup_path: None,
12040        });
12041    }
12042    let carried = containment::current(&roster.containment);
12043    let carrying = carries_containment(spec.carry_containment, carried.is_some());
12044    if role != SpawnRole::Plain && carrying {
12045        return Err(SuperviseError::InvalidSpec {
12046            reason: "a carried container cannot overlap a swap candidate".to_owned(),
12047        });
12048    }
12049    #[cfg(unix)]
12050    let launch_identity = if carrying && carried.is_none() {
12051        Some(
12052            containment::LaunchIdentity::capture().map_err(|source| SuperviseError::Spawn {
12053                program: spec.program.clone(),
12054                source,
12055                cgroup_path: None,
12056            })?,
12057        )
12058    } else {
12059        None
12060    };
12061    #[cfg(target_os = "linux")]
12062    let cgroup_placement = match &carried {
12063        Some(container) => container.cgroup().map(|(placement, _)| placement),
12064        None => cgroup_placement,
12065    };
12066    #[cfg(unix)]
12067    let group_target = if let Some(container) = carried
12068        .as_ref()
12069        .filter(|container| container.group().is_some())
12070    {
12071        containment::GroupTarget::Pinned(Arc::clone(container))
12072    } else {
12073        #[cfg(target_os = "linux")]
12074        let cgroup_container = carrying && cgroup_placement.is_some();
12075        #[cfg(not(target_os = "linux"))]
12076        let cgroup_container = false;
12077        if cgroup_container {
12078            containment::GroupTarget::NoGroup
12079        } else {
12080            containment::GroupTarget::OwnLeader
12081        }
12082    };
12083    #[cfg(target_os = "linux")]
12084    let cgroup_name = {
12085        // Slot names alone are not kill domains: a retired incumbent may still
12086        // be draining when a later enable/restart spawns into the same slot.
12087        // Decimal entropy keeps the suffix unambiguous; Placement performs
12088        // the module-id escaping and constructs the filesystem path.
12089        if let Some((_, name)) = carried.as_ref().and_then(|container| container.cgroup()) {
12090            name.to_owned()
12091        } else if cgroup_placement.is_none() {
12092            swap::cgroup_name(&spec.module_id, alternate_slot)
12093        } else {
12094            let nonce = generate_launch_nonce()?;
12095            let suffix = u128::from_str_radix(&nonce[..32], 16).expect("hex launch nonce");
12096            // Leave room for byte escaping and the suffix under NAME_MAX. The
12097            // label is only for humans; the nonce identifies the kill domain.
12098            let mut end = spec.module_id.len().min(64);
12099            while !spec.module_id.is_char_boundary(end) {
12100                end -= 1;
12101            }
12102            format!(
12103                "{}_{suffix}",
12104                swap::cgroup_name(&spec.module_id[..end], alternate_slot)
12105            )
12106        }
12107    };
12108    #[cfg(not(target_os = "linux"))]
12109    let _ = alternate_slot;
12110    #[cfg(windows)]
12111    let image_capture = windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
12112        program: spec.program.clone(),
12113        source,
12114        cgroup_path: None,
12115    })?;
12116    #[cfg(windows)]
12117    let program_binding = if asynchronous {
12118        let mut resolved = spec.clone();
12119        resolved.program = image_capture.path().to_path_buf();
12120        Some(SpawnProgramBinding::capture(&resolved)?)
12121    } else {
12122        None
12123    };
12124    #[cfg(not(windows))]
12125    let program_binding = (asynchronous || cfg!(target_os = "macos"))
12126        .then(|| SpawnProgramBinding::capture(spec))
12127        .transpose()?;
12128    #[cfg(target_os = "macos")]
12129    validate_spawn_program(spec, spawn_admission.as_ref(), config_delivery)?;
12130    #[cfg(target_os = "macos")]
12131    let (mut command, privacy_exec, exec_ack) = privacy_command(
12132        spec,
12133        program_binding
12134            .as_ref()
12135            .expect("macOS captures every launch"),
12136        roster,
12137        // Ungated launches retain legacy unsuspended exec, including scripts. Suspended
12138        // verification admits approved programs only. prepare() above fails
12139        // closed if the gate cannot decide; an image sample is not authority.
12140        gated,
12141    )?;
12142    #[cfg(windows)]
12143    let mut command = Command::new(image_capture.path());
12144    #[cfg(not(any(target_os = "macos", windows)))]
12145    let mut command = Command::new(
12146        program_binding
12147            .as_ref()
12148            .map_or(spec.program.as_path(), |binding| binding.path.as_path()),
12149    );
12150    command.args(&spec.args);
12151    // AMBIENT `CK_LOG` MUST NOT LEAK INTO AN OTHERWISE UNCONFIGURED MODULE — but
12152    // that is the whole of the intent, so remove that one key rather than the
12153    // environment.
12154    //
12155    // This was `env_clear()` from 0.17.41 until 0.18.3, which achieved the goal
12156    // and took the POSIX environment with it. Modules spawned that way had no
12157    // HOME, XDG_RUNTIME_DIR, TMPDIR or USER, and the consequences ran past
12158    // logging:
12159    //
12160    //   * `connection_file::discover` reads XDG_RUNTIME_DIR and HOME, so with
12161    //     both unset it fell back to the temp dir alone and `ck` could not find
12162    //     a daemon running on the same machine from inside any module's process
12163    //     tree — reporting a path the file has never lived at, which reads as
12164    //     "the daemon did not write its file".
12165    //   * `default_data_home()` with HOME and XDG_DATA_HOME both unset returns
12166    //     the RELATIVE `.local/share`, so a module deriving its own store path
12167    //     resolved it against its own CWD. That is the store-fragmentation
12168    //     defect the daemon already refuses in config (`parse_doc` rejects a
12169    //     relative `storage.data_home`) arriving by derivation instead.
12170    //   * anything a module spawns inherited it: git without ~/.gitconfig,
12171    //     cargo without CARGO_HOME, ssh, python user dirs — all degrading
12172    //     quietly rather than erroring.
12173    //
12174    // Reported by iceteaSA as #104 after deploying 0.18.2, where `ck daemon`
12175    // offered one candidate under /tmp while the file sat in /run/user/1000.
12176    //
12177    // A configured module is unaffected either way: `module_spec()` puts the
12178    // resolved CK_LOG into `spec.env`, which is applied below and therefore
12179    // wins over anything ambient.
12180    apply_child_env(&mut command, spec);
12181    if spec.script.is_some() {
12182        script::remove_runtime_env(&mut command, spec);
12183    }
12184    let origin_witness = crate::program_origin::LaunchWitness::capture_command(spec, &command)
12185        .map_err(|source| SuperviseError::Spawn {
12186            program: spec.program.clone(),
12187            source,
12188            cgroup_path: None,
12189        })?;
12190    command.current_dir(&origin_witness.working_directory);
12191    apply_spawn_role(&mut command, role);
12192    let nonce_handoff = apply_wire_spawn_args_for_admission(
12193        &mut command,
12194        spec,
12195        connection_file_path,
12196        handle,
12197        role,
12198        spawn_admission.as_ref(),
12199    )?;
12200    #[cfg(unix)]
12201    let mut slots = subc_os::registration_channel::ChildDescriptorSlots::default();
12202    command.env_remove(subc_os::script_pipe::SCRIPT_FD_ENV);
12203    let script_delivery = script_content
12204        .map(|content| {
12205            script::Delivery::prepare(
12206                content,
12207                &mut command,
12208                #[cfg(unix)]
12209                &mut slots,
12210            )
12211        })
12212        .transpose()
12213        .map_err(|source| SuperviseError::Spawn {
12214            program: spec.program.clone(),
12215            source,
12216            cgroup_path: None,
12217        })?;
12218    #[cfg(unix)]
12219    let registration_channel = if spec.protocol == ModuleProtocol::Subc {
12220        let (parent, child, metadata) = subc_os::registration_channel::registration_socketpair()
12221            .map_err(|source| SuperviseError::Spawn {
12222                program: spec.program.clone(),
12223                source,
12224                cgroup_path: None,
12225            })?;
12226        slots
12227            .channel(child)
12228            .map_err(|source| SuperviseError::Spawn {
12229                program: spec.program.clone(),
12230                source,
12231                cgroup_path: None,
12232            })?;
12233        command
12234            .env(subc_os::registration_channel::REGISTRATION_FD_ENV, metadata)
12235            .env(
12236                subc_os::registration_channel::DAEMON_PID_ENV,
12237                std::process::id().to_string(),
12238            );
12239        Some(parent)
12240    } else {
12241        None
12242    };
12243    #[cfg(windows)]
12244    let registration_channel = prepare_windows_registration_pipe(&mut command, spec)?;
12245    let binding_publication = if spawn_admission
12246        .as_ref()
12247        .is_some_and(|admission| admission.launch.is_some())
12248    {
12249        handle.and_then(|handle| handle.begin_program_binding(&spec.module_id, role))
12250    } else {
12251        None
12252    };
12253    let registration_spawn = (spec.protocol == ModuleProtocol::Subc)
12254        .then(|| {
12255            handle.map(|handle| {
12256                let spawn = RegistrationSpawn::new_with_binding_requirement(
12257                    handle,
12258                    &spec.module_id,
12259                    role,
12260                    binding_publication.clone(),
12261                    spawn_admission
12262                        .as_ref()
12263                        .is_some_and(|admission| admission.launch.is_some()),
12264                );
12265                if let Some(admission) = &spawn_admission {
12266                    admission.initialize_origin(&spawn.authority, &origin_witness);
12267                }
12268                handle.record_nonce_launch(&spawn);
12269                spawn
12270            })
12271        })
12272        .flatten();
12273
12274    #[cfg(target_os = "linux")]
12275    let cgroup_path = cgroup_placement
12276        .map(|placement| {
12277            if let Some(container) = &carried {
12278                let path = container
12279                    .cgroup_path()
12280                    .ok_or_else(|| io::Error::other("carried container has no cgroup path"))?;
12281                placement.existing_module_path(path)?.ok_or_else(|| {
12282                    io::Error::new(
12283                        io::ErrorKind::NotFound,
12284                        "carried cgroup disappeared before replacement",
12285                    )
12286                })
12287            } else {
12288                if carrying {
12289                    containment::prepare_cgroup_path(placement, &cgroup_name)
12290                } else {
12291                    placement.module_path(&cgroup_name)
12292                }
12293            }
12294        })
12295        .transpose()
12296        .map_err(|source| SuperviseError::Cgroup {
12297            module_id: spec.module_id.clone(),
12298            source,
12299        })?;
12300    #[cfg(not(target_os = "linux"))]
12301    let cgroup_path: Option<PathBuf> = None;
12302    // Own a newly created directory before any fallible admission or command
12303    // preparation. Existing carried containment must never be removed here.
12304    #[cfg(target_os = "linux")]
12305    let cgroup_cleanup = PreparedCgroup(
12306        cgroup_placement
12307            .filter(|_| carried.is_none())
12308            .map(|placement| (placement.clone(), cgroup_name.clone())),
12309    );
12310    #[cfg(unix)]
12311    let mut admission_gate = if carrying {
12312        Some(
12313            admission::Gate::install(&mut command, spec, roster).map_err(|source| {
12314                SuperviseError::Spawn {
12315                    program: spec.program.clone(),
12316                    source,
12317                    cgroup_path: cgroup_path.clone(),
12318                }
12319            })?,
12320        )
12321    } else {
12322        None
12323    };
12324    #[cfg(target_os = "linux")]
12325    if let Some(path) = &cgroup_path {
12326        apply_cgroup_placement(&mut command, spec, path)?;
12327    }
12328
12329    let output_sink = if let Some(logs_dir) = capture_logs_dir {
12330        let path = logs_dir.join(format!("{}.stderr.log", spec.module_id));
12331        match ChildOutputSink::open(&path, capture_retention(spec)) {
12332            Ok(sink) => sink,
12333            Err(error) => {
12334                warn!(
12335                    module_id = %spec.module_id,
12336                    path = %path.display(),
12337                    error = %error,
12338                    "could not open child output capture file; forwarding to stderr"
12339                );
12340                ChildOutputSink::Stderr
12341            }
12342        }
12343    } else {
12344        ChildOutputSink::Stderr
12345    };
12346
12347    command.stdout(Stdio::piped());
12348    command.stderr(Stdio::piped());
12349    command.kill_on_drop(!carrying);
12350    // EACH MODULE LEADS ITS OWN PROCESS GROUP (the child calls setpgid(0, 0)
12351    // before exec). In the daemon's group, a service manager that kills the
12352    // job's process group when the daemon exits (launchd's default) killed
12353    // every module at the same moment its control connection closed, so no
12354    // module ever ran its EOF teardown on a daemon stop. Outside that group a
12355    // module is reached only by the daemon: the EOF it sees when its
12356    // connection closes, and the bounded stop in `child_roster` for anything
12357    // still running after that. On Linux this composes with the cgroup
12358    // placement above: that is a pre_exec write to cgroup.procs, std performs
12359    // setpgid in the child before running pre_exec callbacks, and the two
12360    // change independent process attributes.
12361    //
12362    // stdin is /dev/null because a process outside the terminal's foreground
12363    // group is stopped (SIGTTIN) if it reads the terminal, which a daemon run
12364    // by hand would otherwise hand down. Under a service manager stdin is
12365    // already /dev/null.
12366    #[cfg(unix)]
12367    command.process_group(
12368        carried
12369            .as_ref()
12370            .map(|container| container.verified_join_group())
12371            .transpose()
12372            .map_err(|source| SuperviseError::Spawn {
12373                program: spec.program.clone(),
12374                source,
12375                cgroup_path: cgroup_path.clone(),
12376            })?
12377            .flatten()
12378            .unwrap_or(0) as i32,
12379    );
12380    command.stdin(Stdio::null());
12381    #[cfg(unix)]
12382    if let Some(gate) = &mut admission_gate {
12383        gate.install_placement(&mut command);
12384    }
12385    // Fill all reserved slots in one allocation-free step, after placement has
12386    // stopped using descriptors that the fixed slots may replace.
12387    #[cfg(unix)]
12388    {
12389        if let Some(handoff) = nonce_handoff {
12390            slots.nonce(handoff);
12391        }
12392        #[cfg(target_os = "macos")]
12393        slots
12394            .acknowledgement(exec_ack.into_descriptor())
12395            .map_err(|source| SuperviseError::Spawn {
12396                program: spec.program.clone(),
12397                source,
12398                cgroup_path: cgroup_path.clone(),
12399            })?;
12400        slots.install(command.as_std_mut());
12401    }
12402    #[cfg(not(any(unix, windows)))]
12403    let _ = nonce_handoff;
12404
12405    // Containment, step 1 of 3 (issue #109): create the child suspended so it
12406    // cannot run a single instruction -- and therefore cannot spawn a
12407    // grandchild -- before it is in the job. See `contain_spawned_child` for the
12408    // other two steps and why the window matters.
12409    #[cfg(windows)]
12410    {
12411        subc_jobobject::ensure_root_job().map_err(|source| SuperviseError::Spawn {
12412            program: spec.program.clone(),
12413            source,
12414            cgroup_path: None,
12415        })?;
12416        subc_jobobject::suspend_on_create_async(&mut command);
12417    }
12418    // Timestamp before the spawn call: on Unix the child can serve before that
12419    // call even returns. This conservative bound never labels an older child
12420    // as a replacement for a request received during process creation.
12421    let spawned_at = Instant::now();
12422    let delivery_context = config_delivery;
12423    let config_delivery = config_delivery
12424        .map(|delivery| {
12425            delivery.spawned(
12426                spec,
12427                spawn_admission
12428                    .as_ref()
12429                    .expect("delivery prepares spawn admission"),
12430                spawned_at,
12431                role,
12432                registration_spawn
12433                    .as_ref()
12434                    .map(|spawn| spawn.authority.clone()),
12435            )
12436        })
12437        .transpose()?
12438        .flatten();
12439    let mut delivery_registration =
12440        delivery_context.map(|context| context.registration_guard(config_delivery.as_ref(), role));
12441    if let Some(registration) = &mut delivery_registration {
12442        registration.defer_cleanup();
12443    }
12444    if asynchronous {
12445        #[cfg(test)]
12446        if let Some(context) = delivery_context {
12447            context.pause_preflight_for_test();
12448        }
12449    }
12450    validate_spawn_program(spec, spawn_admission.as_ref(), delivery_context)?;
12451    Ok(PreparedChild {
12452        script_delivery,
12453        registration_spawn,
12454        registration_handle: handle.cloned(),
12455        #[cfg(any(unix, windows))]
12456        registration_channel,
12457        config_context: delivery_context.map(|delivery| delivery.runtime()),
12458        binding_publication,
12459        launch_spec,
12460        spawn_admission,
12461        command,
12462        carrying,
12463        carried: carried.clone(),
12464        #[cfg(unix)]
12465        launch_identity,
12466        #[cfg(unix)]
12467        group_target,
12468        #[cfg(target_os = "linux")]
12469        cgroup_placement: cgroup_placement.cloned(),
12470        #[cfg(target_os = "linux")]
12471        cgroup_cleanup,
12472        #[cfg(target_os = "linux")]
12473        cgroup_name,
12474        cgroup_path,
12475        #[cfg(unix)]
12476        admission_gate,
12477        output_sink,
12478        #[cfg(target_os = "macos")]
12479        privacy_exec,
12480        #[cfg(windows)]
12481        image_capture,
12482        #[cfg(windows)]
12483        nonce_handoff,
12484        spawned_at,
12485        config_delivery,
12486        delivery_registration,
12487        program_binding,
12488    })
12489}
12490
12491fn launch_child_in_slot(
12492    _spec: &ModuleSpec,
12493    ring: &Arc<Mutex<StderrRing>>,
12494    roster: &ChildRoster,
12495    prepared: PreparedChild,
12496    register_timeout: Duration,
12497) -> Result<SupervisedChild, SuperviseError> {
12498    let launch_spec = prepared.launch_spec.clone();
12499    let registration_declaration = prepared
12500        .spawn_admission
12501        .as_ref()
12502        .and_then(|admission| admission.registration_declaration(&launch_spec.module_id));
12503    let admission_base = prepared
12504        .spawn_admission
12505        .as_ref()
12506        .and_then(|admission| admission.approved_base())
12507        .cloned();
12508    let spec = &launch_spec;
12509    let expected_image = prepared
12510        .spawn_admission
12511        .as_ref()
12512        .and_then(|admission| admission.launch.as_ref())
12513        .map(|launch| launch.image);
12514    let program_launch = prepared
12515        .spawn_admission
12516        .and_then(|admission| admission.launch);
12517    let config_owner = prepared
12518        .config_context
12519        .as_ref()
12520        .map(|context| context.0.clone());
12521    let binding_publication = prepared.binding_publication;
12522    #[cfg(test)]
12523    if let Some(context) = &prepared.config_context {
12524        context.0.before_spawn_exec_for_test();
12525    }
12526    #[cfg(feature = "test-support")]
12527    if let Some(context) = &prepared.config_context {
12528        context
12529            .0
12530            .pause_spawn_before_exec()
12531            .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(context)))?;
12532    }
12533    let mut command = prepared.command;
12534    let carrying = prepared.carrying;
12535    let carried = prepared.carried;
12536    #[cfg(unix)]
12537    let launch_identity = prepared.launch_identity;
12538    #[cfg(unix)]
12539    let group_target = prepared.group_target;
12540    #[cfg(target_os = "linux")]
12541    let cgroup_placement = prepared.cgroup_placement.as_ref();
12542    #[cfg(target_os = "linux")]
12543    let cgroup_name = prepared.cgroup_name;
12544    #[cfg(target_os = "linux")]
12545    let mut cgroup_cleanup = prepared.cgroup_cleanup;
12546    #[cfg(target_os = "linux")]
12547    let _ = cgroup_cleanup.0.take();
12548    let cgroup_path = prepared.cgroup_path;
12549    #[cfg(unix)]
12550    let admission_gate = prepared.admission_gate;
12551    let output_sink = prepared.output_sink;
12552    #[cfg(target_os = "macos")]
12553    let mut privacy_exec = prepared.privacy_exec;
12554    #[cfg(target_os = "macos")]
12555    if let Some(pending) = &mut privacy_exec {
12556        pending.admission_binding = binding_publication.clone();
12557        if expected_image.is_some() {
12558            pending.expected = expected_image;
12559        }
12560    }
12561    #[cfg(any(unix, windows))]
12562    let registration_channel = prepared.registration_channel;
12563    let registration_spawn = prepared.registration_spawn;
12564    let registration_handle = prepared.registration_handle;
12565    #[cfg(windows)]
12566    let image_capture = prepared.image_capture;
12567    #[cfg(windows)]
12568    let nonce_handoff = prepared.nonce_handoff;
12569    let spawned_at = prepared.spawned_at;
12570    let config_delivery = prepared.config_delivery;
12571    let delivery_registration = prepared.delivery_registration;
12572    let _program_binding = prepared.program_binding;
12573    #[cfg(all(test, unix))]
12574    containment_tests::record_spawn_attempt(spec, &mut command);
12575    #[cfg(unix)]
12576    let spawned = match admission_gate {
12577        Some(gate) => gate
12578            .spawn(
12579                command,
12580                spec,
12581                roster,
12582                launch_identity,
12583                #[cfg(target_os = "linux")]
12584                cgroup_placement
12585                    .zip(cgroup_path.as_ref())
12586                    .map(|(placement, path)| {
12587                        (placement.clone(), cgroup_name.clone(), path.clone())
12588                    }),
12589            )
12590            .map(|(child, admitted)| (child, Some(admitted))),
12591        None => {
12592            let spawned =
12593                subc_os::child_spawn::tokio_spawn(&mut command).map(|child| (child, None));
12594            // The callback owns all child-only sources. Closing them here is
12595            // necessary for channel EOF and macOS exec acknowledgement EOF.
12596            drop(command);
12597            spawned
12598        }
12599    };
12600    #[cfg(not(unix))]
12601    let spawned = subc_os::child_spawn::tokio_spawn(&mut command);
12602    let spawned = match spawned {
12603        Ok(child) => child,
12604        Err(source) => {
12605            if carried
12606                .as_ref()
12607                .and_then(|container| container.group())
12608                .is_some()
12609            {
12610                containment::terminate_blocking(&roster.containment);
12611            }
12612            #[cfg(target_os = "linux")]
12613            if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12614                remove_module_cgroup(placement, &cgroup_name);
12615            }
12616            return Err(SuperviseError::Spawn {
12617                program: spec.program.clone(),
12618                source,
12619                cgroup_path,
12620            });
12621        }
12622    };
12623    #[cfg(unix)]
12624    let (mut child, mut admitted) = spawned;
12625    #[cfg(unix)]
12626    let group_target = admitted
12627        .as_ref()
12628        .map(|attempt| attempt.group_target())
12629        .unwrap_or(group_target);
12630    #[cfg(not(unix))]
12631    let mut child = spawned;
12632    if let Some(delivery) = prepared.script_delivery {
12633        delivery.start(child.id().expect("spawned child has a pid"));
12634    }
12635    #[cfg(test)]
12636    spawn_record_tests::after_create(&child, spec);
12637
12638    // Bind while the child is still suspended, before job assignment resumes it.
12639    // Keeping the executable handle open across CreateProcessW denies rename
12640    // and deletion, so the file cannot be exchanged during spawn. Bind that
12641    // file ID to the process handle returned by spawn, never a reopened PID.
12642    #[cfg(windows)]
12643    let windows_image = match image_capture.bind_tokio(&child) {
12644        Ok(image) => Arc::new(image),
12645        Err(source) => {
12646            kill_and_reap_rejected_child(&mut child);
12647            return Err(SuperviseError::Spawn {
12648                program: spec.program.clone(),
12649                source,
12650                cgroup_path: None,
12651            });
12652        }
12653    };
12654    // Assign the suspended child to its module job; resume only after its
12655    // process identity has been durably recorded for orphan recovery.
12656    #[cfg(windows)]
12657    let job = contain_spawned_child(&mut child, spec, carried.as_ref())?;
12658    let spawned_at_ms = unix_ms_now();
12659    #[cfg(not(windows))]
12660    let spawned_from = spec.program.clone();
12661    #[cfg(windows)]
12662    let spawned_from = windows_image.path().to_path_buf();
12663    #[cfg(not(windows))]
12664    let spawned_file_identity = spawned_file_identity(&spawned_from);
12665    #[cfg(windows)]
12666    let spawned_file_identity = Some(SpawnedFileIdentity {
12667        device: 0,
12668        inode: 0,
12669        windows_image: Some(Arc::clone(&windows_image)),
12670    });
12671    let pid = child.id().ok_or_else(|| SuperviseError::Spawn {
12672        program: spec.program.clone(),
12673        source: io::Error::other("spawned child exposed no live pid"),
12674        cgroup_path: cgroup_path.clone(),
12675    })?;
12676    #[cfg(windows)]
12677    let nonce_delivery = start_windows_nonce_pipe(nonce_handoff, pid, spec);
12678    #[cfg(not(windows))]
12679    let process_start_time = admitted
12680        .as_ref()
12681        .map(|admitted| admitted.birth)
12682        .or_else(|| crate::provenance::process_start_time(pid));
12683    #[cfg(windows)]
12684    let process_start_time = Some(windows_image.start_time());
12685    let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
12686    #[cfg(all(test, target_os = "macos"))]
12687    privacy_exec_boundary_tests::before_image_sample(spec, pid);
12688    #[cfg(all(test, target_os = "linux"))]
12689    assert!(roster.admission_event_for_test(&spec.module_id, "before_image_binding", Some(pid)));
12690    // Record the committed kernel image, not the configured pathname: PATH
12691    // lookup and shebang interpretation can select a different executable.
12692    // Linux's posix_spawn can return before that image is installed, so the
12693    // observer also waits for the kernel's first-exec flag to clear.
12694    #[cfg(not(windows))]
12695    let recorded_image = observe_spawned_image(pid);
12696    #[cfg(all(test, target_os = "linux"))]
12697    let recorded_image = if roster.admission_event_for_test(
12698        &spec.module_id,
12699        "after_spawn_image_sample",
12700        Some(pid),
12701    ) {
12702        recorded_image
12703    } else {
12704        None
12705    };
12706    #[cfg(target_os = "linux")]
12707    // An exited child cannot receive HELLO service and has no readable /proc/exe.
12708    // Keep its real exit for the supervisor instead of turning a crash into a hold.
12709    let exited_before_binding = expected_image.is_some()
12710        && recorded_image.and_then(|image| image.executable) != expected_image
12711        && child.try_wait().ok().flatten().is_some();
12712    #[cfg(target_os = "linux")]
12713    let unavailable_initial_image = expected_image.is_some()
12714        && recorded_image.and_then(|image| image.executable).is_none()
12715        && !exited_before_binding;
12716    #[cfg(not(target_os = "linux"))]
12717    let unavailable_initial_image = false;
12718    #[cfg(target_os = "linux")]
12719    if expected_image
12720        .is_some_and(|expected| recorded_image.and_then(|image| image.executable) != Some(expected))
12721        && !exited_before_binding
12722        && !unavailable_initial_image
12723    {
12724        kill_module_cgroup(cgroup_placement, &cgroup_name);
12725        kill_and_reap_rejected_child(&mut child, group_target.clone());
12726        return Err(SuperviseError::ConfigHeld {
12727            module_id: spec.module_id.clone(),
12728            code: "program_refused".into(),
12729            detail: format!(
12730                "spawned executable {:?} does not match hashed program {:?}",
12731                recorded_image.and_then(|image| image.executable),
12732                expected_image
12733            ),
12734        });
12735    }
12736    #[cfg(not(target_os = "linux"))]
12737    let _ = expected_image;
12738    #[cfg(target_os = "macos")]
12739    let binding_ready = privacy_exec.is_none();
12740    #[cfg(target_os = "linux")]
12741    let binding_ready = !exited_before_binding;
12742    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
12743    let binding_ready = cfg!(windows);
12744    // spawn() confirms only the first exec, into the trampoline. Never persist
12745    // the trampoline image; the asynchronous acknowledgement publishes the
12746    // module image once the trampoline has replaced itself with the module.
12747    #[cfg(target_os = "macos")]
12748    let recorded_image = if privacy_exec.is_some() {
12749        None
12750    } else {
12751        recorded_image
12752    };
12753    #[cfg(target_os = "linux")]
12754    let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
12755    #[cfg(not(target_os = "linux"))]
12756    let recorded_cgroup_name = None;
12757    #[cfg(unix)]
12758    let preadmitted = admitted
12759        .as_mut()
12760        .and_then(|admitted| admitted.leader.take());
12761    #[cfg(not(unix))]
12762    let preadmitted: Option<crate::child_roster::RosterGuard> = None;
12763    let roster_guard = if let Some(guard) = preadmitted {
12764        Ok(guard)
12765    } else {
12766        roster.admit(
12767            spec.module_id.clone(),
12768            pid,
12769            spec.protocol,
12770            process_start_time,
12771            crate::child_roster::RecordedIdentity {
12772                container: None,
12773                #[cfg(unix)]
12774                carried: None,
12775                #[cfg(not(windows))]
12776                start_time: recorded_image.map(|image| image.start_time),
12777                #[cfg(windows)]
12778                start_time: process_start_time,
12779                #[cfg(not(windows))]
12780                executable: recorded_image
12781                    .and_then(|image| image.executable)
12782                    .map(crate::live_children::ExecutableIdentity::from),
12783                #[cfg(windows)]
12784                executable: Some(crate::live_children::ExecutableIdentity::from(
12785                    windows_image.identity(),
12786                )),
12787                cgroup_name: recorded_cgroup_name,
12788                #[cfg(target_os = "linux")]
12789                cgroup_placement: cgroup_placement.cloned(),
12790            },
12791        )
12792    };
12793    let roster_guard = match roster_guard {
12794        Ok(guard) => guard,
12795        Err(failure) => {
12796            return failure.with_cleanup(|source| {
12797                #[cfg(windows)]
12798                if let Some(job) = &job {
12799                    let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
12800                }
12801                #[cfg(target_os = "linux")]
12802                kill_module_cgroup(cgroup_placement, &cgroup_name);
12803                #[cfg(unix)]
12804                let rejected_group = group_target.clone();
12805                kill_and_reap_rejected_child(
12806                    &mut child,
12807                    #[cfg(unix)]
12808                    rejected_group,
12809                );
12810                #[cfg(target_os = "linux")]
12811                if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12812                    remove_module_cgroup(placement, &cgroup_name);
12813                }
12814                Err(SuperviseError::Spawn {
12815                    program: spec.program.clone(),
12816                    source: io::Error::other(format!(
12817                        "could not durably record module child: {source}"
12818                    )),
12819                    cgroup_path,
12820                })
12821            });
12822        }
12823    };
12824    #[cfg(unix)]
12825    if admitted.is_some() {
12826        if let Some(image) = recorded_image {
12827            if let Err(source) = roster_guard.confirm_executable(image) {
12828                kill_and_reap_rejected_child(&mut child, group_target.clone());
12829                return Err(SuperviseError::Spawn {
12830                    program: spec.program.clone(),
12831                    source,
12832                    cgroup_path,
12833                });
12834            }
12835        }
12836    }
12837    // The pre-spawn check can pass just before shutdown begins. Ownership is
12838    // published at the start of admission, even while a record write is queued.
12839    // If shutdown already saw an empty roster before that publication, this
12840    // check sees the roster closed and ends the child before starting a module.
12841    if roster.is_closed() {
12842        if carrying {
12843            #[cfg(unix)]
12844            let rejected_group = admitted
12845                .as_ref()
12846                .map(|admitted| admitted.rejection_target())
12847                .unwrap_or_else(|| group_target.clone());
12848            #[cfg(windows)]
12849            if let Some(job) = &job {
12850                let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
12851            }
12852            kill_and_reap_rejected_child(
12853                &mut child,
12854                #[cfg(unix)]
12855                rejected_group,
12856            );
12857            #[cfg(all(test, unix))]
12858            let _ =
12859                roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
12860            drop(roster_guard);
12861            return Err(SuperviseError::Spawn {
12862                program: spec.program.clone(),
12863                source: io::Error::other(
12864                    "the daemon began shutting down during carried admission; ended the container",
12865                ),
12866                cgroup_path,
12867            });
12868        }
12869        // This child was never admitted, so there is no module protocol shutdown to wait for.
12870        #[cfg(target_os = "linux")]
12871        kill_module_cgroup(cgroup_placement, &cgroup_name);
12872        if let Err(error) = child.start_kill() {
12873            debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
12874        }
12875        #[cfg(target_os = "linux")]
12876        if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12877            // This spawn was never admitted, so shutdown has no roster entry
12878            // to await. Do not detach its cleanup: the runtime could exit
12879            // before that task reaps the rejected child and removes its group.
12880            while matches!(child.try_wait(), Ok(None)) {
12881                std::thread::yield_now();
12882            }
12883            if matches!(
12884                subc_cgroup::kill_module(Some(placement), &cgroup_name),
12885                subc_cgroup::KillOutcome::Killed
12886            ) {
12887                if let Ok(path) = placement.module_path(&cgroup_name) {
12888                    while std::fs::read_to_string(path.join("cgroup.events"))
12889                        .ok()
12890                        .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
12891                    {
12892                        std::thread::yield_now();
12893                    }
12894                }
12895            }
12896            remove_module_cgroup(placement, &cgroup_name);
12897        }
12898        drop(roster_guard);
12899        return Err(SuperviseError::Spawn {
12900            program: spec.program.clone(),
12901            source: io::Error::other(
12902                "the daemon began shutting down while this process was starting; ended it",
12903            ),
12904            cgroup_path,
12905        });
12906    }
12907
12908    let stdout_pump = match child.stdout.take() {
12909        Some(stdout) => Some(tokio::spawn(pump_stdout_to(stdout, output_sink.clone()))),
12910        None => {
12911            warn!(
12912                module_id = %spec.module_id,
12913                "spawned child exposed no stdout pipe; file capture will be incomplete"
12914            );
12915            None
12916        }
12917    };
12918    let stderr_pump = match child.stderr.take() {
12919        Some(stderr) => {
12920            let generation = ring
12921                .lock()
12922                .unwrap_or_else(|poisoned| poisoned.into_inner())
12923                .begin_process();
12924            Some(StderrPump {
12925                task: tokio::spawn(pump_stderr_to(
12926                    stderr,
12927                    Arc::clone(ring),
12928                    generation,
12929                    output_sink,
12930                )),
12931                generation,
12932            })
12933        }
12934        None => {
12935            // Spawning succeeded but the pipe did not materialise. Recording it as
12936            // uncaptured keeps the tail honest: the alternative is an empty tail
12937            // that reads as a module which printed nothing.
12938            ring.lock()
12939                .unwrap_or_else(|poisoned| poisoned.into_inner())
12940                .mark_not_captured("stderr pipe was not available on spawn");
12941            warn!(
12942                module_id = %spec.module_id,
12943                "spawned child exposed no stderr pipe; tail will be unavailable"
12944            );
12945            None
12946        }
12947    };
12948
12949    let exec = Arc::new(crate::activity::ExecOutcome::new());
12950    #[cfg(target_os = "macos")]
12951    let pending_exec = privacy_exec.is_some();
12952    #[cfg(not(target_os = "macos"))]
12953    let pending_exec = false;
12954    if !pending_exec {
12955        exec.finish(crate::activity::ExecState::CommittedExec);
12956    }
12957    #[cfg(windows)]
12958    let subtree_target = job
12959        .as_ref()
12960        .map(|job| crate::subtree_resources::Target::Job(Arc::downgrade(job)))
12961        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_job"));
12962    #[cfg(target_os = "linux")]
12963    let subtree_target = cgroup_path
12964        .map(crate::subtree_resources::Target::Cgroup)
12965        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_cgroup"));
12966    #[cfg(not(any(target_os = "linux", windows)))]
12967    let subtree_target = crate::subtree_resources::Target::Unavailable("unsupported_platform");
12968    let mut supervised = SupervisedChild {
12969        registration_spawn,
12970        #[cfg(any(unix, windows))]
12971        registration_channel,
12972        live_program_binding: None,
12973        registered_config_connection: None,
12974        admission_base,
12975        registration_declaration,
12976        _program_binding: binding_publication,
12977        subtree_target,
12978        child: containment::ProcessChild::plain(child, pid),
12979        exec: crate::activity::ExecOwner(exec),
12980        #[cfg(windows)]
12981        nonce_delivery,
12982        protocol: spec.protocol,
12983        #[cfg(target_os = "linux")]
12984        module_id: cgroup_name,
12985        #[cfg(target_os = "linux")]
12986        cgroup_placement: cgroup_placement.cloned(),
12987        #[cfg(windows)]
12988        job,
12989        stdout_pump,
12990        stderr_pump,
12991        stderr_ring: Arc::clone(ring),
12992        spawned_at,
12993        config_delivery,
12994        registration_deadline: None,
12995        registration_watch: None,
12996        spawned_at_ms,
12997        spawned_from,
12998        launch_spec_digest: LaunchSpecDigest::from_spec(spec),
12999        spawned_file_identity,
13000        process_start_time,
13001        process_identity,
13002        pid,
13003        roster_guard: Some(roster_guard),
13004        #[cfg(target_os = "macos")]
13005        privacy_exec,
13006        #[cfg(target_os = "macos")]
13007        report_ready: Arc::new(OnceLock::new()),
13008        spawn_failure: None,
13009        admission_kill_sent: false,
13010    };
13011    if let Err(error) = containment::adopt(&mut supervised, spec, roster) {
13012        supervised.child.reject(
13013            #[cfg(unix)]
13014            group_target,
13015        );
13016        #[cfg(all(test, unix))]
13017        let _ = roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
13018        return Err(error);
13019    }
13020    if let (Some(launch), Some(owner), Some(base)) = (
13021        program_launch,
13022        config_owner,
13023        supervised.admission_base.clone(),
13024    ) {
13025        supervised.live_program_binding =
13026            content_binding::LiveProgramBinding::new(launch, &supervised, owner, base);
13027        if let (Some(publication), Some(live)) = (
13028            &supervised._program_binding,
13029            &supervised.live_program_binding,
13030        ) {
13031            publication.attach(live);
13032        }
13033    }
13034    #[cfg(unix)]
13035    if let Some(admitted) = admitted.take() {
13036        admitted.disarm();
13037    }
13038    #[cfg(windows)]
13039    if let Err(error) = resume_suspended_child(pid, spec) {
13040        containment::terminate_blocking(&roster.containment);
13041        let _ = supervised.child.start_kill();
13042        return Err(error);
13043    }
13044    if binding_ready {
13045        // An unreadable initial image is not a definite mismatch. Keep the
13046        // owned child and delivery registration until its reaped status decides
13047        // whether it crashed on its own or was stopped by admission's kill.
13048        let checked = if unavailable_initial_image {
13049            Err(crate::config_gate::GateError::new(
13050                "config_delivery_deferred",
13051                "initial process image is unavailable",
13052            ))
13053        } else {
13054            match (
13055                &supervised._program_binding,
13056                &supervised.live_program_binding,
13057            ) {
13058                (Some(binding), _) => binding.verify(),
13059                (None, Some(live)) => live.check(),
13060                _ if supervised.admission_base.is_some() => {
13061                    Err(crate::config_gate::GateError::new(
13062                        "config_delivery_deferred",
13063                        "live program witness is unavailable",
13064                    ))
13065                }
13066                _ => Ok(()),
13067            }
13068        };
13069        #[cfg(all(test, target_os = "linux"))]
13070        let checked = if roster.admission_event_for_test(
13071            &spec.module_id,
13072            "after_content_witness_check",
13073            Some(pid),
13074        ) {
13075            checked
13076        } else {
13077            Err(crate::config_gate::GateError::new(
13078                "config_delivery_deferred",
13079                "current process image is unavailable",
13080            ))
13081        };
13082        if let Err(error) = checked {
13083            if let Some(binding) = &mut supervised._program_binding {
13084                binding.reject();
13085            }
13086            // Reap through the normal child-reaping path, retaining the real exit record and
13087            // its roster ownership. A refusal must also end any helpers.
13088            if error.code == "program_refused" || supervised.try_wait().ok().flatten().is_none() {
13089                supervised.spawn_failure = Some(format!("{}: {}", error.code, error.detail));
13090                #[cfg(all(test, target_os = "linux"))]
13091                assert!(roster.admission_event_for_test(
13092                    &spec.module_id,
13093                    if unavailable_initial_image {
13094                        "before_initial_image_kill"
13095                    } else {
13096                        "before_content_witness_kill"
13097                    },
13098                    Some(pid),
13099                ));
13100                let _ = supervised.start_admission_kill();
13101                #[cfg(all(test, target_os = "linux"))]
13102                if supervised.admission_kill_sent {
13103                    assert!(roster.admission_event_for_test(
13104                        &spec.module_id,
13105                        "after_admission_kill_sent",
13106                        Some(pid),
13107                    ));
13108                }
13109            }
13110        }
13111    }
13112    if let Some(registration) = delivery_registration {
13113        registration.commit();
13114    }
13115    if let Some(spawn) = &supervised.registration_spawn {
13116        if let Some(identity) = supervised.process_identity {
13117            let _ = spawn.identity.set(identity);
13118        }
13119        if supervised.spawn_failure.is_some() {
13120            spawn.refuse();
13121        } else if binding_ready {
13122            spawn.ready();
13123        }
13124        #[cfg(any(unix, windows))]
13125        if let (Some(handle), Some(channel)) =
13126            (registration_handle, supervised.registration_channel.take())
13127        {
13128            handle.serve_registration(channel, spawn.clone(), pid, spawned_at + register_timeout);
13129        }
13130    }
13131    Ok(supervised)
13132}
13133
13134#[cfg(test)]
13135mod spawn_record_tests {
13136    use super::*;
13137
13138    thread_local! {
13139        static LAST_PID: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
13140    }
13141
13142    pub(super) fn after_create(child: &Child, _spec: &ModuleSpec) {
13143        LAST_PID.set(child.id());
13144        #[cfg(windows)]
13145        if let Some((_, address)) = _spec
13146            .env
13147            .iter()
13148            .find(|(key, _)| key == "SUBC_TEST_AFTER_CREATE")
13149        {
13150            use std::io::{Read, Write};
13151            let mut stream = std::net::TcpStream::connect(address).unwrap();
13152            stream
13153                .write_all(&child.id().unwrap().to_ne_bytes())
13154                .unwrap();
13155            let mut release = [0];
13156            stream.read_exact(&mut release).unwrap();
13157        }
13158    }
13159
13160    #[cfg(windows)]
13161    pub(super) fn assignment_failpoint(spec: &ModuleSpec) -> io::Result<()> {
13162        if spec
13163            .env
13164            .iter()
13165            .any(|(key, _)| key == "SUBC_TEST_ASSIGNMENT_FAILURE")
13166        {
13167            Err(io::Error::other("injected module job assignment failure"))
13168        } else {
13169            Ok(())
13170        }
13171    }
13172
13173    fn spec() -> ModuleSpec {
13174        ModuleSpec {
13175            script: None,
13176            module_id: "spawn-record-worker".into(),
13177            #[cfg(unix)]
13178            program: "/bin/sleep".into(),
13179            #[cfg(windows)]
13180            program: std::env::current_exe().unwrap(),
13181            #[cfg(unix)]
13182            args: vec!["60".into()],
13183            #[cfg(windows)]
13184            args: vec![
13185                "--exact".into(),
13186                "supervise::spawn_record_tests::windows_store_touch_fixture".into(),
13187                "--nocapture".into(),
13188            ],
13189            env: vec![],
13190            reserved: false,
13191            reserved_prefixes: vec![],
13192            protocol: ModuleProtocol::None,
13193            overlap: Default::default(),
13194            carry_containment: false,
13195        }
13196    }
13197
13198    #[tokio::test]
13199    async fn record_sync_failure_fails_spawn_and_reaps_child() {
13200        let home = cortexkit_test_support::ScratchDir::new("record-sync-failure");
13201        let supervisor =
13202            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
13203                .with_live_children_record(home.join("live-children.json"));
13204        crate::live_children::fail_next_file_sync();
13205        let result = supervisor.spawn(spec());
13206        let failed = result.is_err();
13207        if let Ok(module) = result {
13208            module.stop().await.unwrap();
13209        }
13210        assert!(failed, "record failure must fail spawn");
13211        let pid = LAST_PID.get().expect("the real OS child was created");
13212        assert!(
13213            subc_os::Process::open(pid).unwrap().is_none(),
13214            "child {pid} survived rejected admission or was not reaped"
13215        );
13216    }
13217
13218    #[cfg(target_os = "macos")]
13219    #[test]
13220    #[ignore = "manual on-device latency measurement"]
13221    fn durable_record_write_latency_50() {
13222        let home = cortexkit_test_support::ScratchDir::new("record-latency");
13223        let path = home.join("live-children.json");
13224        let children = vec![crate::live_children::LiveChild {
13225            module_id: "latency-worker".into(),
13226            pid: std::process::id(),
13227            protocol: ModuleProtocol::None,
13228            start_time: Some(1),
13229            executable: None,
13230            cgroup_name: None,
13231            container: None,
13232        }];
13233        let mut samples = Vec::new();
13234        for _ in 0..50 {
13235            let start = std::time::Instant::now();
13236            crate::live_children::write_record(&path, &children).unwrap();
13237            samples.push(start.elapsed());
13238        }
13239        samples.sort();
13240        eprintln!(
13241            "durable_record_write_latency_50: n=50 median={:?} p95={:?}",
13242            (samples[24] + samples[25]) / 2,
13243            samples[47]
13244        );
13245    }
13246
13247    #[cfg(windows)]
13248    #[test]
13249    fn windows_store_touch_fixture() {
13250        if let Some(path) = std::env::var_os("SUBC_TEST_STORE_TOUCH") {
13251            std::fs::write(path, b"module ran").unwrap();
13252        }
13253    }
13254
13255    #[cfg(windows)]
13256    #[tokio::test]
13257    async fn windows_daemon_fixture() {
13258        let Ok(address) = std::env::var("SUBC_TEST_DAEMON_BARRIER") else {
13259            return;
13260        };
13261        let mut spec = spec();
13262        spec.env.push(("SUBC_TEST_AFTER_CREATE".into(), address));
13263        let supervisor =
13264            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13265        let _module = supervisor.spawn(spec).unwrap();
13266    }
13267
13268    #[cfg(windows)]
13269    #[test]
13270    fn windows_daemon_death_before_module_job_assignment_leaves_no_child() {
13271        use std::io::Read;
13272        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
13273        // An outer job models a scheduler/service host. The daemon's root and
13274        // root job must nest without requiring breakaway from this job.
13275        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
13276        command
13277            .args([
13278                "--exact",
13279                "supervise::spawn_record_tests::windows_daemon_fixture",
13280                "--nocapture",
13281            ])
13282            .env(
13283                "SUBC_TEST_DAEMON_BARRIER",
13284                listener.local_addr().unwrap().to_string(),
13285            );
13286        let mut daemon = subc_jobobject::spawn_contained(&mut command).unwrap();
13287        listener.set_nonblocking(true).unwrap();
13288        let deadline = std::time::Instant::now() + Duration::from_secs(30);
13289        let mut stream = loop {
13290            if let Ok((stream, _)) = listener.accept() {
13291                break stream;
13292            }
13293            assert!(
13294                daemon.child.try_wait().unwrap().is_none(),
13295                "daemon failed before rendezvous"
13296            );
13297            assert!(
13298                std::time::Instant::now() < deadline,
13299                "daemon did not reach CreateProcess failpoint"
13300            );
13301            std::thread::yield_now();
13302        };
13303        stream
13304            .set_read_timeout(Some(Duration::from_secs(30)))
13305            .unwrap();
13306        let mut pid = [0; 4];
13307        stream.read_exact(&mut pid).unwrap();
13308        let pid = u32::from_ne_bytes(pid);
13309        assert!(subc_jobobject::process_exists(pid));
13310        // Terminate only the daemon, not its outer job: otherwise the host job
13311        // would also kill a child whose daemon never joined its root job.
13312        daemon.child.kill().unwrap();
13313        daemon.child.wait().unwrap();
13314        let exited = subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10));
13315        if !exited {
13316            daemon.job.terminate().unwrap();
13317        }
13318        assert!(exited, "suspended child {pid} outlived hard-killed daemon");
13319    }
13320
13321    #[cfg(windows)]
13322    #[tokio::test]
13323    async fn windows_containment_failure_never_resumes() {
13324        let home = cortexkit_test_support::ScratchDir::new("assignment-refusal");
13325        let sentinel = home.join("store-touched");
13326        let mut spec = spec();
13327        spec.env
13328            .push(("SUBC_TEST_ASSIGNMENT_FAILURE".into(), "1".into()));
13329        spec.env.push((
13330            "SUBC_TEST_STORE_TOUCH".into(),
13331            sentinel.display().to_string(),
13332        ));
13333        let supervisor =
13334            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13335        let result = supervisor.spawn(spec);
13336        // A version that resumes despite assignment failure must have time to
13337        // execute its sentinel before dropping the returned module kills it.
13338        if let Ok(module) = result {
13339            let _ = tokio::time::timeout(Duration::from_secs(10), async {
13340                while !sentinel.exists() && module.state().unwrap() == ModuleState::Running {
13341                    tokio::task::yield_now().await;
13342                }
13343            })
13344            .await;
13345            let _ = module.stop().await;
13346            panic!(
13347                "assignment failure resumed a module; store touched={}",
13348                sentinel.exists()
13349            );
13350        }
13351        assert!(
13352            !sentinel.exists(),
13353            "refused module executed store-touch sentinel"
13354        );
13355        assert!(!subc_jobobject::process_exists(LAST_PID.get().unwrap()));
13356    }
13357
13358    #[cfg(windows)]
13359    #[tokio::test]
13360    async fn windows_nested_daemon_fixture() {
13361        let Some(sentinel) = std::env::var_os("SUBC_TEST_NESTED_STORE") else {
13362            return;
13363        };
13364        let mut spec = spec();
13365        spec.env.push((
13366            "SUBC_TEST_STORE_TOUCH".into(),
13367            sentinel.to_str().unwrap().into(),
13368        ));
13369        let supervisor =
13370            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13371        let module = supervisor
13372            .spawn(spec)
13373            .expect("per-module job must nest below daemon and host jobs");
13374        tokio::time::timeout(Duration::from_secs(10), async {
13375            while !PathBuf::from(&sentinel).exists() {
13376                tokio::task::yield_now().await;
13377            }
13378        })
13379        .await
13380        .unwrap();
13381        module.stop().await.unwrap();
13382    }
13383
13384    #[cfg(windows)]
13385    #[test]
13386    fn windows_module_job_nests_under_host_job() {
13387        let home = cortexkit_test_support::ScratchDir::new("nested-jobs");
13388        let sentinel = home.join("nested-store-touched");
13389        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
13390        command
13391            .args([
13392                "--exact",
13393                "supervise::spawn_record_tests::windows_nested_daemon_fixture",
13394                "--nocapture",
13395            ])
13396            .env("SUBC_TEST_NESTED_STORE", &sentinel);
13397        let mut daemon = subc_jobobject::spawn_contained(&mut command).unwrap();
13398        assert!(daemon.child.wait().unwrap().success());
13399        assert!(sentinel.exists(), "nested protocol:none module never ran");
13400    }
13401}
13402
13403#[cfg(target_os = "linux")]
13404pub(crate) fn kill_module_cgroup(placement: Option<&subc_cgroup::Placement>, module_id: &str) {
13405    use subc_cgroup::KillOutcome;
13406    match subc_cgroup::kill_module(placement, module_id) {
13407        KillOutcome::Killed => {}
13408        KillOutcome::NotPlaced | KillOutcome::Unsupported => {
13409            debug!(
13410                module_id,
13411                "cgroup tree kill unavailable; using direct-child kill"
13412            );
13413        }
13414        KillOutcome::IoError { path, error } => {
13415            warn!(module_id, path = %path.display(), %error, "cgroup tree kill failed; using direct-child kill");
13416        }
13417    }
13418}
13419
13420/// Assign a freshly spawned Windows child without ever resuming on failure.
13421///
13422/// Steps 2 and 3 of the suspended-create contract: the job is created and the
13423/// child assigned **while it is still suspended** (step 1 is
13424/// `suspend_on_create_async` at the spawn site). The caller resumes only after
13425/// the child's roster admission is durable. Failed containment kills and reaps
13426/// the suspended child instead of running an unprotected module.
13427#[cfg(windows)]
13428fn contain_spawned_child(
13429    child: &mut Child,
13430    spec: &ModuleSpec,
13431    carried: Option<&Arc<containment::CarriedContainment>>,
13432) -> Result<Option<Arc<Mutex<subc_jobobject::JobObject>>>, SuperviseError> {
13433    let assignment = || {
13434        let job = match carried {
13435            Some(container) => container.job(),
13436            None => Arc::new(Mutex::new(subc_jobobject::JobObject::new()?)),
13437        };
13438        #[cfg(test)]
13439        spawn_record_tests::assignment_failpoint(spec)?;
13440        job.lock()
13441            .unwrap_or_else(|p| p.into_inner())
13442            .assign(child)?;
13443        Ok::<_, io::Error>(job)
13444    };
13445    match assignment() {
13446        Ok(job) => Ok(Some(job)),
13447        Err(source) => {
13448            kill_and_reap_rejected_child(child);
13449            Err(SuperviseError::Spawn {
13450                program: spec.program.clone(),
13451                source: io::Error::other(format!(
13452                    "Windows module job containment failed: {source}"
13453                )),
13454                cgroup_path: None,
13455            })
13456        }
13457    }
13458}
13459
13460/// Rejection is synchronous: do not return a spawn error while the child can
13461/// still run, or rely on kill-on-drop to reap it at some later runtime turn.
13462fn kill_and_reap_rejected_child(child: &mut Child, #[cfg(unix)] group: containment::GroupTarget) {
13463    #[cfg(unix)]
13464    group.signal_rejected(child);
13465    let _ = child.start_kill();
13466    while matches!(child.try_wait(), Ok(None)) {
13467        std::thread::yield_now();
13468    }
13469}
13470
13471/// Resume a suspended child, killing it if it cannot be started.
13472///
13473/// A suspended process holds a pid and does nothing, so there is no useful
13474/// state to return: the caller gets an error and the spawn fails.
13475#[cfg(windows)]
13476fn resume_suspended_child(pid: u32, spec: &ModuleSpec) -> Result<(), SuperviseError> {
13477    if let Err(source) = subc_jobobject::resume_main_thread(pid) {
13478        // Kill it here rather than leaving a suspended process for the caller
13479        // to notice; `kill_on_drop` would eventually do this, but the module
13480        // would have been reported as running in between.
13481        let _ = subc_os::child_spawn::status(
13482            std::process::Command::new("taskkill.exe")
13483                .args(["/PID", &pid.to_string(), "/T", "/F"])
13484                .stdin(Stdio::null())
13485                .stdout(Stdio::null())
13486                .stderr(Stdio::null()),
13487        );
13488        return Err(SuperviseError::Spawn {
13489            program: spec.program.clone(),
13490            source,
13491            cgroup_path: None,
13492        });
13493    }
13494    Ok(())
13495}
13496
13497#[cfg(target_os = "linux")]
13498fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
13499    match placement.remove_module(module_id) {
13500        Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
13501        Err(error) => warn!(
13502            module_id,
13503            error = %error,
13504            "could not remove module cgroup after process exit; continuing teardown"
13505        ),
13506    }
13507}
13508
13509#[cfg(target_os = "linux")]
13510const REAPED_CGROUP_TERM_GRACE: Duration = Duration::from_secs(2);
13511#[cfg(target_os = "linux")]
13512const REAPED_CGROUP_FREEZE_TIMEOUT: Duration = Duration::from_millis(100);
13513
13514#[cfg(target_os = "linux")]
13515async fn cleanup_reaped_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
13516    let path = placement.module_path(module_id).ok();
13517    if path.as_ref().is_some_and(|path| {
13518        std::fs::read_to_string(path.join("cgroup.events"))
13519            .ok()
13520            .is_some_and(|events| events.lines().any(|line| line == "populated 0"))
13521    }) {
13522        remove_module_cgroup(placement, module_id);
13523        return;
13524    }
13525
13526    // Freeze before enumerating: a frozen task cannot exit and release its PID
13527    // for reuse by a process outside this module while SIGTERM is being sent.
13528    if terminate_reaped_cgroup(placement, module_id).await {
13529        if let Some(path) = &path {
13530            let deadline = Instant::now() + REAPED_CGROUP_TERM_GRACE;
13531            while cgroup_is_populated(path) && Instant::now() < deadline {
13532                sleep_until((Instant::now() + Duration::from_millis(1)).min(deadline)).await;
13533            }
13534        }
13535    }
13536
13537    // Reaping the direct child is not proof its descendants exited. Kill any
13538    // survivors; when `cgroup.kill` succeeds, wait for the kernel to report the
13539    // cgroup empty before rmdir.
13540    if matches!(
13541        subc_cgroup::kill_module(Some(placement), module_id),
13542        subc_cgroup::KillOutcome::Killed
13543    ) {
13544        if let Some(path) = &path {
13545            while cgroup_is_populated(path) {
13546                sleep(Duration::from_millis(1)).await;
13547            }
13548        }
13549    }
13550    remove_module_cgroup(placement, module_id);
13551}
13552
13553#[cfg(target_os = "linux")]
13554fn cgroup_is_populated(path: &std::path::Path) -> bool {
13555    std::fs::read_to_string(path.join("cgroup.events"))
13556        .ok()
13557        .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
13558}
13559
13560#[cfg(target_os = "linux")]
13561async fn terminate_reaped_cgroup(placement: &subc_cgroup::Placement, module_id: &str) -> bool {
13562    let frozen =
13563        match subc_cgroup::freeze_module(Some(placement), module_id, REAPED_CGROUP_FREEZE_TIMEOUT)
13564            .await
13565        {
13566            subc_cgroup::FreezeOutcome::Frozen(frozen) => frozen,
13567            outcome => {
13568                tracing::debug!(
13569                    module_id,
13570                    ?outcome,
13571                    "cgroup freeze failed; skipping SIGTERM grace"
13572                );
13573                return false;
13574            }
13575        };
13576    let listed = match frozen.processes() {
13577        subc_cgroup::ProcsOutcome::Listed(pids) => {
13578            for pid in pids.into_iter().filter(|pid| *pid > 1) {
13579                if let Some(pid) = rustix::process::Pid::from_raw(pid) {
13580                    if let Err(error) =
13581                        rustix::process::kill_process(pid, rustix::process::Signal::TERM)
13582                    {
13583                        tracing::debug!(module_id, %pid, %error, "leftover cgroup SIGTERM failed");
13584                    }
13585                }
13586            }
13587            true
13588        }
13589        outcome => {
13590            tracing::debug!(
13591                module_id,
13592                ?outcome,
13593                "cgroup process listing failed; skipping SIGTERM grace"
13594            );
13595            false
13596        }
13597    };
13598    match frozen.thaw() {
13599        subc_cgroup::ThawOutcome::Thawed => listed,
13600        outcome => {
13601            tracing::debug!(
13602                module_id,
13603                ?outcome,
13604                "cgroup thaw failed; proceeding to cgroup.kill"
13605            );
13606            false
13607        }
13608    }
13609}
13610
13611#[cfg(target_os = "linux")]
13612fn apply_cgroup_placement(
13613    command: &mut Command,
13614    spec: &ModuleSpec,
13615    path: &std::path::Path,
13616) -> Result<(), SuperviseError> {
13617    subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
13618        module_id: spec.module_id.clone(),
13619        source,
13620    })
13621}
13622
13623fn capture_retention(spec: &ModuleSpec) -> Retention {
13624    let defaults = Retention::default();
13625    let value = |name: &str| {
13626        spec.env
13627            .iter()
13628            .rev()
13629            .find_map(|(key, value)| (key == name).then_some(value.as_str()))
13630    };
13631    Retention {
13632        max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
13633            .and_then(|value| value.parse().ok())
13634            .unwrap_or(defaults.max_file_mb),
13635        keep: value(CAPTURE_KEEP_ENV)
13636            .and_then(|value| value.parse().ok())
13637            .unwrap_or(defaults.keep),
13638        max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
13639            .and_then(|value| value.parse().ok())
13640            .unwrap_or(defaults.max_age_days),
13641    }
13642}
13643
13644/// A fresh 256-bit CSPRNG launch nonce, lowercase hex. Used to bind a reserved
13645/// module's registration to the exact process the supervisor spawned.
13646fn generate_launch_nonce() -> Result<String, SuperviseError> {
13647    let mut bytes = [0u8; 32];
13648    getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
13649        reason: source.to_string(),
13650    })?;
13651    let mut hex = String::with_capacity(64);
13652    for b in bytes {
13653        use std::fmt::Write;
13654        let _ = write!(hex, "{b:02x}");
13655    }
13656    Ok(hex)
13657}
13658
13659/// Constant-time byte comparison so a reserved-nonce mismatch leaks no timing
13660/// signal about how many leading bytes matched.
13661fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
13662    if a.len() != b.len() {
13663        return false;
13664    }
13665    let mut diff = 0u8;
13666    for (x, y) in a.iter().zip(b.iter()) {
13667        diff |= x ^ y;
13668    }
13669    diff == 0
13670}
13671
13672/// The kernel's image after an acknowledged exec, shared by ordinary launches
13673/// and privacy trampolines. PATH and shebang interpretation are kernel facts,
13674/// not identities inferred from a configured pathname.
13675#[cfg(not(windows))]
13676fn observe_spawned_image(pid: u32) -> Option<subc_os::Observation> {
13677    let process = subc_os::Process::open(pid).ok().flatten()?;
13678    #[cfg(target_os = "linux")]
13679    return sample_after_linux_exec(
13680        || {
13681            let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
13682            let committed = linux_exec_committed(&stat);
13683            #[cfg(test)]
13684            spawn_image_tests::report_exec_state(committed);
13685            committed
13686        },
13687        || process.observe(),
13688    );
13689    #[cfg(not(target_os = "linux"))]
13690    process.observe()
13691}
13692
13693/// glibc's posix_spawn parent can wake in exec_mmap before the child's new mm
13694/// is installed. PF_FORKNOEXEC is cleared later in begin_new_exec, after that
13695/// installation. Until it clears, /proc/pid/exe can still name the daemon.
13696#[cfg(target_os = "linux")]
13697fn linux_exec_committed(stat: &str) -> Option<bool> {
13698    const PF_FORKNOEXEC: u64 = 0x40;
13699    let flags = stat.rsplit_once(')')?.1.split_whitespace().nth(6)?;
13700    Some(flags.parse::<u64>().ok()? & PF_FORKNOEXEC == 0)
13701}
13702
13703#[cfg(target_os = "linux")]
13704fn sample_after_linux_exec(
13705    mut exec_committed: impl FnMut() -> Option<bool>,
13706    observe: impl FnOnce() -> Option<subc_os::Observation>,
13707) -> Option<subc_os::Observation> {
13708    let deadline = std::time::Instant::now() + Duration::from_secs(1);
13709    while !exec_committed()? {
13710        // A failed or indefinitely stalled exec must not publish the inherited
13711        // image as authority to signal a future orphan. Missing identity keeps
13712        // the existing conservative orphan-sweep behavior.
13713        if std::time::Instant::now() >= deadline {
13714            return None;
13715        }
13716        std::thread::sleep(Duration::from_micros(50));
13717    }
13718    observe()
13719}
13720
13721#[cfg(all(test, target_os = "linux"))]
13722mod spawn_image_tests {
13723    use super::*;
13724    use std::cell::{Cell, RefCell};
13725
13726    enum ExecEvent {
13727        Uncommitted,
13728        Image(Option<subc_os::Observation>),
13729    }
13730
13731    thread_local! {
13732        static EXEC_EVENTS: RefCell<Option<std::sync::mpsc::Sender<ExecEvent>>> = const { RefCell::new(None) };
13733    }
13734
13735    pub(super) fn report_exec_state(committed: Option<bool>) {
13736        if committed == Some(false) {
13737            EXEC_EVENTS.with(|events| {
13738                if let Some(events) = events.borrow_mut().take() {
13739                    let _ = events.send(ExecEvent::Uncommitted);
13740                }
13741            });
13742        }
13743    }
13744
13745    #[test]
13746    fn linux_spawn_observation_waits_for_a_paused_fork_to_exec() {
13747        use std::io::{Read, Write};
13748        use std::os::fd::AsRawFd;
13749
13750        let descriptor = std::fs::File::open("/dev/null").unwrap();
13751        let mut command = std::process::Command::new("/bin/sleep");
13752        command.arg("30");
13753        let (mut ready, mut release) =
13754            subc_os::fork_exec_test::pause_before_exec(&mut command, descriptor.as_raw_fd())
13755                .unwrap();
13756        let spawn = std::thread::spawn(move || command.spawn());
13757        let mut message = [0u8; 8];
13758        ready.read_exact(&mut message).unwrap();
13759        let pid = i32::from_ne_bytes(message[..4].try_into().unwrap()) as u32;
13760        let before = std::fs::read_to_string(format!("/proc/{pid}/stat"));
13761        let inherited = subc_os::Process::open(pid).unwrap().unwrap().observe();
13762        let (events, received) = std::sync::mpsc::channel();
13763        let observer = std::thread::spawn(move || {
13764            EXEC_EVENTS.with(|slot| *slot.borrow_mut() = Some(events.clone()));
13765            let image = observe_spawned_image(pid);
13766            let _ = events.send(ExecEvent::Image(image));
13767        });
13768        // Release only once the production observer has seen the uncommitted
13769        // exec, or has incorrectly returned the inherited image. Either way,
13770        // release and reap before asserting so a regression cannot leak a child.
13771        let first = received.recv_timeout(Duration::from_secs(5));
13772        release.write_all(&[1]).unwrap();
13773        let mut child = spawn.join().unwrap().unwrap();
13774        let after = match first {
13775            Ok(ExecEvent::Uncommitted) => match received.recv_timeout(Duration::from_secs(5)) {
13776                Ok(ExecEvent::Image(image)) => image,
13777                _ => None,
13778            },
13779            Ok(ExecEvent::Image(image)) => image,
13780            Err(_) => None,
13781        };
13782        observer.join().unwrap();
13783        child.kill().unwrap();
13784        child.wait().unwrap();
13785
13786        assert_eq!(linux_exec_committed(&before.unwrap()), Some(false));
13787        assert_eq!(
13788            inherited.unwrap().executable,
13789            subc_os::file_identity(&std::env::current_exe().unwrap())
13790        );
13791        assert_eq!(
13792            after.unwrap().executable,
13793            subc_os::file_identity(std::path::Path::new("/bin/sleep"))
13794        );
13795    }
13796
13797    #[test]
13798    fn spawned_image_is_not_sampled_until_linux_exec_commits() {
13799        let committed = Cell::new(false);
13800        let inherited = subc_os::Observation {
13801            start_time: 23,
13802            executable: Some(subc_os::FileIdentity {
13803                device: 29,
13804                inode: 31,
13805            }),
13806        };
13807        let module = subc_os::Observation {
13808            start_time: 23,
13809            executable: Some(subc_os::FileIdentity {
13810                device: 29,
13811                inode: 37,
13812            }),
13813        };
13814        let polls = Cell::new(0);
13815        let image = sample_after_linux_exec(
13816            || {
13817                polls.set(polls.get() + 1);
13818                // Hold the inherited image through the first poll, as in the
13819                // posix_spawn parent-wake window, then commit the module image.
13820                committed.set(polls.get() == 2);
13821                Some(committed.get())
13822            },
13823            || Some(if committed.get() { module } else { inherited }),
13824        );
13825        assert_eq!(image, Some(module));
13826        assert_eq!(polls.get(), 2);
13827    }
13828
13829    #[test]
13830    fn linux_exec_flag_is_read_from_flags_after_the_last_parenthesis() {
13831        assert_eq!(
13832            linux_exec_committed("17 (a ) b) R 1 2 3 4 5 4194368"),
13833            Some(false)
13834        );
13835        assert_eq!(
13836            linux_exec_committed("17 (a ) b) R 1 2 3 4 5 4194304"),
13837            Some(true)
13838        );
13839        assert_eq!(linux_exec_committed("17 (a) R 1 2 3 4 5 invalid"), None);
13840        assert_eq!(linux_exec_committed("17 (a) R"), None);
13841    }
13842
13843    #[test]
13844    fn unreadable_exec_state_never_samples_an_inherited_image() {
13845        assert_eq!(
13846            sample_after_linux_exec(
13847                || None,
13848                || panic!("must not sample before exec confirmation")
13849            ),
13850            None
13851        );
13852    }
13853
13854    #[test]
13855    fn uncommitted_exec_times_out_without_sampling_an_inherited_image() {
13856        assert_eq!(
13857            sample_after_linux_exec(
13858                || Some(false),
13859                || panic!("must not sample after an exec timeout")
13860            ),
13861            None
13862        );
13863    }
13864}
13865
13866/// Resolve once and spawn that exact path, so PATH lookup cannot choose a
13867/// different executable after the no-delete capture was taken.
13868#[cfg(windows)]
13869pub(crate) fn windows_spawn_capture(spec: &ModuleSpec) -> io::Result<subc_os::ExecutableCapture> {
13870    if let Err(error) = require_program_search_path(spec) {
13871        return Err(match error {
13872            SuperviseError::Spawn { source, .. } => source,
13873            error => io::Error::other(error),
13874        });
13875    }
13876    let mut program = spec.program.clone();
13877    if program.is_absolute() || program.components().count() > 1 {
13878        // An explicit path can name a PE image with no extension. Try that
13879        // exact file first, as Command does, before falling back to .exe.
13880        match subc_os::ExecutableCapture::open(&program) {
13881            Ok(capture) => return Ok(capture),
13882            Err(error)
13883                if error.kind() == io::ErrorKind::NotFound && program.extension().is_none() => {}
13884            Err(error) => return Err(error),
13885        }
13886        program.set_extension("exe");
13887        return subc_os::ExecutableCapture::open(&program);
13888    }
13889    if program.extension().is_none() {
13890        program.set_extension("exe");
13891    }
13892    let custom_path = spec
13893        .env
13894        .iter()
13895        .rev()
13896        .find(|(key, _)| key.eq_ignore_ascii_case("PATH"));
13897    let mut directories = Vec::new();
13898    // These are Windows' default executable search locations. A configured
13899    // PATH still overrides the inherited PATH, not the system directories.
13900    if let Some(parent) = std::env::current_exe()?.parent() {
13901        directories.push(parent.to_path_buf());
13902    }
13903    directories.push(std::env::current_dir()?);
13904    if let Some(windows) = std::env::var_os("SystemRoot") {
13905        let windows = PathBuf::from(windows);
13906        directories.push(windows.join("System32"));
13907        directories.push(windows.clone());
13908    }
13909    let path = custom_path
13910        .map(|(_, value)| std::ffi::OsString::from(value))
13911        .or_else(|| std::env::var_os("PATH"));
13912    if let Some(path) = path {
13913        directories.extend(std::env::split_paths(&path));
13914    }
13915    for directory in directories {
13916        match subc_os::ExecutableCapture::open(&directory.join(&program)) {
13917            Ok(capture) => return Ok(capture),
13918            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
13919            Err(error) => return Err(error),
13920        }
13921    }
13922    Err(io::Error::new(
13923        io::ErrorKind::NotFound,
13924        "resolved executable not found",
13925    ))
13926}
13927
13928async fn spawn_and_mark_running_async(
13929    spec: &ModuleSpec,
13930    runtime: &SupervisorRuntimeConfig,
13931    snapshot: &SharedSnapshot,
13932) -> Result<SupervisedChild, SuperviseError> {
13933    let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
13934    let registration_watch = watch_registration(&runtime.registry, spec);
13935    #[cfg(unix)]
13936    let joining_group = containment::current(&runtime.child_roster.containment)
13937        .is_some_and(|container| container.group().is_some());
13938    let result = spawn_child_async(spec, runtime).await;
13939    #[cfg(unix)]
13940    let result = match result {
13941        Err(error)
13942            if joining_group
13943                && !is_launch_deferral(&error)
13944                && !runtime.child_roster.is_closed()
13945                && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
13946                && runtime
13947                    .child_roster
13948                    .previous_instance(&spec.module_id)
13949                    .is_none() =>
13950        {
13951            // A failed group join has already ended the old container. Its single
13952            // fresh-container retry belongs to the same restart budget entry.
13953            warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
13954            spawn_child_async(spec, runtime).await
13955        }
13956        other => other,
13957    };
13958    let mut child = result?;
13959    arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
13960    if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
13961        containment::terminate_blocking(&runtime.child_roster.containment);
13962        return Err(error);
13963    }
13964    if let Some(spawn) = activity_spawn {
13965        spawn.complete(snapshot);
13966    }
13967    Ok(child)
13968}
13969
13970#[cfg(test)]
13971fn spawn_and_mark_running(
13972    spec: &ModuleSpec,
13973    runtime: &SupervisorRuntimeConfig,
13974    snapshot: &SharedSnapshot,
13975) -> Result<SupervisedChild, SuperviseError> {
13976    let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
13977    let registration_watch = watch_registration(&runtime.registry, spec);
13978    #[cfg(unix)]
13979    let joining_group = containment::current(&runtime.child_roster.containment)
13980        .is_some_and(|container| container.group().is_some());
13981    let spawn = || {
13982        spawn_child(
13983            spec,
13984            runtime.connection_file_path.as_deref(),
13985            runtime.supervisor_handle.as_ref(),
13986            &runtime.stderr_ring,
13987            runtime.capture_logs_dir.as_deref(),
13988            &runtime.child_roster,
13989            runtime.spawn_delivery(),
13990            #[cfg(target_os = "linux")]
13991            runtime.cgroup_placement.as_ref(),
13992            runtime.register_timeout,
13993        )
13994    };
13995    let result = spawn();
13996    #[cfg(unix)]
13997    let result = match result {
13998        Err(error)
13999            if joining_group
14000                && !is_launch_deferral(&error)
14001                && !runtime.child_roster.is_closed()
14002                && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
14003                && runtime
14004                    .child_roster
14005                    .previous_instance(&spec.module_id)
14006                    .is_none() =>
14007        {
14008            // The failed join already destroyed and verified the old container.
14009            // Try one fresh group as part of this same restart, without spending
14010            // another crash-budget entry. Cgroups and Windows jobs do not retry.
14011            warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
14012            spawn()
14013        }
14014        other => other,
14015    };
14016    let child = result?;
14017    let mut child = child;
14018    arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
14019    if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
14020        containment::terminate_blocking(&runtime.child_roster.containment);
14021        return Err(error);
14022    }
14023    if let Some(spawn) = activity_spawn {
14024        spawn.complete(snapshot);
14025    }
14026    Ok(child)
14027}
14028
14029struct RegistrationWatch {
14030    changes: watch::Receiver<u64>,
14031    baseline: u64,
14032}
14033
14034// Capture before spawning: a fast child's accepted HELLO can disappear from the
14035// active registry before the monitor first runs. A pre-existing registration
14036// must not satisfy a new process's deadline either.
14037fn watch_registration(registry: &Registry, spec: &ModuleSpec) -> Option<RegistrationWatch> {
14038    if spec.protocol != ModuleProtocol::Subc {
14039        return None;
14040    }
14041    let changes = registry.subscribe_module_changes(&spec.module_id).ok()?;
14042    let baseline = *changes.borrow();
14043    Some(RegistrationWatch { changes, baseline })
14044}
14045
14046fn arm_registration_deadline(
14047    child: &mut SupervisedChild,
14048    budget: Duration,
14049    registration_watch: Option<RegistrationWatch>,
14050) {
14051    child.registration_watch = registration_watch;
14052    child.registration_deadline = (child.protocol == ModuleProtocol::Subc
14053        && child.awaiting_registration())
14054    .then_some(child.spawned_at + budget);
14055}
14056
14057async fn stop_unregistered_child(child: &mut SupervisedChild) -> io::Result<()> {
14058    child.retire_registration();
14059    if let Some(container) = child.child.container() {
14060        container.stop_members().await;
14061        child.kill_leader()?;
14062        child.wait().await?;
14063        return Ok(());
14064    }
14065    #[cfg(unix)]
14066    {
14067        // Children lead their own process groups. Signal the whole group so a
14068        // helper stuck before HELLO cannot survive its supervised parent.
14069        let group = unreaped_registration_group(child)?;
14070        let _ = rustix::process::kill_process_group(group, rustix::process::Signal::TERM);
14071        // Process-group safety rule: only signal a group while its leader is
14072        // our unreaped child. Even a zombie leader reserves its pid/group id;
14073        // reaping it before KILL would let that id name an unrelated group.
14074        // Sleep without waiting so TERM-ignoring helpers get the full grace.
14075        sleep(crate::child_roster::TERM_TO_KILL).await;
14076        let group = unreaped_registration_group(child)?;
14077        let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
14078    }
14079    // Windows terminates the containing Job Object as well as the direct
14080    // child. Linux also kills the child's cgroup when placement is enabled.
14081    child.start_kill()?;
14082    child.wait().await?;
14083    Ok(())
14084}
14085
14086#[cfg(unix)]
14087fn unreaped_registration_group(child: &SupervisedChild) -> io::Result<rustix::process::Pid> {
14088    if let Some(container) = child.child.container() {
14089        return container
14090            .group()
14091            .and_then(|pid| rustix::process::Pid::from_raw(pid as i32))
14092            .ok_or_else(|| io::Error::other("a carried cgroup has no signalable process group"));
14093    }
14094    // The group id comes only from the pid recorded at spawn, when the child
14095    // created its own group. Never admit init's group or a negative group id.
14096    let group = i32::try_from(child.pid)
14097        .ok()
14098        .filter(|pid| *pid > 1)
14099        .and_then(rustix::process::Pid::from_raw)
14100        .ok_or_else(|| {
14101            io::Error::new(
14102                io::ErrorKind::InvalidInput,
14103                "invalid supervised process group",
14104            )
14105        })?;
14106    if child.child.id() != Some(child.pid) {
14107        return Err(io::Error::new(
14108            io::ErrorKind::InvalidInput,
14109            "refusing process-group signal after supervised child was reaped",
14110        ));
14111    }
14112    Ok(group)
14113}
14114
14115enum RegistrationWaitOutcome {
14116    Registered,
14117    Exited(ExitReport),
14118    TimedOut,
14119}
14120
14121struct ReloadRegistrationFailure {
14122    exit_report: ExitReport,
14123    reason: String,
14124}
14125
14126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14127enum BusyGaugeObservation {
14128    Quiescent,
14129    Busy,
14130    Omitted,
14131}
14132
14133/// What one health answer said about one declared busy gauge.
14134#[derive(Debug, Clone, PartialEq, Eq)]
14135enum GaugeVerdict {
14136    /// The gauge read 0: this gauge is not what holds the drain.
14137    Zero,
14138    /// The gauge read a positive count.
14139    NonZero(u64),
14140    /// The gauge was present but not a non-negative integer (`0.0`, a string,
14141    /// a negative number). It counts as busy, because the daemon cannot tell
14142    /// it is idle. Carries the value as JSON text, cut to a short prefix.
14143    NotACount(String),
14144    /// The health answer had no metrics object, or one without this gauge.
14145    Missing,
14146    /// The probe produced no health answer to read; carries the probe error's
14147    /// evidence label (`no-answer` for a probe that timed out).
14148    ProbeFailed(&'static str),
14149}
14150
14151impl GaugeVerdict {
14152    fn reads_quiet(&self) -> bool {
14153        matches!(self, Self::Zero)
14154    }
14155}
14156
14157impl fmt::Display for GaugeVerdict {
14158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14159        match self {
14160            Self::Zero => f.write_str("zero"),
14161            Self::NonZero(value) => write!(f, "non_zero({value})"),
14162            Self::NotACount(value) => write!(f, "not_a_count({value})"),
14163            Self::Missing => f.write_str("missing_from_health_body"),
14164            Self::ProbeFailed(kind) => write!(f, "probe_failed({kind})"),
14165        }
14166    }
14167}
14168
14169/// The longest JSON text kept for a gauge value that is not a count, so a
14170/// module reporting a large object as a gauge cannot flood the drain log.
14171const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
14172
14173/// Read each declared gauge out of one health answer's metrics.
14174fn gauge_verdicts(metrics: Option<&Value>, gauges: &[String]) -> Vec<GaugeVerdict> {
14175    let metrics = metrics.and_then(Value::as_object);
14176    gauges
14177        .iter()
14178        .map(
14179            |gauge| match metrics.and_then(|metrics| metrics.get(gauge)) {
14180                None => GaugeVerdict::Missing,
14181                Some(value) => match value.as_u64() {
14182                    Some(0) => GaugeVerdict::Zero,
14183                    Some(count) => GaugeVerdict::NonZero(count),
14184                    None => {
14185                        let mut text = value.to_string();
14186                        if text.len() > GAUGE_VALUE_TEXT_LIMIT {
14187                            let mut end = GAUGE_VALUE_TEXT_LIMIT;
14188                            while !text.is_char_boundary(end) {
14189                                end -= 1;
14190                            }
14191                            text.truncate(end);
14192                            text.push_str("...");
14193                        }
14194                        GaugeVerdict::NotACount(text)
14195                    }
14196                },
14197            },
14198        )
14199        .collect()
14200}
14201
14202/// The drain's overall reading of one health answer: omitted when any
14203/// declared gauge is missing, quiescent only when every gauge reads 0.
14204fn busy_gauge_observation(verdicts: &[GaugeVerdict]) -> BusyGaugeObservation {
14205    if verdicts
14206        .iter()
14207        .any(|verdict| matches!(verdict, GaugeVerdict::Missing))
14208    {
14209        BusyGaugeObservation::Omitted
14210    } else if verdicts.iter().all(GaugeVerdict::reads_quiet) {
14211        BusyGaugeObservation::Quiescent
14212    } else {
14213        BusyGaugeObservation::Busy
14214    }
14215}
14216
14217/// One declared gauge's history over a drain: the latest verdict on it, and
14218/// the latest value actually read for it (which a later failed probe or
14219/// missing gauge does not erase). Times are offsets from the start of the
14220/// drain's wait.
14221#[derive(Debug, Clone, Default, PartialEq, Eq)]
14222struct GaugeTrace {
14223    latest: Option<(GaugeVerdict, Duration)>,
14224    last_value: Option<(GaugeVerdict, Duration)>,
14225}
14226
14227/// What a drain's busy-gauge probes saw, kept so that a drain which runs to
14228/// its ceiling can say in its timeout line which declared gauge held it and
14229/// why. Without it, a gauge that read busy, a gauge the module never
14230/// reported, and a probe that never got an answer all looked the same: a
14231/// drain that ended at its ceiling with nothing in flight.
14232#[derive(Debug, Clone, Default, PartialEq, Eq)]
14233struct DrainGaugeTrace {
14234    /// Health probes the drain sent.
14235    probes: u32,
14236    /// Each declared gauge, in declaration order.
14237    gauges: Vec<(String, GaugeTrace)>,
14238}
14239
14240impl DrainGaugeTrace {
14241    fn new(gauges: &[String]) -> Self {
14242        Self {
14243            probes: 0,
14244            gauges: gauges
14245                .iter()
14246                .map(|gauge| (gauge.clone(), GaugeTrace::default()))
14247                .collect(),
14248        }
14249    }
14250
14251    /// Record one probe's verdicts, one per declared gauge, `at` into the drain.
14252    fn record(&mut self, verdicts: &[GaugeVerdict], at: Duration) {
14253        self.probes = self.probes.saturating_add(1);
14254        for ((_, trace), verdict) in self.gauges.iter_mut().zip(verdicts) {
14255            trace.latest = Some((verdict.clone(), at));
14256            if matches!(
14257                verdict,
14258                GaugeVerdict::Zero | GaugeVerdict::NonZero(_) | GaugeVerdict::NotACount(_)
14259            ) {
14260                trace.last_value = Some((verdict.clone(), at));
14261            }
14262        }
14263    }
14264}
14265
14266/// Renders as `gauge: latest verdict @ offset; last value @ offset` for each
14267/// declared gauge, separated by ` | `. A value is shown as its verdict
14268/// (`zero`, `non_zero(n)`, `not_a_count(json)`), so it says both what was read
14269/// and whether that counted as busy.
14270impl fmt::Display for DrainGaugeTrace {
14271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14272        if self.gauges.is_empty() {
14273            return f.write_str("none declared");
14274        }
14275        for (index, (name, trace)) in self.gauges.iter().enumerate() {
14276            if index > 0 {
14277                f.write_str(" | ")?;
14278            }
14279            write!(f, "{name}: ")?;
14280            match &trace.latest {
14281                Some((verdict, at)) => write!(f, "{verdict} @{}ms", at.as_millis())?,
14282                None => f.write_str("never probed")?,
14283            }
14284            match &trace.last_value {
14285                Some((value, at)) => write!(f, "; last value {value} @{}ms", at.as_millis())?,
14286                None => f.write_str("; no value ever read")?,
14287            }
14288        }
14289        Ok(())
14290    }
14291}
14292
14293pub(crate) fn declared_busy_gauges(
14294    registry: &Registry,
14295    module_id: &str,
14296) -> Result<Vec<String>, SuperviseError> {
14297    busy_gauges_of(
14298        registry
14299            .get_module(module_id)
14300            .map_err(SuperviseError::Registry)?,
14301    )
14302}
14303
14304/// [`declared_busy_gauges`] for the registration a connection holds, in any
14305/// slot: after cutover the incumbent is no longer the id's active
14306/// registration, and its own manifest is the one that names its gauges.
14307fn declared_busy_gauges_for_connection(
14308    registry: &Registry,
14309    connection_id: ConnectionId,
14310) -> Result<Vec<String>, SuperviseError> {
14311    busy_gauges_of(
14312        registry
14313            .get_module_by_connection(connection_id)
14314            .map_err(SuperviseError::Registry)?,
14315    )
14316}
14317
14318fn busy_gauges_of(
14319    registration: Option<crate::registry::ModuleRegistration>,
14320) -> Result<Vec<String>, SuperviseError> {
14321    let Some(registration) = registration else {
14322        return Ok(Vec::new());
14323    };
14324    let Some(self_signals) = registration.manifest.self_signals else {
14325        return Ok(Vec::new());
14326    };
14327
14328    let mut gauges = Vec::new();
14329    for declaration in self_signals {
14330        if declaration.kind != SelfSignalKind::Busy {
14331            continue;
14332        }
14333        match declaration.anchored_to {
14334            SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
14335                gauges.extend(declared)
14336            }
14337            _ => {
14338                // An invalid Busy anchor is fail-safe: the empty name cannot be
14339                // present in a conforming health report, so this drain stays busy.
14340                gauges.push(String::new());
14341            }
14342        }
14343    }
14344    Ok(gauges)
14345}
14346
14347/// Wait for `endpoint` to have nothing in flight and, when the module declares
14348/// busy gauges, for a health probe to report them quiet. The probe is addressed
14349/// by `scope`: a swap's superseded incumbent must be asked about its own
14350/// gauges, and by module id the probe would reach the promoted candidate.
14351/// While the gauges read busy, the probe repeats every
14352/// [`DRAIN_BUSY_REPROBE_INTERVAL`] until they read quiet or `deadline` passes.
14353/// Every probe's reading of each gauge is recorded in `trace`, for the caller's
14354/// timeout line.
14355#[allow(clippy::too_many_arguments)]
14356async fn wait_for_forwarding_quiescence(
14357    forwarding: &ForwardingTable,
14358    module_id: &str,
14359    runtime: &SupervisorRuntimeConfig,
14360    endpoint: crate::ModuleEndpointId,
14361    deadline: Instant,
14362    busy_gauges: &[String],
14363    scope: DrainScope,
14364    trace: &mut DrainGaugeTrace,
14365) -> Result<bool, SuperviseError> {
14366    let wait_started = Instant::now();
14367    let mut gauges_quiescent = busy_gauges.is_empty();
14368    let mut next_probe_at = wait_started;
14369    let mut omission_reported = false;
14370
14371    loop {
14372        let now = Instant::now();
14373        if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
14374            let report = match scope {
14375                DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
14376                DrainScope::Endpoint(endpoint) => {
14377                    probe_endpoint_health(endpoint, runtime, Some(deadline)).await
14378                }
14379            };
14380            let verdicts = match &report {
14381                Ok(report) => gauge_verdicts(report.metrics.as_ref(), busy_gauges),
14382                Err(err) => vec![GaugeVerdict::ProbeFailed(err.label()); busy_gauges.len()],
14383            };
14384            trace.record(&verdicts, wait_started.elapsed());
14385            gauges_quiescent = match report {
14386                Ok(_) => match busy_gauge_observation(&verdicts) {
14387                    BusyGaugeObservation::Quiescent => true,
14388                    BusyGaugeObservation::Busy => false,
14389                    BusyGaugeObservation::Omitted => {
14390                        // Once per drain: a module that never reports a gauge
14391                        // it declared would otherwise say so on every probe.
14392                        if !omission_reported {
14393                            forwarding
14394                                .counters()
14395                                .increment_drains_with_undeclared_gauge();
14396                            let missing = busy_gauges
14397                                .iter()
14398                                .zip(&verdicts)
14399                                .filter(|(_, verdict)| matches!(verdict, GaugeVerdict::Missing))
14400                                .map(|(gauge, _)| gauge.as_str())
14401                                .collect::<Vec<_>>()
14402                                .join(",");
14403                            warn!(
14404                                module_id,
14405                                missing_gauges = %missing,
14406                                "drain health.check answer lacks a declared busy gauge; the drain treats the module as busy until it reports it"
14407                            );
14408                            omission_reported = true;
14409                        }
14410                        false
14411                    }
14412                },
14413                Err(err) => {
14414                    warn!(
14415                        module_id,
14416                        error = %err,
14417                        "drain health.check did not produce declared busy gauges; treating module as busy"
14418                    );
14419                    false
14420                }
14421            };
14422            // Counted from the probe's completion: the probe above was awaited,
14423            // so no second probe can start while one is still outstanding.
14424            next_probe_at = Instant::now() + drain_busy_reprobe_interval();
14425        }
14426
14427        let in_flight = forwarding
14428            .endpoint_in_flight_count(endpoint)
14429            .map_err(SuperviseError::Forwarding)?;
14430        if in_flight == 0 && gauges_quiescent {
14431            return Ok(true);
14432        }
14433
14434        let now = Instant::now();
14435        if now >= deadline {
14436            return Ok(false);
14437        }
14438        let mut wait = deadline
14439            .saturating_duration_since(now)
14440            .min(REGISTRY_RELEASE_POLL);
14441        if !busy_gauges.is_empty() {
14442            wait = wait.min(next_probe_at.saturating_duration_since(now));
14443        }
14444        sleep(wait).await;
14445    }
14446}
14447
14448/// The wait between drain busy-gauge probes: the larger of
14449/// [`DRAIN_BUSY_REPROBE_INTERVAL`] and [`REGISTRY_RELEASE_POLL`], the
14450/// drain's own in-flight poll interval.
14451fn drain_busy_reprobe_interval() -> Duration {
14452    DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
14453}
14454
14455/// Logs why a drain gave up: the drain waited its full timeout without the
14456/// module going quiet, and teardown is being forced.
14457///
14458/// The line names two kinds of evidence, because a bare "timed out" hides
14459/// causes that need different fixes:
14460/// - `holdouts`: the requests and routes still open when the timeout hit,
14461///   and on which connections. One stuck call is a module bug; a held stream
14462///   on every session is a module that should end its streams when it
14463///   receives `module.draining`.
14464/// - `gauges`: for each busy gauge the module declares, its latest reading
14465///   and how many probes ran. This separates a module that kept reporting
14466///   itself busy, one whose health answer never contained the gauge, and one
14467///   that never answered the probes, which otherwise all look like a timeout
14468///   with nothing in flight.
14469fn warn_drain_timed_out(
14470    module_id: &str,
14471    drain_timeout: Duration,
14472    reason: RouteCloseReason,
14473    holdouts: &crate::forwarding::DrainHoldouts,
14474    gauges: &DrainGaugeTrace,
14475) {
14476    warn!(
14477        module_id = %module_id,
14478        waited = ?drain_timeout,
14479        ?reason,
14480        held_requests = holdouts.requests,
14481        held_routes = holdouts.routes,
14482        total_routes = holdouts.total_routes,
14483        top_connections = ?holdouts.top_connections,
14484        // `module_channel:corr`, so the module can find each held request
14485        // in its own log; capped, so `held_requests` is the full count.
14486        held = %holdouts
14487            .held
14488            .iter()
14489            .map(|(channel, corr)| format!("{channel}:{corr}"))
14490            .collect::<Vec<_>>()
14491            .join(","),
14492        gauge_probes = gauges.probes,
14493        busy_gauges = %gauges,
14494        "route drain timed out before request quiescence; forcing teardown"
14495    );
14496}
14497
14498/// The `route.closed` `drained` value implied by a quiescence-wait outcome.
14499///
14500/// `Ok` is always honest and passed straight through -- the wait actually measured
14501/// in-flight state. `Err` means the wait produced no measurement at all (the
14502/// forwarding table's lock was poisoned), so `false` is reported as the one honest
14503/// constant: the drain did not complete. Never recomputed from route state, never a
14504/// third "unknown" value -- the caller must still send a well-formed `route.closed`.
14505fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
14506    match wait_result {
14507        Ok(drained) => *drained,
14508        Err(_) => false,
14509    }
14510}
14511
14512fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
14513    for released in released_routes {
14514        let frame = match Frame::build_with_version(
14515            released.negotiated_ver,
14516            FrameType::Goodbye,
14517            control_flags(),
14518            released.channel,
14519            released.epoch,
14520            0,
14521            Vec::new(),
14522        ) {
14523            Ok(frame) => frame,
14524            Err(err) => {
14525                warn!(
14526                    route_channel = released.channel,
14527                    error = %err,
14528                    "failed to build supervisor drain route GOODBYE frame"
14529                );
14530                continue;
14531            }
14532        };
14533        if !released.close_on_delivery_failure() {
14534            crate::forwarding::send_module_route_goodbye(
14535                &forwarding.counters(),
14536                &released.sink,
14537                frame,
14538                released.module_id.as_deref(),
14539                "supervisor drain",
14540            );
14541            continue;
14542        }
14543        if let Err(err) = released.sink.try_send(frame) {
14544            warn!(
14545                target_connection_id = released.connection_id.get(),
14546                route_channel = released.channel,
14547                error = %err,
14548                "supervisor drain route GOODBYE was not delivered to client; closing target connection"
14549            );
14550            let _ = forwarding.escalate_client_delivery_failure(
14551                released.connection_id,
14552                released.channel,
14553                released.epoch,
14554                CloseReason::new(
14555                    "route_goodbye_delivery_failed",
14556                    format!(
14557                        "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
14558                        released.channel
14559                    ),
14560                ),
14561                crate::forwarding::UndeliveredFrame {
14562                    module_id: released.module_id.as_deref(),
14563                    sink: &released.sink,
14564                },
14565            );
14566        }
14567    }
14568}
14569
14570async fn send_module_draining(
14571    module_id: &str,
14572    reason: RouteCloseReason,
14573    deadline_ms: u64,
14574    target: &ModuleDrainTarget,
14575    _wait_for_flush: bool,
14576) -> bool {
14577    let body = match serde_json::to_vec(&ModuleControlCommand::Draining {
14578        reason,
14579        deadline_ms,
14580    }) {
14581        Ok(body) => body,
14582        Err(err) => {
14583            warn!(
14584                module_id,
14585                error = %err,
14586                "failed to encode module draining command"
14587            );
14588            return false;
14589        }
14590    };
14591    let frame = match Frame::build_with_version(
14592        target.negotiated_ver,
14593        FrameType::Push,
14594        control_flags(),
14595        0,
14596        0,
14597        0,
14598        body,
14599    ) {
14600        Ok(frame) => frame,
14601        Err(err) => {
14602            warn!(
14603                module_id,
14604                error = %err,
14605                "failed to build module draining command frame"
14606            );
14607            return false;
14608        }
14609    };
14610    #[cfg(unix)]
14611    if _wait_for_flush {
14612        return target.sink.send_flushed(frame).await.is_ok();
14613    }
14614    if let Err(err) = target.sink.try_send(frame) {
14615        warn!(
14616            module_id,
14617            target_connection_id = target.endpoint.connection_id.get(),
14618            error = %err,
14619            "module draining command was not delivered to peer"
14620        );
14621        return false;
14622    }
14623    true
14624}
14625
14626/// The channel-0 GOODBYE that tells a module its stop is planned.
14627fn module_goodbye_frame(module_id: &str, negotiated_ver: u8) -> Option<Frame> {
14628    match Frame::build_with_version(
14629        negotiated_ver,
14630        FrameType::Goodbye,
14631        control_flags(),
14632        0,
14633        0,
14634        0,
14635        Vec::new(),
14636    ) {
14637        Ok(frame) => Some(frame),
14638        Err(err) => {
14639            warn!(
14640                module_id,
14641                error = %err,
14642                "failed to build module GOODBYE frame"
14643            );
14644            None
14645        }
14646    }
14647}
14648
14649/// Send every registered module connection its module GOODBYE at daemon
14650/// shutdown, then request that connection's close.
14651///
14652/// A module tells a planned stop from a lost daemon by whether a GOODBYE came
14653/// before EOF, so the GOODBYE must reach the socket before the close. A close
14654/// request does not wait for the connection's queued frames: its writer gets a
14655/// bounded grace after the close, is aborted if it overruns it, and the daemon
14656/// process may exit before that grace ends. So with `wait_for_flush`, each
14657/// connection is closed only after its writer has acknowledged writing the
14658/// GOODBYE, or once a short shared budget runs out, so one module that is not
14659/// reading cannot hold up the others or the shutdown. Without it the GOODBYEs
14660/// are only queued, for a shutdown the operator has told to stop waiting.
14661/// A connection that is already gone is skipped.
14662#[cfg(unix)]
14663async fn send_module_goodbyes_for_daemon_shutdown(
14664    forwarding: &Arc<ForwardingTable>,
14665    reason: &CloseReason,
14666    wait_for_flush: bool,
14667) {
14668    const GOODBYE_BUDGET: Duration = Duration::from_millis(500);
14669    let targets = match forwarding.module_connections() {
14670        Ok(targets) => targets,
14671        Err(err) => {
14672            warn!(error = %err, "could not list module connections for shutdown GOODBYE");
14673            return;
14674        }
14675    };
14676    let deadline = Instant::now() + GOODBYE_BUDGET;
14677    let mut sends = tokio::task::JoinSet::new();
14678    for target in targets {
14679        let Some(frame) = module_goodbye_frame(&target.module_id, target.negotiated_ver) else {
14680            continue;
14681        };
14682        if !wait_for_flush {
14683            if let Err(err) = target.sink.try_send(frame) {
14684                debug!(
14685                    module_id = %target.module_id,
14686                    error = %err,
14687                    "shutdown module GOODBYE was not queued"
14688                );
14689            }
14690            continue;
14691        }
14692        let forwarding = Arc::clone(forwarding);
14693        let reason = reason.clone();
14694        sends.spawn(async move {
14695            match timeout_at(deadline, target.sink.send_flushed(frame)).await {
14696                Ok(Ok(())) => {}
14697                Ok(Err(err)) => debug!(
14698                    module_id = %target.module_id,
14699                    error = %err,
14700                    "module connection closed before its shutdown GOODBYE was written"
14701                ),
14702                Err(_) => warn!(
14703                    module_id = %target.module_id,
14704                    budget = ?GOODBYE_BUDGET,
14705                    "shutdown module GOODBYE was not written within its budget; closing anyway"
14706                ),
14707            }
14708            forwarding.request_connection_close(target.endpoint.connection_id, reason);
14709        });
14710    }
14711    // Every task ends by the shared deadline, so this wait is bounded too.
14712    while sends.join_next().await.is_some() {}
14713}
14714
14715async fn send_module_goodbye(
14716    module_id: &str,
14717    forwarding: &ForwardingTable,
14718    target: &ModuleDrainTarget,
14719    wait_for_flush: bool,
14720) {
14721    let Some(frame) = module_goodbye_frame(module_id, target.negotiated_ver) else {
14722        return;
14723    };
14724    // A channel is shut down synchronously after its drain. Its final frame
14725    // must reach the socket writer first; queue admission alone can lose it.
14726    let sent = if wait_for_flush {
14727        timeout(Duration::from_millis(500), target.sink.send_flushed(frame))
14728            .await
14729            .map_err(|_| "module GOODBYE flush exceeded 500ms".to_owned())
14730            .and_then(|result| result.map_err(|err| err.to_string()))
14731    } else {
14732        target.sink.try_send(frame).map_err(|err| err.to_string())
14733    };
14734    if let Err(err) = sent {
14735        warn!(
14736            module_id,
14737            target_connection_id = target.endpoint.connection_id.get(),
14738            error = %err,
14739            "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
14740        );
14741        forwarding.request_connection_close(
14742            target.endpoint.connection_id,
14743            CloseReason::new(
14744                "module_goodbye_delivery_failed",
14745                format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
14746            ),
14747        );
14748    }
14749}
14750
14751#[derive(Clone, Copy)]
14752struct ForwardingDrainContext<'a> {
14753    spec: &'a ModuleSpec,
14754    runtime: &'a SupervisorRuntimeConfig,
14755    registry: &'a Registry,
14756    scope: DrainScope,
14757}
14758
14759/// Which process a forwarding drain addresses.
14760#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14761enum DrainScope {
14762    /// Whatever endpoint is active for the module id: every plain stop,
14763    /// restart and reload. Also moves the module's state to `Draining`.
14764    Active,
14765    /// One specific endpoint: a swap's incumbent after cutover. Draining it by
14766    /// module id would resolve to the promoted candidate and leave neither
14767    /// process routable. The module's state is left alone, since the promoted
14768    /// candidate is what it describes and that process is running.
14769    Endpoint(crate::ModuleEndpointId),
14770}
14771
14772/// Whether a child being drained has already been asked to stop by the time
14773/// its drain wait starts.
14774///
14775/// The drain wait is the same budget whatever this says. What it decides is
14776/// whether the supervisor must ask by signal before that wait begins: a child
14777/// that nobody asked will sit out the whole budget and then be SIGKILLed,
14778/// healthy or not.
14779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14780enum StopNotice {
14781    /// The module was sent `module.draining` and a module GOODBYE over its own
14782    /// registered connection, and stops itself.
14783    SentOverConnection,
14784    /// The forwarding drain found no registered connection for the module: a
14785    /// subc child spawned moments ago that has not sent HELLO yet, or a
14786    /// `protocol: "none"` child, which never registers.
14787    NoConnection,
14788    /// This path sends nothing over the module's connection: the supervisor has
14789    /// no forwarding table, or the caller stops the child without a forwarding
14790    /// drain.
14791    NotSent,
14792}
14793
14794async fn begin_forwarding_drain(
14795    spec: &ModuleSpec,
14796    runtime: &SupervisorRuntimeConfig,
14797    registry: &Registry,
14798    snapshot: &SharedSnapshot,
14799    enabled: Option<bool>,
14800    reason: RouteCloseReason,
14801) -> Result<StopNotice, SuperviseError> {
14802    let Some(forwarding) = runtime.forwarding.as_ref() else {
14803        return Err(SuperviseError::ReloadUnavailable {
14804            module_id: spec.module_id.clone(),
14805            reason: "supervisor was not configured with a forwarding table".to_string(),
14806        });
14807    };
14808
14809    begin_forwarding_drain_with(
14810        forwarding,
14811        ForwardingDrainContext {
14812            spec,
14813            runtime,
14814            registry,
14815            scope: DrainScope::Active,
14816        },
14817        snapshot,
14818        enabled,
14819        reason,
14820        runtime.drain_timeout,
14821    )
14822    .await
14823}
14824
14825async fn begin_forwarding_drain_if_configured(
14826    spec: &ModuleSpec,
14827    runtime: &SupervisorRuntimeConfig,
14828    registry: &Registry,
14829    snapshot: &SharedSnapshot,
14830    enabled: Option<bool>,
14831    reason: RouteCloseReason,
14832) -> Result<StopNotice, SuperviseError> {
14833    begin_forwarding_drain_with_timeout(
14834        spec,
14835        runtime,
14836        registry,
14837        snapshot,
14838        enabled,
14839        reason,
14840        runtime.drain_timeout,
14841    )
14842    .await
14843}
14844
14845/// Like [`begin_forwarding_drain_if_configured`] but with an explicit drain
14846/// budget, for paths where the operator overrides the module's configured one
14847/// (`supervisor.restart{drain_timeout_ms}`).
14848async fn begin_forwarding_drain_with_timeout(
14849    spec: &ModuleSpec,
14850    runtime: &SupervisorRuntimeConfig,
14851    registry: &Registry,
14852    snapshot: &SharedSnapshot,
14853    enabled: Option<bool>,
14854    reason: RouteCloseReason,
14855    drain_timeout: Duration,
14856) -> Result<StopNotice, SuperviseError> {
14857    let Some(forwarding) = runtime.forwarding.as_ref() else {
14858        return Ok(StopNotice::NotSent);
14859    };
14860
14861    begin_forwarding_drain_with(
14862        forwarding,
14863        ForwardingDrainContext {
14864            spec,
14865            runtime,
14866            registry,
14867            scope: DrainScope::Active,
14868        },
14869        snapshot,
14870        enabled,
14871        reason,
14872        drain_timeout,
14873    )
14874    .await
14875}
14876
14877async fn begin_forwarding_drain_with(
14878    forwarding: &ForwardingTable,
14879    context: ForwardingDrainContext<'_>,
14880    snapshot: &SharedSnapshot,
14881    enabled: Option<bool>,
14882    reason: RouteCloseReason,
14883    drain_timeout: Duration,
14884) -> Result<StopNotice, SuperviseError> {
14885    let ForwardingDrainContext {
14886        spec,
14887        runtime,
14888        registry,
14889        scope,
14890    } = context;
14891    debug_assert_ne!(reason, RouteCloseReason::Crash);
14892    let terminal = matches!(reason, RouteCloseReason::Disable);
14893    let drain_started_at = Instant::now();
14894    let drain_deadline = drain_started_at + drain_timeout;
14895    let deadline_ms =
14896        unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
14897    let busy_gauges = match scope {
14898        DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
14899        DrainScope::Endpoint(endpoint) => {
14900            declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
14901        }
14902    };
14903
14904    // Admission gate first: route.open/commit and route REQUEST admission are closed
14905    // before the first quiescence check, so the outstanding count can only fall.
14906    let gate_started = Instant::now();
14907    let drain_target = match scope {
14908        DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
14909        DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
14910    }
14911    .map_err(SuperviseError::Forwarding)?;
14912    // The instant admission closed, and how long taking the forwarding write
14913    // lock to close it took. The timeout line reports only the quiescence
14914    // wait, so without this a drain that started late looked like one that
14915    // started on time.
14916    info!(
14917        module_id = %spec.module_id,
14918        ?reason,
14919        gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
14920        connected = drain_target.is_some(),
14921        "module drain began; route admission closed"
14922    );
14923    if scope == DrainScope::Active {
14924        update_snapshot(snapshot, Some(&spec.module_id), |state| {
14925            state.state = ModuleState::Draining;
14926            state.draining_to_replace =
14927                matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
14928            if let Some(enabled) = enabled {
14929                state.enabled = enabled;
14930            }
14931        })?;
14932    }
14933
14934    let Some(target) = drain_target.as_ref() else {
14935        // Nothing was sent: the module has no registered connection to carry
14936        // `module.draining` or a GOODBYE. The caller must not assume the child
14937        // was asked to stop.
14938        return Ok(StopNotice::NoConnection);
14939    };
14940    let flush_goodbye = runtime.supervisor_handle.as_ref().is_some_and(|handle| {
14941        handle
14942            .registration_spawn(target.endpoint.connection_id)
14943            .is_some()
14944    });
14945    {
14946        send_module_draining(&spec.module_id, reason, deadline_ms, target, false).await;
14947        #[cfg(feature = "test-support")]
14948        forwarding.wait_before_route_closing_for_test().await;
14949        let routes = forwarding
14950            .endpoint_routes(target.endpoint)
14951            .map_err(SuperviseError::Forwarding)?;
14952        let routes_notified = routes.len();
14953        crate::control::send_route_control_pushes(
14954            forwarding,
14955            routes.clone(),
14956            ClientControlPush::RouteClosing {
14957                module_id: spec.module_id.clone(),
14958                channels: Vec::new(),
14959                reason,
14960            },
14961        );
14962        send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
14963
14964        // `route.closing` was just sent above: from here on every return path,
14965        // including an early one, MUST send `route.closed` before propagating
14966        // anything else. A client holds `closing` as a promise that a verdict is
14967        // coming; leaving early without `closed` strands it waiting forever, since
14968        // `closing` carries no timeout of its own.
14969        let mut gauge_trace = DrainGaugeTrace::new(&busy_gauges);
14970        let wait_result = wait_for_forwarding_quiescence(
14971            forwarding,
14972            &spec.module_id,
14973            runtime,
14974            target.endpoint,
14975            drain_deadline,
14976            &busy_gauges,
14977            scope,
14978            &mut gauge_trace,
14979        )
14980        .await;
14981        let drained = drained_after_quiescence_wait(&wait_result);
14982        if let Err(err) = &wait_result {
14983            error!(
14984                module_id = %spec.module_id,
14985                ?reason,
14986                error = %err,
14987                "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
14988            );
14989        } else if !drained {
14990            // Read before teardown releases the routes.
14991            let holdouts = forwarding
14992                .endpoint_drain_holdouts(target.endpoint)
14993                .unwrap_or_default();
14994            warn_drain_timed_out(
14995                &spec.module_id,
14996                drain_timeout,
14997                reason,
14998                &holdouts,
14999                &gauge_trace,
15000            );
15001        }
15002        crate::control::send_route_control_pushes(
15003            forwarding,
15004            routes,
15005            ClientControlPush::RouteClosed {
15006                module_id: spec.module_id.clone(),
15007                channels: Vec::new(),
15008                reason,
15009                drained,
15010                abandoned: target.abandoned_bindings.len() as u32,
15011                excluded_subscriptions: target.excluded_subscriptions,
15012                terminal: Some(terminal),
15013            },
15014        );
15015        wait_result?;
15016
15017        // `route.closed` has now been sent unconditionally above. From here the
15018        // remaining steps are cleanup (route + module GOODBYE) rather than a
15019        // promise the client is waiting on, but a lock-poisoned
15020        // `release_module_endpoint_routes` would otherwise skip the module
15021        // GOODBYE silently too -- send it before propagating the error.
15022        let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
15023            Ok(routes) => routes,
15024            Err(err) => {
15025                warn!(
15026                    module_id = %spec.module_id,
15027                    ?reason,
15028                    error = %err,
15029                    "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
15030                );
15031                send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
15032                return Err(SuperviseError::Forwarding(err));
15033            }
15034        };
15035        let route_goodbye_count = released_routes.len();
15036        send_route_goodbyes(forwarding, released_routes);
15037        send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
15038
15039        // The drain's happy path was previously silent: every emission above is
15040        // best-effort with only its failure arm logged, so "were consumers told"
15041        // was unprovable from the daemon log (surfaced by a 30-minute consumer
15042        // hang where the open question was exactly whether teardown notice went
15043        // out). One summary line makes that class decidable in one grep.
15044        info!(
15045            module_id = %spec.module_id,
15046            ?reason,
15047            routes_notified,
15048            route_goodbyes = route_goodbye_count,
15049            abandoned_reservations = target.abandoned_bindings.len(),
15050            excluded_subscriptions = target.excluded_subscriptions,
15051            drained,
15052            "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
15053        );
15054    }
15055
15056    Ok(StopNotice::SentOverConnection)
15057}
15058
15059/// Wait for the freshly spawned child to take the ACTIVE slot for `module_id`,
15060/// the only slot a plain (non-swap) spawn can register into.
15061async fn wait_for_registration_after_reload(
15062    registry: &Registry,
15063    module_id: &str,
15064    snapshot: &SharedSnapshot,
15065    child: &mut SupervisedChild,
15066    wait: Duration,
15067) -> Result<RegistrationWaitOutcome, SuperviseError> {
15068    wait_for_slot_registration(
15069        registry,
15070        crate::registry::RegistrationSlot::Active(module_id),
15071        module_id,
15072        snapshot,
15073        child,
15074        wait,
15075    )
15076    .await
15077}
15078
15079/// Wait for `child` to register into `slot`, or to exit, or for `wait` to pass.
15080///
15081/// Keyed on the slot rather than the bare module id because during a swap the
15082/// id's active slot is already held by the incumbent: an id-keyed wait would
15083/// report the incumbent's registration as the candidate's and a candidate that
15084/// never registers would look registered. A swap candidate waits on
15085/// `crate::registry::RegistrationSlot::Candidate`.
15086async fn wait_for_slot_registration(
15087    registry: &Registry,
15088    slot: crate::registry::RegistrationSlot<'_>,
15089    module_id: &str,
15090    snapshot: &SharedSnapshot,
15091    child: &mut SupervisedChild,
15092    wait: Duration,
15093) -> Result<RegistrationWaitOutcome, SuperviseError> {
15094    let deadline = Instant::now() + wait;
15095    loop {
15096        if registry
15097            .registration(slot)
15098            .map_err(SuperviseError::Registry)?
15099            .is_some()
15100        {
15101            return Ok(RegistrationWaitOutcome::Registered);
15102        }
15103
15104        let now = Instant::now();
15105        if now >= deadline {
15106            return Ok(RegistrationWaitOutcome::TimedOut);
15107        }
15108        let remaining = deadline.saturating_duration_since(now);
15109        let poll = remaining.min(REGISTRY_RELEASE_POLL);
15110
15111        tokio::select! {
15112            wait_result = child.wait() => {
15113                let status = wait_result.map_err(|source| SuperviseError::Wait {
15114                    module_id: module_id.to_string(),
15115                    source,
15116                })?;
15117                return Ok(RegistrationWaitOutcome::Exited(classify_reaped_child_exit(
15118                    snapshot,
15119                    child,
15120                    &status,
15121                )));
15122            }
15123            _ = sleep(poll) => {}
15124        }
15125    }
15126}
15127
15128fn registration_failure_exit_report(mut exit_report: ExitReport) -> ExitReport {
15129    // A process stopped for missing its first HELLO did not provide service,
15130    // even if its TERM handler exits zero. Reload also uses this classification
15131    // when a replacement exits before registering.
15132    if exit_report.kind != ExitKind::DeliberateSeverance {
15133        exit_report.kind = ExitKind::Crash;
15134    }
15135    exit_report
15136}
15137
15138async fn handle_reload_child_registration_failure(
15139    spec: &ModuleSpec,
15140    runtime: &SupervisorRuntimeConfig,
15141    registry: &Registry,
15142    process_liveness: &SupervisorProcessLiveness,
15143    snapshot: &SharedSnapshot,
15144    _child: &mut Option<SupervisedChild>,
15145    failure: ReloadRegistrationFailure,
15146) -> Result<(), SuperviseError> {
15147    let ReloadRegistrationFailure {
15148        exit_report,
15149        reason,
15150    } = failure;
15151    match on_child_exit(
15152        spec,
15153        runtime.restart_policy,
15154        registry,
15155        snapshot,
15156        &runtime.terminal_ring,
15157        &runtime.spawn_events,
15158        &runtime.child_roster,
15159        exit_report,
15160        runtime.recovery_is_daemon,
15161    )
15162    .await
15163    {
15164        NextAction::Stop {
15165            registration_released,
15166        } => {
15167            if registration_released {
15168                process_liveness.untrack_if_current(&spec.module_id, snapshot);
15169            }
15170        }
15171        NextAction::Restart { schedule } => {
15172            let delay = schedule.map_or(runtime.restart_policy.delay_for_restart(0), |schedule| {
15173                schedule.delay
15174            });
15175            if let Some(schedule) = schedule {
15176                log_crash_respawn(&spec.module_id, schedule);
15177            }
15178            schedule_respawn(
15179                runtime,
15180                snapshot,
15181                &spec.module_id,
15182                delay,
15183                RespawnKind::Spawn,
15184                true,
15185            )?;
15186        }
15187    }
15188    Err(SuperviseError::ReloadFailed {
15189        module_id: spec.module_id.clone(),
15190        reason,
15191    })
15192}
15193
15194async fn handle_reload_spawn_failure(
15195    spec: &ModuleSpec,
15196    runtime: &SupervisorRuntimeConfig,
15197    process_liveness: &SupervisorProcessLiveness,
15198    snapshot: &SharedSnapshot,
15199    _child: &mut Option<SupervisedChild>,
15200    reason: String,
15201) -> Result<(), SuperviseError> {
15202    let now = Instant::now();
15203    let mut schedule = None;
15204    update_snapshot(snapshot, Some(&spec.module_id), |state| {
15205        clear_current_process_facts(state);
15206        if state.enabled {
15207            schedule = state.next_crash_restart(&runtime.restart_policy, now);
15208            state.state = if schedule.is_some() {
15209                ModuleState::Restarting
15210            } else {
15211                if runtime
15212                    .failure_context(runtime.recovery_is_daemon)
15213                    .may_retry()
15214                {
15215                    state.failed_retry.schedule(&spec.module_id);
15216                }
15217                ModuleState::Failed
15218            };
15219        } else {
15220            state.state = ModuleState::Disabled;
15221        }
15222    })?;
15223    if let Some(schedule) = schedule {
15224        schedule_respawn(
15225            runtime,
15226            snapshot,
15227            &spec.module_id,
15228            schedule.delay,
15229            RespawnKind::Spawn,
15230            true,
15231        )?;
15232    } else {
15233        process_liveness.untrack_if_current(&spec.module_id, snapshot);
15234    }
15235    Err(SuperviseError::ReloadFailed {
15236        module_id: spec.module_id.clone(),
15237        reason,
15238    })
15239}
15240
15241fn control_flags() -> Flags {
15242    Flags::new(false, Priority::Passive, false)
15243}
15244
15245#[allow(clippy::too_many_arguments)]
15246async fn drain_optional_child(
15247    module_id: &str,
15248    protocol: ModuleProtocol,
15249    stop_notice: StopNotice,
15250    registry: &Registry,
15251    forwarding: Option<&ForwardingTable>,
15252    snapshot: &SharedSnapshot,
15253    terminal_ring: &Arc<Mutex<TerminalRing>>,
15254    spawn_events: &SpawnEventFeed,
15255    child: &mut Option<SupervisedChild>,
15256    drain_timeout: Duration,
15257    final_state: ModuleState,
15258    enabled: Option<bool>,
15259    failure: &FailureContext,
15260) -> Result<(), SuperviseError> {
15261    if let Some(child) = child.take() {
15262        drain_child_to_state(
15263            module_id,
15264            protocol,
15265            stop_notice,
15266            registry,
15267            forwarding,
15268            snapshot,
15269            terminal_ring,
15270            spawn_events,
15271            child,
15272            drain_timeout,
15273            final_state,
15274            enabled,
15275            failure,
15276        )
15277        .await
15278    } else {
15279        update_snapshot(snapshot, Some(module_id), |state| {
15280            state.state = final_state;
15281            if final_state == ModuleState::Failed {
15282                state.failed_retry.failed_at = Some(Instant::now());
15283            }
15284            if let Some(enabled) = enabled {
15285                state.enabled = enabled;
15286            }
15287            clear_current_process_facts(state);
15288        })?;
15289        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await
15290    }
15291}
15292
15293#[allow(clippy::too_many_arguments)]
15294async fn drain_child_to_state(
15295    module_id: &str,
15296    _protocol: ModuleProtocol,
15297    stop_notice: StopNotice,
15298    registry: &Registry,
15299    forwarding: Option<&ForwardingTable>,
15300    snapshot: &SharedSnapshot,
15301    terminal_ring: &Arc<Mutex<TerminalRing>>,
15302    spawn_events: &SpawnEventFeed,
15303    mut child: SupervisedChild,
15304    drain_timeout: Duration,
15305    final_state: ModuleState,
15306    enabled: Option<bool>,
15307    failure: &FailureContext,
15308) -> Result<(), SuperviseError> {
15309    let protocol = child.protocol;
15310    child.retire_registration();
15311    update_snapshot(snapshot, Some(module_id), |state| {
15312        state.state = ModuleState::Draining;
15313        state.draining_to_replace = final_state == ModuleState::Restarting;
15314        if let Some(enabled) = enabled {
15315            state.enabled = enabled;
15316        }
15317    })?;
15318
15319    // The wait below is the same budget in every case; what differs is
15320    // whether anything has ASKED the child to stop before it starts. Only a
15321    // forwarding drain that reached the module's registered connection has
15322    // (`module.draining`, then a module GOODBYE). Every other child was told
15323    // nothing: a `protocol: "none"` module, which never registers; a subc
15324    // module spawned moments ago that has not sent HELLO yet; or a stop that
15325    // runs no forwarding drain. Without a signal the budget is only a delay
15326    // in front of SIGKILL -- and the not-yet-registered child is the worst
15327    // case, because it registers into a module that is already draining,
15328    // is never told, and is killed while healthy.
15329    if stop_notice != StopNotice::SentOverConnection {
15330        if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
15331            info!(
15332                module_id,
15333                pid = child.pid,
15334                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
15335                "module has no connection yet; requesting stop by signal"
15336            );
15337        }
15338        request_graceful_stop(module_id, &child);
15339    }
15340
15341    let exit_report = match timeout(drain_timeout, child.wait()).await {
15342        Ok(Ok(status)) => classify_reaped_child_exit(snapshot, &child, &status),
15343        Ok(Err(source)) => {
15344            fail_after_wait_error(
15345                module_id,
15346                snapshot,
15347                terminal_ring,
15348                spawn_events,
15349                format!("failed to wait during drain: {source}"),
15350                failure,
15351            );
15352            return Err(SuperviseError::Wait {
15353                module_id: module_id.to_string(),
15354                source,
15355            });
15356        }
15357        Err(_) => {
15358            // Mirror the sibling arm above: state is already `Draining`, and an
15359            // error propagated from here would strand it there -- a state
15360            // `set_enabled(true)` cannot heal (`revive_terminal` matches only
15361            // `Failed | Stopped`), leaving an operator Restart as the only exit.
15362            // `Failed` before `?` keeps the module operator-visible and
15363            // revivable. Trigger is an ESRCH race (process exits between the
15364            // drain timeout firing and the kill) or a post-kill wait failure
15365            // (issue #34).
15366            //
15367            // Logged because the kill is otherwise visible only as signal 9 in
15368            // the terminal ring, and the budget it follows can be long enough
15369            // that consumers see a stretch of refusals with no stated cause.
15370            warn!(
15371                module_id,
15372                pid = child.pid,
15373                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
15374                reason = ?final_state,
15375                ?stop_notice,
15376                "drain budget expired before the module exited; killing it"
15377            );
15378            let kill =
15379                if final_state == ModuleState::Restarting && child.child.container().is_some() {
15380                    child.kill_leader()
15381                } else {
15382                    child.start_kill()
15383                };
15384            kill.map_err(|source| {
15385                fail_after_wait_error(
15386                    module_id,
15387                    snapshot,
15388                    terminal_ring,
15389                    spawn_events,
15390                    format!("failed to kill during drain: {source}"),
15391                    failure,
15392                );
15393                SuperviseError::Kill {
15394                    module_id: module_id.to_string(),
15395                    source,
15396                }
15397            })?;
15398            let status = child.wait().await.map_err(|source| {
15399                fail_after_wait_error(
15400                    module_id,
15401                    snapshot,
15402                    terminal_ring,
15403                    spawn_events,
15404                    format!("failed to wait after drain kill: {source}"),
15405                    failure,
15406                );
15407                SuperviseError::Wait {
15408                    module_id: module_id.to_string(),
15409                    source,
15410                }
15411            })?;
15412            classify_reaped_child_exit(snapshot, &child, &status)
15413        }
15414    };
15415
15416    let detail = lock_snapshot(snapshot)?.drain_disposition_detail.take();
15417    publish_after_terminal_record(
15418        module_id,
15419        || {
15420            record_terminal_with_detail(
15421                module_id,
15422                terminal_ring,
15423                spawn_events,
15424                &exit_report,
15425                terminal_disposition(final_state),
15426                detail,
15427            )
15428        },
15429        || {
15430            update_snapshot(snapshot, Some(module_id), |state| {
15431                state.state = final_state;
15432                if final_state == ModuleState::Failed {
15433                    state.failed_retry.failed_at = Some(Instant::now());
15434                }
15435                if let Some(enabled) = enabled {
15436                    state.enabled = enabled;
15437                }
15438                clear_current_process_facts(state);
15439                state.last_exit = Some(exit_report.clone());
15440                if exit_report.kind == ExitKind::DeliberateSeverance {
15441                    state.lifetime_restarts += 1;
15442                }
15443            })
15444        },
15445    )?;
15446    child.drain_stderr(module_id).await;
15447
15448    let released =
15449        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
15450    child
15451        .finish_exit(
15452            released.is_ok()
15453                && final_state == ModuleState::Restarting
15454                && child.spawn_failure.is_none(),
15455        )
15456        .await
15457        .map_err(|source| SuperviseError::Wait {
15458            module_id: module_id.to_owned(),
15459            source,
15460        })?;
15461    released
15462}
15463
15464/// Ask a child that nothing else has asked to stop, by signal.
15465///
15466/// A registered subc module is asked over its own connection: the drain sends
15467/// `route.closing`/`route.closed` to its consumers, a GOODBYE per route, then a
15468/// module GOODBYE, and the module stops itself. A module that speaks no subc
15469/// wire receives none of that, and neither does a subc module that has not
15470/// registered yet, so for them the drain budget would be pure delay in front of
15471/// a SIGKILL -- and for a process with a store to flush (JetStream is the
15472/// reason `protocol: "none"` exists) a SIGKILL turns every ordinary teardown
15473/// into a recovery on the next start.
15474///
15475/// NEVER CALLED FOR A MODULE THAT WAS TOLD OVER ITS CONNECTION, and that is a
15476/// rule rather than an optimisation: that module's graceful stop is already
15477/// running by the time its child is drained, and a signal would race it.
15478///
15479/// Best-effort by construction. A child that has already exited is the ordinary
15480/// case rather than an error (the kill lands on a reaped or exiting pid), so a
15481/// failure is logged at debug and the wait-then-kill below still decides the
15482/// outcome.
15483#[cfg(unix)]
15484fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
15485    let Some(pid) = child
15486        .id()
15487        .and_then(|pid| i32::try_from(pid).ok())
15488        .and_then(rustix::process::Pid::from_raw)
15489    else {
15490        debug!(
15491            module_id,
15492            "no pid to signal for teardown; falling through to the drain wait"
15493        );
15494        return;
15495    };
15496    match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
15497        Ok(()) => debug!(
15498            module_id,
15499            "sent SIGTERM to a module nothing else asked to stop"
15500        ),
15501        Err(err) => debug!(
15502            module_id,
15503            error = %err,
15504            "SIGTERM to module failed; the drain wait and kill still apply"
15505        ),
15506    }
15507}
15508
15509/// Windows has no SIGTERM and no portable stand-in for one. The graceful stops
15510/// Windows does offer need cooperation this supervisor cannot assume: a console
15511/// control event requires sharing a console with the child, and `WM_CLOSE`
15512/// requires the child to pump a message loop. A supervised server process does
15513/// neither, so there is nothing to send and teardown is the wait followed by the
15514/// kill. Emulating a signal here would mean inventing a stop protocol, which is
15515/// the thing `protocol: "none"` exists to avoid.
15516#[cfg(not(unix))]
15517fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
15518    debug!(
15519        module_id,
15520        "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
15521    );
15522}
15523
15524fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
15525    match final_state {
15526        ModuleState::Stopped => TerminalDisposition::Stopped,
15527        ModuleState::Disabled => TerminalDisposition::Disabled,
15528        ModuleState::Restarting => TerminalDisposition::Restarting,
15529        ModuleState::Failed => TerminalDisposition::Failed,
15530        ModuleState::Starting
15531        | ModuleState::Running
15532        | ModuleState::Unresponsive
15533        | ModuleState::Draining => {
15534            unreachable!("terminal exits only finish in terminal or restarting states")
15535        }
15536    }
15537}
15538
15539/// Release a reaped child's registration before allowing another spawn.
15540///
15541/// EOF is not a process-lifetime signal: an inherited socket can stay open
15542/// indefinitely, and serial frame dispatch can be waiting on egress instead of
15543/// reading EOF. After the normal release grace, request connection close (which
15544/// cancels both reads and dispatch), then allow one more release grace for the
15545/// connection guard's forwarding cleanup. Never evict a different connection.
15546async fn release_dead_registration(
15547    registry: &Registry,
15548    forwarding: Option<&ForwardingTable>,
15549    snapshot: &SharedSnapshot,
15550    module_id: &str,
15551    failure: &FailureContext,
15552) -> Result<(), SuperviseError> {
15553    let result = async {
15554        let registration = registry
15555            .get_module(module_id)
15556            .map_err(SuperviseError::Registry)?;
15557        match wait_for_registration_release(registry, module_id, REGISTRY_RELEASE_TIMEOUT).await {
15558            Ok(()) => return Ok(()),
15559            Err(SuperviseError::RegistrationStillActive { .. }) => {}
15560            Err(err) => return Err(err),
15561        }
15562        let pid = lock_snapshot(snapshot)?.reaped_pid;
15563        if let (Some(registration), Some(forwarding), Some(pid)) = (registration, forwarding, pid) {
15564            warn!(
15565                module_id,
15566                pid,
15567                connection_id = registration.connection_id.get(),
15568                "reaped module registration outlived release grace; closing dead connection"
15569            );
15570            forwarding.request_connection_close(
15571                registration.connection_id,
15572                CloseReason::new(
15573                    "supervised_process_reaped",
15574                    format!("module '{module_id}' pid {pid} exited"),
15575                ),
15576            );
15577            wait_for_slot_registration_release(
15578                registry,
15579                crate::registry::RegistrationSlot::Connection(registration.connection_id),
15580                REGISTRY_RELEASE_TIMEOUT,
15581            )
15582            .await?;
15583        }
15584        wait_for_registration_release(registry, module_id, Duration::ZERO).await
15585    }
15586    .await;
15587    if let Err(err) = &result {
15588        fail_snapshot(snapshot, Some(module_id), None, failure);
15589        error!(module_id, error = %err, "registration release failed after child exit; module is failed and start can retry");
15590    }
15591    result
15592}
15593
15594/// Wait for the ACTIVE registration of `module_id` to go away, which is what a
15595/// plain stop or restart waits for before it spawns a replacement.
15596async fn wait_for_registration_release(
15597    registry: &Registry,
15598    module_id: &str,
15599    wait: Duration,
15600) -> Result<(), SuperviseError> {
15601    wait_for_slot_registration_release(
15602        registry,
15603        crate::registry::RegistrationSlot::Active(module_id),
15604        wait,
15605    )
15606    .await
15607}
15608
15609/// Wait for the registration in `slot` to go away.
15610///
15611/// Keyed on the slot rather than the bare module id because a successful swap
15612/// never empties the id's active slot (the promoted candidate is in it), so an
15613/// id-keyed wait for the incumbent's release would always time out. Draining a
15614/// swap's incumbent waits on `crate::registry::RegistrationSlot::Connection` with the
15615/// incumbent's connection instead.
15616async fn wait_for_slot_registration_release(
15617    registry: &Registry,
15618    slot: crate::registry::RegistrationSlot<'_>,
15619    wait: Duration,
15620) -> Result<(), SuperviseError> {
15621    let deadline = Instant::now() + wait;
15622    let mut release_events = registration_release_events().subscribe();
15623    let still_active = |registration: &crate::registry::ModuleRegistration| {
15624        SuperviseError::RegistrationStillActive {
15625            module_id: registration.manifest.module_id.clone(),
15626            waited: wait,
15627        }
15628    };
15629    loop {
15630        let _observed_generation = *release_events.borrow_and_update();
15631        let Some(registration) = registry
15632            .registration(slot)
15633            .map_err(SuperviseError::Registry)?
15634        else {
15635            return Ok(());
15636        };
15637
15638        let now = Instant::now();
15639        if now >= deadline {
15640            return Err(still_active(&registration));
15641        }
15642
15643        let remaining = deadline.saturating_duration_since(now);
15644        match timeout(remaining, release_events.changed()).await {
15645            Ok(Ok(())) | Ok(Err(_)) => {}
15646            Err(_) => return Err(still_active(&registration)),
15647        }
15648    }
15649}
15650
15651#[cfg(test)]
15652mod slot_registration_wait_tests {
15653    use super::*;
15654    use crate::registry::{ConnectionId, RegistrationSlot};
15655    use subc_protocol::manifest::ModuleManifest;
15656
15657    #[tokio::test]
15658    async fn enable_release_failure_is_failed_and_a_second_enable_retries() {
15659        let registry = Arc::new(Registry::default());
15660        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default());
15661        let runtime = supervisor.runtime_config();
15662        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::disabled()));
15663        let spec = ModuleSpec {
15664            script: None,
15665            module_id: "enable-stale-registration".to_string(),
15666            program: PathBuf::from("/missing/enable-retry-test"),
15667            args: Vec::new(),
15668            env: Vec::new(),
15669            reserved: false,
15670            reserved_prefixes: Vec::new(),
15671            protocol: ModuleProtocol::Subc,
15672            overlap: Default::default(),
15673            carry_containment: false,
15674        };
15675        let connection = ConnectionId::new(90);
15676        registry
15677            .register_with_control_ops(
15678                ModuleManifest::builder(&spec.module_id, "0.1.0").build(),
15679                1,
15680                connection,
15681                Vec::new(),
15682            )
15683            .unwrap();
15684        let mut child = None;
15685        let err = set_child_enabled(
15686            &spec,
15687            &runtime,
15688            &registry,
15689            &supervisor.process_liveness,
15690            &snapshot,
15691            &mut child,
15692            true,
15693            &runtime.failure_context(false),
15694        )
15695        .await
15696        .unwrap_err();
15697        assert!(matches!(
15698            err,
15699            SuperviseError::RegistrationStillActive { .. }
15700        ));
15701        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
15702        assert!(child.is_none());
15703        registry.deregister_connection(connection).unwrap();
15704        let err = set_child_enabled(
15705            &spec,
15706            &runtime,
15707            &registry,
15708            &supervisor.process_liveness,
15709            &snapshot,
15710            &mut child,
15711            true,
15712            &runtime.failure_context(false),
15713        )
15714        .await
15715        .unwrap_err();
15716        assert!(
15717            matches!(err, SuperviseError::Spawn { .. }),
15718            "second enable must attempt a spawn: {err}"
15719        );
15720        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
15721    }
15722
15723    const INCUMBENT: u64 = 1;
15724    const CANDIDATE: u64 = 2;
15725
15726    fn swapped_registry() -> Arc<Registry> {
15727        let registry = Arc::new(Registry::default());
15728        let manifest = ModuleManifest::builder("m", "0.1.0").build();
15729        registry
15730            .register_with_control_ops(
15731                manifest.clone(),
15732                1,
15733                ConnectionId::new(INCUMBENT),
15734                Vec::new(),
15735            )
15736            .unwrap();
15737        registry
15738            .register_candidate_with_control_ops(
15739                manifest,
15740                1,
15741                ConnectionId::new(CANDIDATE),
15742                Vec::new(),
15743            )
15744            .unwrap();
15745        registry
15746    }
15747
15748    /// After a promotion the id's active slot is held by the new process, so an
15749    /// id-keyed wait for the incumbent's release can never succeed; the
15750    /// connection-keyed wait completes as soon as the incumbent deregisters.
15751    #[tokio::test]
15752    async fn incumbent_release_is_awaited_by_connection_not_by_module_id() {
15753        let registry = swapped_registry();
15754        registry.promote_candidate("m").unwrap().unwrap();
15755
15756        assert!(matches!(
15757            wait_for_registration_release(&registry, "m", Duration::from_millis(50)).await,
15758            Err(SuperviseError::RegistrationStillActive { .. })
15759        ));
15760
15761        // Still held while the incumbent's connection has not deregistered.
15762        assert!(matches!(
15763            wait_for_slot_registration_release(
15764                &registry,
15765                RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
15766                Duration::from_millis(50),
15767            )
15768            .await,
15769            Err(SuperviseError::RegistrationStillActive { .. })
15770        ));
15771
15772        let releaser = Arc::clone(&registry);
15773        let release = tokio::spawn(async move {
15774            sleep(Duration::from_millis(20)).await;
15775            releaser
15776                .deregister_connection(ConnectionId::new(INCUMBENT))
15777                .unwrap();
15778            notify_registration_release();
15779        });
15780        wait_for_slot_registration_release(
15781            &registry,
15782            RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
15783            Duration::from_secs(5),
15784        )
15785        .await
15786        .expect("the incumbent's own registration is released");
15787        release.await.unwrap();
15788        assert!(registry.get_module("m").unwrap().is_some());
15789    }
15790
15791    /// The candidate slot is waited on separately from the active slot: the
15792    /// incumbent's registration neither holds up nor stands in for it.
15793    #[tokio::test]
15794    async fn candidate_slot_wait_ignores_the_incumbents_registration() {
15795        let registry = swapped_registry();
15796        assert!(matches!(
15797            wait_for_slot_registration_release(
15798                &registry,
15799                RegistrationSlot::Candidate("m"),
15800                Duration::from_millis(50),
15801            )
15802            .await,
15803            Err(SuperviseError::RegistrationStillActive { .. })
15804        ));
15805        registry
15806            .deregister_connection(ConnectionId::new(CANDIDATE))
15807            .unwrap();
15808        wait_for_slot_registration_release(
15809            &registry,
15810            RegistrationSlot::Candidate("m"),
15811            Duration::from_millis(50),
15812        )
15813        .await
15814        .expect("a candidate slot with no candidate is released");
15815        assert!(registry
15816            .registration(RegistrationSlot::Active("m"))
15817            .unwrap()
15818            .is_some());
15819    }
15820}
15821
15822fn classify_exit(status: &ExitStatus) -> ExitReport {
15823    ExitReport {
15824        kind: if status.success() {
15825            ExitKind::Clean
15826        } else {
15827            ExitKind::Crash
15828        },
15829        code: status.code(),
15830        signal: exit_signal(status),
15831        at_ms: unix_ms_now(),
15832    }
15833}
15834
15835/// The terminal record for a module whose `wait()` call itself errored (e.g. the
15836/// child was already reaped out-of-band). There is no `ExitStatus` to read a code
15837/// or signal from -- `None`/`None` is the honest shape, not a guess -- but the
15838/// disposition still must be `Failed` so the terminal ring is not silently missing
15839/// an entry, matching what `fail_snapshot` records for this same arm.
15840fn wait_error_exit_report() -> ExitReport {
15841    ExitReport {
15842        kind: ExitKind::Crash,
15843        code: None,
15844        signal: None,
15845        at_ms: unix_ms_now(),
15846    }
15847}
15848
15849#[cfg(unix)]
15850fn exit_signal(status: &ExitStatus) -> Option<i32> {
15851    use std::os::unix::process::ExitStatusExt;
15852
15853    status.signal()
15854}
15855
15856#[cfg(not(unix))]
15857fn exit_signal(_status: &ExitStatus) -> Option<i32> {
15858    None
15859}
15860
15861/// Give an operator-touched module its full crash budget back.
15862///
15863/// Named for the counter it used to zero; it now empties the in-window ring,
15864/// which is the same act. `lifetime_restarts` is untouched on purpose -- the
15865/// ledger of what happened survives every operator action.
15866fn reset_restart_count(snapshot: &SharedSnapshot, module_id: &str) -> Result<(), SuperviseError> {
15867    update_snapshot(snapshot, Some(module_id), |state| {
15868        state.clear_crash_restarts();
15869    })
15870}
15871
15872fn set_running(
15873    snapshot: &SharedSnapshot,
15874    child: &SupervisedChild,
15875    module_id: &str,
15876    spawn_events: &SpawnEventFeed,
15877) -> Result<(), SuperviseError> {
15878    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
15879        module_id: Some(module_id.to_string()),
15880    })?;
15881    state.spawn_generation = spawn_events.emit_spawned(
15882        module_id,
15883        child
15884            .registration_spawn
15885            .as_ref()
15886            .map(|spawn| spawn.authority.spawn_number()),
15887        child.pid,
15888        child.spawned_at_ms,
15889    );
15890    if std::mem::take(&mut state.coalesced_restart_pending) {
15891        let generation = state.spawn_generation;
15892        info!(module_id, "restart already satisfied by generation {generation}; coalesced pending request completed");
15893    }
15894    state.drain_disposition_detail = None;
15895    state.spawn_failure = None;
15896    state.admission_refused = None;
15897    state.config_hold_parked = false;
15898    state.config_hold_daemon_initiated = false;
15899    state.config_hold_approval = None;
15900    state.legacy_registration_spawn =
15901        child.registration_spawn.is_some() && child.admission_base.is_none();
15902    state.registration_declaration = child.registration_declaration.clone();
15903    state.stop_reason = None;
15904    state.config_exit_failed_approval = None;
15905    state.waiting_for_previous_pid = None;
15906    state.waiting_for_previous_detail = None;
15907    // Every caller of this is a plain spawn, which always uses the primary key;
15908    // a promoted swap candidate sets the flag itself after this returns.
15909    state.in_alternate_slot = false;
15910    state.configuration_updated_since_spawn = false;
15911    state.spawned_protocol = Some(child.protocol);
15912    state.state = ModuleState::Running;
15913    state.approved_start_failure = None;
15914    state.enabled = true;
15915    state.process_alive = true;
15916    state.pid = child.id();
15917    state.subtree_target = child.subtree_target.clone();
15918    // Probe samples belong to one process. Keep module-level escalation and
15919    // late-answer history, but never charge a new child for its predecessor's misses.
15920    state.health.status = SupervisorHealthStatus::Unknown;
15921    state.last_probe_evidence = None;
15922    state.health.consecutive_failures = 0;
15923    state.health.detail = None;
15924    state.health.metrics = None;
15925    state.health.last_probe_ms = None;
15926    state.failed_retry.healthy_since = None;
15927    state.failed_retry.failed_at = None;
15928    state.failed_retry.running_since = Some(child.spawned_at);
15929    #[cfg(windows)]
15930    {
15931        state.pipe_consumed = child
15932            .nonce_delivery
15933            .as_ref()
15934            .map(|delivery| delivery.consumed());
15935    }
15936    #[cfg(target_os = "macos")]
15937    {
15938        state.report_ready = Some(Arc::clone(&child.report_ready));
15939    }
15940    state.spawned_at_ms = Some(child.spawned_at_ms);
15941    state.exec_outcome = Some(Arc::clone(&child.exec.0));
15942    state.spawned_from = Some(child.spawned_from.clone());
15943    state.launch_spec_digest = Some(child.launch_spec_digest.clone());
15944    state.spawned_file_identity = child.spawned_file_identity.clone();
15945    state.process_start_time = child.process_start_time;
15946    Ok(())
15947}
15948
15949fn clear_current_process_facts(state: &mut SupervisorSnapshot) {
15950    state.legacy_registration_spawn = false;
15951    state.registration_declaration = None;
15952    state.subtree_target = crate::subtree_resources::Target::Unavailable("not_running");
15953    state.failed_retry.healthy_since = None;
15954    state.failed_retry.running_since = None;
15955    state.waiting_for_previous_pid = None;
15956    state.waiting_for_previous_detail = None;
15957    state.process_alive = false;
15958    state.spawned_protocol = None;
15959    state.pid = None;
15960    #[cfg(windows)]
15961    {
15962        state.pipe_consumed = None;
15963    }
15964    #[cfg(target_os = "macos")]
15965    {
15966        state.report_ready = None;
15967    }
15968    state.spawned_at_ms = None;
15969    state.exec_outcome = None;
15970    state.spawned_from = None;
15971    state.launch_spec_digest = None;
15972    state.spawned_file_identity = None;
15973    state.process_start_time = None;
15974    state.deliberate_severance = None;
15975}
15976
15977#[cfg(test)]
15978fn record_deliberate_severance(
15979    snapshot: &SharedSnapshot,
15980    identity: ProcessIdentity,
15981) -> Result<(), SuperviseError> {
15982    update_snapshot(snapshot, None, |state| {
15983        state.deliberate_severance = Some(identity);
15984    })
15985}
15986
15987fn apply_deliberate_severance_marker(
15988    snapshot: &SharedSnapshot,
15989    exited_identity: Option<ProcessIdentity>,
15990    mut exit_report: ExitReport,
15991) -> ExitReport {
15992    let marker = lock_snapshot(snapshot)
15993        .ok()
15994        .and_then(|mut state| state.deliberate_severance.take());
15995    if marker.is_some() && marker == exited_identity {
15996        exit_report.kind = ExitKind::DeliberateSeverance;
15997    }
15998    exit_report
15999}
16000
16001fn classify_reaped_child_exit(
16002    snapshot: &SharedSnapshot,
16003    child: &SupervisedChild,
16004    status: &ExitStatus,
16005) -> ExitReport {
16006    let _ = update_snapshot(snapshot, None, |state| {
16007        state.reaped_pid = Some(child.pid);
16008        state.spawn_failure = child.spawn_failure.clone();
16009    });
16010    if matches!(
16011        child.spawn_failure.as_deref(),
16012        Some("registration_timeout" | "registration_channel_closed")
16013    ) {
16014        registration_failure_exit_report(classify_exit(status))
16015    } else {
16016        apply_deliberate_severance_marker(snapshot, child.process_identity(), classify_exit(status))
16017    }
16018}
16019
16020fn fail_snapshot(
16021    snapshot: &SharedSnapshot,
16022    module_id: Option<&str>,
16023    last_exit: Option<ExitReport>,
16024    failure: &FailureContext,
16025) {
16026    if let Err(err) = update_snapshot(snapshot, module_id, |state| {
16027        state.state = ModuleState::Failed;
16028        state.config_hold_parked = false;
16029        state.config_hold_daemon_initiated = false;
16030        state.config_hold_approval = None;
16031        clear_current_process_facts(state);
16032        if failure.may_retry() && state.enabled {
16033            state.failed_retry.schedule(module_id.unwrap_or("unknown"));
16034        } else if failure.shutdown.is_set() {
16035            state.failed_retry.cancel();
16036        }
16037        if let Some(last_exit) = last_exit {
16038            state.last_exit = Some(last_exit);
16039        }
16040    }) {
16041        error!(error = %err, "failed to mark supervisor state failed");
16042    }
16043}
16044
16045fn update_snapshot(
16046    snapshot: &SharedSnapshot,
16047    module_id: Option<&str>,
16048    update: impl FnOnce(&mut SupervisorSnapshot),
16049) -> Result<(), SuperviseError> {
16050    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
16051        module_id: module_id.map(ToOwned::to_owned),
16052    })?;
16053    update(&mut state);
16054    Ok(())
16055}
16056
16057const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
16058
16059fn lock_snapshot_for_control<'a>(
16060    snapshot: &'a SharedSnapshot,
16061    module_id: &str,
16062    caller: &'static str,
16063) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
16064    let started_at = Instant::now();
16065    let guard = lock_snapshot(snapshot)?;
16066    let waited = started_at.elapsed();
16067    if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
16068        warn!(
16069            module_id = %module_id,
16070            waited_ms = waited.as_millis() as u64,
16071            caller = %caller,
16072            "slow snapshot lock"
16073        );
16074    }
16075    Ok(guard)
16076}
16077
16078fn lock_snapshot(
16079    snapshot: &SharedSnapshot,
16080) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
16081    snapshot
16082        .lock()
16083        .map_err(|_| SuperviseError::StatePoisoned { module_id: None })
16084}
16085
16086#[cfg(test)]
16087mod terminal_history_tests {
16088    include!("supervise_route_open_recovery_tests.rs");
16089    use std::{
16090        path::PathBuf,
16091        sync::Arc,
16092        time::{Duration, Instant},
16093    };
16094
16095    use tokio::{sync::mpsc, time::sleep};
16096
16097    use super::{
16098        apply_deliberate_severance_marker, daemon_will_restart, drain_child_to_state,
16099        drained_after_quiescence_wait, handle_reload_spawn_failure, health_restart_child,
16100        lock_snapshot, on_child_exit, record_deliberate_severance, record_wait_error_terminal,
16101        reset_restart_count, spawn_and_mark_running, update_snapshot, wait_error_exit_report,
16102        ExitKind, ExitReport, ModuleProtocol, ModuleSpec, ModuleState, NextAction, ProcessIdentity,
16103        RestartPolicy, SpawnEventKind, StopNotice, SuperviseError, SupervisedConfiguration,
16104        SupervisedModule, SupervisedModuleInner, Supervisor, SupervisorHandle,
16105        SupervisorHealthStatus, SupervisorSnapshot,
16106    };
16107    // The supervisor's clock, distinct from the `std::time::Instant` these tests
16108    // use for their own wall-clock deadlines: crash-restart instants must be on
16109    // the same clock the production code stamps them with, which is tokio's (and
16110    // is what `start_paused` tests can move).
16111    use super::Instant as ClockInstant;
16112    use crate::{
16113        registry::Registry,
16114        terminal_ring::{TerminalRing, TerminalRingConfig},
16115    };
16116    use std::sync::Mutex;
16117    use subc_control::TerminalDisposition;
16118
16119    /// See the twin in `control.rs` for why this derives the path from
16120    /// `current_exe()` and why the existence check is here: `--lib` alone does
16121    /// not build `[[bin]]` targets, and a bare spawn then fails with a raw
16122    /// `NotFound` that reads as a broken test rather than an unbuilt dependency.
16123    pub(super) fn fake_aft_stub_path() -> PathBuf {
16124        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
16125        assert!(
16126            path.exists(),
16127            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
16128             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
16129            path.display()
16130        );
16131        path
16132    }
16133
16134    #[test]
16135    fn reserved_never_spawned_refuses_every_hello() {
16136        // The canary hole: a reserved id whose module has never spawned had NO
16137        // gate entry and admitted anyone -- the reservation protected the nonce
16138        // holder, not the NAME. Now the entry is present with no legitimate
16139        // holder and refuses all comers.
16140        let supervisor = SupervisorHandle::default();
16141        supervisor.apply_identity_configuration(&ModuleSpec {
16142            script: None,
16143            module_id: "never-spawned".to_string(),
16144            program: PathBuf::from("/usr/bin/false"),
16145            args: Vec::new(),
16146            env: Vec::new(),
16147            reserved: true,
16148            reserved_prefixes: Vec::new(),
16149            protocol: ModuleProtocol::Subc,
16150            overlap: Default::default(),
16151            carry_containment: false,
16152        });
16153        assert!(
16154            supervisor
16155                .reserved_hello_verification("never-spawned", Some("any-forged-nonce"))
16156                .is_err(),
16157            "forged nonce must refuse on a reserved never-spawned id"
16158        );
16159        assert!(
16160            supervisor
16161                .reserved_hello_verification("never-spawned", None)
16162                .is_err(),
16163            "absent nonce must refuse on a reserved never-spawned id"
16164        );
16165        // And a real spawn nonce minted later admits exactly that nonce.
16166        supervisor.set_spawn_nonce("never-spawned", "minted".to_string());
16167        supervisor.apply_identity_configuration(&ModuleSpec {
16168            script: None,
16169            module_id: "never-spawned".to_string(),
16170            program: PathBuf::from("/usr/bin/false"),
16171            args: Vec::new(),
16172            env: Vec::new(),
16173            reserved: true,
16174            reserved_prefixes: Vec::new(),
16175            protocol: ModuleProtocol::Subc,
16176            overlap: Default::default(),
16177            carry_containment: false,
16178        });
16179        assert!(supervisor
16180            .reserved_hello_verification("never-spawned", Some("minted"))
16181            .is_ok());
16182        assert!(supervisor
16183            .reserved_hello_verification("never-spawned", Some("forged"))
16184            .is_err());
16185    }
16186
16187    /// Put `count` crash restarts on a snapshot's ring as if they had all just
16188    /// happened, which is what "spent budget" looks like to every reader.
16189    fn seed_crash_restarts(state: &mut SupervisorSnapshot, count: u32) {
16190        let now = ClockInstant::now();
16191        for _ in 0..count {
16192            state.crash_restarts.push_back(now);
16193        }
16194    }
16195
16196    /// Age the oldest recorded restart out of `window`, standing in for the hours
16197    /// that would otherwise have to pass. Injecting the instant is the point: a
16198    /// test that slept a real window would take ten minutes and still prove less.
16199    fn age_oldest_crash_restart_out_of_window(state: &mut SupervisorSnapshot, window: Duration) {
16200        let aged = state
16201            .crash_restarts
16202            .front()
16203            .expect("a crash restart must be recorded before it can be aged")
16204            .checked_sub(window + Duration::from_secs(1))
16205            .expect("the test clock is far enough from its origin to age an instant");
16206        state.crash_restarts[0] = aged;
16207    }
16208
16209    fn snapshot_with_restarts(enabled: bool, count: u32) -> SupervisorSnapshot {
16210        let mut state = SupervisorSnapshot::new(ModuleState::Running, enabled);
16211        seed_crash_restarts(&mut state, count);
16212        state
16213    }
16214
16215    #[test]
16216    fn daemon_owned_recovery_predicate_uses_the_pre_increment_budget() {
16217        let policy = RestartPolicy::new(3, Duration::ZERO);
16218        let now = ClockInstant::now();
16219        assert!(daemon_will_restart(
16220            &mut snapshot_with_restarts(true, 2),
16221            &policy,
16222            now
16223        ));
16224        assert!(!daemon_will_restart(
16225            &mut snapshot_with_restarts(true, 3),
16226            &policy,
16227            now
16228        ));
16229        assert!(!daemon_will_restart(
16230            &mut snapshot_with_restarts(false, 0),
16231            &policy,
16232            now
16233        ));
16234    }
16235
16236    #[test]
16237    fn crash_restart_backoff_escalates_with_in_window_count() {
16238        let policy = RestartPolicy::new(4, Duration::from_millis(100))
16239            .with_max_backoff(Duration::from_secs(30));
16240        let now = ClockInstant::now();
16241        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16242        let schedules = (0..4)
16243            .map(|_| {
16244                state
16245                    .next_crash_restart(&policy, now)
16246                    .expect("the test policy allows four crash restarts")
16247            })
16248            .collect::<Vec<_>>();
16249
16250        assert_eq!(
16251            schedules
16252                .iter()
16253                .map(|schedule| schedule.restart_in_window)
16254                .collect::<Vec<_>>(),
16255            vec![0, 1, 2, 3]
16256        );
16257        assert_eq!(
16258            schedules
16259                .iter()
16260                .map(|schedule| schedule.delay)
16261                .collect::<Vec<_>>(),
16262            vec![
16263                Duration::from_millis(100),
16264                Duration::from_secs(1),
16265                Duration::from_secs(10),
16266                Duration::from_secs(30),
16267            ]
16268        );
16269    }
16270
16271    #[test]
16272    fn crash_restart_backoff_resets_after_ring_clear() {
16273        let policy = RestartPolicy::new(3, Duration::from_millis(100));
16274        let now = ClockInstant::now();
16275        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16276        assert_eq!(
16277            state.next_crash_restart(&policy, now).unwrap().delay,
16278            Duration::from_millis(100)
16279        );
16280        assert_eq!(
16281            state.next_crash_restart(&policy, now).unwrap().delay,
16282            Duration::from_secs(1)
16283        );
16284
16285        state.clear_crash_restarts();
16286        let schedule = state
16287            .next_crash_restart(&policy, now)
16288            .expect("a cleared ring must allow another restart");
16289        assert_eq!(schedule.restart_in_window, 0);
16290        assert_eq!(schedule.delay, Duration::from_millis(100));
16291    }
16292
16293    #[test]
16294    fn crash_restart_backoff_ignores_aged_restarts() {
16295        let policy = RestartPolicy::new(3, Duration::from_millis(100));
16296        let now = ClockInstant::now();
16297        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16298        state
16299            .next_crash_restart(&policy, now)
16300            .expect("the first restart is allowed");
16301        state
16302            .next_crash_restart(&policy, now)
16303            .expect("the second restart is allowed");
16304        state.crash_restarts[0] = now
16305            .checked_sub(policy.window + Duration::from_secs(1))
16306            .expect("the fake clock can age a restart past the window");
16307
16308        let schedule = state
16309            .next_crash_restart(&policy, now)
16310            .expect("an aged restart must release its slot");
16311        assert_eq!(schedule.restart_in_window, 1);
16312        assert_eq!(schedule.delay, Duration::from_secs(1));
16313        assert_eq!(state.crash_restarts.len(), 2);
16314    }
16315
16316    /// The budget is a rate: the same three spent restarts refuse a respawn
16317    /// while they are recent and allow one once they have aged past the window.
16318    /// Nothing about the module changed in between, which is the whole point.
16319    #[test]
16320    fn a_budget_spent_before_the_window_no_longer_refuses() {
16321        let policy = RestartPolicy::new(3, Duration::ZERO);
16322        let mut state = snapshot_with_restarts(true, 3);
16323        let now = ClockInstant::now();
16324        assert!(!daemon_will_restart(&mut state, &policy, now));
16325
16326        assert!(daemon_will_restart(
16327            &mut state,
16328            &policy,
16329            now + policy.window + Duration::from_secs(1)
16330        ));
16331        assert!(
16332            state.crash_restarts.is_empty(),
16333            "reading the budget must drop the instants that left the window"
16334        );
16335    }
16336
16337    fn module_with_recovery_snapshot(
16338        state: ModuleState,
16339        enabled: bool,
16340        restart_count: u32,
16341    ) -> SupervisedModule {
16342        let registry = Arc::new(Registry::default());
16343        let supervisor =
16344            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(3, Duration::ZERO));
16345        let runtime = supervisor.runtime_config();
16346        let spec = ModuleSpec {
16347            script: None,
16348            module_id: "recovery-snapshot".to_string(),
16349            program: fake_aft_stub_path(),
16350            args: Vec::new(),
16351            env: Vec::new(),
16352            reserved: false,
16353            reserved_prefixes: Vec::new(),
16354            protocol: ModuleProtocol::Subc,
16355            overlap: Default::default(),
16356            carry_containment: false,
16357        };
16358        let mut snapshot = SupervisorSnapshot::new(state, enabled);
16359        seed_crash_restarts(&mut snapshot, restart_count);
16360        // These tests read synthetic snapshots. A real child and monitor would
16361        // race those reads by replacing the requested state during startup.
16362        let (commands, _rx) = mpsc::channel(4);
16363        let configured_enabled = snapshot.enabled;
16364        SupervisedModule {
16365            inner: Arc::new(SupervisedModuleInner {
16366                module_id: spec.module_id.clone(),
16367                registry,
16368                snapshot: Arc::new(Mutex::new(snapshot)),
16369                configuration: Arc::new(Mutex::new(SupervisedConfiguration {
16370                    spec,
16371                    enabled: configured_enabled,
16372                    health: runtime.health,
16373                    register_timeout: runtime.register_timeout,
16374                    restart_policy: runtime.restart_policy,
16375                })),
16376                stderr_ring: runtime.stderr_ring,
16377                terminal_ring: runtime.terminal_ring,
16378                commands,
16379                monitor: Mutex::new(None),
16380                effective_drain_timeout: runtime.effective_drain_timeout,
16381                provenance_probe: supervisor.provenance_probe.clone(),
16382                retained: runtime.child_roster.retained_view(),
16383            }),
16384        }
16385    }
16386
16387    #[cfg(target_os = "linux")]
16388    #[tokio::test]
16389    async fn no_cgroup_placement_does_not_block_fake_aft_stub_spawn() {
16390        let supervisor =
16391            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
16392                .with_cgroup_placement(None);
16393        let result = supervisor.spawn(ModuleSpec {
16394            script: None,
16395            module_id: "no-cgroup-placement".to_string(),
16396            program: fake_aft_stub_path(),
16397            args: Vec::new(),
16398            env: Vec::new(),
16399            reserved: false,
16400            reserved_prefixes: Vec::new(),
16401            protocol: ModuleProtocol::Subc,
16402            overlap: Default::default(),
16403            carry_containment: false,
16404        });
16405
16406        assert!(
16407            result.is_ok(),
16408            "no delegation must not turn an otherwise valid spawn into a failure: {result:?}"
16409        );
16410    }
16411
16412    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16413    async fn undecided_snapshot_uses_shared_restart_predicate() {
16414        assert!(module_with_recovery_snapshot(ModuleState::Running, true, 2)
16415            .will_recover_after_connection_loss()
16416            .unwrap());
16417        assert!(
16418            !module_with_recovery_snapshot(ModuleState::Running, true, 3)
16419                .will_recover_after_connection_loss()
16420                .unwrap()
16421        );
16422    }
16423
16424    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16425    async fn restarting_snapshot_at_exhausted_budget_is_non_terminal() {
16426        assert!(
16427            module_with_recovery_snapshot(ModuleState::Restarting, true, 3)
16428                .will_recover_after_connection_loss()
16429                .unwrap()
16430        );
16431    }
16432
16433    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16434    async fn terminal_phase_snapshots_are_terminal_before_budget_exhaustion() {
16435        assert!(!module_with_recovery_snapshot(ModuleState::Failed, true, 0)
16436            .will_recover_after_connection_loss()
16437            .unwrap());
16438        assert!(
16439            !module_with_recovery_snapshot(ModuleState::Disabled, true, 0)
16440                .will_recover_after_connection_loss()
16441                .unwrap()
16442        );
16443    }
16444
16445    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16446    async fn warming_snapshot_is_limited_to_startup_phases() {
16447        for state in [
16448            ModuleState::Starting,
16449            ModuleState::Running,
16450            ModuleState::Restarting,
16451        ] {
16452            assert!(
16453                module_with_recovery_snapshot(state, true, 0)
16454                    .is_warming()
16455                    .unwrap(),
16456                "{state:?} should be warming"
16457            );
16458        }
16459        for state in [
16460            ModuleState::Unresponsive,
16461            ModuleState::Draining,
16462            ModuleState::Stopped,
16463            ModuleState::Failed,
16464            ModuleState::Disabled,
16465        ] {
16466            assert!(
16467                !module_with_recovery_snapshot(state, true, 0)
16468                    .is_warming()
16469                    .unwrap(),
16470                "{state:?} should not be warming"
16471            );
16472        }
16473    }
16474
16475    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16476    async fn terminal_history_survives_respawn_and_keeps_both_crashes_in_order() {
16477        let registry = Arc::new(Registry::default());
16478        let supervisor =
16479            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO));
16480        let module = supervisor
16481            .spawn(ModuleSpec {
16482                script: None,
16483                module_id: "terminal-history".to_string(),
16484                program: fake_aft_stub_path(),
16485                args: Vec::new(),
16486                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
16487                reserved: false,
16488                reserved_prefixes: Vec::new(),
16489                protocol: ModuleProtocol::Subc,
16490                overlap: Default::default(),
16491                carry_containment: false,
16492            })
16493            .unwrap();
16494
16495        let deadline = Instant::now() + Duration::from_secs(5);
16496        loop {
16497            let history = module.terminal_history();
16498            if history.entries.len() == 2 {
16499                assert_eq!(module.status().unwrap().state, ModuleState::Failed);
16500                assert_eq!(history.dropped, 0);
16501                assert_eq!(
16502                    history
16503                        .entries
16504                        .iter()
16505                        .map(|entry| entry.exit_code)
16506                        .collect::<Vec<_>>(),
16507                    vec![Some(23), Some(23)]
16508                );
16509                assert!(history.entries[0].at_ms <= history.entries[1].at_ms);
16510                return;
16511            }
16512            assert!(
16513                Instant::now() < deadline,
16514                "module did not retain two terminal exits: {history:?}"
16515            );
16516            sleep(Duration::from_millis(10)).await;
16517        }
16518    }
16519
16520    /// A disable issued while a crash respawn is still backing off must preempt
16521    /// that respawn: the operator's stop wins, the disable must not queue behind
16522    /// the backoff, and the module must never come back up afterwards.
16523    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16524    async fn disable_during_crash_backoff_cancels_pending_respawn() {
16525        let backoff = Duration::from_secs(2);
16526        let supervisor = Supervisor::new_for_test(
16527            Arc::new(Registry::default()),
16528            RestartPolicy::new(10, backoff),
16529        );
16530        let module = supervisor
16531            .spawn(ModuleSpec {
16532                script: None,
16533                module_id: "disable-during-backoff".to_string(),
16534                program: fake_aft_stub_path(),
16535                args: Vec::new(),
16536                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
16537                reserved: false,
16538                reserved_prefixes: Vec::new(),
16539                protocol: ModuleProtocol::Subc,
16540                overlap: Default::default(),
16541                carry_containment: false,
16542            })
16543            .unwrap();
16544
16545        // Wait for the first crash to put the module into its backoff window.
16546        let deadline = Instant::now() + Duration::from_secs(5);
16547        loop {
16548            if module.status().unwrap().state == ModuleState::Restarting {
16549                break;
16550            }
16551            assert!(
16552                Instant::now() < deadline,
16553                "module never entered the crash backoff"
16554            );
16555            sleep(Duration::from_millis(10)).await;
16556        }
16557
16558        let started = Instant::now();
16559        module.set_enabled(false).await.unwrap();
16560        let waited = started.elapsed();
16561
16562        assert!(
16563            waited < backoff / 2,
16564            "disable waited {waited:?} behind the {backoff:?} crash backoff; the operator command must preempt the pending respawn"
16565        );
16566        assert_eq!(module.status().unwrap().state, ModuleState::Disabled);
16567
16568        // Outlast the backoff: the respawn it was counting down to must never run.
16569        sleep(backoff + Duration::from_millis(500)).await;
16570        let status = module.status().unwrap();
16571        assert_eq!(status.state, ModuleState::Disabled);
16572        assert_eq!(
16573            status.spawn_generation, 1,
16574            "module respawned after the operator disabled it"
16575        );
16576    }
16577
16578    /// A `protocol: "none"` child that stays parked and exits 0 on SIGTERM:
16579    /// the shape of nats-server, the program this rule exists for.
16580    #[cfg(unix)]
16581    fn protocol_none_sigterm_exits_clean_spec(
16582        module_id: &str,
16583        dir: &std::path::Path,
16584    ) -> (ModuleSpec, PathBuf, PathBuf) {
16585        let ready = dir.join("ready");
16586        let marker = dir.join("sigterm");
16587        let spec = ModuleSpec {
16588            script: None,
16589            module_id: module_id.to_string(),
16590            program: fake_aft_stub_path(),
16591            args: Vec::new(),
16592            env: vec![
16593                ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
16594                (
16595                    "FAKE_AFT_SIGTERM_MARKER_PATH".to_string(),
16596                    marker.display().to_string(),
16597                ),
16598                (
16599                    "FAKE_AFT_NEVER_CONNECT_READY_PATH".to_string(),
16600                    ready.display().to_string(),
16601                ),
16602            ],
16603            reserved: false,
16604            reserved_prefixes: Vec::new(),
16605            protocol: ModuleProtocol::None,
16606            overlap: Default::default(),
16607            carry_containment: false,
16608        };
16609        (spec, ready, marker)
16610    }
16611
16612    /// Wait for a file the child writes, so a signal is never sent before the
16613    /// child's SIGTERM handler is installed (the default disposition would
16614    /// kill it by signal and the exit would not be clean).
16615    #[cfg(unix)]
16616    async fn wait_for_file(path: &std::path::Path) {
16617        let deadline = Instant::now() + Duration::from_secs(10);
16618        while !path.exists() {
16619            assert!(
16620                Instant::now() < deadline,
16621                "{} never appeared",
16622                path.display()
16623            );
16624            sleep(Duration::from_millis(10)).await;
16625        }
16626    }
16627
16628    /// A protocol-none module that exits 0 because something OUTSIDE the
16629    /// supervisor sent it SIGTERM is respawned, and the terminal record carries
16630    /// the crash-path disposition rather than `stopped`.
16631    #[cfg(unix)]
16632    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16633    async fn protocol_none_unrequested_clean_exit_restarts_as_a_crash() {
16634        let dir = cortexkit_test_support::ScratchDir::new("none-unrequested-clean-exit");
16635        let (spec, ready, marker) =
16636            protocol_none_sigterm_exits_clean_spec("none-unrequested-clean-exit", dir.path());
16637        let supervisor = Supervisor::new_for_test(
16638            Arc::new(Registry::default()),
16639            RestartPolicy::new(3, Duration::ZERO),
16640        );
16641        let module = supervisor.spawn(spec).unwrap();
16642        wait_for_file(&ready).await;
16643        // The ready file proves the child installed its SIGTERM handler, not
16644        // that the supervisor has processed the privacy trampoline's exec
16645        // acknowledgement. On macOS status withholds the pid until then.
16646        let deadline = Instant::now() + Duration::from_secs(10);
16647        let first_pid = loop {
16648            let status = module.status().unwrap();
16649            if status.state == ModuleState::Running {
16650                if let Some(pid) = status.pid {
16651                    break pid;
16652                }
16653            }
16654            assert!(
16655                Instant::now() < deadline,
16656                "a running module must report its pid after exec confirmation: {status:?}"
16657            );
16658            sleep(Duration::from_millis(10)).await;
16659        };
16660
16661        rustix::process::kill_process(
16662            rustix::process::Pid::from_raw(i32::try_from(first_pid).unwrap()).unwrap(),
16663            rustix::process::Signal::TERM,
16664        )
16665        .unwrap();
16666
16667        let deadline = Instant::now() + Duration::from_secs(10);
16668        let respawned = loop {
16669            let status = module.status().unwrap();
16670            if status.state == ModuleState::Running
16671                && status.pid.is_some_and(|pid| pid != first_pid)
16672            {
16673                break status;
16674            }
16675            assert!(
16676                Instant::now() < deadline,
16677                "protocol-none module was not respawned after an unrequested clean exit: {status:?}"
16678            );
16679            sleep(Duration::from_millis(10)).await;
16680        };
16681        assert_eq!(respawned.spawn_generation, 2);
16682        assert!(
16683            marker.exists(),
16684            "the child must have exited through its SIGTERM handler (exit 0), or this proves nothing about clean exits"
16685        );
16686
16687        let history = module.terminal_history();
16688        assert_eq!(history.entries.len(), 1, "{history:?}");
16689        let entry = &history.entries[0];
16690        assert_eq!(entry.exit_code, Some(0));
16691        assert_eq!(entry.exit_kind, subc_control::TerminalExitKind::Clean);
16692        assert_eq!(entry.disposition, TerminalDisposition::Restarting);
16693
16694        module.stop().await.unwrap();
16695    }
16696
16697    /// Repeated unrequested clean exits of a protocol-none module spend the
16698    /// restart budget exactly as crashes do, and the module ends `failed` with
16699    /// the budget named.
16700    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16701    async fn protocol_none_repeated_clean_exits_exhaust_the_restart_budget() {
16702        let supervisor = Supervisor::new_for_test(
16703            Arc::new(Registry::default()),
16704            RestartPolicy::new(1, Duration::ZERO),
16705        );
16706        let module = supervisor
16707            .spawn(ModuleSpec {
16708                script: None,
16709                module_id: "none-clean-exit-budget".to_string(),
16710                program: fake_aft_stub_path(),
16711                args: Vec::new(),
16712                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "0".to_string())],
16713                reserved: false,
16714                reserved_prefixes: Vec::new(),
16715                protocol: ModuleProtocol::None,
16716                overlap: Default::default(),
16717                carry_containment: false,
16718            })
16719            .unwrap();
16720
16721        // Failed follows the terminal write; this deadline only bounds a hang,
16722        // not an assumed duration for the two launches or their exit recording.
16723        let deadline = Instant::now() + Duration::from_secs(10);
16724        loop {
16725            let status = module.status().unwrap();
16726            if status.state == ModuleState::Failed {
16727                break;
16728            }
16729            assert!(
16730                Instant::now() < deadline,
16731                "module never exhausted its budget: {status:?} {:?}",
16732                module.terminal_history()
16733            );
16734            sleep(Duration::from_millis(10)).await;
16735        }
16736        let history = module.terminal_history();
16737        assert_eq!(
16738            history
16739                .entries
16740                .iter()
16741                .map(|entry| (entry.exit_code, entry.disposition.clone()))
16742                .collect::<Vec<_>>(),
16743            vec![
16744                (Some(0), TerminalDisposition::Restarting),
16745                (Some(0), TerminalDisposition::Failed),
16746            ]
16747        );
16748        let detail = history.entries[1]
16749            .disposition_detail
16750            .as_deref()
16751            .expect("a budget failure names the budget");
16752        assert!(detail.contains("max_restarts=1"), "{detail}");
16753        assert_eq!(module.status().unwrap().spawn_generation, 2);
16754    }
16755
16756    #[test]
16757    fn restart_budget_failure_is_published_after_its_terminal_record() {
16758        use std::io::{Read, Write};
16759        let supervisor = Supervisor::new_for_test(
16760            Arc::new(Registry::default()),
16761            RestartPolicy::new(0, Duration::ZERO),
16762        );
16763        let runtime = supervisor.runtime_config();
16764        let spec = ModuleSpec {
16765            script: None,
16766            protocol: ModuleProtocol::None,
16767            ..windowed_crash_spec("budget-publication-order")
16768        };
16769        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
16770            ModuleState::Running,
16771            true,
16772        )));
16773        lock_snapshot(&snapshot).unwrap().process_alive = true;
16774        let reaped_snapshot = snapshot.clone();
16775        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16776        let history = runtime.terminal_ring.clone();
16777        let reap = std::thread::spawn(move || {
16778            tokio::runtime::Builder::new_current_thread()
16779                .enable_all()
16780                .build()
16781                .unwrap()
16782                .block_on(on_child_exit(
16783                    &spec,
16784                    runtime.restart_policy,
16785                    &supervisor.registry,
16786                    &reaped_snapshot,
16787                    &runtime.terminal_ring,
16788                    &runtime.spawn_events,
16789                    &runtime.child_roster,
16790                    ExitReport {
16791                        kind: ExitKind::Clean,
16792                        code: Some(0),
16793                        signal: None,
16794                        at_ms: 1,
16795                    },
16796                    true,
16797                ))
16798        });
16799        let mut reached = [0];
16800        barrier.read_exact(&mut reached).unwrap();
16801        assert_eq!(&reached, b"R");
16802        let (before_state, before_alive) = {
16803            let state = lock_snapshot(&snapshot).unwrap();
16804            (state.state, state.process_alive)
16805        };
16806        let before_history = history.lock().unwrap().snapshot();
16807        barrier.write_all(b"X").unwrap();
16808        assert!(matches!(reap.join().unwrap(), NextAction::Stop { .. }));
16809        assert!(before_history.entries.is_empty());
16810        assert_ne!(
16811            before_state,
16812            ModuleState::Failed,
16813            "Failed was visible before its terminal record could be written"
16814        );
16815        assert!(before_alive);
16816        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
16817        let history = history.lock().unwrap().snapshot();
16818        assert_eq!(history.entries.len(), 1);
16819        assert_eq!(history.entries[0].exit_code, Some(0));
16820        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16821    }
16822
16823    #[test]
16824    fn crash_restart_at_budget_limit_remains_recoverable_while_recording() {
16825        use std::io::{Read, Write};
16826
16827        let supervisor = Supervisor::new_for_test(
16828            Arc::new(Registry::default()),
16829            RestartPolicy::new(3, Duration::ZERO),
16830        );
16831        let mut runtime = supervisor.runtime_config();
16832        let module = module_with_recovery_snapshot(ModuleState::Running, true, 2);
16833        let snapshot = module.inner.snapshot.clone();
16834        lock_snapshot(&snapshot).unwrap().process_alive = true;
16835        runtime.terminal_ring = module.inner.terminal_ring.clone();
16836        let spec = windowed_crash_spec(module.module_id());
16837        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16838        let reaped_snapshot = snapshot.clone();
16839        let reap = std::thread::spawn(move || {
16840            tokio::runtime::Builder::new_current_thread()
16841                .enable_all()
16842                .build()
16843                .unwrap()
16844                .block_on(on_child_exit(
16845                    &spec,
16846                    runtime.restart_policy,
16847                    &supervisor.registry,
16848                    &reaped_snapshot,
16849                    &runtime.terminal_ring,
16850                    &runtime.spawn_events,
16851                    &runtime.child_roster,
16852                    ExitReport {
16853                        kind: ExitKind::Crash,
16854                        code: Some(2),
16855                        signal: None,
16856                        at_ms: 1,
16857                    },
16858                    true,
16859                ))
16860        });
16861
16862        // Hold the crash handler between its budget decision and publication.
16863        // Connection cleanup must still see the recovery that this crash chose,
16864        // even when that recovery consumes the last available restart slot.
16865        let mut reached = [0];
16866        barrier.read_exact(&mut reached).unwrap();
16867        assert_eq!(&reached, b"R");
16868        let before_status = module.status().unwrap();
16869        let before_history = module.terminal_history();
16870        let before_recovers = module.will_recover_after_connection_loss().unwrap();
16871        barrier.write_all(b"X").unwrap();
16872        assert!(matches!(reap.join().unwrap(), NextAction::Restart { .. }));
16873
16874        assert_eq!(before_status.state, ModuleState::Running);
16875        assert!(before_status.process_alive);
16876        assert_eq!(before_status.restart_count, 3);
16877        assert!(before_history.entries.is_empty());
16878        assert!(
16879            before_recovers,
16880            "connection cleanup would report a terminal close for a scheduled crash restart"
16881        );
16882        let restarting = module.status().unwrap();
16883        assert_eq!(restarting.state, ModuleState::Restarting);
16884        assert_eq!(restarting.restart_count, 3);
16885        assert!(module.will_recover_after_connection_loss().unwrap());
16886        let history = module.terminal_history();
16887        assert_eq!(history.entries.len(), 1);
16888        assert_eq!(
16889            history.entries[0].disposition,
16890            TerminalDisposition::Restarting
16891        );
16892
16893        // Once the replacement is running, its next crash must be judged
16894        // against the exhausted budget rather than the previous recovery.
16895        update_snapshot(&snapshot, Some(module.module_id()), |state| {
16896            state.state = ModuleState::Running;
16897            state.respawn_pending = false;
16898        })
16899        .unwrap();
16900        assert!(!module.will_recover_after_connection_loss().unwrap());
16901        update_snapshot(&snapshot, Some(module.module_id()), |state| {
16902            state.enabled = false;
16903            state.respawn_pending = true;
16904        })
16905        .unwrap();
16906        assert!(!module.will_recover_after_connection_loss().unwrap());
16907    }
16908
16909    fn terminal_record_barrier(events: &super::SpawnEventFeed) -> std::net::TcpStream {
16910        use std::net::{TcpListener, TcpStream};
16911        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
16912        let writer = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
16913        let (barrier, _) = listener.accept().unwrap();
16914        for stream in [&writer, &barrier] {
16915            stream
16916                .set_read_timeout(Some(Duration::from_secs(10)))
16917                .unwrap();
16918            stream
16919                .set_write_timeout(Some(Duration::from_secs(10)))
16920                .unwrap();
16921        }
16922        *events.1.lock().unwrap() = Some(writer);
16923        barrier
16924    }
16925
16926    pub(super) fn before_terminal_record(events: &super::SpawnEventFeed) {
16927        use std::io::{Read, Write};
16928        let barrier = events.1.lock().unwrap().take();
16929        if let Some(mut barrier) = barrier {
16930            barrier.write_all(b"R").unwrap();
16931            let mut release = [0];
16932            barrier.read_exact(&mut release).unwrap();
16933            assert_eq!(&release, b"X");
16934        }
16935    }
16936
16937    #[test]
16938    fn health_restart_budget_failure_is_published_after_its_terminal_record() {
16939        use std::io::{Read, Write};
16940
16941        let supervisor = Supervisor::new_for_test(
16942            Arc::new(Registry::default()),
16943            RestartPolicy::new(0, Duration::ZERO),
16944        );
16945        let mut runtime = supervisor.runtime_config();
16946        let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
16947        let snapshot = module.inner.snapshot.clone();
16948        runtime.terminal_ring = module.inner.terminal_ring.clone();
16949        let spec = ModuleSpec {
16950            script: None,
16951            module_id: module.module_id().into(),
16952            program: fake_aft_stub_path(),
16953            protocol: ModuleProtocol::None,
16954            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
16955            ..windowed_crash_spec(module.module_id())
16956        };
16957        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16958        let reap = std::thread::spawn(move || {
16959            tokio::runtime::Builder::new_current_thread()
16960                .enable_all()
16961                .build()
16962                .unwrap()
16963                .block_on(async {
16964                    let mut child =
16965                        Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
16966                    health_restart_child(
16967                        &spec,
16968                        &runtime,
16969                        &supervisor.registry,
16970                        &supervisor.process_liveness,
16971                        &snapshot,
16972                        &mut child,
16973                        SupervisorHealthStatus::Failing,
16974                        Some("health probe did not answer"),
16975                        1,
16976                    )
16977                    .await
16978                    .unwrap();
16979                    assert!(child.is_none());
16980                });
16981        });
16982        // The loopback barrier acknowledges entry into terminal recording by
16983        // health_restart_child's drain, then waits for the test's release byte.
16984        // Status and history are observed while that writer is held, not after
16985        // an elapsed-time guess about when the health action has completed.
16986        let mut reached = [0];
16987        barrier.read_exact(&mut reached).unwrap();
16988        assert_eq!(&reached, b"R");
16989        let before_status = module.status().unwrap();
16990        let before_history = module.terminal_history();
16991        barrier.write_all(b"X").unwrap();
16992        reap.join().unwrap();
16993        assert!(before_history.entries.is_empty());
16994        assert_ne!(
16995            before_status.state,
16996            ModuleState::Failed,
16997            "Failed was visible before its terminal record could be written"
16998        );
16999        assert!(
17000            before_status.process_alive,
17001            "process death was visible before its terminal record could be written"
17002        );
17003        let failed = module.status().unwrap();
17004        assert_eq!(failed.state, ModuleState::Failed);
17005        assert!(!failed.process_alive);
17006        let history = module.terminal_history();
17007        assert_eq!(history.entries.len(), 1);
17008        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
17009        assert_eq!(
17010            history.entries[0].disposition_detail.as_deref(),
17011            Some("crash budget exhausted: max_restarts=0 within window_secs=600")
17012        );
17013    }
17014
17015    #[test]
17016    fn observed_exits_publish_process_death_after_terminal_history() {
17017        use std::io::{Read, Write};
17018        for (kind, enabled, shutdown, wait_error, expected_state) in [
17019            (ExitKind::Clean, true, false, false, ModuleState::Stopped),
17020            (ExitKind::Crash, true, false, false, ModuleState::Restarting),
17021            (ExitKind::Crash, false, false, false, ModuleState::Disabled),
17022            (
17023                ExitKind::DeliberateSeverance,
17024                true,
17025                false,
17026                false,
17027                ModuleState::Restarting,
17028            ),
17029            #[cfg(unix)]
17030            (ExitKind::Crash, true, true, false, ModuleState::Stopped),
17031            (ExitKind::Crash, true, false, true, ModuleState::Failed),
17032        ] {
17033            let supervisor = Supervisor::new_for_test(
17034                Arc::new(Registry::default()),
17035                RestartPolicy::new(1, Duration::ZERO),
17036            );
17037            let runtime = supervisor.runtime_config();
17038            #[cfg(unix)]
17039            if shutdown {
17040                runtime.child_roster.close();
17041            }
17042            #[cfg(not(unix))]
17043            let _ = shutdown;
17044            let spec = windowed_crash_spec("exit-publication-order");
17045            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
17046                ModuleState::Running,
17047                enabled,
17048            )));
17049            lock_snapshot(&snapshot).unwrap().process_alive = true;
17050            let reaped_snapshot = snapshot.clone();
17051            let history = runtime.terminal_ring.clone();
17052            let mut barrier = terminal_record_barrier(&runtime.spawn_events);
17053            let reap = std::thread::spawn(move || {
17054                if wait_error {
17055                    super::fail_after_wait_error(
17056                        &spec.module_id,
17057                        &reaped_snapshot,
17058                        &runtime.terminal_ring,
17059                        &runtime.spawn_events,
17060                        "wait failed".into(),
17061                        &runtime.failure_context(true),
17062                    );
17063                } else {
17064                    tokio::runtime::Builder::new_current_thread()
17065                        .enable_all()
17066                        .build()
17067                        .unwrap()
17068                        .block_on(on_child_exit(
17069                            &spec,
17070                            runtime.restart_policy,
17071                            &supervisor.registry,
17072                            &reaped_snapshot,
17073                            &runtime.terminal_ring,
17074                            &runtime.spawn_events,
17075                            &runtime.child_roster,
17076                            ExitReport {
17077                                kind,
17078                                code: Some(0),
17079                                signal: None,
17080                                at_ms: 1,
17081                            },
17082                            true,
17083                        ));
17084                }
17085            });
17086            let mut reached = [0];
17087            barrier.read_exact(&mut reached).unwrap();
17088            assert_eq!(&reached, b"R");
17089            let before_alive = lock_snapshot(&snapshot).unwrap().process_alive;
17090            let before_history = history.lock().unwrap().snapshot();
17091            barrier.write_all(b"X").unwrap();
17092            reap.join().unwrap();
17093            assert!(
17094                before_alive,
17095                "{kind:?}: death was published before recording"
17096            );
17097            assert!(before_history.entries.is_empty());
17098            assert_eq!(lock_snapshot(&snapshot).unwrap().state, expected_state);
17099            assert!(!lock_snapshot(&snapshot).unwrap().process_alive);
17100            assert_eq!(history.lock().unwrap().snapshot().entries.len(), 1);
17101        }
17102    }
17103
17104    #[tokio::test]
17105    async fn health_restart_budget_failure_remains_failed_when_journal_append_fails() {
17106        let dir = cortexkit_test_support::ScratchDir::new("health-budget-journal-failure");
17107        let path = dir.join("terminals.jsonl");
17108        std::fs::create_dir(&path).unwrap();
17109        let supervisor = Supervisor::new_for_test(
17110            Arc::new(Registry::default()),
17111            RestartPolicy::new(0, Duration::ZERO),
17112        )
17113        .with_terminal_journal(path, "health-budget-journal-failure".into());
17114        let runtime = supervisor.runtime_config();
17115        let spec = ModuleSpec {
17116            script: None,
17117            program: fake_aft_stub_path(),
17118            protocol: ModuleProtocol::None,
17119            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
17120            ..windowed_crash_spec("health-budget-journal-failure")
17121        };
17122        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17123        let mut child = Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
17124        health_restart_child(
17125            &spec,
17126            &runtime,
17127            &supervisor.registry,
17128            &supervisor.process_liveness,
17129            &snapshot,
17130            &mut child,
17131            SupervisorHealthStatus::Failing,
17132            None,
17133            1,
17134        )
17135        .await
17136        .unwrap();
17137        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17138        assert!(!lock_snapshot(&snapshot).unwrap().process_alive);
17139        let history = runtime
17140            .terminal_ring
17141            .lock()
17142            .unwrap()
17143            .durable_history(&spec.module_id);
17144        assert!(history.journal_write_failures > 0);
17145        assert_eq!(history.entries.len(), 1);
17146        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
17147    }
17148
17149    #[test]
17150    fn health_restart_budget_failure_remains_failed_when_exit_recording_panics() {
17151        let supervisor = Supervisor::new_for_test(
17152            Arc::new(Registry::default()),
17153            RestartPolicy::new(0, Duration::ZERO),
17154        );
17155        let runtime = supervisor.runtime_config();
17156        let spec = ModuleSpec {
17157            script: None,
17158            program: fake_aft_stub_path(),
17159            protocol: ModuleProtocol::None,
17160            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
17161            ..windowed_crash_spec("health-budget-recording-panic")
17162        };
17163        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17164        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
17165            tokio::runtime::Builder::new_current_thread()
17166                .enable_all()
17167                .build()
17168                .unwrap()
17169                .block_on(async {
17170                    let mut child =
17171                        Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
17172                    runtime.spawn_events.0.lock().unwrap().seq = u64::MAX;
17173                    health_restart_child(
17174                        &spec,
17175                        &runtime,
17176                        &supervisor.registry,
17177                        &supervisor.process_liveness,
17178                        &snapshot,
17179                        &mut child,
17180                        SupervisorHealthStatus::Failing,
17181                        None,
17182                        1,
17183                    )
17184                    .await
17185                    .unwrap();
17186                });
17187        }));
17188        let panic = result.expect_err("recording must still unwind");
17189        assert_eq!(
17190            panic.downcast_ref::<String>().map(String::as_str),
17191            Some("spawn event sequence exhausted")
17192        );
17193        let state = lock_snapshot(&snapshot).unwrap();
17194        assert_eq!(state.state, ModuleState::Failed);
17195        assert!(!state.process_alive);
17196        assert!(state.last_exit.is_some());
17197    }
17198
17199    #[tokio::test]
17200    async fn restart_budget_failure_remains_failed_when_journal_append_fails() {
17201        let dir = cortexkit_test_support::ScratchDir::new("budget-journal-failure");
17202        let path = dir.join("terminals.jsonl");
17203        std::fs::create_dir(&path).unwrap();
17204        let supervisor = Supervisor::new_for_test(
17205            Arc::new(Registry::default()),
17206            RestartPolicy::new(0, Duration::ZERO),
17207        )
17208        .with_terminal_journal(path, "budget-journal-failure".into());
17209        let runtime = supervisor.runtime_config();
17210        let spec = windowed_crash_spec("budget-journal-failure");
17211        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17212        assert!(matches!(
17213            on_child_exit(
17214                &spec,
17215                runtime.restart_policy,
17216                &supervisor.registry,
17217                &snapshot,
17218                &runtime.terminal_ring,
17219                &runtime.spawn_events,
17220                &runtime.child_roster,
17221                crash_exit_report(1),
17222                true,
17223            )
17224            .await,
17225            NextAction::Stop { .. }
17226        ));
17227        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17228        let history = runtime
17229            .terminal_ring
17230            .lock()
17231            .unwrap()
17232            .durable_history(&spec.module_id);
17233        assert!(history.journal_write_failures > 0);
17234        assert_eq!(history.entries.len(), 1);
17235        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
17236    }
17237
17238    #[test]
17239    fn restart_budget_failure_remains_failed_when_exit_recording_panics() {
17240        let supervisor = Supervisor::new_for_test(
17241            Arc::new(Registry::default()),
17242            RestartPolicy::new(0, Duration::ZERO),
17243        );
17244        let runtime = supervisor.runtime_config();
17245        let spec = windowed_crash_spec("budget-recording-panic");
17246        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17247        runtime
17248            .spawn_events
17249            .emit_spawned(&spec.module_id, None, 1, 1);
17250        // Exhausting the event sequence makes emit_exited panic before the
17251        // terminal write, exercising publication on the recording unwind.
17252        runtime.spawn_events.0.lock().unwrap().seq = u64::MAX;
17253        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
17254            tokio::runtime::Builder::new_current_thread()
17255                .enable_all()
17256                .build()
17257                .unwrap()
17258                .block_on(on_child_exit(
17259                    &spec,
17260                    runtime.restart_policy,
17261                    &supervisor.registry,
17262                    &snapshot,
17263                    &runtime.terminal_ring,
17264                    &runtime.spawn_events,
17265                    &runtime.child_roster,
17266                    crash_exit_report(1),
17267                    true,
17268                ))
17269        }));
17270        let panic = result.err().expect("recording must still unwind");
17271        assert_eq!(
17272            panic.downcast_ref::<String>().map(String::as_str),
17273            Some("spawn event sequence exhausted")
17274        );
17275        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17276    }
17277
17278    /// A stop the supervisor itself requests still stops a protocol-none
17279    /// module, even though the child answers the SIGTERM with exit 0.
17280    #[cfg(unix)]
17281    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17282    async fn protocol_none_requested_stop_and_disable_do_not_respawn() {
17283        for disable in [false, true] {
17284            let label = if disable {
17285                "none-requested-disable"
17286            } else {
17287                "none-requested-stop"
17288            };
17289            let dir = cortexkit_test_support::ScratchDir::new(label);
17290            let (spec, ready, marker) = protocol_none_sigterm_exits_clean_spec(label, dir.path());
17291            let supervisor = Supervisor::new_for_test(
17292                Arc::new(Registry::default()),
17293                RestartPolicy::new(3, Duration::ZERO),
17294            );
17295            let module = supervisor.spawn(spec).unwrap();
17296            wait_for_file(&ready).await;
17297
17298            if disable {
17299                module.set_enabled(false).await.unwrap();
17300            } else {
17301                module.stop().await.unwrap();
17302            }
17303            assert!(
17304                marker.exists(),
17305                "{label}: the child must have left through its SIGTERM handler with exit 0"
17306            );
17307
17308            // Long enough for a zero-backoff respawn to have happened if the
17309            // exit had been treated as a crash.
17310            sleep(Duration::from_millis(500)).await;
17311            let status = module.status().unwrap();
17312            let expected = if disable {
17313                ModuleState::Disabled
17314            } else {
17315                ModuleState::Stopped
17316            };
17317            assert_eq!(status.state, expected, "{label}");
17318            assert_eq!(
17319                status.spawn_generation, 1,
17320                "{label}: respawned after a requested stop"
17321            );
17322            let history = module.terminal_history();
17323            assert_eq!(history.entries.len(), 1, "{label}: {history:?}");
17324            assert_eq!(history.entries[0].exit_code, Some(0), "{label}");
17325            assert_ne!(
17326                history.entries[0].disposition,
17327                TerminalDisposition::Restarting,
17328                "{label}"
17329            );
17330        }
17331    }
17332
17333    /// A subc-wire module that exits 0 on its own is still a stop: the
17334    /// protocol-none rule must not reach it.
17335    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17336    async fn subc_wire_clean_exit_is_still_a_stop() {
17337        let supervisor = Supervisor::new_for_test(
17338            Arc::new(Registry::default()),
17339            RestartPolicy::new(3, Duration::ZERO),
17340        );
17341        let module = supervisor
17342            .spawn(ModuleSpec {
17343                script: None,
17344                module_id: "wire-clean-exit".to_string(),
17345                program: fake_aft_stub_path(),
17346                args: Vec::new(),
17347                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "0".to_string())],
17348                reserved: false,
17349                reserved_prefixes: Vec::new(),
17350                protocol: ModuleProtocol::Subc,
17351                overlap: Default::default(),
17352                carry_containment: false,
17353            })
17354            .unwrap();
17355
17356        let deadline = Instant::now() + Duration::from_secs(10);
17357        while module.terminal_history().entries.is_empty() {
17358            assert!(Instant::now() < deadline, "module never exited");
17359            sleep(Duration::from_millis(10)).await;
17360        }
17361        // Long enough for a zero-backoff respawn to have happened.
17362        sleep(Duration::from_millis(500)).await;
17363        let status = module.status().unwrap();
17364        assert_eq!(status.state, ModuleState::Stopped);
17365        assert_eq!(status.spawn_generation, 1);
17366        let history = module.terminal_history();
17367        assert_eq!(history.entries.len(), 1, "{history:?}");
17368        assert_eq!(history.entries[0].exit_code, Some(0));
17369        assert_eq!(history.entries[0].disposition, TerminalDisposition::Stopped);
17370    }
17371
17372    #[cfg(unix)]
17373    #[tokio::test]
17374    async fn reload_exit_keeps_roster_until_terminal_is_recorded_during_shutdown() {
17375        let dir = cortexkit_test_support::ScratchDir::new("reload-roster-terminal-order");
17376        let record = dir.join("live-children.json");
17377        let supervisor = Supervisor::new_for_test(
17378            Arc::new(Registry::default()),
17379            RestartPolicy::new(0, Duration::ZERO),
17380        );
17381        let mut runtime = supervisor.runtime_config();
17382        runtime.child_roster.record_to(record.clone());
17383        let gate = Arc::new(super::ReloadExitRecordGate::default());
17384        runtime.test_reload_exit_record_gate = Some(Arc::clone(&gate));
17385        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17386        let spec = ModuleSpec {
17387            script: None,
17388            module_id: "reload-exit-roster".into(),
17389            program: fake_aft_stub_path(),
17390            args: Vec::new(),
17391            env: vec![("FAKE_AFT_EXIT_CODE".into(), "23".into())],
17392            reserved: false,
17393            reserved_prefixes: Vec::new(),
17394            protocol: ModuleProtocol::Subc,
17395            overlap: Default::default(),
17396            carry_containment: false,
17397        };
17398        let mut child = None;
17399        let reload = super::finish_reload_child(
17400            &spec,
17401            &runtime,
17402            &supervisor.registry,
17403            &supervisor.process_liveness,
17404            &snapshot,
17405            &mut child,
17406        );
17407        tokio::pin!(reload);
17408        tokio::select! {
17409            result = &mut reload => panic!("reload missed the before-record gate: {result:?}"),
17410            _ = gate.reached.notified() => {}
17411        }
17412        assert!(runtime
17413            .terminal_ring
17414            .lock()
17415            .unwrap()
17416            .snapshot()
17417            .entries
17418            .is_empty());
17419        assert_eq!(
17420            crate::live_children::read_record(&record).unwrap().len(),
17421            1,
17422            "shutdown must still wait for the reaped child until its terminal record exists"
17423        );
17424        runtime.child_roster.close();
17425        gate.resume.notify_one();
17426        assert!(reload.await.is_err());
17427        assert!(crate::live_children::read_record(&record)
17428            .unwrap()
17429            .is_empty());
17430        let history = runtime.terminal_ring.lock().unwrap().snapshot();
17431        assert_eq!(history.entries.len(), 1);
17432        assert_eq!(
17433            history.entries[0].disposition,
17434            TerminalDisposition::DaemonShutdown
17435        );
17436    }
17437
17438    /// Each restart-producing arm has its own state transition. Keeping their
17439    /// lifetime count assertions adjacent prevents a later new arm from silently
17440    /// spending budget without recording the historical restart.
17441    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17442    async fn every_restart_increment_path_advances_lifetime_count() {
17443        let supervisor = Supervisor::new_for_test(
17444            Arc::new(Registry::default()),
17445            RestartPolicy::new(1, Duration::ZERO),
17446        );
17447        let runtime = supervisor.runtime_config();
17448        let spec = ModuleSpec {
17449            script: None,
17450            module_id: "lifetime-increment-path".to_string(),
17451            program: PathBuf::from("/unused/lifetime-increment-path"),
17452            args: Vec::new(),
17453            env: Vec::new(),
17454            reserved: false,
17455            reserved_prefixes: Vec::new(),
17456            protocol: ModuleProtocol::Subc,
17457            overlap: Default::default(),
17458            carry_containment: false,
17459        };
17460
17461        let crash_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17462        assert!(matches!(
17463            on_child_exit(
17464                &spec,
17465                runtime.restart_policy,
17466                &supervisor.registry,
17467                &crash_snapshot,
17468                &runtime.terminal_ring,
17469                &runtime.spawn_events,
17470                &runtime.child_roster,
17471                ExitReport {
17472                    kind: ExitKind::Crash,
17473                    code: Some(1),
17474                    signal: None,
17475                    at_ms: 1,
17476                },
17477                true,
17478            )
17479            .await,
17480            NextAction::Restart { schedule: _ }
17481        ));
17482        let (crash_restarts, crash_lifetime) = {
17483            let state = lock_snapshot(&crash_snapshot).unwrap();
17484            (state.crash_restarts.len(), state.lifetime_restarts)
17485        };
17486        assert_eq!(crash_restarts, 1);
17487        assert_eq!(crash_lifetime, 1);
17488
17489        let health_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17490        let mut health_child = None;
17491        assert!(matches!(
17492            health_restart_child(
17493                &spec,
17494                &runtime,
17495                &supervisor.registry,
17496                &supervisor.process_liveness,
17497                &health_snapshot,
17498                &mut health_child,
17499                SupervisorHealthStatus::Failing,
17500                None,
17501                2,
17502            )
17503            .await,
17504            Ok(())
17505        ));
17506        assert!(health_child.is_none());
17507        assert!(lock_snapshot(&health_snapshot).unwrap().respawn_pending);
17508        assert!(runtime.scheduled_respawn.lock().unwrap().take().is_some());
17509        let (health_restarts, health_lifetime) = {
17510            let state = lock_snapshot(&health_snapshot).unwrap();
17511            (state.crash_restarts.len(), state.lifetime_restarts)
17512        };
17513        assert_eq!(health_restarts, 1);
17514        assert_eq!(health_lifetime, 1);
17515
17516        let reload_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17517        let mut reload_child = None;
17518        assert!(matches!(
17519            handle_reload_spawn_failure(
17520                &spec,
17521                &runtime,
17522                &supervisor.process_liveness,
17523                &reload_snapshot,
17524                &mut reload_child,
17525                "forced reload spawn failure".to_string(),
17526            )
17527            .await,
17528            Err(SuperviseError::ReloadFailed { .. })
17529        ));
17530        let (reload_restarts, reload_lifetime) = {
17531            let state = lock_snapshot(&reload_snapshot).unwrap();
17532            (state.crash_restarts.len(), state.lifetime_restarts)
17533        };
17534        assert_eq!(reload_restarts, 1);
17535        assert_eq!(reload_lifetime, 1);
17536    }
17537
17538    #[tokio::test]
17539    async fn deliberately_severed_live_child_records_lifetime_without_spending_restart_budget() {
17540        let supervisor = Supervisor::new_for_test(
17541            Arc::new(Registry::default()),
17542            RestartPolicy::new(3, Duration::ZERO),
17543        );
17544        let runtime = supervisor.runtime_config();
17545        let spec = ModuleSpec {
17546            script: None,
17547            module_id: "deliberately-severed".to_string(),
17548            program: PathBuf::from("/unused/deliberately-severed"),
17549            args: Vec::new(),
17550            env: Vec::new(),
17551            reserved: false,
17552            reserved_prefixes: Vec::new(),
17553            protocol: ModuleProtocol::Subc,
17554            overlap: Default::default(),
17555            carry_containment: false,
17556        };
17557        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17558        let process = ProcessIdentity {
17559            pid: 41,
17560            start_time: 101,
17561        };
17562        record_deliberate_severance(&snapshot, process).unwrap();
17563        let exit_report = apply_deliberate_severance_marker(
17564            &snapshot,
17565            Some(process),
17566            ExitReport {
17567                kind: ExitKind::Crash,
17568                code: Some(1),
17569                signal: None,
17570                at_ms: 1,
17571            },
17572        );
17573        assert_eq!(exit_report.kind, ExitKind::DeliberateSeverance);
17574
17575        assert!(matches!(
17576            on_child_exit(
17577                &spec,
17578                runtime.restart_policy,
17579                &supervisor.registry,
17580                &snapshot,
17581                &runtime.terminal_ring,
17582                &runtime.spawn_events,
17583                &runtime.child_roster,
17584                exit_report,
17585                true,
17586            )
17587            .await,
17588            NextAction::Restart { schedule: _ }
17589        ));
17590        let state = lock_snapshot(&snapshot).unwrap();
17591        assert_eq!(state.lifetime_restarts, 1);
17592        assert_eq!(state.crash_restarts.len(), 0);
17593    }
17594
17595    #[tokio::test]
17596    async fn genuine_crash_spends_restart_budget_and_records_lifetime() {
17597        let supervisor = Supervisor::new_for_test(
17598            Arc::new(Registry::default()),
17599            RestartPolicy::new(3, Duration::ZERO),
17600        );
17601        let runtime = supervisor.runtime_config();
17602        let spec = ModuleSpec {
17603            script: None,
17604            module_id: "genuine-crash".to_string(),
17605            program: PathBuf::from("/unused/genuine-crash"),
17606            args: Vec::new(),
17607            env: Vec::new(),
17608            reserved: false,
17609            reserved_prefixes: Vec::new(),
17610            protocol: ModuleProtocol::Subc,
17611            overlap: Default::default(),
17612            carry_containment: false,
17613        };
17614        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17615
17616        assert!(matches!(
17617            on_child_exit(
17618                &spec,
17619                runtime.restart_policy,
17620                &supervisor.registry,
17621                &snapshot,
17622                &runtime.terminal_ring,
17623                &runtime.spawn_events,
17624                &runtime.child_roster,
17625                ExitReport {
17626                    kind: ExitKind::Crash,
17627                    code: Some(1),
17628                    signal: None,
17629                    at_ms: 1,
17630                },
17631                true,
17632            )
17633            .await,
17634            NextAction::Restart { schedule: _ }
17635        ));
17636        let state = lock_snapshot(&snapshot).unwrap();
17637        assert_eq!(state.lifetime_restarts, 1);
17638        assert_eq!(state.crash_restarts.len(), 1);
17639    }
17640
17641    fn crash_exit_report(at_ms: u64) -> ExitReport {
17642        ExitReport {
17643            kind: ExitKind::Crash,
17644            code: Some(1),
17645            signal: None,
17646            at_ms,
17647        }
17648    }
17649
17650    fn windowed_crash_spec(module_id: &str) -> ModuleSpec {
17651        ModuleSpec {
17652            script: None,
17653            module_id: module_id.to_string(),
17654            program: PathBuf::from("/unused").join(module_id),
17655            args: Vec::new(),
17656            env: Vec::new(),
17657            reserved: false,
17658            reserved_prefixes: Vec::new(),
17659            protocol: ModuleProtocol::Subc,
17660            overlap: Default::default(),
17661            carry_containment: false,
17662        }
17663    }
17664
17665    /// A real crash loop still stops. Three crashes with nothing aging out spend
17666    /// a budget of two and the third respawn is refused, and both surfaces an
17667    /// operator has -- the log line and the retained terminal record -- name the
17668    /// window rather than only the cap, because `max_restarts=2` alone is what
17669    /// this budget used to mean.
17670    #[tokio::test]
17671    async fn three_crashes_inside_the_window_stop_the_module_and_name_the_window() {
17672        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::ERROR);
17673        let supervisor = Supervisor::new_for_test(
17674            Arc::new(Registry::default()),
17675            RestartPolicy::new(2, Duration::ZERO),
17676        );
17677        let runtime = supervisor.runtime_config();
17678        let spec = windowed_crash_spec("crash-loop-in-window");
17679        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17680
17681        for attempt in 1..=2 {
17682            assert!(
17683                matches!(
17684                    on_child_exit(
17685                        &spec,
17686                        runtime.restart_policy,
17687                        &supervisor.registry,
17688                        &snapshot,
17689                        &runtime.terminal_ring,
17690                        &runtime.spawn_events,
17691                        &runtime.child_roster,
17692                        crash_exit_report(attempt),
17693                        true,
17694                    )
17695                    .await,
17696                    NextAction::Restart { schedule: _ }
17697                ),
17698                "crash {attempt} is inside the budget and must respawn"
17699            );
17700        }
17701
17702        assert!(matches!(
17703            on_child_exit(
17704                &spec,
17705                runtime.restart_policy,
17706                &supervisor.registry,
17707                &snapshot,
17708                &runtime.terminal_ring,
17709                &runtime.spawn_events,
17710                &runtime.child_roster,
17711                crash_exit_report(3),
17712                true,
17713            )
17714            .await,
17715            NextAction::Stop { .. }
17716        ));
17717
17718        {
17719            let state = lock_snapshot(&snapshot).unwrap();
17720            assert_eq!(state.state, ModuleState::Failed);
17721            assert_eq!(state.crash_restarts.len(), 2);
17722            assert_eq!(state.lifetime_restarts, 2);
17723        }
17724
17725        let history = runtime
17726            .terminal_ring
17727            .lock()
17728            .expect("terminal ring is not poisoned")
17729            .snapshot();
17730        let last = history
17731            .entries
17732            .last()
17733            .expect("the refused crash is retained");
17734        assert_eq!(last.disposition, TerminalDisposition::Failed);
17735        assert_eq!(
17736            last.disposition_detail.as_deref(),
17737            Some("crash budget exhausted: max_restarts=2 within window_secs=600")
17738        );
17739
17740        let captured = crate::router::test_log::captured_logs(&logs);
17741        assert!(
17742            captured.contains("crash budget exhausted: max_restarts=2 within window_secs=600"),
17743            "the stop must be logged with its window: {captured}"
17744        );
17745    }
17746
17747    /// The rate, stated as a test: three crashes where the first has aged past
17748    /// the window are two crashes as far as the budget is concerned, so the
17749    /// third respawn is allowed and the ring holds only the two recent ones.
17750    ///
17751    /// This is the case a lifetime counter got wrong -- and the case the daemon
17752    /// now hits routinely, since a module exits non-zero every time its
17753    /// connection to the daemon drops.
17754    #[tokio::test]
17755    async fn a_crash_older_than_the_window_frees_its_slot_for_a_later_crash() {
17756        let supervisor = Supervisor::new_for_test(
17757            Arc::new(Registry::default()),
17758            RestartPolicy::new(2, Duration::ZERO),
17759        );
17760        let runtime = supervisor.runtime_config();
17761        let spec = windowed_crash_spec("crash-across-windows");
17762        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17763
17764        for attempt in 1..=2 {
17765            assert!(matches!(
17766                on_child_exit(
17767                    &spec,
17768                    runtime.restart_policy,
17769                    &supervisor.registry,
17770                    &snapshot,
17771                    &runtime.terminal_ring,
17772                    &runtime.spawn_events,
17773                    &runtime.child_roster,
17774                    crash_exit_report(attempt),
17775                    true,
17776                )
17777                .await,
17778                NextAction::Restart { schedule: _ }
17779            ));
17780        }
17781
17782        // The oldest crash moves out of the window; nothing else about the
17783        // module changes.
17784        update_snapshot(&snapshot, Some(&spec.module_id), |state| {
17785            age_oldest_crash_restart_out_of_window(state, runtime.restart_policy.window);
17786        })
17787        .unwrap();
17788
17789        assert!(
17790            matches!(
17791                on_child_exit(
17792                    &spec,
17793                    runtime.restart_policy,
17794                    &supervisor.registry,
17795                    &snapshot,
17796                    &runtime.terminal_ring,
17797                    &runtime.spawn_events,
17798                    &runtime.child_roster,
17799                    crash_exit_report(3),
17800                    true,
17801                )
17802                .await,
17803                NextAction::Restart { schedule: _ }
17804            ),
17805            "a crash older than the window must not hold a budget slot"
17806        );
17807
17808        let state = lock_snapshot(&snapshot).unwrap();
17809        assert_eq!(state.state, ModuleState::Restarting);
17810        assert_eq!(
17811            state.crash_restarts.len(),
17812            2,
17813            "the aged instant is dropped and the new one takes its place"
17814        );
17815        assert_eq!(
17816            state.lifetime_restarts, 3,
17817            "the ledger counts every restart, including the ones the window forgot"
17818        );
17819    }
17820
17821    /// An operator restart hands the budget back whole, and the ledger keeps
17822    /// counting. Those are different questions -- "how close is this module to
17823    /// being stopped" and "how many times has it been replaced" -- and the
17824    /// operator action answers only the first.
17825    #[tokio::test]
17826    async fn an_operator_restart_clears_the_ring_and_leaves_the_ledger_alone() {
17827        let supervisor = Supervisor::new_for_test(
17828            Arc::new(Registry::default()),
17829            RestartPolicy::new(2, Duration::ZERO),
17830        );
17831        let runtime = supervisor.runtime_config();
17832        let spec = windowed_crash_spec("operator-cleared-budget");
17833        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17834
17835        for attempt in 1..=2 {
17836            assert!(matches!(
17837                on_child_exit(
17838                    &spec,
17839                    runtime.restart_policy,
17840                    &supervisor.registry,
17841                    &snapshot,
17842                    &runtime.terminal_ring,
17843                    &runtime.spawn_events,
17844                    &runtime.child_roster,
17845                    crash_exit_report(attempt),
17846                    true,
17847                )
17848                .await,
17849                NextAction::Restart { schedule: _ }
17850            ));
17851        }
17852
17853        reset_restart_count(&snapshot, &spec.module_id).unwrap();
17854        {
17855            let state = lock_snapshot(&snapshot).unwrap();
17856            assert!(
17857                state.crash_restarts.is_empty(),
17858                "an operator restart returns the full budget"
17859            );
17860            assert_eq!(
17861                state.lifetime_restarts, 2,
17862                "clearing the budget must not unmake the crashes"
17863            );
17864        }
17865
17866        assert!(
17867            matches!(
17868                on_child_exit(
17869                    &spec,
17870                    runtime.restart_policy,
17871                    &supervisor.registry,
17872                    &snapshot,
17873                    &runtime.terminal_ring,
17874                    &runtime.spawn_events,
17875                    &runtime.child_roster,
17876                    crash_exit_report(3),
17877                    true,
17878                )
17879                .await,
17880                NextAction::Restart { schedule: _ }
17881            ),
17882            "the cleared budget must be spendable again"
17883        );
17884        let state = lock_snapshot(&snapshot).unwrap();
17885        assert_eq!(state.crash_restarts.len(), 1);
17886        assert_eq!(state.lifetime_restarts, 3);
17887    }
17888
17889    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17890    async fn severance_marker_for_a_dead_child_does_not_label_its_successor() {
17891        let severed = ProcessIdentity {
17892            pid: 41,
17893            start_time: 101,
17894        };
17895        let successor = ProcessIdentity {
17896            pid: 41,
17897            start_time: 202,
17898        };
17899        let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
17900        update_snapshot(&module.inner.snapshot, Some("recovery-snapshot"), |state| {
17901            state.pid = Some(successor.pid);
17902            state.process_start_time = Some(successor.start_time);
17903        })
17904        .unwrap();
17905        assert!(!module.record_deliberate_severance(severed).unwrap());
17906
17907        let exit_report = apply_deliberate_severance_marker(
17908            &module.inner.snapshot,
17909            Some(successor),
17910            ExitReport {
17911                kind: ExitKind::Crash,
17912                code: Some(1),
17913                signal: None,
17914                at_ms: 1,
17915            },
17916        );
17917
17918        assert_eq!(exit_report.kind, ExitKind::Crash);
17919    }
17920
17921    #[tokio::test]
17922    async fn drain_reap_marks_deliberate_severance_and_records_lifetime_without_budget() {
17923        let registry = Registry::default();
17924        let supervisor = Supervisor::new_for_test(
17925            Arc::new(Registry::default()),
17926            RestartPolicy::new(3, Duration::ZERO),
17927        );
17928        let runtime = supervisor.runtime_config();
17929        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17930        let spec = ModuleSpec {
17931            script: None,
17932            module_id: "drain-deliberate-severance".to_string(),
17933            program: fake_aft_stub_path(),
17934            args: Vec::new(),
17935            env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
17936            reserved: false,
17937            reserved_prefixes: Vec::new(),
17938            protocol: ModuleProtocol::Subc,
17939            overlap: Default::default(),
17940            carry_containment: false,
17941        };
17942        let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
17943        let process = ProcessIdentity {
17944            pid: 41,
17945            start_time: 101,
17946        };
17947        child.process_identity = Some(process);
17948        update_snapshot(&snapshot, Some(&spec.module_id), |state| {
17949            state.pid = Some(process.pid);
17950            state.process_start_time = Some(process.start_time);
17951        })
17952        .unwrap();
17953        record_deliberate_severance(&snapshot, process).unwrap();
17954
17955        drain_child_to_state(
17956            &spec.module_id,
17957            spec.protocol,
17958            // The child exits on its own; no signal may change the exit this
17959            // test classifies.
17960            StopNotice::SentOverConnection,
17961            &registry,
17962            None,
17963            &snapshot,
17964            &runtime.terminal_ring,
17965            &runtime.spawn_events,
17966            child,
17967            Duration::from_secs(1),
17968            ModuleState::Stopped,
17969            Some(false),
17970            &super::FailureContext::operator(),
17971        )
17972        .await
17973        .unwrap();
17974
17975        let state = lock_snapshot(&snapshot).unwrap();
17976        assert_eq!(
17977            state.last_exit.as_ref().map(|exit| exit.kind),
17978            Some(ExitKind::DeliberateSeverance)
17979        );
17980        assert_eq!(state.lifetime_restarts, 1);
17981        assert_eq!(state.crash_restarts.len(), 0);
17982        drop(state);
17983        let history = runtime.terminal_ring.lock().unwrap().snapshot();
17984        assert_eq!(
17985            history.entries[0].exit_kind,
17986            subc_control::TerminalExitKind::DeliberateSeverance
17987        );
17988    }
17989
17990    #[tokio::test]
17991    async fn ordinary_drain_reap_does_not_record_a_lifetime_restart() {
17992        let registry = Registry::default();
17993        let supervisor = Supervisor::new_for_test(
17994            Arc::new(Registry::default()),
17995            RestartPolicy::new(3, Duration::ZERO),
17996        );
17997        let runtime = supervisor.runtime_config();
17998        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17999        let spec = ModuleSpec {
18000            script: None,
18001            module_id: "ordinary-drain".to_string(),
18002            program: fake_aft_stub_path(),
18003            args: Vec::new(),
18004            env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
18005            reserved: false,
18006            reserved_prefixes: Vec::new(),
18007            protocol: ModuleProtocol::Subc,
18008            overlap: Default::default(),
18009            carry_containment: false,
18010        };
18011        let child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
18012
18013        drain_child_to_state(
18014            &spec.module_id,
18015            spec.protocol,
18016            // The child exits on its own; no signal may change the exit this
18017            // test classifies.
18018            StopNotice::SentOverConnection,
18019            &registry,
18020            None,
18021            &snapshot,
18022            &runtime.terminal_ring,
18023            &runtime.spawn_events,
18024            child,
18025            Duration::from_secs(1),
18026            ModuleState::Stopped,
18027            Some(false),
18028            &super::FailureContext::operator(),
18029        )
18030        .await
18031        .unwrap();
18032
18033        let state = lock_snapshot(&snapshot).unwrap();
18034        assert_eq!(
18035            state.last_exit.as_ref().map(|exit| exit.kind),
18036            Some(ExitKind::Crash)
18037        );
18038        assert_eq!(state.lifetime_restarts, 0);
18039        assert_eq!(state.crash_restarts.len(), 0);
18040    }
18041
18042    #[test]
18043    fn fatal_connection_teardown_cannot_arm_a_marker_for_a_surviving_process() {
18044        // The server's generic fatal-routing branch only knows that the
18045        // connection failed; it does not know that the daemon deliberately
18046        // initiated a process-killing severance. Keep this seam explicit so a
18047        // future connection error path cannot silently reintroduce the stale
18048        // exemption that mislabels a later genuine crash.
18049        assert!(!include_str!("server.rs")
18050            .contains("router.record_deliberate_connection_severance(ctx.connection_id)"));
18051    }
18052
18053    /// The `route.closed` `drained` value must be the quiescence wait's own
18054    /// measurement (`Ok`), never invented -- except on `Err`, where there is no
18055    /// measurement at all and `false` is the one honest constant. This is the exact
18056    /// logic `begin_forwarding_drain_with` now applies before sending `route.closed`
18057    /// on every return path, including the one that used to return early via `?`
18058    /// with `route.closing` already sent and no `route.closed` ever following.
18059    #[test]
18060    fn drained_after_quiescence_wait_passes_ok_through_and_forces_false_on_err() {
18061        assert!(drained_after_quiescence_wait(&Ok(true)));
18062        assert!(!drained_after_quiescence_wait(&Ok(false)));
18063        assert!(!drained_after_quiescence_wait(&Err(
18064            SuperviseError::StatePoisoned { module_id: None }
18065        )));
18066    }
18067
18068    /// `supervise_loop`'s `wait()`-error arm now calls `record_terminal` like every
18069    /// other exit path does, so a module whose child `wait()` itself errored (e.g.
18070    /// already reaped out-of-band) still leaves a terminal record rather than none
18071    /// at all. Triggering the real `wait()` I/O error from an integration test would
18072    /// need a genuine already-reaped-child race, which is OS-specific and not
18073    /// something this suite attempts elsewhere; this test instead verifies the
18074    /// record produced for that arm end-to-end through the real `TerminalRing`, and
18075    /// the call site itself is verified by inspection to sit in that exact arm.
18076    #[test]
18077    fn wait_error_exit_report_records_a_failed_terminal_with_no_code_or_signal() {
18078        let ring = Arc::new(Mutex::new(TerminalRing::new(
18079            TerminalRingConfig::default(),
18080            0,
18081        )));
18082        record_wait_error_terminal("wait-error", &ring, &super::SpawnEventFeed::default());
18083
18084        let snapshot = ring.lock().unwrap().snapshot();
18085        assert_eq!(snapshot.entries.len(), 1);
18086        let entry = &snapshot.entries[0];
18087        assert_eq!(entry.exit_code, None);
18088        assert_eq!(entry.exit_signal, None);
18089        assert_eq!(entry.disposition, TerminalDisposition::Failed);
18090    }
18091
18092    /// A launch is numbered before it starts. One that never runs keeps its
18093    /// number, and the next launch of the module is numbered after it.
18094    #[test]
18095    fn spawn_generation_of_a_failed_launch_is_never_reused() {
18096        let feed = super::SpawnEventFeed::default();
18097        feed.configure_incarnation("launch-numbering".to_string());
18098        let (incarnation, failed) = feed.allocate_generation("relaunched");
18099        assert_eq!(incarnation, "launch-numbering");
18100        let (_, next) = feed.allocate_generation("relaunched");
18101        assert!(next > failed);
18102        assert_eq!(feed.emit_spawned("relaunched", Some(next), 7, 1), next);
18103        // A process with no pre-allocated number is numbered after both.
18104        assert!(feed.emit_spawned("relaunched", None, 8, 2) > next);
18105        assert_eq!(
18106            feed.allocate_generation("other").1,
18107            1,
18108            "numbering is per module"
18109        );
18110    }
18111
18112    #[test]
18113    fn wait_error_exit_path_preserves_spawn_event_density() {
18114        let feed = super::SpawnEventFeed::default();
18115        feed.configure_incarnation("wait-error-density".to_string());
18116        feed.emit_spawned("wait-error", None, 41, 1);
18117        let ring = Arc::new(Mutex::new(TerminalRing::new(
18118            TerminalRingConfig::default(),
18119            0,
18120        )));
18121
18122        record_wait_error_terminal("wait-error", &ring, &feed);
18123        feed.emit_spawned("after-wait-error", None, 42, 2);
18124
18125        let state = feed.0.lock().unwrap();
18126        let sequences = state
18127            .events
18128            .iter()
18129            .map(|event| event.cursor.seq)
18130            .collect::<Vec<_>>();
18131        assert_eq!(sequences, vec![1, 2, 3]);
18132        assert_eq!(state.events[1].kind, SpawnEventKind::Exited);
18133        assert_eq!(state.events[1].exit_code, None);
18134        assert_eq!(state.events[1].exit_signal, None);
18135    }
18136
18137    /// Pins the report's `kind` too: the wait-error arm treats an unwaitable child
18138    /// as a crash (matching `fail_snapshot`'s `Failed` disposition for this arm),
18139    /// not a clean exit it never actually observed.
18140    #[test]
18141    fn wait_error_exit_report_is_classified_as_a_crash() {
18142        assert_eq!(wait_error_exit_report().kind, ExitKind::Crash);
18143    }
18144}
18145
18146#[cfg(all(test, unix))]
18147mod restart_ordering_tests {
18148    use super::*;
18149    use std::io::Write;
18150    use tokio::io::AsyncReadExt;
18151
18152    #[test]
18153    #[ignore = "child process fixture"]
18154    fn serving_child() {
18155        let Ok(address_file) = std::env::var("RESTART_TEST_ADDRESS_FILE") else {
18156            return;
18157        };
18158        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
18159        std::fs::write(address_file, listener.local_addr().unwrap().to_string()).unwrap();
18160        for stream in listener.incoming() {
18161            writeln!(stream.unwrap(), "{}", std::process::id()).unwrap();
18162        }
18163    }
18164
18165    async fn restart_before_publication(requests: usize) {
18166        let home = cortexkit_test_support::ScratchDir::new("restart-before-publication");
18167        let address_file = home.path().join("address");
18168        let spec = ModuleSpec {
18169            script: None,
18170            module_id: "restart-serving-child".into(),
18171            program: std::env::current_exe().unwrap(),
18172            args: vec![
18173                "--exact".into(),
18174                "supervise::restart_ordering_tests::serving_child".into(),
18175                "--ignored".into(),
18176                "--nocapture".into(),
18177            ],
18178            env: vec![(
18179                "RESTART_TEST_ADDRESS_FILE".into(),
18180                address_file.display().to_string(),
18181            )],
18182            reserved: false,
18183            reserved_prefixes: vec![],
18184            protocol: ModuleProtocol::None,
18185            overlap: Default::default(),
18186            carry_containment: false,
18187        };
18188        let mut supervisor =
18189            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
18190        let (spawned_tx, spawned_rx) = oneshot::channel();
18191        let spawned_tx = Mutex::new(Some(spawned_tx));
18192        let (release_tx, release_rx) = std::sync::mpsc::channel();
18193        let release_rx = Mutex::new(release_rx);
18194        // Hold publication, not the child: it must answer a real request before
18195        // the restart enters the queue, even though status still has generation 0.
18196        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |_| {
18197            spawned_tx.lock().unwrap().take().unwrap().send(()).unwrap();
18198            release_rx
18199                .lock()
18200                .unwrap()
18201                .recv_timeout(Duration::from_secs(20))
18202                .unwrap();
18203        })));
18204        let registered = supervisor
18205            .register_configured_with_health(
18206                spec.clone(),
18207                true,
18208                HealthConfig::default(),
18209                None,
18210                RestartPolicy::new(3, Duration::ZERO),
18211                DEFAULT_REGISTER_TIMEOUT,
18212            )
18213            .unwrap();
18214        let module = registered.module.clone();
18215        let startup = tokio::task::spawn_blocking(move || {
18216            supervisor.start_registered_configured(registered, None, true)
18217        });
18218        spawned_rx.await.unwrap();
18219        let old_pid = tokio::time::timeout(Duration::from_secs(10), async {
18220            let address = loop {
18221                if let Ok(address) = std::fs::read_to_string(&address_file) {
18222                    if !address.is_empty() {
18223                        break address;
18224                    }
18225                }
18226                tokio::time::sleep(Duration::from_millis(1)).await;
18227            };
18228            let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();
18229            let mut reply = String::new();
18230            stream.read_to_string(&mut reply).await.unwrap();
18231            reply.trim().parse::<u32>().unwrap()
18232        })
18233        .await
18234        .expect("child must serve before generation publication");
18235        assert_eq!(
18236            lock_snapshot(&module.inner.snapshot)
18237                .unwrap()
18238                .spawn_generation,
18239            0
18240        );
18241        let mut replies = Vec::new();
18242        for _ in 0..requests {
18243            let mut restart = Box::pin(module.restart(Some(0)));
18244            // Poll the public API through queue admission, leaving only its ACK
18245            // pending. The monitor cannot consume the command until released.
18246            std::future::poll_fn(|cx| {
18247                assert!(std::future::Future::poll(restart.as_mut(), cx).is_pending());
18248                std::task::Poll::Ready(())
18249            })
18250            .await;
18251            replies.push(restart);
18252        }
18253        release_tx.send(()).unwrap();
18254        startup.await.unwrap().unwrap();
18255        for reply in replies {
18256            reply.await.unwrap();
18257        }
18258        // Restart schedules its replacement after completing the handler. Wait
18259        // for that separate actor turn before placing the command barrier.
18260        let replacement = tokio::time::timeout(Duration::from_secs(10), async {
18261            loop {
18262                if lock_snapshot(&module.inner.snapshot)
18263                    .unwrap()
18264                    .spawn_generation
18265                    > 1
18266                {
18267                    break;
18268                }
18269                tokio::time::sleep(Duration::from_millis(1)).await;
18270            }
18271        })
18272        .await;
18273        // Commands are handled serially. The update-spec reply proves every
18274        // restart handler has finished before we inspect the snapshot; restart's
18275        // own ACK only acknowledges initiation, not replacement completion.
18276        module.update_spec_for_test(spec).await.unwrap();
18277        let (generation, pid) = {
18278            let state = lock_snapshot(&module.inner.snapshot).unwrap();
18279            (state.spawn_generation, state.pid)
18280        };
18281        module.stop().await.unwrap();
18282        replacement.expect("restart must publish a replacement for the already-serving child");
18283        assert_ne!(
18284            pid,
18285            Some(old_pid),
18286            "a serving child predating the restart must be replaced"
18287        );
18288        assert_eq!(generation, 2, "queued restarts must share one replacement");
18289    }
18290
18291    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
18292    async fn restart_received_after_serving_before_generation_publication_replaces_child() {
18293        restart_before_publication(1).await;
18294    }
18295
18296    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
18297    async fn restart_queued_behind_restart_does_not_kill_its_replacement() {
18298        restart_before_publication(2).await;
18299    }
18300
18301    #[tokio::test]
18302    async fn restart_queued_before_replacement_spawn_keeps_the_new_child() {
18303        let supervisor =
18304            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
18305        let registered = supervisor
18306            .register_configured_with_health(
18307                ModuleSpec {
18308                    script: None,
18309                    module_id: "queued-before-replacement".into(),
18310                    // `/bin/sleep` itself, not `/bin/sh -c "exec sleep"`: on
18311                    // macOS a module whose running image is not the configured
18312                    // program is refused once its exec is confirmed (see
18313                    // `record_write_stall_tests::sleeping_spec`).
18314                    program: "/bin/sleep".into(),
18315                    args: vec!["600".into()],
18316                    env: vec![],
18317                    reserved: false,
18318                    reserved_prefixes: vec![],
18319                    protocol: ModuleProtocol::None,
18320                    overlap: Default::default(),
18321                    carry_containment: false,
18322                },
18323                true,
18324                HealthConfig::default(),
18325                None,
18326                RestartPolicy::default(),
18327                DEFAULT_REGISTER_TIMEOUT,
18328            )
18329            .unwrap();
18330        let RegisteredConfiguredModule {
18331            mut spec,
18332            mut runtime,
18333            module,
18334            mut commands,
18335        } = registered;
18336        let snapshot = &module.inner.snapshot;
18337        let mut restart = Box::pin(module.restart(Some(0)));
18338        std::future::poll_fn(|cx| {
18339            assert!(std::future::Future::poll(restart.as_mut(), cx).is_pending());
18340            std::task::Poll::Ready(())
18341        })
18342        .await;
18343        // Drive the actor explicitly so a replacement is definitely spawned
18344        // after receipt, but before this queued command is dequeued.
18345        let mut child = Some(spawn_and_mark_running(&spec, &runtime, snapshot).unwrap());
18346        let replacement_pid = child.as_ref().unwrap().id();
18347        let command = commands.recv().await.unwrap();
18348        assert!(
18349            handle_supervisor_command(
18350                command,
18351                &mut spec,
18352                &mut runtime,
18353                &supervisor.registry,
18354                &supervisor.process_liveness,
18355                snapshot,
18356                &mut child,
18357                &mut commands,
18358                &mut VecDeque::new(),
18359            )
18360            .await
18361        );
18362        restart.await.unwrap();
18363        let kept_pid = child.as_ref().and_then(SupervisedChild::id);
18364        let pending = lock_snapshot(snapshot).unwrap().respawn_pending;
18365        if let Some(mut child) = child {
18366            child.start_kill().unwrap();
18367            child.wait().await.unwrap();
18368        }
18369        assert_eq!(
18370            kept_pid, replacement_pid,
18371            "a newer replacement must survive"
18372        );
18373        assert!(
18374            !pending,
18375            "a satisfied restart must not schedule another spawn"
18376        );
18377    }
18378}
18379
18380#[cfg(all(test, unix))]
18381mod health_event_tests {
18382    use super::*;
18383    use cortexkit_test_support::ScratchDir;
18384    use subc_protocol::{manifest::Concurrency, session::ModuleControlResponse};
18385
18386    struct Actor {
18387        module: SupervisedModule,
18388        registry: Arc<Registry>,
18389        forwarding: Arc<ForwardingTable>,
18390        spec: ModuleSpec,
18391        health: HealthConfig,
18392        rx: mpsc::Receiver<crate::router::OutboundFrame>,
18393        roster: ChildRoster,
18394        _home: ScratchDir,
18395    }
18396
18397    async fn wait_for<T>(reason: &str, mut observe: impl FnMut() -> Option<T>) -> T {
18398        // OS exec and socket readiness are real I/O. Stay runnable while waiting
18399        // for an observed condition, rather than letting paused time auto-advance
18400        // deadlines or assuming a fixed number of yields finishes the work.
18401        let deadline = std::time::Instant::now() + Duration::from_secs(10);
18402        let tick = Instant::now();
18403        loop {
18404            if let Some(value) = observe() {
18405                assert_eq!(Instant::now(), tick, "{reason} must not wait for a timer");
18406                return value;
18407            }
18408            assert!(
18409                std::time::Instant::now() < deadline,
18410                "timed out waiting for {reason}"
18411            );
18412            tokio::task::yield_now().await;
18413        }
18414    }
18415
18416    impl Actor {
18417        async fn start(protocol: ModuleProtocol, cadence: Duration) -> Self {
18418            Self::start_with_policy(
18419                protocol,
18420                cadence,
18421                DEFAULT_REGISTER_TIMEOUT,
18422                RestartPolicy::new(3, Duration::ZERO),
18423            )
18424            .await
18425        }
18426
18427        async fn start_with_policy(
18428            protocol: ModuleProtocol,
18429            cadence: Duration,
18430            register_timeout: Duration,
18431            policy: RestartPolicy,
18432        ) -> Self {
18433            let home = ScratchDir::new("health-events");
18434            let registry = Arc::new(Registry::default());
18435            let forwarding = Arc::new(ForwardingTable::default());
18436            let health = HealthConfig {
18437                cadence,
18438                deadline: Duration::from_secs(3600),
18439                ..HealthConfig::default()
18440            };
18441            let supervisor = Supervisor::new_for_test(registry.clone(), policy)
18442                .with_forwarding(forwarding.clone())
18443                .with_health_config(health.clone());
18444            let spec = ModuleSpec {
18445                script: None,
18446                module_id: "event-health-child".into(),
18447                // `/bin/sleep` itself, not `/bin/sh -c "exec sleep"`: on macOS
18448                // the privacy trampoline refuses a module whose running image
18449                // is not the configured program, and `start` below waits for
18450                // the process to be confirmed (`reported_pid`). The shell form
18451                // passed only while the image check ran before the shell had
18452                // replaced itself with `sleep` (see
18453                // `record_write_stall_tests::sleeping_spec`).
18454                program: PathBuf::from("/bin/sleep"),
18455                // The process stays alive but has no real bus peer. Registrations
18456                // below exercise the same registry writes as accepted HELLOs.
18457                args: vec!["600".into()],
18458                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
18459                    .into_iter()
18460                    .map(|key| (key.into(), home.path().display().to_string()))
18461                    .collect(),
18462                reserved: false,
18463                reserved_prefixes: vec![],
18464                protocol,
18465                overlap: Default::default(),
18466                carry_containment: false,
18467            };
18468            let module = supervisor
18469                .supervise_configured_requested(
18470                    spec.clone(),
18471                    true,
18472                    health.clone(),
18473                    Some(0),
18474                    policy,
18475                    register_timeout,
18476                    None,
18477                )
18478                .unwrap();
18479            let (_, rx) = mpsc::channel(8);
18480            let actor = Self {
18481                module,
18482                registry,
18483                forwarding,
18484                spec,
18485                health,
18486                rx,
18487                roster: supervisor.child_roster.clone(),
18488                _home: home,
18489            };
18490            actor
18491                .wait_for_select(|checkpoint| checkpoint.generation > 0)
18492                .await;
18493            actor
18494        }
18495
18496        async fn expire_registration_wait(&self, remaining: Duration) {
18497            tokio::time::advance(remaining).await;
18498            wait_for("registration timeout TERM grace", || {
18499                lock_snapshot(&self.module.inner.snapshot)
18500                    .unwrap()
18501                    .actor_select
18502                    .is_none()
18503                    .then_some(())
18504            })
18505            .await;
18506            tokio::time::advance(crate::child_roster::TERM_TO_KILL).await;
18507        }
18508
18509        fn turns(&self) -> u64 {
18510            lock_snapshot(&self.module.inner.snapshot)
18511                .unwrap()
18512                .actor_turns
18513        }
18514
18515        async fn wait_for_select(
18516            &self,
18517            expected: impl Fn(&ActorSelectCheckpoint) -> bool,
18518        ) -> ActorSelectCheckpoint {
18519            wait_for("actor select checkpoint", || {
18520                let state = lock_snapshot(&self.module.inner.snapshot).unwrap();
18521                state.actor_select.filter(|checkpoint| {
18522                    checkpoint.generation == state.spawn_generation
18523                        && state.state == ModuleState::Running
18524                        && state.process_alive
18525                        && state.reported_pid().is_some()
18526                        && expected(checkpoint)
18527                })
18528            })
18529            .await
18530        }
18531
18532        fn hello(&mut self, connection: u64, health: bool) {
18533            let manifest =
18534                subc_protocol::manifest::ModuleManifest::builder(&self.spec.module_id, "1.0.0")
18535                    .protocol_ver(subc_protocol::PROTOCOL_VERSION)
18536                    .build();
18537            let connection = ConnectionId::new(connection);
18538            let (tx, rx) = mpsc::channel(8);
18539            self.rx = rx;
18540            self.forwarding
18541                .register_module_connection(
18542                    connection,
18543                    self.spec.module_id.clone(),
18544                    subc_protocol::PROTOCOL_VERSION,
18545                    Concurrency::ModuleManaged,
18546                    FrameSink::new(tx),
18547                )
18548                .unwrap();
18549            self.registry
18550                .register_with_control_ops(
18551                    manifest,
18552                    subc_protocol::PROTOCOL_VERSION,
18553                    connection,
18554                    if health {
18555                        vec![MODULE_CONTROL_OP_HEALTH_CHECK.into()]
18556                    } else {
18557                        vec![]
18558                    },
18559                )
18560                .unwrap();
18561        }
18562
18563        async fn probe(&mut self) -> crate::router::OutboundFrame {
18564            let frame = wait_for("outbound health probe", || match self.rx.try_recv() {
18565                Ok(frame) => Some(frame),
18566                Err(mpsc::error::TryRecvError::Empty) => None,
18567                Err(mpsc::error::TryRecvError::Disconnected) => panic!("health peer disconnected"),
18568            })
18569            .await;
18570            let body: Value = serde_json::from_slice(&frame.body).unwrap();
18571            assert_eq!(body["op"], MODULE_CONTROL_OP_HEALTH_CHECK);
18572            frame
18573        }
18574
18575        fn no_probe(&mut self) {
18576            assert!(matches!(
18577                self.rx.try_recv(),
18578                Err(mpsc::error::TryRecvError::Empty)
18579            ));
18580        }
18581
18582        fn answer(&self, connection: u64, frame: crate::router::OutboundFrame) {
18583            self.forwarding
18584                .complete_module_control_rpc(
18585                    ConnectionId::new(connection),
18586                    frame.header.corr,
18587                    Some(MODULE_CONTROL_OP_HEALTH_CHECK),
18588                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
18589                        status: HealthStatus::Ok,
18590                        detail: None,
18591                        metrics: None,
18592                    }),
18593                )
18594                .unwrap();
18595        }
18596    }
18597
18598    #[tokio::test(start_paused = true)]
18599    async fn registration_timeout_kills_at_120_seconds_and_respawns() {
18600        let actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18601        let initial = actor.module.status().unwrap();
18602        tokio::time::advance(Duration::from_secs(119)).await;
18603        tokio::task::yield_now().await;
18604        assert_eq!(actor.module.status().unwrap().pid, initial.pid);
18605        assert!(actor.module.terminal_history().entries.is_empty());
18606        actor.expire_registration_wait(Duration::from_secs(1)).await;
18607        actor
18608            .wait_for_select(|at| at.generation > initial.spawn_generation)
18609            .await;
18610        let status = actor.module.status().unwrap();
18611        assert_ne!(status.pid, initial.pid);
18612        assert!(!cortexkit_test_support::process_alive(
18613            initial.pid.unwrap() as i32
18614        ));
18615        assert_eq!(status.restart_count, 1);
18616        assert_eq!(status.last_exit.unwrap().kind, ExitKind::Crash);
18617        let entries = actor.module.terminal_history().entries;
18618        assert_eq!(entries.len(), 1);
18619        assert_eq!(
18620            entries[0].disposition_detail.as_deref(),
18621            Some("registration_timeout")
18622        );
18623        actor.module.stop().await.unwrap();
18624    }
18625
18626    #[tokio::test(start_paused = true)]
18627    async fn registration_timeout_is_cancelled_by_hello_at_119_seconds() {
18628        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18629        let pid = actor.module.status().unwrap().pid;
18630        tokio::time::advance(Duration::from_secs(119)).await;
18631        actor.hello(1, false);
18632        let registered = actor
18633            .wait_for_select(|at| at.registered_connection.is_some())
18634            .await;
18635        assert_eq!(
18636            registered.wake_after, None,
18637            "HELLO must cancel the deadline"
18638        );
18639        tokio::time::advance(Duration::from_secs(300)).await;
18640        tokio::task::yield_now().await;
18641        assert_eq!(actor.module.status().unwrap().pid, pid);
18642        assert!(actor.module.terminal_history().entries.is_empty());
18643        // A disconnect after the first HELLO must not re-arm a startup timer.
18644        actor
18645            .registry
18646            .deregister_connection(ConnectionId::new(1))
18647            .unwrap();
18648        actor
18649            .wait_for_select(|at| at.registered_connection.is_none())
18650            .await;
18651        tokio::time::advance(Duration::from_secs(300)).await;
18652        tokio::task::yield_now().await;
18653        assert_eq!(actor.module.status().unwrap().pid, pid);
18654        assert!(actor.module.terminal_history().entries.is_empty());
18655        actor.module.stop().await.unwrap();
18656
18657        let mut transient = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18658        let pid = transient.module.status().unwrap().pid;
18659        tokio::time::advance(Duration::from_secs(119)).await;
18660        let turns = transient.turns();
18661        // Both writes happen before the supervisor can refresh the registry.
18662        // An accepted HELLO must remain evidence after its connection is gone.
18663        transient.hello(1, false);
18664        transient
18665            .registry
18666            .deregister_connection(ConnectionId::new(1))
18667            .unwrap();
18668        let parked = transient.wait_for_select(|at| at.turn > turns).await;
18669        assert_eq!(
18670            parked.wake_after, None,
18671            "transient HELLO must cancel the deadline"
18672        );
18673        tokio::time::advance(Duration::from_secs(300)).await;
18674        tokio::task::yield_now().await;
18675        assert_eq!(transient.module.status().unwrap().pid, pid);
18676        assert!(transient.module.terminal_history().entries.is_empty());
18677        transient.module.stop().await.unwrap();
18678    }
18679
18680    #[tokio::test(start_paused = true)]
18681    async fn registration_timeouts_exhaust_budget_and_schedule_slow_retry() {
18682        let actor = Actor::start_with_policy(
18683            ModuleProtocol::Subc,
18684            Duration::from_secs(30),
18685            Duration::from_secs(10),
18686            RestartPolicy::new(1, Duration::ZERO),
18687        )
18688        .await;
18689        let generation = actor.module.status().unwrap().spawn_generation;
18690        actor
18691            .expire_registration_wait(Duration::from_secs(10))
18692            .await;
18693        actor.wait_for_select(|at| at.generation > generation).await;
18694        actor
18695            .expire_registration_wait(Duration::from_secs(10))
18696            .await;
18697        let retry = wait_for("failed retry schedule", || {
18698            let state = lock_snapshot(&actor.module.inner.snapshot).unwrap();
18699            (state.state == ModuleState::Failed)
18700                .then_some(state.failed_retry.pending)
18701                .flatten()
18702        })
18703        .await;
18704        assert_eq!(retry.delay, Duration::from_secs(600));
18705        assert_eq!(retry.attempt, 1);
18706        let entries = actor.module.terminal_history().entries;
18707        assert_eq!(entries.len(), 2);
18708        assert_eq!(entries[1].disposition, TerminalDisposition::Failed);
18709        assert!(entries[1]
18710            .disposition_detail
18711            .as_deref()
18712            .unwrap()
18713            .contains("registration_timeout"));
18714        tokio::time::advance(Duration::from_secs(599)).await;
18715        tokio::task::yield_now().await;
18716        assert_eq!(actor.module.state().unwrap(), ModuleState::Failed);
18717        tokio::time::advance(Duration::from_secs(1)).await;
18718        actor
18719            .wait_for_select(|at| at.generation > generation + 1)
18720            .await;
18721        // The slow retry is another ordinary spawn, with its own HELLO budget.
18722        actor
18723            .expire_registration_wait(Duration::from_secs(10))
18724            .await;
18725        wait_for("slow retry registration timeout", || {
18726            (actor.module.terminal_history().entries.len() == 3).then_some(())
18727        })
18728        .await;
18729        actor.module.stop().await.unwrap();
18730    }
18731
18732    #[tokio::test(start_paused = true)]
18733    async fn registration_timeout_honours_ten_second_override() {
18734        let actor = Actor::start_with_policy(
18735            ModuleProtocol::Subc,
18736            Duration::from_secs(30),
18737            Duration::from_secs(10),
18738            RestartPolicy::new(3, Duration::ZERO),
18739        )
18740        .await;
18741        let generation = actor.module.status().unwrap().spawn_generation;
18742        tokio::time::advance(Duration::from_secs(9)).await;
18743        tokio::task::yield_now().await;
18744        assert!(actor.module.terminal_history().entries.is_empty());
18745        actor.expire_registration_wait(Duration::from_secs(1)).await;
18746        actor.wait_for_select(|at| at.generation > generation).await;
18747        assert_eq!(actor.module.terminal_history().entries.len(), 1);
18748        actor.module.stop().await.unwrap();
18749    }
18750
18751    #[tokio::test]
18752    async fn registration_timeout_kills_term_ignoring_helper_before_reaping_leader() {
18753        use std::os::unix::process::{CommandExt, ExitStatusExt};
18754
18755        struct Helper(std::process::Child);
18756        impl Drop for Helper {
18757            fn drop(&mut self) {
18758                // This handle still owns the helper until wait returns. Never
18759                // clean up its old process group after the leader is reaped.
18760                if matches!(self.0.try_wait(), Ok(None)) {
18761                    let _ = self.0.kill();
18762                    let _ = self.0.wait();
18763                }
18764            }
18765        }
18766
18767        let home = ScratchDir::new("registration-timeout-helper");
18768        let supervisor = Supervisor::new_for_test(
18769            Arc::new(Registry::default()),
18770            RestartPolicy::new(0, Duration::ZERO),
18771        );
18772        let spec = ModuleSpec {
18773            script: None,
18774            module_id: "registration-timeout-group".into(),
18775            program: "/bin/sleep".into(),
18776            args: vec!["120".into()],
18777            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
18778                .into_iter()
18779                .map(|key| (key.into(), home.path().display().to_string()))
18780                .collect(),
18781            reserved: false,
18782            reserved_prefixes: vec![],
18783            protocol: ModuleProtocol::Subc,
18784            overlap: Default::default(),
18785            carry_containment: false,
18786        };
18787        let module = supervisor
18788            .supervise_configured_requested(
18789                spec,
18790                true,
18791                HealthConfig::default(),
18792                None,
18793                RestartPolicy::new(0, Duration::ZERO),
18794                Duration::from_secs(10),
18795                None,
18796            )
18797            .unwrap();
18798        let leader = timeout(Duration::from_secs(5), async {
18799            loop {
18800                if let Some(pid) = module.status().unwrap().pid {
18801                    break pid;
18802                }
18803                sleep(Duration::from_millis(5)).await;
18804            }
18805        })
18806        .await
18807        .expect("supervised group leader must be reported before the deadline");
18808        assert!(leader > 1);
18809        let ready = home.join("helper.ready");
18810        // Own the helper separately so even a broken group kill can be cleaned
18811        // up by its own unreaped child handle, without signalling a stale pgid.
18812        let mut helper = Helper(
18813            std::process::Command::new("/bin/sh")
18814                .args([
18815                    "-c",
18816                    "trap '' TERM; : > \"$1\"; exec /bin/sleep 120",
18817                    "helper",
18818                ])
18819                .arg(&ready)
18820                .process_group(i32::try_from(leader).unwrap())
18821                .stdout(std::process::Stdio::null())
18822                .stderr(std::process::Stdio::null())
18823                .spawn()
18824                .unwrap(),
18825        );
18826        timeout(Duration::from_secs(5), async {
18827            while !ready.exists() {
18828                assert!(helper.0.try_wait().unwrap().is_none());
18829                sleep(Duration::from_millis(5)).await;
18830            }
18831        })
18832        .await
18833        .expect("helper must install TERM ignore before the registration deadline");
18834        let helper_pid =
18835            rustix::process::Pid::from_raw(i32::try_from(helper.0.id()).unwrap()).unwrap();
18836        rustix::process::kill_process(helper_pid, rustix::process::Signal::TERM).unwrap();
18837        sleep(Duration::from_millis(20)).await;
18838        assert!(
18839            helper.0.try_wait().unwrap().is_none(),
18840            "helper must ignore TERM"
18841        );
18842
18843        timeout(Duration::from_secs(20), async {
18844            while module.state().unwrap() != ModuleState::Failed {
18845                sleep(Duration::from_millis(5)).await;
18846            }
18847        })
18848        .await
18849        .expect("registration timeout must stop and reap the group leader");
18850        let helper_exit = timeout(Duration::from_secs(3), async {
18851            loop {
18852                if let Some(status) = helper.0.try_wait().unwrap() {
18853                    break status;
18854                }
18855                sleep(Duration::from_millis(5)).await;
18856            }
18857        })
18858        .await
18859        .expect("TERM-ignoring helper survived the registration timeout's group KILL");
18860        assert_eq!(helper_exit.signal(), Some(9));
18861        assert!(!cortexkit_test_support::process_alive(
18862            i32::try_from(leader).unwrap()
18863        ));
18864        assert_eq!(
18865            module.status().unwrap().last_exit.unwrap().kind,
18866            ExitKind::Crash
18867        );
18868        assert!(module.terminal_history().entries[0]
18869            .disposition_detail
18870            .as_deref()
18871            .unwrap()
18872            .contains("registration_timeout"));
18873        module.stop().await.unwrap();
18874    }
18875
18876    #[tokio::test(start_paused = true)]
18877    async fn registration_timeout_does_not_count_an_earlier_exit() {
18878        let actor = Actor::start_with_policy(
18879            ModuleProtocol::Subc,
18880            Duration::from_secs(30),
18881            DEFAULT_REGISTER_TIMEOUT,
18882            RestartPolicy::new(0, Duration::ZERO),
18883        )
18884        .await;
18885        let pid = actor.module.status().unwrap().pid.unwrap();
18886        rustix::process::kill_process(
18887            rustix::process::Pid::from_raw(pid as i32).unwrap(),
18888            rustix::process::Signal::TERM,
18889        )
18890        .unwrap();
18891        wait_for("early exit", || {
18892            (actor.module.state().unwrap() == ModuleState::Failed).then_some(())
18893        })
18894        .await;
18895        tokio::time::advance(Duration::from_secs(121)).await;
18896        tokio::task::yield_now().await;
18897        let entries = actor.module.terminal_history().entries;
18898        assert_eq!(entries.len(), 1);
18899        assert!(!entries[0]
18900            .disposition_detail
18901            .as_deref()
18902            .unwrap()
18903            .contains("registration_timeout"));
18904        assert_eq!(actor.module.status().unwrap().lifetime_restarts, 0);
18905        actor.module.stop().await.unwrap();
18906    }
18907
18908    #[tokio::test(start_paused = true)]
18909    async fn registration_timeout_is_cancelled_by_daemon_shutdown() {
18910        let actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18911        let pid = actor.module.status().unwrap().pid;
18912        tokio::time::advance(Duration::from_secs(119)).await;
18913        actor.roster.close();
18914        let turns = actor.turns();
18915        tokio::time::advance(Duration::from_secs(300)).await;
18916        let parked = actor.wait_for_select(|at| at.turn > turns).await;
18917        assert_eq!(parked.wake_after, None);
18918        assert_eq!(actor.module.status().unwrap().pid, pid);
18919        assert!(actor.module.terminal_history().entries.is_empty());
18920        actor.module.stop().await.unwrap();
18921        let status = actor.module.status().unwrap();
18922        assert_eq!(status.restart_count, 0);
18923        assert_eq!(
18924            actor.module.terminal_history().entries[0].disposition,
18925            TerminalDisposition::DaemonShutdown
18926        );
18927    }
18928
18929    #[tokio::test(start_paused = true)]
18930    async fn no_health_children_park_for_sixty_seconds() {
18931        let none = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
18932        let unregistered = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18933        let mut unadvertised = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18934        unadvertised.hello(1, false);
18935        // Include any one-off registration wake in the budget; receiving a
18936        // no-health HELLO must not turn a parked child into a polling child.
18937        // Advance in 10 ms steps so the old poll really executes ~6,000 turns;
18938        // a single 60 s jump would only observe one expired timer.
18939        for _ in 0..6000 {
18940            tokio::time::advance(Duration::from_millis(10)).await;
18941            tokio::task::yield_now().await;
18942        }
18943        for actor in [&none, &unregistered, &unadvertised] {
18944            assert!(
18945                actor.turns() <= 5,
18946                "no-health actor woke {} times",
18947                actor.turns()
18948            );
18949            assert_eq!(actor.module.state().unwrap(), ModuleState::Running);
18950        }
18951    }
18952
18953    #[tokio::test(start_paused = true)]
18954    async fn late_hello_starts_a_due_probe_in_the_notification_tick() {
18955        // With a zero cadence the first probe is due at once, so this measures
18956        // only how fast the registration notification starts health probing,
18957        // not the normal 30-33 s wait before a first probe (checked below).
18958        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::ZERO).await;
18959        let tick = Instant::now();
18960        actor.hello(1, true);
18961        actor.probe().await;
18962        assert_eq!(Instant::now(), tick, "HELLO must not wait for a poll");
18963    }
18964
18965    #[tokio::test(start_paused = true)]
18966    async fn hello_keeps_the_jittered_cadence_and_catalog_updates_do_not_reset_it() {
18967        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18968        let hello_tick = Instant::now();
18969        actor.hello(1, true);
18970        let armed = actor
18971            .wait_for_select(|checkpoint| {
18972                checkpoint.registered_connection == Some(ConnectionId::new(1))
18973                    && checkpoint.next_probe_at.is_some()
18974            })
18975            .await;
18976        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18977        assert!((Duration::from_secs(30)..Duration::from_secs(33)).contains(&delay));
18978        let first_deadline = hello_tick + delay;
18979        assert_eq!(armed.next_probe_at, Some(first_deadline));
18980        tokio::time::advance(Duration::from_secs(29)).await;
18981        let turns = actor.turns();
18982        actor
18983            .registry
18984            .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
18985            .unwrap();
18986        let updated = actor
18987            .wait_for_select(|checkpoint| checkpoint.turn > turns)
18988            .await;
18989        assert_eq!(
18990            updated.next_probe_at,
18991            Some(first_deadline),
18992            "catalog update must not reset cadence"
18993        );
18994        actor.no_probe();
18995        tokio::time::advance(first_deadline - Instant::now()).await;
18996        let frame = actor.probe().await;
18997        actor.answer(1, frame);
18998        let next = jittered_health_delay(&actor.spec.module_id, 1, actor.health.cadence);
18999        let next_deadline = Instant::now() + next;
19000        let rearmed = actor
19001            .wait_for_select(|checkpoint| {
19002                checkpoint
19003                    .next_probe_at
19004                    .is_some_and(|deadline| deadline > first_deadline)
19005            })
19006            .await;
19007        assert_eq!(rearmed.next_probe_at, Some(next_deadline));
19008        tokio::time::advance(next - Duration::from_nanos(1)).await;
19009        actor.no_probe();
19010        tokio::time::advance(Duration::from_nanos(1)).await;
19011        actor.probe().await;
19012    }
19013
19014    #[tokio::test(start_paused = true)]
19015    async fn disconnect_disarms_and_reconnect_rearms_health() {
19016        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
19017        actor.hello(1, true);
19018        actor
19019            .wait_for_select(|checkpoint| {
19020                checkpoint.registered_connection == Some(ConnectionId::new(1))
19021                    && checkpoint.next_probe_at.is_some()
19022            })
19023            .await;
19024        let turns = actor.turns();
19025        let tick = Instant::now();
19026        actor
19027            .registry
19028            .deregister_connection(ConnectionId::new(1))
19029            .unwrap();
19030        let disarmed = actor
19031            .wait_for_select(|checkpoint| {
19032                checkpoint.turn > turns && checkpoint.registered_connection.is_none()
19033            })
19034            .await;
19035        assert_eq!(disarmed.next_probe_at, None);
19036        assert_eq!(disarmed.wake_after, None);
19037        assert_eq!(
19038            Instant::now(),
19039            tick,
19040            "disconnect must disarm in the notification tick"
19041        );
19042        tokio::time::advance(Duration::from_secs(60)).await;
19043        actor.no_probe();
19044        let reconnect_tick = Instant::now();
19045        actor.hello(2, true);
19046        let rearmed = actor
19047            .wait_for_select(|checkpoint| {
19048                checkpoint.registered_connection == Some(ConnectionId::new(2))
19049                    && checkpoint.next_probe_at.is_some()
19050            })
19051            .await;
19052        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
19053        assert_eq!(rearmed.next_probe_at, Some(reconnect_tick + delay));
19054        tokio::time::advance(delay).await;
19055        actor.probe().await;
19056    }
19057
19058    #[tokio::test(start_paused = true)]
19059    async fn reregistration_without_health_disarms_the_old_schedule() {
19060        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
19061        actor.hello(1, true);
19062        actor
19063            .wait_for_select(|checkpoint| {
19064                checkpoint.registered_connection == Some(ConnectionId::new(1))
19065                    && checkpoint.next_probe_at.is_some()
19066            })
19067            .await;
19068        actor
19069            .registry
19070            .deregister_connection(ConnectionId::new(1))
19071            .unwrap();
19072        actor.hello(2, false);
19073        let disarmed = actor
19074            .wait_for_select(|checkpoint| {
19075                checkpoint.registered_connection == Some(ConnectionId::new(2))
19076            })
19077            .await;
19078        assert_eq!(disarmed.next_probe_at, None);
19079        assert_eq!(disarmed.wake_after, None);
19080        tokio::time::advance(Duration::from_secs(60)).await;
19081        actor.no_probe();
19082    }
19083
19084    #[tokio::test(start_paused = true)]
19085    async fn restart_waits_for_its_own_hello_before_rearming_health() {
19086        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
19087        actor.hello(1, true);
19088        let armed = actor
19089            .wait_for_select(|checkpoint| {
19090                checkpoint.registered_connection == Some(ConnectionId::new(1))
19091                    && checkpoint.next_probe_at.is_some()
19092            })
19093            .await;
19094        // Simulate the old process's connection closing before the restart
19095        // tears the process down. The replacement process has started but has
19096        // not sent its HELLO, so it is not registered.
19097        actor
19098            .registry
19099            .deregister_connection(ConnectionId::new(1))
19100            .unwrap();
19101        actor.module.restart(Some(0)).await.unwrap();
19102        let parked = actor
19103            .wait_for_select(|checkpoint| {
19104                checkpoint.generation > armed.generation
19105                    && checkpoint.registered_connection.is_none()
19106                    && checkpoint.next_probe_at.is_none()
19107            })
19108            .await;
19109        assert_eq!(parked.wake_after, Some(DEFAULT_REGISTER_TIMEOUT));
19110        actor.rx.close();
19111        // Drain the stop notice the restart queued for the old process's connection,
19112        // so it isn't mistaken for traffic to the replacement.
19113        while actor.rx.try_recv().is_ok() {}
19114        let turns = actor.turns();
19115        tokio::time::advance(Duration::from_secs(60)).await;
19116        let after = actor.turns();
19117        eprintln!(
19118            "restart park turns: before={turns} after={after} delta={}",
19119            after - turns
19120        );
19121        assert_eq!(after, turns, "replacement must park before HELLO");
19122        let hello_tick = Instant::now();
19123        actor.hello(2, true);
19124        let rearmed = actor
19125            .wait_for_select(|checkpoint| {
19126                checkpoint.registered_connection == Some(ConnectionId::new(2))
19127                    && checkpoint.next_probe_at.is_some()
19128            })
19129            .await;
19130        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
19131        assert_eq!(rearmed.next_probe_at, Some(hello_tick + delay));
19132        tokio::time::advance(delay).await;
19133        actor.probe().await;
19134    }
19135
19136    #[tokio::test(start_paused = true)]
19137    async fn http_probe_waits_a_full_cadence_for_each_spawn() {
19138        use tokio::{
19139            io::{AsyncReadExt, AsyncWriteExt},
19140            net::TcpListener,
19141        };
19142        let mut actor = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
19143        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
19144        actor.health.http = Some(format!("http://{}/healthz", listener.local_addr().unwrap()));
19145        let (started_tx, mut started_rx) = mpsc::channel(8);
19146        let peer = tokio::spawn(async move {
19147            loop {
19148                let (mut socket, _) = listener.accept().await.unwrap();
19149                let mut request = [0; 1024];
19150                assert!(socket.read(&mut request).await.unwrap() > 0);
19151                started_tx.send(Instant::now()).await.unwrap();
19152                socket
19153                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
19154                    .await
19155                    .unwrap();
19156            }
19157        });
19158        actor
19159            .module
19160            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
19161            .await
19162            .unwrap();
19163        let first_tick = Instant::now();
19164        let first = actor
19165            .wait_for_select(|checkpoint| checkpoint.next_probe_at.is_some())
19166            .await;
19167        assert!(first.next_probe_at.unwrap() >= first_tick + actor.health.cadence);
19168        assert!(started_rx.try_recv().is_err());
19169
19170        // Restart just before the old deadline: reusing it would give the new
19171        // process only one second to start, rather than a full cadence.
19172        tokio::time::advance(
19173            first.next_probe_at.unwrap() - Instant::now() - Duration::from_secs(1),
19174        )
19175        .await;
19176        actor.module.restart(Some(0)).await.unwrap();
19177        let spawn_tick = Instant::now();
19178        let replacement = actor
19179            .wait_for_select(|checkpoint| checkpoint.generation > first.generation)
19180            .await;
19181        let deadline = replacement.next_probe_at.unwrap();
19182        assert!(
19183            deadline >= spawn_tick + actor.health.cadence,
19184            "a replacement must not inherit its predecessor's probe deadline"
19185        );
19186        tokio::time::advance(actor.health.cadence - Duration::from_nanos(1)).await;
19187        assert!(
19188            started_rx.try_recv().is_err(),
19189            "no HTTP probe during startup grace"
19190        );
19191        tokio::time::advance(deadline - Instant::now()).await;
19192        let landed = wait_for("first replacement HTTP probe", || {
19193            started_rx.try_recv().ok()
19194        })
19195        .await;
19196        assert!(landed >= spawn_tick + actor.health.cadence);
19197        wait_for("healthy replacement", || {
19198            (actor.module.status().unwrap().health.status == SupervisorHealthStatus::Ok)
19199                .then_some(())
19200        })
19201        .await;
19202        peer.abort();
19203    }
19204
19205    #[tokio::test(start_paused = true)]
19206    async fn rescan_adds_and_removes_http_health_without_polling() {
19207        use tokio::{
19208            io::{AsyncReadExt, AsyncWriteExt},
19209            net::TcpListener,
19210        };
19211        let mut actor = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
19212        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
19213        actor.health.http = Some(format!("http://{}/health", listener.local_addr().unwrap()));
19214        // One millisecond separates successive probes without a polling delay.
19215        actor.health.cadence = Duration::from_millis(1);
19216        let (started_tx, mut started_rx) = mpsc::channel(8);
19217        let peer = tokio::spawn(async move {
19218            loop {
19219                let (mut socket, _) = listener.accept().await.unwrap();
19220                let mut request = [0; 1024];
19221                assert!(socket.read(&mut request).await.unwrap() > 0);
19222                started_tx.send(()).await.unwrap();
19223                socket
19224                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
19225                    .await
19226                    .unwrap();
19227            }
19228        });
19229        let tick = Instant::now();
19230        let turns = actor.turns();
19231        actor
19232            .module
19233            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
19234            .await
19235            .unwrap();
19236        let armed = actor
19237            .wait_for_select(|checkpoint| {
19238                checkpoint.turn > turns && checkpoint.next_probe_at.is_some()
19239            })
19240            .await;
19241        assert_eq!(armed.next_probe_at, Some(tick + Duration::from_millis(1)));
19242        assert_eq!(Instant::now(), tick);
19243        tokio::time::advance(Duration::from_millis(1)).await;
19244        let mut started = false;
19245        wait_for("successful HTTP probe", || {
19246            started |= started_rx.try_recv().is_ok();
19247            (started && actor.module.status().unwrap().health.status == SupervisorHealthStatus::Ok)
19248                .then_some(())
19249        })
19250        .await;
19251        assert!(started, "added HTTP check must start at its first deadline");
19252        assert_eq!(
19253            actor.module.status().unwrap().health.status,
19254            SupervisorHealthStatus::Ok
19255        );
19256        assert_eq!(Instant::now(), tick + Duration::from_millis(1));
19257        actor.health.http = None;
19258        let turns = actor.turns();
19259        actor
19260            .module
19261            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
19262            .await
19263            .unwrap();
19264        let parked = actor
19265            .wait_for_select(|checkpoint| {
19266                checkpoint.turn > turns && checkpoint.next_probe_at.is_none()
19267            })
19268            .await;
19269        assert_eq!(parked.wake_after, None);
19270        let turns = actor.turns();
19271        tokio::time::advance(Duration::from_secs(60)).await;
19272        assert_eq!(
19273            actor.turns(),
19274            turns,
19275            "removed HTTP check must park the actor"
19276        );
19277        assert!(
19278            started_rx.try_recv().is_err(),
19279            "removed HTTP check must stay disarmed"
19280        );
19281        assert_eq!(
19282            actor.module.status().unwrap().health,
19283            ModuleHealthStatus::default()
19284        );
19285        peer.abort();
19286    }
19287}
19288
19289#[cfg(test)]
19290mod drain_busy_reprobe_tests {
19291    //! The drain's busy-gauge wait, driven against an in-process module
19292    //! connection whose health answers the test scripts. Time is paused, so
19293    //! every elapsed duration below is exact virtual time.
19294    use super::*;
19295    use std::collections::BTreeMap;
19296    use std::sync::Mutex as StdMutex;
19297    use subc_protocol::{manifest::Concurrency, session::ModuleControlResponse};
19298
19299    const MODULE_ID: &str = "drain-reprobe-module";
19300    const CONNECTION: u64 = 7;
19301    const GAUGE: &str = "runs_in_flight";
19302    /// The production default for both the health cadence and the drain
19303    /// ceiling, which is the pairing that used to cost a full ceiling.
19304    const CADENCE: Duration = Duration::from_secs(30);
19305    const CEILING: Duration = Duration::from_secs(30);
19306
19307    /// How the scripted module answers each `health.check`.
19308    #[derive(Clone, Copy)]
19309    enum Answer {
19310        /// Report the gauge busy until this instant, quiet from then on, after
19311        /// taking `latency` to answer.
19312        BusyUntil { until: Instant, latency: Duration },
19313        /// Answer at once, with metrics that leave the declared gauge out.
19314        OmitsGauge,
19315        /// Never answer.
19316        Silent,
19317    }
19318
19319    struct Drain {
19320        forwarding: Arc<ForwardingTable>,
19321        runtime: SupervisorRuntimeConfig,
19322        endpoint: crate::ModuleEndpointId,
19323        /// When each probe reached the module.
19324        probes: Arc<StdMutex<Vec<Instant>>>,
19325        responder: tokio::task::JoinHandle<()>,
19326    }
19327
19328    impl Drain {
19329        fn start(answer: Answer) -> Self {
19330            let registry = Arc::new(Registry::default());
19331            let forwarding = Arc::new(ForwardingTable::default());
19332            let health = HealthConfig {
19333                cadence: CADENCE,
19334                ..HealthConfig::default()
19335            };
19336            let runtime = Supervisor::new_for_test(registry, RestartPolicy::new(3, Duration::ZERO))
19337                .with_forwarding(forwarding.clone())
19338                .with_health_config(health)
19339                .runtime_config();
19340            let (tx, mut rx) = mpsc::channel::<crate::router::OutboundFrame>(8);
19341            let endpoint = forwarding
19342                .register_module_connection(
19343                    ConnectionId::new(CONNECTION),
19344                    MODULE_ID.to_string(),
19345                    subc_protocol::PROTOCOL_VERSION,
19346                    Concurrency::ModuleManaged,
19347                    FrameSink::new(tx),
19348                )
19349                .unwrap();
19350            let probes = Arc::new(StdMutex::new(Vec::new()));
19351            let responder = tokio::spawn({
19352                let forwarding = forwarding.clone();
19353                let probes = probes.clone();
19354                async move {
19355                    while let Some(frame) = rx.recv().await {
19356                        let body: Value = serde_json::from_slice(&frame.body).unwrap();
19357                        assert_eq!(body["op"], MODULE_CONTROL_OP_HEALTH_CHECK);
19358                        probes.lock().unwrap().push(Instant::now());
19359                        let metrics = match answer {
19360                            Answer::BusyUntil { until, latency } => {
19361                                sleep(latency).await;
19362                                let busy = u64::from(Instant::now() < until);
19363                                serde_json::json!({ GAUGE: busy })
19364                            }
19365                            Answer::OmitsGauge => serde_json::json!({ "queue_depth": 0 }),
19366                            Answer::Silent => continue,
19367                        };
19368                        // A probe abandoned at its deadline has no RPC left to
19369                        // complete, so a late answer may be refused.
19370                        let _ = forwarding.complete_module_control_rpc(
19371                            ConnectionId::new(CONNECTION),
19372                            frame.header.corr,
19373                            Some(MODULE_CONTROL_OP_HEALTH_CHECK),
19374                            ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19375                                status: HealthStatus::Ok,
19376                                detail: None,
19377                                metrics: Some(metrics),
19378                            }),
19379                        );
19380                    }
19381                }
19382            });
19383            Self {
19384                forwarding,
19385                runtime,
19386                endpoint,
19387                probes,
19388                responder,
19389            }
19390        }
19391
19392        /// Run one by-id drain wait with `ceiling`, returning its verdict and
19393        /// how long it took.
19394        async fn run(&self, ceiling: Duration) -> (bool, Duration) {
19395            let (drained, elapsed, _) = self.run_traced(ceiling).await;
19396            (drained, elapsed)
19397        }
19398
19399        /// [`Self::run`], also returning what the drain's probes read.
19400        async fn run_traced(&self, ceiling: Duration) -> (bool, Duration, DrainGaugeTrace) {
19401            let started = Instant::now();
19402            let mut trace = DrainGaugeTrace::new(&[GAUGE.to_string()]);
19403            let drained = wait_for_forwarding_quiescence(
19404                &self.forwarding,
19405                MODULE_ID,
19406                &self.runtime,
19407                self.endpoint,
19408                started + ceiling,
19409                &[GAUGE.to_string()],
19410                DrainScope::Active,
19411                &mut trace,
19412            )
19413            .await
19414            .unwrap();
19415            (drained, started.elapsed(), trace)
19416        }
19417
19418        fn probes(&self) -> Vec<Instant> {
19419            self.probes.lock().unwrap().clone()
19420        }
19421    }
19422
19423    impl Drop for Drain {
19424        fn drop(&mut self) {
19425            self.responder.abort();
19426        }
19427    }
19428
19429    #[tokio::test(start_paused = true)]
19430    async fn busy_at_first_probe_then_quiet_drains_long_before_the_ceiling() {
19431        let drain = Drain::start(Answer::BusyUntil {
19432            until: Instant::now() + Duration::from_secs(1),
19433            latency: Duration::ZERO,
19434        });
19435        let (drained, elapsed) = drain.run(CEILING).await;
19436        assert!(
19437            drained,
19438            "gauges that read zero during the drain must let it finish drained, \
19439             not wait out the {CADENCE:?} health cadence (elapsed {elapsed:?})"
19440        );
19441        assert!(
19442            elapsed < Duration::from_secs(3),
19443            "drain took {elapsed:?} after the gauges went quiet at 1s"
19444        );
19445        let probes = drain.probes();
19446        assert!(
19447            probes.len() >= 2,
19448            "the module was busy at the first probe, so a quiet verdict needs a second: {probes:?}"
19449        );
19450    }
19451
19452    /// The same shape in real time on a multi-threaded runtime: the first
19453    /// probe is answered busy at once, within a millisecond of the drain
19454    /// starting, and later probes read idle. The drain must keep probing
19455    /// after that first instant answer and end soon after the gauge falls.
19456    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
19457    async fn an_instant_busy_first_answer_does_not_stop_later_probes_in_real_time() {
19458        let drain = Drain::start(Answer::BusyUntil {
19459            until: Instant::now() + Duration::from_millis(600),
19460            latency: Duration::ZERO,
19461        });
19462        let (drained, elapsed, trace) = drain.run_traced(CEILING).await;
19463        assert!(drained, "the gauge fell at 600ms: {trace}");
19464        assert!(
19465            elapsed < Duration::from_secs(3),
19466            "drain took {elapsed:?} after the gauge fell at 600ms: {trace}"
19467        );
19468        let probes = drain.probes();
19469        assert!(
19470            probes.len() >= 2 && trace.probes as usize == probes.len(),
19471            "the drain must re-probe after the first busy answer: {probes:?}, {trace}"
19472        );
19473    }
19474
19475    #[tokio::test(start_paused = true)]
19476    async fn busy_throughout_ends_undrained_at_the_ceiling_with_bounded_probes() {
19477        let started = Instant::now();
19478        let drain = Drain::start(Answer::BusyUntil {
19479            until: started + Duration::from_secs(3600),
19480            latency: Duration::ZERO,
19481        });
19482        let (drained, elapsed) = drain.run(CEILING).await;
19483        assert!(!drained, "a module busy throughout must not drain");
19484        assert!(
19485            elapsed >= CEILING && elapsed < CEILING + drain_busy_reprobe_interval(),
19486            "a busy module is held until the ceiling and no longer: {elapsed:?}"
19487        );
19488        // Re-probing is paced by the interval, not a busy loop: at most one
19489        // probe per interval across the ceiling, plus the first at time zero.
19490        let probes = drain.probes();
19491        let max_probes = (CEILING.as_millis() / drain_busy_reprobe_interval().as_millis()) + 1;
19492        assert!(
19493            probes.len() as u128 <= max_probes,
19494            "{} probes in a {CEILING:?} drain exceeds the {max_probes} the interval allows",
19495            probes.len()
19496        );
19497        for pair in probes.windows(2) {
19498            assert!(
19499                pair[1] - pair[0] >= drain_busy_reprobe_interval(),
19500                "consecutive probes {:?} apart",
19501                pair[1] - pair[0]
19502            );
19503        }
19504    }
19505
19506    #[tokio::test(start_paused = true)]
19507    async fn a_slow_probe_is_never_overlapped_by_the_next() {
19508        // Each answer takes longer than the re-probe interval; the next probe
19509        // must wait for the previous answer and then the interval.
19510        let latency = Duration::from_secs(1);
19511        let drain = Drain::start(Answer::BusyUntil {
19512            until: Instant::now() + Duration::from_secs(3600),
19513            latency,
19514        });
19515        let (drained, _) = drain.run(Duration::from_secs(5)).await;
19516        assert!(!drained);
19517        let probes = drain.probes();
19518        assert!(probes.len() >= 2, "the drain must re-probe: {probes:?}");
19519        for pair in probes.windows(2) {
19520            assert!(
19521                pair[1] - pair[0] >= latency + drain_busy_reprobe_interval(),
19522                "a probe started {:?} after the previous one, before it could finish",
19523                pair[1] - pair[0]
19524            );
19525        }
19526    }
19527
19528    #[tokio::test(start_paused = true)]
19529    async fn an_unanswered_probe_cannot_hold_the_drain_past_its_ceiling() {
19530        let drain = Drain::start(Answer::Silent);
19531        let ceiling = Duration::from_secs(2);
19532        let (drained, elapsed) = drain.run(ceiling).await;
19533        assert!(!drained, "an unanswered probe counts as busy");
19534        assert!(
19535            elapsed >= ceiling && elapsed < ceiling + drain_busy_reprobe_interval(),
19536            "the probe deadline is capped at the drain ceiling: {elapsed:?}"
19537        );
19538        assert_eq!(
19539            drain.probes().len(),
19540            1,
19541            "the unanswered probe holds the only slot until the ceiling"
19542        );
19543    }
19544
19545    /// Every event logged while it is installed, as `message` plus fields.
19546    #[derive(Clone, Default)]
19547    struct LogCapture {
19548        events: Arc<StdMutex<Vec<BTreeMap<String, String>>>>,
19549    }
19550
19551    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for LogCapture {
19552        fn on_event(
19553            &self,
19554            event: &tracing::Event<'_>,
19555            _context: tracing_subscriber::layer::Context<'_, S>,
19556        ) {
19557            struct Fields(BTreeMap<String, String>);
19558            impl tracing::field::Visit for Fields {
19559                fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
19560                    self.0
19561                        .insert(field.name().to_string(), format!("{value:?}"));
19562                }
19563            }
19564            let mut fields = Fields(BTreeMap::new());
19565            event.record(&mut fields);
19566            self.events.lock().unwrap().push(fields.0);
19567        }
19568    }
19569
19570    impl LogCapture {
19571        fn install(&self) -> tracing::subscriber::DefaultGuard {
19572            use tracing_subscriber::layer::SubscriberExt;
19573            tracing::subscriber::set_default(tracing_subscriber::registry().with(self.clone()))
19574        }
19575
19576        fn with_message(&self, needle: &str) -> Vec<BTreeMap<String, String>> {
19577            self.events
19578                .lock()
19579                .unwrap()
19580                .iter()
19581                .filter(|fields| fields.get("message").is_some_and(|m| m.contains(needle)))
19582                .cloned()
19583                .collect()
19584        }
19585    }
19586
19587    /// A module that declares a busy gauge but leaves it out of its health
19588    /// answers holds a drain to its ceiling. The timeout line must say so by
19589    /// name, and the drain must warn about the missing gauge once, not on
19590    /// every probe.
19591    #[tokio::test(start_paused = true)]
19592    async fn a_missing_declared_gauge_is_named_on_the_drain_timeout_line() {
19593        let capture = LogCapture::default();
19594        let _guard = capture.install();
19595        let drain = Drain::start(Answer::OmitsGauge);
19596        let (drained, _, trace) = drain.run_traced(Duration::from_secs(2)).await;
19597        assert!(!drained, "a gauge never reported cannot read quiet");
19598        assert!(trace.probes >= 2, "the drain must re-probe: {trace:?}");
19599
19600        let missing = capture.with_message("lacks a declared busy gauge");
19601        assert_eq!(missing.len(), 1, "one warning per drain: {missing:?}");
19602        assert_eq!(
19603            missing[0].get("missing_gauges").map(String::as_str),
19604            Some(GAUGE)
19605        );
19606
19607        warn_drain_timed_out(
19608            MODULE_ID,
19609            Duration::from_secs(2),
19610            RouteCloseReason::Restart,
19611            &Default::default(),
19612            &trace,
19613        );
19614        let timeouts = capture.with_message("route drain timed out");
19615        assert_eq!(timeouts.len(), 1, "{timeouts:?}");
19616        let gauges = &timeouts[0]["busy_gauges"];
19617        assert!(
19618            gauges.starts_with(&format!("{GAUGE}: missing_from_health_body @")),
19619            "the timeout line must name the gauge and why it read busy: {gauges}"
19620        );
19621        assert!(
19622            gauges.ends_with("; no value ever read"),
19623            "no value was ever read for the gauge: {gauges}"
19624        );
19625        assert_eq!(timeouts[0]["gauge_probes"], trace.probes.to_string());
19626    }
19627
19628    /// The trace names a busy value and when it was read. For a probe that
19629    /// never got an answer, it names the probe's error kind and says that no
19630    /// value was ever read.
19631    #[tokio::test(start_paused = true)]
19632    async fn the_drain_trace_names_a_busy_value_and_an_unanswered_probe() {
19633        let busy = Drain::start(Answer::BusyUntil {
19634            until: Instant::now() + Duration::from_secs(3600),
19635            latency: Duration::ZERO,
19636        });
19637        let (_, _, trace) = busy.run_traced(Duration::from_secs(1)).await;
19638        let rendered = trace.to_string();
19639        assert!(
19640            rendered.starts_with(&format!("{GAUGE}: non_zero(1) @"))
19641                && rendered.contains("; last value non_zero(1) @"),
19642            "{rendered}"
19643        );
19644
19645        let silent = Drain::start(Answer::Silent);
19646        let (_, _, trace) = silent.run_traced(Duration::from_secs(1)).await;
19647        // The probe is capped at the 1 s ceiling, and its reading is stamped
19648        // when it gave up.
19649        assert_eq!(
19650            trace.to_string(),
19651            format!("{GAUGE}: probe_failed(no-answer) @1000ms; no value ever read")
19652        );
19653        assert_eq!(trace.probes, 1);
19654    }
19655
19656    /// A gauge value that is not a count reads busy and is shown as sent.
19657    #[test]
19658    fn a_gauge_that_is_not_a_count_is_busy_and_shown_as_sent() {
19659        let gauges = [GAUGE.to_string()];
19660        let verdicts = gauge_verdicts(Some(&serde_json::json!({ GAUGE: 0.0 })), &gauges);
19661        assert_eq!(verdicts, vec![GaugeVerdict::NotACount("0.0".to_string())]);
19662        assert_eq!(
19663            busy_gauge_observation(&verdicts),
19664            BusyGaugeObservation::Busy
19665        );
19666        let zero = gauge_verdicts(Some(&serde_json::json!({ GAUGE: 0 })), &gauges);
19667        assert_eq!(
19668            busy_gauge_observation(&zero),
19669            BusyGaugeObservation::Quiescent
19670        );
19671        let none = gauge_verdicts(None, &gauges);
19672        assert_eq!(busy_gauge_observation(&none), BusyGaugeObservation::Omitted);
19673    }
19674}
19675
19676#[cfg(test)]
19677mod health_evidence_tests {
19678    use super::{HealthProbeError, HealthProbeEvidence};
19679    use std::collections::HashSet;
19680
19681    /// The evidential asymmetry, asserted rather than described.
19682    ///
19683    /// Exactly ONE observation is proof a module cannot serve, and the one that
19684    /// fires under CPU starvation is not it. Before the split, all fifteen
19685    /// construction sites collapsed into a single String, so a timeout carried the
19686    /// same weight as a dead lane -- which is how a healthy module was restarted
19687    /// three times in one day.
19688    #[test]
19689    fn only_a_dead_lane_is_proof_of_death() {
19690        assert!(HealthProbeError::lane_dead("gone").is_proof_of_death());
19691        // Three non-proof classes, each for a different reason: silence is
19692        // consistent with health, a bad answer proves the module ALIVE, and a
19693        // daemon-side fault never reached the module at all.
19694        assert!(!HealthProbeError::no_answer("timed out").is_proof_of_death());
19695        assert!(!HealthProbeError::bad_answer("garbage").is_proof_of_death());
19696        assert!(!HealthProbeError::misconfigured("no table").is_proof_of_death());
19697    }
19698
19699    /// Labels must be distinct, or the operator-facing distinction is cosmetic.
19700    ///
19701    /// A shared label renders two different observations identically in the line an
19702    /// operator reads after an unexplained restart -- the exact confusion this
19703    /// change removes.
19704    #[test]
19705    fn every_evidence_class_has_a_distinct_label() {
19706        let labels = [
19707            HealthProbeError::lane_dead("").label(),
19708            HealthProbeError::no_answer("").label(),
19709            HealthProbeError::bad_answer("").label(),
19710            HealthProbeError::misconfigured("").label(),
19711        ];
19712        let unique: HashSet<_> = labels.iter().collect();
19713        assert_eq!(unique.len(), labels.len(), "labels collided: {labels:?}");
19714    }
19715
19716    /// The class is additional information, not a replacement.
19717    ///
19718    /// An operator needs both "this was silence" and the specific text saying how
19719    /// long we waited; a classification that swallowed the message would trade one
19720    /// missing distinction for another.
19721    #[test]
19722    fn classification_preserves_the_original_message() {
19723        let err = HealthProbeError::no_answer("module did not answer within 5s");
19724        assert_eq!(err.to_string(), "module did not answer within 5s");
19725        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19726    }
19727}
19728
19729#[cfg(test)]
19730mod health_tombstone_tests {
19731    use std::{path::PathBuf, sync::Arc, time::Duration};
19732
19733    use subc_protocol::{
19734        manifest::Concurrency,
19735        session::{HealthStatus, ModuleControlResponse},
19736    };
19737    use tokio::sync::mpsc;
19738
19739    use super::{
19740        probe_module_health, HealthAction, HealthConfig, HealthProbeEvidence, ModuleProtocol,
19741        ModuleSpec, RestartPolicy, Supervisor, SupervisorRuntimeConfig,
19742    };
19743    use crate::{
19744        control::ControlHandler,
19745        forwarding::{ForwardingTable, ModuleControlRpcCompletion, ModuleControlRpcOutcome},
19746        registry::{ConnectionId, Registry},
19747        router::FrameSink,
19748    };
19749
19750    struct ProbeHarness {
19751        spec: ModuleSpec,
19752        runtime: SupervisorRuntimeConfig,
19753        forwarding: Arc<ForwardingTable>,
19754        module_connection: ConnectionId,
19755        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19756        handler: ControlHandler,
19757        module: super::SupervisedModule,
19758    }
19759
19760    fn probe_harness() -> ProbeHarness {
19761        let registry = Arc::new(Registry::default());
19762        let forwarding = Arc::new(ForwardingTable::default());
19763        let supervisor_handle = super::SupervisorHandle::new();
19764        let health = HealthConfig {
19765            http: None,
19766            cadence: Duration::from_secs(30),
19767            deadline: Duration::from_secs(5),
19768            failure_threshold: 3,
19769            on_degraded: HealthAction::Report,
19770            on_failing: HealthAction::Report,
19771            critical: false,
19772        };
19773        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
19774            .with_forwarding(Arc::clone(&forwarding))
19775            .with_handle(supervisor_handle.clone())
19776            .with_health_config(health);
19777        let spec = ModuleSpec {
19778            script: None,
19779            module_id: "late-health-module".to_string(),
19780            program: PathBuf::from("disabled-module"),
19781            args: Vec::new(),
19782            env: Vec::new(),
19783            reserved: false,
19784            reserved_prefixes: Vec::new(),
19785            protocol: ModuleProtocol::Subc,
19786            overlap: Default::default(),
19787            carry_containment: false,
19788        };
19789        let module = supervisor
19790            .supervise_configured(spec.clone(), false)
19791            .unwrap();
19792        let runtime = supervisor.runtime_config();
19793        let handler = ControlHandler::with_forwarding(registry, Arc::clone(&forwarding))
19794            .with_supervisor(supervisor_handle);
19795        let module_connection = ConnectionId::new(700);
19796        let (module_tx, module_rx) = mpsc::channel(8);
19797        forwarding
19798            .register_module_connection(
19799                module_connection,
19800                spec.module_id.clone(),
19801                subc_protocol::PROTOCOL_VERSION,
19802                Concurrency::ModuleManaged,
19803                FrameSink::new(module_tx),
19804            )
19805            .unwrap();
19806
19807        ProbeHarness {
19808            spec,
19809            runtime,
19810            forwarding,
19811            module_connection,
19812            module_rx,
19813            handler,
19814            module,
19815        }
19816    }
19817
19818    async fn finish_after(
19819        harness: &mut ProbeHarness,
19820        stall: Duration,
19821    ) -> ModuleControlRpcCompletion {
19822        assert!(stall > harness.runtime.health.deadline);
19823        let deadline = harness.runtime.health.deadline;
19824        let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
19825        let answer = async {
19826            let frame = harness.module_rx.recv().await.expect("health.check frame");
19827            tokio::time::advance(deadline).await;
19828            tokio::task::yield_now().await;
19829            tokio::time::advance(stall - deadline).await;
19830            harness
19831                .forwarding
19832                .complete_module_control_rpc(
19833                    harness.module_connection,
19834                    frame.header.corr,
19835                    Some("health.check"),
19836                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19837                        status: HealthStatus::Ok,
19838                        detail: None,
19839                        metrics: None,
19840                    }),
19841                )
19842                .unwrap()
19843        };
19844        let (probe_result, completion) = tokio::join!(probe, answer);
19845        let err = probe_result.expect_err("probe must miss its deadline");
19846        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19847        completion
19848    }
19849
19850    async fn time_out_without_answer(harness: &mut ProbeHarness) {
19851        let deadline = harness.runtime.health.deadline;
19852        let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
19853        let exhaust_deadline = async {
19854            let _frame = harness.module_rx.recv().await.expect("health.check frame");
19855            tokio::time::advance(deadline).await;
19856            tokio::task::yield_now().await;
19857        };
19858        let (probe_result, ()) = tokio::join!(probe, exhaust_deadline);
19859        let err = probe_result.expect_err("probe must miss its deadline");
19860        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19861    }
19862
19863    async fn run_probe_cycle(harness: &mut ProbeHarness, answer: bool) {
19864        let registry = Arc::clone(&harness.module.inner.registry);
19865        let snapshot = Arc::clone(&harness.module.inner.snapshot);
19866        let process_liveness = super::SupervisorProcessLiveness::default();
19867        let mut child = None;
19868        let cycle = super::run_health_probe_cycle(
19869            &harness.spec,
19870            &harness.runtime,
19871            &registry,
19872            &process_liveness,
19873            &snapshot,
19874            &mut child,
19875        );
19876        let peer = async {
19877            let frame = harness.module_rx.recv().await.expect("health.check frame");
19878            if answer {
19879                harness
19880                    .forwarding
19881                    .complete_module_control_rpc(
19882                        harness.module_connection,
19883                        frame.header.corr,
19884                        Some("health.check"),
19885                        ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19886                            status: HealthStatus::Ok,
19887                            detail: None,
19888                            metrics: Some(serde_json::json!({"ready": true})),
19889                        }),
19890                    )
19891                    .unwrap();
19892            } else {
19893                tokio::time::advance(harness.runtime.health.deadline).await;
19894                tokio::task::yield_now().await;
19895            }
19896        };
19897        tokio::join!(cycle, peer);
19898    }
19899
19900    #[tokio::test(start_paused = true)]
19901    async fn unanswered_probe_is_unknown_until_threshold_and_ok_report_recovers() {
19902        let mut harness = probe_harness();
19903        // Drive the probe cycle directly with an in-memory wire peer. Stop the
19904        // disabled module's monitor so only this test owns lifecycle transitions;
19905        // no OS process is launched, and a restart is observed at scheduling.
19906        let monitor = harness.module.inner.monitor.lock().unwrap().take().unwrap();
19907        monitor.abort();
19908        let _ = monitor.await;
19909        super::update_snapshot(&harness.module.inner.snapshot, None, |state| {
19910            state.enabled = true;
19911            state.state = super::ModuleState::Running;
19912            state.process_alive = true;
19913        })
19914        .unwrap();
19915
19916        run_probe_cycle(&mut harness, true).await;
19917        assert_eq!(
19918            harness.module.status().unwrap().health.status,
19919            super::SupervisorHealthStatus::Ok
19920        );
19921
19922        for failures in 1..harness.runtime.health.failure_threshold {
19923            run_probe_cycle(&mut harness, false).await;
19924            let status = harness.module.status().unwrap();
19925            assert_eq!(status.health.status, super::SupervisorHealthStatus::Unknown);
19926            assert_eq!(status.health.consecutive_failures, failures);
19927            assert!(status.health.last_probe_ms.is_some());
19928            assert!(status.health.detail.unwrap().starts_with("[no-answer]"));
19929            assert!(status.health.metrics.is_none());
19930            assert_eq!(status.state, super::ModuleState::Running);
19931            assert!(status.process_alive);
19932            assert_eq!(status.restart_count, 0);
19933            assert_eq!(status.lifetime_restarts, 0);
19934            assert!(status.health.last_action.is_none());
19935            assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_none());
19936        }
19937
19938        run_probe_cycle(&mut harness, true).await;
19939        let recovered = harness.module.status().unwrap();
19940        assert_eq!(recovered.health.status, super::SupervisorHealthStatus::Ok);
19941        assert_eq!(recovered.health.consecutive_failures, 0);
19942        assert!(recovered.health.detail.is_none());
19943        assert_eq!(
19944            recovered.health.metrics,
19945            Some(serde_json::json!({"ready": true}))
19946        );
19947        assert_eq!(recovered.lifetime_restarts, 0);
19948
19949        for failures in 1..=harness.runtime.health.failure_threshold {
19950            run_probe_cycle(&mut harness, false).await;
19951            let status = harness.module.status().unwrap();
19952            assert_eq!(status.health.consecutive_failures, failures);
19953            if failures < harness.runtime.health.failure_threshold {
19954                assert_eq!(status.health.status, super::SupervisorHealthStatus::Unknown);
19955                assert_eq!(status.state, super::ModuleState::Running);
19956                assert_eq!(status.lifetime_restarts, 0);
19957                assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_none());
19958            } else {
19959                assert_eq!(
19960                    status.health.status,
19961                    super::SupervisorHealthStatus::Unresponsive
19962                );
19963                assert_eq!(status.state, super::ModuleState::Restarting);
19964                assert_eq!(status.restart_count, 1);
19965                assert_eq!(status.lifetime_restarts, 1);
19966                assert_eq!(status.health.last_action.as_deref(), Some("restart"));
19967                assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_some());
19968            }
19969        }
19970    }
19971
19972    #[tokio::test(start_paused = true)]
19973    async fn late_health_answers_record_start_anchored_latency_for_two_stalls() {
19974        let mut harness = probe_harness();
19975
19976        let first = finish_after(&mut harness, Duration::from_secs(8)).await;
19977        let first_latency = match &first {
19978            ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
19979            other => panic!("late answer was not retained: {other:?}"),
19980        };
19981        assert!(harness.handler.observe_module_control_completion(first));
19982
19983        let second = finish_after(&mut harness, Duration::from_secs(11)).await;
19984        let second_latency = match &second {
19985            ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
19986            other => panic!("late answer was not retained: {other:?}"),
19987        };
19988        assert!(harness.handler.observe_module_control_completion(second));
19989
19990        assert_eq!(first_latency, Duration::from_secs(8));
19991        assert_eq!(
19992            second_latency - first_latency,
19993            Duration::from_secs(3),
19994            "latency must grow linearly with the additional stall"
19995        );
19996        let health = harness.module.status().unwrap().health;
19997        assert_eq!(health.late_answer_count, 2);
19998        assert_eq!(health.last_late_answer_latency_ms, Some(11_000));
19999    }
20000
20001    /// A module that answers every probe late must never march to the kill
20002    /// threshold: the late answer proves it is alive, so it must clear the miss
20003    /// streak the timeout recorded. Without the reset, a CPU-starved module
20004    /// that serves every probe seconds past the deadline accumulates
20005    /// `consecutive_failures` to the threshold and is killed — the exact
20006    /// sequence from the 2026-08-14 aft disable, where the daemon logged
20007    /// "proves the module is alive" five times while counting five misses.
20008    #[tokio::test(start_paused = true)]
20009    async fn late_answer_clears_the_consecutive_failure_streak() {
20010        let mut harness = probe_harness();
20011
20012        // Timeout recorded first: the probe path saw no answer in time.
20013        time_out_without_answer(&mut harness).await;
20014        harness
20015            .module
20016            .record_health_probe_failure_for_test("[no-answer] test miss")
20017            .unwrap();
20018        assert_eq!(
20019            harness.module.status().unwrap().health.consecutive_failures,
20020            1,
20021            "precondition: the miss must be on the streak before the late answer"
20022        );
20023
20024        // The stalled reply then lands: proof of life.
20025        let late = finish_after(&mut harness, Duration::from_secs(9)).await;
20026        assert!(matches!(
20027            late,
20028            ModuleControlRpcCompletion::LateHealthAnswer { .. }
20029        ));
20030        assert!(harness.handler.observe_module_control_completion(late));
20031
20032        let health = harness.module.status().unwrap().health;
20033        assert_eq!(
20034            health.consecutive_failures, 0,
20035            "a late answer is an answer: the streak must reset"
20036        );
20037        assert_eq!(health.late_answer_count, 1);
20038    }
20039
20040    #[tokio::test(start_paused = true)]
20041    async fn repeated_serial_probe_cycles_keep_one_tombstone_per_endpoint() {
20042        let mut harness = probe_harness();
20043
20044        for _ in 0..20 {
20045            time_out_without_answer(&mut harness).await;
20046            assert_eq!(
20047                harness.forwarding.health_probe_tombstone_count().unwrap(),
20048                1
20049            );
20050        }
20051    }
20052}
20053
20054#[cfg(test)]
20055mod child_env_tests {
20056    #[cfg(windows)]
20057    use super::{
20058        clear_current_process_facts, observed_launch_nonce_source, ModuleState, SupervisorSnapshot,
20059    };
20060    #[cfg(windows)]
20061    use std::sync::{Arc, OnceLock};
20062    #[cfg(windows)]
20063    #[test]
20064    fn windows_wire_spawn_prepares_pipe_and_keeps_phase_one_env() {
20065        let spec = spec(Vec::new());
20066        let mut command = Command::new("unused");
20067        let handoff = apply_wire_spawn_args(&mut command, &spec, None, None)
20068            .unwrap()
20069            .unwrap();
20070        let name = command
20071            .as_std()
20072            .get_envs()
20073            .find(|(key, _)| *key == OsStr::new(subc_os::launch_nonce::LAUNCH_NONCE_PIPE_ENV))
20074            .and_then(|(_, value)| value)
20075            .unwrap();
20076        assert_eq!(name, OsStr::new(handoff.name()));
20077        assert!(handoff.name().starts_with(r"\\.\pipe\subc-launch-"));
20078        assert!(command.as_std().get_envs().any(|(key, value)| key
20079            == OsStr::new(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV)
20080            && value == Some(OsStr::new("env"))));
20081        assert!(command
20082            .as_std()
20083            .get_envs()
20084            .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()));
20085    }
20086
20087    #[cfg(windows)]
20088    #[test]
20089    fn windows_source_reporting_tracks_consumption_and_resets_per_spawn() {
20090        let mut snapshot = SupervisorSnapshot::new(ModuleState::Running, true);
20091        snapshot.process_alive = true;
20092        snapshot.spawned_protocol = Some(ModuleProtocol::Subc);
20093        assert_eq!(
20094            observed_launch_nonce_source(&snapshot).as_deref(),
20095            Some("env")
20096        );
20097        let consumed = Arc::new(OnceLock::new());
20098        snapshot.pipe_consumed = Some(consumed.clone());
20099        assert_eq!(
20100            observed_launch_nonce_source(&snapshot).as_deref(),
20101            Some("env")
20102        );
20103        consumed.set(()).unwrap();
20104        assert_eq!(
20105            observed_launch_nonce_source(&snapshot).as_deref(),
20106            Some("pipe")
20107        );
20108        snapshot.pipe_consumed = Some(Arc::new(OnceLock::new()));
20109        assert_eq!(
20110            observed_launch_nonce_source(&snapshot).as_deref(),
20111            Some("env")
20112        );
20113        clear_current_process_facts(&mut snapshot);
20114        assert_eq!(observed_launch_nonce_source(&snapshot), None);
20115    }
20116    use super::{
20117        apply_child_env, apply_spawn_role, apply_wire_spawn_args, LaunchSpecDigest, ModuleProtocol,
20118        ModuleSpec, SpawnRole, SupervisorHandle, SPAWN_ROLE_SWAP_CANDIDATE, SUBC_ARG,
20119        SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV, SUBC_SPAWN_ROLE_ENV,
20120    };
20121    use std::{ffi::OsStr, path::PathBuf};
20122    use tokio::process::Command;
20123
20124    fn spec(env: Vec<(String, String)>) -> ModuleSpec {
20125        ModuleSpec {
20126            script: None,
20127            module_id: "env-plan".to_string(),
20128            program: PathBuf::from("/nonexistent"),
20129            args: Vec::new(),
20130            env,
20131            reserved: false,
20132            reserved_prefixes: Vec::new(),
20133            protocol: ModuleProtocol::Subc,
20134            overlap: Default::default(),
20135            carry_containment: false,
20136        }
20137    }
20138
20139    #[test]
20140    fn configured_launch_spec_digest_is_canonical_and_excludes_injected_inputs() {
20141        let base = spec(vec![("A".into(), "B=C".into()), ("Z".into(), "v".into())]);
20142        let digest = LaunchSpecDigest::from_spec(&base);
20143        let mut reordered = base.clone();
20144        reordered.env.reverse();
20145        reordered.module_id = "different-id".into();
20146        reordered.reserved = true;
20147        reordered.overlap = Default::default();
20148        assert_eq!(digest, LaunchSpecDigest::from_spec(&reordered));
20149        let mut delimiter_collision = base.clone();
20150        delimiter_collision.env[0] = ("A=B".into(), "C".into());
20151        assert_ne!(digest, LaunchSpecDigest::from_spec(&delimiter_collision));
20152        let mut changed = base.clone();
20153        changed.protocol = ModuleProtocol::None;
20154        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
20155        changed = base.clone();
20156        changed.args.push("--flag".into());
20157        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
20158        changed = base.clone();
20159        changed.program = PathBuf::from("/other");
20160        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
20161        changed = base.clone();
20162        changed.env[1].1 = "other".into();
20163        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
20164        assert!(!format!("{digest:?}").contains("B=C"));
20165        assert!(!format!("{digest:?}").contains("[u8"));
20166    }
20167
20168    #[cfg(unix)]
20169    #[test]
20170    fn native_program_bytes_do_not_collapse_through_lossy_utf8() {
20171        use std::os::unix::ffi::OsStringExt;
20172        let mut left = spec(Vec::new());
20173        left.program = std::ffi::OsString::from_vec(vec![b'/', 0xff]).into();
20174        let mut right = left.clone();
20175        right.program = std::ffi::OsString::from_vec(vec![b'/', 0xfe]).into();
20176        assert_eq!(
20177            left.program.to_string_lossy(),
20178            right.program.to_string_lossy()
20179        );
20180        assert_ne!(
20181            LaunchSpecDigest::from_spec(&left),
20182            LaunchSpecDigest::from_spec(&right)
20183        );
20184    }
20185
20186    /// Ambient `CK_LOG` is REMOVED for an unconfigured module, and a configured
20187    /// one still gets its own.
20188    ///
20189    /// This is the narrow goal `env_clear()` was reached for, and the reason the
20190    /// fix is `env_remove` rather than deleting the line: an operator's ambient
20191    /// filter silently becoming an unconfigured module's log level is a real
20192    /// defect, just a much smaller one than clearing the environment.
20193    ///
20194    /// Asserted on the command plan rather than a spawned child because proving
20195    /// the ABSENCE of an inherited variable needs the parent's environment
20196    /// mutated, and `forbid(unsafe_code)` refuses that. `get_envs()` reports a
20197    /// removal as `(key, None)`, which is exactly the distinction wanted: not
20198    /// "absent because nobody set it" but "explicitly unset for the child".
20199    #[test]
20200    fn ambient_ck_log_is_removed_and_a_configured_one_survives() {
20201        let mut command = Command::new("/nonexistent");
20202        apply_child_env(&mut command, &spec(Vec::new()));
20203        let removed = command
20204            .as_std()
20205            .get_envs()
20206            .any(|(key, value)| key == OsStr::new("CK_LOG") && value.is_none());
20207        assert!(
20208            removed,
20209            "ambient CK_LOG must be explicitly removed for an unconfigured module"
20210        );
20211
20212        let mut configured = Command::new("/nonexistent");
20213        apply_child_env(
20214            &mut configured,
20215            &spec(vec![("CK_LOG".to_string(), "debug".to_string())]),
20216        );
20217        let effective = configured
20218            .as_std()
20219            .get_envs()
20220            .filter(|(key, _)| *key == OsStr::new("CK_LOG"))
20221            .last()
20222            .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
20223        assert_eq!(
20224            effective,
20225            Some(Some("debug".to_string())),
20226            "a module's configured CK_LOG must survive the ambient removal"
20227        );
20228    }
20229
20230    /// A `protocol: "none"` spawn carries NO `--subc` argument and NO launch
20231    /// nonce; a subc-wire spawn carries both. Asserted on the command plan for
20232    /// the same reason as the CK_LOG test above.
20233    ///
20234    /// The argument is the load-bearing half: a stock binary exits on an
20235    /// unknown flag before it listens, so with `--subc` appended the mode
20236    /// could not supervise the one process it exists for. Found by the first
20237    /// conformance run (nats-server: `flag provided but not defined: -subc`).
20238    #[test]
20239    fn protocol_none_spawn_carries_no_subc_argument_and_no_nonce() {
20240        let connection_file = std::path::Path::new("/run/subc-connection.json");
20241        let handle = SupervisorHandle::new();
20242
20243        let mut none_spec = spec(Vec::new());
20244        none_spec.protocol = ModuleProtocol::None;
20245        let mut none = Command::new("/nonexistent");
20246        let none_handoff =
20247            apply_wire_spawn_args(&mut none, &none_spec, Some(connection_file), Some(&handle))
20248                .expect("protocol-none spawn args apply");
20249        assert!(
20250            none_handoff.is_none(),
20251            "protocol:none spawn must not receive a nonce descriptor"
20252        );
20253        #[cfg(windows)]
20254        assert!(!none.as_std().get_envs().any(|(key, value)| key
20255            == OsStr::new(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV)
20256            && value.is_some()));
20257        assert!(
20258            !none.as_std().get_envs().any(|(key, value)| key
20259                == OsStr::new(subc_os::LAUNCH_NONCE_FD_ENV)
20260                && value.is_some()),
20261            "protocol:none spawn must not name a nonce descriptor"
20262        );
20263        let none_args: Vec<String> = none
20264            .as_std()
20265            .get_args()
20266            .map(|a| a.to_string_lossy().into_owned())
20267            .collect();
20268        assert!(
20269            !none_args.iter().any(|a| a == SUBC_ARG),
20270            "protocol:none argv must not carry --subc; got {none_args:?}"
20271        );
20272        let none_has_nonce = none
20273            .as_std()
20274            .get_envs()
20275            .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some());
20276        assert!(
20277            !none_has_nonce,
20278            "protocol:none spawn must not receive a launch nonce"
20279        );
20280        let none_has_module_id = none
20281            .as_std()
20282            .get_envs()
20283            .any(|(key, value)| key == OsStr::new(SUBC_MODULE_ID_ENV) && value.is_some());
20284        assert!(
20285            none_has_module_id,
20286            "SUBC_MODULE_ID is inert and stays on every path"
20287        );
20288        assert!(
20289            handle.spawn_nonce(&none_spec.module_id).is_none(),
20290            "no nonce record for a process that will never present one"
20291        );
20292
20293        // Control: the subc-wire path is unchanged by the branch above.
20294        let wire_spec = spec(Vec::new());
20295        let mut wire = Command::new("/nonexistent");
20296        let wire_handoff =
20297            apply_wire_spawn_args(&mut wire, &wire_spec, Some(connection_file), Some(&handle))
20298                .expect("subc-wire spawn args apply");
20299        let wire_fd_env = wire
20300            .as_std()
20301            .get_envs()
20302            .find(|(key, _)| *key == OsStr::new(subc_os::LAUNCH_NONCE_FD_ENV))
20303            .and_then(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
20304        #[cfg(unix)]
20305        assert_eq!(
20306            wire_fd_env,
20307            Some(wire_handoff.expect("a descriptor handoff").fd_env_value()),
20308            "a subc-wire spawn names the pipe it will receive at descriptor 3"
20309        );
20310        #[cfg(windows)]
20311        assert!(wire_handoff.is_some() && wire_fd_env.is_none());
20312        #[cfg(not(any(unix, windows)))]
20313        assert!(wire_handoff.is_none() && wire_fd_env.is_none());
20314        let wire_args: Vec<String> = wire
20315            .as_std()
20316            .get_args()
20317            .map(|a| a.to_string_lossy().into_owned())
20318            .collect();
20319        assert_eq!(
20320            wire_args,
20321            vec![
20322                SUBC_ARG.to_string(),
20323                connection_file.to_string_lossy().into_owned()
20324            ],
20325            "a subc-wire spawn still carries --subc <path>"
20326        );
20327        assert_eq!(
20328            wire.as_std()
20329                .get_envs()
20330                .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()),
20331            !cfg!(unix),
20332            "only Windows supplies the environment nonce"
20333        );
20334        assert!(handle.spawn_nonce(&wire_spec.module_id).is_some());
20335    }
20336
20337    /// A plain spawn EXPLICITLY REMOVES the spawn role, even when the module's
20338    /// spec tries to set it; only a swap candidate carries it.
20339    ///
20340    /// "Set it only on candidates" is not enough, because spawn applies the
20341    /// spec's env verbatim and the daemon's own environment is inherited: either
20342    /// could hand a plain restart the swap role, and a module reading it would
20343    /// warm on its long swap budget while callers wait. Asserted as an explicit
20344    /// removal (`(key, None)`), not mere absence, for the reason the `CK_LOG`
20345    /// test above gives.
20346    #[test]
20347    fn plain_spawn_removes_the_spawn_role_even_when_the_spec_sets_it() {
20348        let role = |command: &Command| {
20349            command
20350                .as_std()
20351                .get_envs()
20352                .filter(|(key, _)| *key == OsStr::new(SUBC_SPAWN_ROLE_ENV))
20353                .last()
20354                .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()))
20355        };
20356        let forged = spec(vec![(
20357            SUBC_SPAWN_ROLE_ENV.to_string(),
20358            SPAWN_ROLE_SWAP_CANDIDATE.to_string(),
20359        )]);
20360
20361        let mut plain = Command::new("/nonexistent");
20362        apply_child_env(&mut plain, &forged);
20363        apply_spawn_role(&mut plain, SpawnRole::Plain);
20364        assert_eq!(
20365            role(&plain),
20366            Some(None),
20367            "a plain spawn must remove SUBC_SPAWN_ROLE, whatever the spec says"
20368        );
20369
20370        let mut candidate = Command::new("/nonexistent");
20371        apply_child_env(&mut candidate, &spec(Vec::new()));
20372        apply_spawn_role(&mut candidate, SpawnRole::SwapCandidate);
20373        assert_eq!(
20374            role(&candidate),
20375            Some(Some(SPAWN_ROLE_SWAP_CANDIDATE.to_string()))
20376        );
20377    }
20378
20379    /// Daemon-private capture retention keys never reach the child.
20380    ///
20381    /// cortexkit-log exposes retention as a Rust struct with no environment
20382    /// names, so these entries are supervisor metadata. Passing them through
20383    /// would invent a public child-process contract by accident.
20384    #[test]
20385    fn daemon_private_capture_keys_are_not_passed_to_the_child() {
20386        let mut command = Command::new("/nonexistent");
20387        apply_child_env(
20388            &mut command,
20389            &spec(vec![
20390                (super::CAPTURE_KEEP_ENV.to_string(), "5".to_string()),
20391                ("KEPT".to_string(), "yes".to_string()),
20392            ]),
20393        );
20394        let keys: Vec<String> = command
20395            .as_std()
20396            .get_envs()
20397            .filter(|(_, value)| value.is_some())
20398            .map(|(key, _)| key.to_string_lossy().into_owned())
20399            .collect();
20400        assert!(keys.contains(&"KEPT".to_string()), "got {keys:?}");
20401        assert!(
20402            !keys.contains(&super::CAPTURE_KEEP_ENV.to_string()),
20403            "daemon-private capture key leaked to the child: {keys:?}"
20404        );
20405    }
20406}
20407
20408#[cfg(test)]
20409mod jitter_tests {
20410    use super::jittered_health_delay;
20411    use std::{collections::HashSet, time::Duration};
20412
20413    /// Module ids drawn from a real fleet, so the dispersal claim is about names
20414    /// that actually occur rather than invented ones.
20415    ///
20416    /// This is a SAMPLE, not a registry: the property under test is that distinct
20417    /// ids disperse, which holds for any set of distinct strings. Several entries
20418    /// are already historical (modules get renamed), and that costs nothing here --
20419    /// but it means a reader must not mistake this for the live module set, and a
20420    /// rename sweep will match it without there being anything to change.
20421    const FLEET: [&str; 14] = [
20422        "aft",
20423        "alfonso-core",
20424        "magic-context",
20425        "broca",
20426        "thalamus",
20427        "quota",
20428        "engram",
20429        "plexus",
20430        "cerebellum",
20431        "astrocyte",
20432        "synapse",
20433        "subc-mcp",
20434        "cortexkit-credentials",
20435        "subc-federation",
20436    ];
20437
20438    /// Probes must not converge after a fleet-wide restart.
20439    ///
20440    /// This is the property the jitter exists for: every module reconnects at
20441    /// once, and without dispersal all fourteen would then probe on the same
20442    /// tick forever. Nothing failed visibly when this went untested -- a
20443    /// convergent fleet still probes correctly, just in a burst, so the symptom
20444    /// is a periodic load spike that looks like whatever else is running.
20445    #[test]
20446    fn probe_delays_disperse_across_the_fleet() {
20447        let cadence = Duration::from_secs(30);
20448        let delays: HashSet<Duration> = FLEET
20449            .iter()
20450            .map(|id| jittered_health_delay(id, 0, cadence))
20451            .collect();
20452        assert_eq!(
20453            delays.len(),
20454            FLEET.len(),
20455            "every supervised module must land on its own probe offset"
20456        );
20457    }
20458
20459    /// The offset may only ever DELAY a probe, never bring it forward.
20460    ///
20461    /// A delay below the cadence would probe a module more often than
20462    /// configured, which is the opposite of what an operator asked for and
20463    /// would tighten the failure budget without anyone changing it.
20464    #[test]
20465    fn jitter_only_delays_and_stays_within_one_tenth_of_cadence() {
20466        let cadence = Duration::from_secs(30);
20467        let span = cadence / 10;
20468        for id in FLEET {
20469            for probe_index in 0..8 {
20470                let delay = jittered_health_delay(id, probe_index, cadence);
20471                assert!(
20472                    delay >= cadence,
20473                    "{id}#{probe_index}: jitter must not shorten the cadence"
20474                );
20475                assert!(
20476                    delay < cadence + span,
20477                    "{id}#{probe_index}: jitter must stay inside one tenth of the cadence"
20478                );
20479            }
20480        }
20481    }
20482
20483    /// A module keeps its offset across daemon restarts.
20484    ///
20485    /// The delay is derived rather than randomised precisely so a restart does
20486    /// not re-roll every module into a fresh chance of collision. A random
20487    /// source would satisfy the dispersal test above and quietly lose this.
20488    #[test]
20489    fn a_module_offset_is_stable_across_restarts() {
20490        let cadence = Duration::from_secs(30);
20491        for id in FLEET {
20492            assert_eq!(
20493                jittered_health_delay(id, 0, cadence),
20494                jittered_health_delay(id, 0, cadence),
20495                "{id}: the same module and probe index must produce the same offset"
20496            );
20497        }
20498    }
20499
20500    /// A zero cadence disables probing rather than producing a busy loop.
20501    #[test]
20502    fn zero_cadence_yields_zero_delay() {
20503        assert_eq!(
20504            jittered_health_delay("aft", 0, Duration::ZERO),
20505            Duration::ZERO
20506        );
20507    }
20508}
20509
20510#[cfg(all(test, target_os = "linux"))]
20511mod cgroup_placement_tests {
20512    use super::{
20513        apply_cgroup_placement, remove_module_cgroup, LaunchSpecDigest, ModuleProtocol, ModuleSpec,
20514        SuperviseError, SupervisedChild,
20515    };
20516    use crate::stderr_tail::{StderrRing, StderrTailConfig};
20517    use cortexkit_test_support::ScratchDir;
20518    use std::{
20519        fs, io,
20520        path::{Path, PathBuf},
20521        sync::{Arc, Mutex},
20522    };
20523    use tokio::process::Command;
20524
20525    #[tokio::test]
20526    async fn unique_spawn_cgroups_clean_up_across_restarts_and_shutdown() {
20527        use super::*;
20528        let dir = ScratchDir::new("unique-spawn-cgroups");
20529        let root = PathBuf::from(format!(
20530            "/sys/fs/cgroup/subc-unique-test-{}-{}",
20531            std::process::id(),
20532            unix_ms_now()
20533        ));
20534        if let Err(error) = fs::create_dir(&root) {
20535            assert!(
20536                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
20537                "required cgroup test cannot execute: {error}"
20538            );
20539            eprintln!("SKIP unique_spawn_cgroups_clean_up_across_restarts_and_shutdown: {error}");
20540            return;
20541        }
20542        let placement = subc_cgroup::prepare_at(&root).unwrap().unwrap();
20543        let group_count = || {
20544            fs::read_dir(root.join("subc-modules"))
20545                .unwrap()
20546                .map(|entry| entry.unwrap().file_type().unwrap())
20547                .filter(|kind| kind.is_dir())
20548                .count()
20549        };
20550        let supervisor =
20551            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
20552                .with_cgroup_placement(Some(placement.clone()));
20553        let runtime = supervisor.runtime_config();
20554        let mut spec = ModuleSpec {
20555            script: None,
20556            module_id: "unique-spawn".into(),
20557            program: PathBuf::from("/bin/sleep"),
20558            args: vec!["60".into()],
20559            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
20560                .into_iter()
20561                .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
20562                .collect(),
20563            reserved: false,
20564            reserved_prefixes: vec![],
20565            protocol: ModuleProtocol::None,
20566            overlap: Default::default(),
20567            carry_containment: false,
20568        };
20569        let spawn = |spec: &ModuleSpec| {
20570            spawn_child(
20571                spec,
20572                None,
20573                None,
20574                &runtime.stderr_ring,
20575                None,
20576                &runtime.child_roster,
20577                runtime.spawn_delivery(),
20578                Some(&placement),
20579                runtime.register_timeout,
20580            )
20581            .unwrap()
20582        };
20583        let mut live = spawn(&spec);
20584        for _ in 0..3 {
20585            // A new process can enter the old slot while retirement is pending.
20586            let next = spawn(&spec);
20587            assert_ne!(live.module_id, next.module_id);
20588            live.start_kill().unwrap();
20589            live.wait().await.unwrap();
20590            live = next;
20591            assert!(
20592                live.child.try_wait().unwrap().is_none(),
20593                "retiring the old slot must not kill the replacement"
20594            );
20595            assert_eq!(
20596                group_count(),
20597                1,
20598                "only the live spawn's cgroup should remain"
20599            );
20600        }
20601        supervisor.begin_daemon_shutdown();
20602        let reap = tokio::spawn(async move {
20603            live.wait().await.unwrap();
20604        });
20605        supervisor
20606            .end_children_for_daemon_shutdown(false, std::future::pending())
20607            .await;
20608        reap.await.unwrap();
20609        assert_eq!(group_count(), 0);
20610        // A normal exit uses the same tree-cleanup path as a killed spawn.
20611        spec.program = PathBuf::from("/bin/true");
20612        spec.args.clear();
20613        let fresh_roster = ChildRoster::default();
20614        let mut short = spawn_child(
20615            &spec,
20616            None,
20617            None,
20618            &runtime.stderr_ring,
20619            None,
20620            &fresh_roster,
20621            None,
20622            Some(&placement),
20623            runtime.register_timeout,
20624        )
20625        .unwrap();
20626        short.wait().await.unwrap();
20627        assert_eq!(group_count(), 0);
20628        spec.module_id = "_".repeat(255);
20629        let mut long_id = spawn_child(
20630            &spec,
20631            None,
20632            None,
20633            &runtime.stderr_ring,
20634            None,
20635            &fresh_roster,
20636            None,
20637            Some(&placement),
20638            runtime.register_timeout,
20639        )
20640        .unwrap();
20641        long_id.wait().await.unwrap();
20642        assert_eq!(
20643            group_count(),
20644            0,
20645            "valid long module IDs must not exceed cgroup NAME_MAX"
20646        );
20647        fs::remove_dir(root.join("subc-modules")).unwrap();
20648        fs::remove_dir(root).unwrap();
20649        eprintln!("EXECUTED unique_spawn_cgroups_clean_up_across_restarts_and_shutdown");
20650    }
20651
20652    #[test]
20653    fn failed_parent_cgroup_open_is_a_cgroup_supervision_error() {
20654        let path = Path::new("/definitely-missing-subc-cgroup");
20655        let mut command = Command::new("true");
20656        let error = apply_cgroup_placement(
20657            &mut command,
20658            &ModuleSpec {
20659                script: None,
20660                module_id: "broken-cgroup".to_string(),
20661                program: PathBuf::from("true"),
20662                args: Vec::new(),
20663                env: Vec::new(),
20664                reserved: false,
20665                reserved_prefixes: Vec::new(),
20666                protocol: ModuleProtocol::Subc,
20667                overlap: Default::default(),
20668                carry_containment: false,
20669            },
20670            path,
20671        )
20672        .expect_err("a parent cgroup open failure must reject the supervised spawn");
20673        let reason = error.to_string();
20674
20675        assert!(
20676            matches!(error, SuperviseError::Cgroup { .. }),
20677            "parent cgroup open must be reported as a cgroup supervision error: {reason}"
20678        );
20679        assert!(
20680            reason.contains("/definitely-missing-subc-cgroup/cgroup.procs"),
20681            "parent cgroup open failure must name cgroup.procs: {reason}"
20682        );
20683    }
20684
20685    #[tokio::test]
20686    async fn reaping_a_child_removes_its_empty_module_cgroup() {
20687        let root = ScratchDir::new("supervisor-reap-cgroup");
20688        fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
20689        let placement = subc_cgroup::prepare_at(&root)
20690            .expect("prepare scratch cgroup root")
20691            .expect("scratch root has a cgroup.procs marker");
20692        let module_id = "reaped-module";
20693        let module = placement
20694            .module_path(module_id)
20695            .expect("create scratch module cgroup");
20696        let child = Command::new("true")
20697            .env("XDG_DATA_HOME", root.path())
20698            .env("XDG_RUNTIME_DIR", root.path())
20699            .env("XDG_CONFIG_HOME", root.path())
20700            .spawn()
20701            .expect("spawn short-lived child");
20702        let pid = child.id().expect("spawned child has pid");
20703        let mut child = SupervisedChild {
20704            registration_channel: None,
20705            registration_spawn: None,
20706            live_program_binding: None,
20707            registered_config_connection: None,
20708            admission_base: None,
20709            registration_declaration: None,
20710            _program_binding: None,
20711            subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
20712            child: crate::supervise::containment::ProcessChild::plain(child, pid),
20713            exec: crate::activity::ExecOwner(Arc::new(crate::activity::ExecOutcome::new())),
20714            protocol: ModuleProtocol::Subc,
20715            module_id: module_id.to_string(),
20716            cgroup_placement: Some(placement),
20717            stdout_pump: None,
20718            stderr_pump: None,
20719            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
20720            spawned_at: tokio::time::Instant::now(),
20721            config_delivery: None,
20722            registration_deadline: None,
20723            registration_watch: None,
20724            spawned_at_ms: 0,
20725            spawned_from: PathBuf::from("true"),
20726            launch_spec_digest: LaunchSpecDigest([0; 32]),
20727            spawned_file_identity: None,
20728            process_start_time: None,
20729            process_identity: None,
20730            pid,
20731            roster_guard: None,
20732            #[cfg(target_os = "macos")]
20733            privacy_exec: None,
20734            spawn_failure: None,
20735            admission_kill_sent: false,
20736        };
20737
20738        child.wait().await.expect("reap short-lived child");
20739
20740        assert!(
20741            !module.exists(),
20742            "waiting for a non-carried child must remove its empty cgroup before returning"
20743        );
20744        child.finish_exit(false).await.unwrap();
20745    }
20746
20747    #[test]
20748    fn non_empty_cgroup_removal_is_reported_without_blocking_teardown() {
20749        let root = ScratchDir::new("supervisor-non-empty-cgroup");
20750        fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
20751        let placement = subc_cgroup::prepare_at(&root)
20752            .expect("prepare scratch cgroup root")
20753            .expect("scratch root has a cgroup.procs marker");
20754        let module = placement
20755            .module_path("surviving-module")
20756            .expect("create scratch module cgroup");
20757        fs::write(module.join("surviving-process"), b"still present")
20758            .expect("make scratch cgroup non-empty");
20759        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
20760
20761        remove_module_cgroup(&placement, "surviving-module");
20762
20763        let logs = crate::router::test_log::captured_logs(&logs);
20764        assert!(
20765            module.exists(),
20766            "failed removal must leave the cgroup intact"
20767        );
20768        assert!(
20769            logs.contains("could not remove module cgroup after process exit; continuing teardown")
20770                && logs.contains("surviving-module"),
20771            "best-effort removal must report the failure without returning it: {logs}"
20772        );
20773    }
20774
20775    #[test]
20776    fn cgroup_pre_exec_spawn_failure_names_the_cgroup_path() {
20777        let cgroup_path = PathBuf::from("/sys/fs/cgroup/subc-modules/broken-module");
20778        let reason = SuperviseError::Spawn {
20779            program: PathBuf::from("/bin/true"),
20780            source: io::Error::from_raw_os_error(13),
20781            cgroup_path: Some(cgroup_path.clone()),
20782        }
20783        .to_string();
20784
20785        assert!(
20786            reason.contains(&cgroup_path.display().to_string()),
20787            "a pre_exec spawn failure must name the cgroup path: {reason}"
20788        );
20789    }
20790}
20791
20792#[cfg(test)]
20793mod spawn_subscriber_lag_tests {
20794    use super::*;
20795
20796    /// A subscriber whose connection stops draining is dropped once its frame
20797    /// channel fills. The client must learn that from a terminal Error frame
20798    /// after the frames already queued for it, not from a stream that simply
20799    /// goes quiet.
20800    #[tokio::test]
20801    async fn lagged_spawn_subscriber_receives_a_terminal_lagged_error_after_its_queued_frames() {
20802        let feed = SpawnEventFeed::default();
20803        feed.configure_incarnation("lag-incarnation".to_string());
20804        // A one-slot connection queue that nobody reads until the emits are
20805        // done: the forwarder parks on it and the subscriber channel fills.
20806        let (tx, mut rx) = mpsc::channel(1);
20807        feed.subscribe(ConnectionId::new(1), 7, 1, None, FrameSink::new(tx))
20808            .expect("subscribe");
20809        let emitted = SPAWN_SUBSCRIBER_BUFFER + 16;
20810        for index in 0..emitted {
20811            feed.emit_spawned(&format!("lag-module-{index}"), None, 1000, 0);
20812            // Let the forwarder take what it can so the fill point is the
20813            // subscriber channel, not a scheduling accident.
20814            tokio::task::yield_now().await;
20815        }
20816        assert_eq!(
20817            feed.subscriber_count(),
20818            0,
20819            "the lagged subscriber must be removed"
20820        );
20821
20822        let mut data = Vec::new();
20823        let mut last = None;
20824        loop {
20825            let next = tokio::time::timeout(Duration::from_secs(5), rx.recv())
20826                .await
20827                .expect("the forwarder must finish once the subscriber is dropped");
20828            let Some(outbound) = next else { break };
20829            let frame = outbound.frame;
20830            if frame.header.ty == FrameType::StreamData {
20831                assert!(last.is_none(), "no data may follow the terminal frame");
20832                let event: SpawnEvent = serde_json::from_slice(&frame.body).unwrap();
20833                data.push(event.cursor.seq);
20834            } else {
20835                assert!(last.is_none(), "exactly one terminal frame");
20836                last = Some(frame);
20837            }
20838        }
20839        assert!(!data.is_empty(), "queued frames drain before the terminal");
20840        for pair in data.windows(2) {
20841            assert_eq!(
20842                pair[1],
20843                pair[0] + 1,
20844                "queued frames arrive dense and in order"
20845            );
20846        }
20847        let terminal = last.expect("a lagged subscriber must receive a terminal frame");
20848        assert_eq!(terminal.header.ty, FrameType::Error);
20849        assert_eq!(terminal.header.corr, 7);
20850        let body: subc_protocol::ErrorBody = serde_json::from_slice(&terminal.body).unwrap();
20851        assert_eq!(body.code, SPAWN_SUBSCRIBER_LAGGED_CODE);
20852        let detail = body.detail.expect("lagged error carries detail");
20853        assert_eq!(
20854            detail["first_undelivered_cursor"]["seq"],
20855            data.last().unwrap() + 1,
20856            "the named cursor is the first event the subscriber did not receive"
20857        );
20858        assert_eq!(
20859            detail["first_undelivered_cursor"]["daemon_incarnation"],
20860            "lag-incarnation"
20861        );
20862    }
20863}
20864
20865#[cfg(test)]
20866mod terminal_history_read_concurrency_tests {
20867    use super::*;
20868    use crate::terminal_journal::read_pause;
20869    use cortexkit_test_support::ScratchDir;
20870    use std::sync::mpsc as std_mpsc;
20871
20872    fn journaled_ring(
20873        journal: &Arc<crate::terminal_journal::TerminalJournal>,
20874    ) -> Arc<Mutex<TerminalRing>> {
20875        Arc::new(Mutex::new(
20876            TerminalRing::new(TerminalRingConfig::default(), 1)
20877                .with_journal(Some(Arc::clone(journal))),
20878        ))
20879    }
20880
20881    fn crash(at_ms: u64) -> ExitReport {
20882        ExitReport {
20883            kind: ExitKind::Crash,
20884            code: Some(1),
20885            signal: None,
20886            at_ms,
20887        }
20888    }
20889
20890    /// Record an exit on another thread and report whether it finished within
20891    /// `bound`. The recorder thread is left running if it did not.
20892    fn record_within(
20893        module_id: &'static str,
20894        ring: &Arc<Mutex<TerminalRing>>,
20895        at_ms: u64,
20896        bound: Duration,
20897    ) -> bool {
20898        let ring = Arc::clone(ring);
20899        let (done, done_rx) = std_mpsc::channel();
20900        std::thread::spawn(move || {
20901            record_terminal(
20902                module_id,
20903                &ring,
20904                &SpawnEventFeed::default(),
20905                &crash(at_ms),
20906                TerminalDisposition::Restarting,
20907            );
20908            let _ = done.send(());
20909        });
20910        done_rx.recv_timeout(bound).is_ok()
20911    }
20912
20913    /// A history read in progress must not hold the journal writer (which every
20914    /// module's exit recording needs) or the module's own ring. Exits recorded
20915    /// while the read is paused complete promptly; the paused read answers as of
20916    /// the moment it started, and the next read has each exit exactly once.
20917    #[test]
20918    fn exits_recorded_during_a_paused_history_read_are_not_blocked_or_half_merged() {
20919        let dir = ScratchDir::new("terminal-history-concurrent-read");
20920        let path = dir.join("terminals.jsonl");
20921        let journal = Arc::new(crate::terminal_journal::TerminalJournal::open(
20922            path.clone(),
20923            "daemon".into(),
20924        ));
20925        let reader_ring = journaled_ring(&journal);
20926        let other_ring = journaled_ring(&journal);
20927        assert!(record_within(
20928            "reader-module",
20929            &reader_ring,
20930            10,
20931            Duration::from_secs(5)
20932        ));
20933
20934        let (started, release) = read_pause::install(&path);
20935        let reading = {
20936            let ring = Arc::clone(&reader_ring);
20937            std::thread::spawn(move || durable_terminal_history_of(&ring, "reader-module"))
20938        };
20939        started
20940            .recv_timeout(Duration::from_secs(5))
20941            .expect("the history read reached its pause");
20942
20943        let bound = Duration::from_secs(1);
20944        assert!(
20945            record_within("other-module", &other_ring, 20, bound),
20946            "another module's exit waited on a history read (journal writer held)"
20947        );
20948        assert!(
20949            record_within("reader-module", &reader_ring, 30, bound),
20950            "the read module's own exit waited on its history read (ring held)"
20951        );
20952
20953        drop(release);
20954        let paused = reading.join().unwrap();
20955        assert_eq!(
20956            paused.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
20957            vec![10],
20958            "an exit recorded after the read began lands in neither half of it"
20959        );
20960        assert_eq!(paused.journal_skipped_lines, 0);
20961        assert_eq!(paused.journal_read_errors, 0);
20962
20963        let after = durable_terminal_history_of(&reader_ring, "reader-module");
20964        assert_eq!(
20965            after.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
20966            vec![10, 30],
20967            "the next read merges ring and journal with no duplicate"
20968        );
20969        assert_eq!(after.journal_skipped_lines, 0);
20970    }
20971}
20972
20973/// What a restart does with the exited process's output readers. These drive
20974/// the same settle functions the supervisor calls, with a reader the test
20975/// holds, so a reader that has not been scheduled by the bound is a controlled
20976/// input rather than something only a loaded machine produces.
20977#[cfg(test)]
20978mod stderr_settle_tests {
20979    use std::{
20980        future::Future,
20981        io,
20982        pin::Pin,
20983        sync::{Arc, Mutex},
20984        task::{Context, Poll},
20985        time::Duration,
20986    };
20987
20988    use tokio::{
20989        io::{AsyncRead, ReadBuf},
20990        sync::oneshot,
20991        time::Instant,
20992    };
20993
20994    use super::{settle_stderr_pump, settle_stdout_pump, StderrPump};
20995    use crate::stderr_tail::{
20996        pump_stderr_to, pump_stdout_to, split_capture_stamp, untimed, CaptureState,
20997        ChildOutputSink, OutputSink, StderrRing, StderrTailConfig, TailEntry,
20998    };
20999
21000    const BOUND: Duration = Duration::from_millis(250);
21001
21002    /// Yields `before`, then stays pending until the gate is released, then
21003    /// yields `after` and reaches EOF. The bytes after the gate were written
21004    /// by a process that has already exited; only the reader is behind.
21005    struct HeldReader {
21006        before: Option<Vec<u8>>,
21007        gate: Option<oneshot::Receiver<()>>,
21008        after: io::Cursor<Vec<u8>>,
21009    }
21010
21011    impl AsyncRead for HeldReader {
21012        fn poll_read(
21013            mut self: Pin<&mut Self>,
21014            cx: &mut Context<'_>,
21015            buf: &mut ReadBuf<'_>,
21016        ) -> Poll<io::Result<()>> {
21017            if let Some(bytes) = self.before.take() {
21018                buf.put_slice(&bytes);
21019                return Poll::Ready(Ok(()));
21020            }
21021            if let Some(gate) = self.gate.as_mut() {
21022                match Pin::new(gate).poll(cx) {
21023                    Poll::Pending => return Poll::Pending,
21024                    Poll::Ready(_) => self.gate = None,
21025                }
21026            }
21027            Pin::new(&mut self.after).poll_read(cx, buf)
21028        }
21029    }
21030
21031    struct DiscardSink;
21032
21033    impl OutputSink for DiscardSink {
21034        fn write_line(&mut self, _line: &[u8]) {}
21035    }
21036
21037    fn line(text: &str) -> TailEntry {
21038        TailEntry::Line {
21039            text: text.to_string(),
21040            truncated: false,
21041            at_ms: None,
21042        }
21043    }
21044
21045    fn lock(ring: &Arc<Mutex<StderrRing>>) -> std::sync::MutexGuard<'_, StderrRing> {
21046        ring.lock().unwrap()
21047    }
21048
21049    /// Start a reader for a new process generation that delivers `before`
21050    /// immediately and `after` only once the returned sender fires (or is
21051    /// dropped).
21052    fn held_pump(
21053        ring: &Arc<Mutex<StderrRing>>,
21054        before: &str,
21055        after: &str,
21056    ) -> (StderrPump, oneshot::Sender<()>) {
21057        let generation = lock(ring).begin_process();
21058        let (release, gate) = oneshot::channel();
21059        let reader = HeldReader {
21060            before: Some(before.as_bytes().to_vec()),
21061            gate: Some(gate),
21062            after: io::Cursor::new(after.as_bytes().to_vec()),
21063        };
21064        let task = tokio::spawn(pump_stderr_to(
21065            reader,
21066            Arc::clone(ring),
21067            generation,
21068            DiscardSink,
21069        ));
21070        (StderrPump { task, generation }, release)
21071    }
21072
21073    async fn wait_until(ring: &Arc<Mutex<StderrRing>>, done: impl Fn(&StderrRing) -> bool) {
21074        for _ in 0..1000 {
21075            if done(&lock(ring)) {
21076                return;
21077            }
21078            tokio::time::sleep(Duration::from_millis(1)).await;
21079        }
21080        panic!(
21081            "ring never reached the expected state: {:?}",
21082            lock(ring).snapshot(None, None)
21083        );
21084    }
21085
21086    #[tokio::test(start_paused = true)]
21087    async fn a_crash_line_the_reader_had_not_reached_by_the_bound_is_kept_before_the_restart() {
21088        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21089        let (pump, release) = held_pump(&ring, "booting\n", "config error: missing storage\n");
21090
21091        settle_stderr_pump("crasher", &ring, pump, BOUND).await;
21092        let before_release = lock(&ring).snapshot(None, None);
21093        assert!(
21094            matches!(before_release.capture, CaptureState::Incomplete { .. }),
21095            "a reader that has not reached EOF cannot claim a whole tail: {before_release:?}"
21096        );
21097
21098        // The restart: the next process starts and writes before the old
21099        // reader catches up.
21100        let next = lock(&ring).begin_process();
21101        lock(&ring).push_line_from(next, "next process booting");
21102        release.send(()).unwrap();
21103        wait_until(&ring, |ring| {
21104            ring.snapshot(None, None).capture == CaptureState::Captured
21105        })
21106        .await;
21107
21108        assert_eq!(
21109            untimed(lock(&ring).snapshot(None, None).entries),
21110            vec![
21111                line("booting"),
21112                line("config error: missing storage"),
21113                TailEntry::ProcessStart,
21114                line("next process booting"),
21115            ],
21116            "the crash's last line must survive a slow reader and stay in the crashed process's section"
21117        );
21118    }
21119
21120    #[tokio::test(start_paused = true)]
21121    async fn a_pipe_held_open_by_a_descendant_reads_incomplete_without_delaying_the_restart_past_the_bound(
21122    ) {
21123        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21124        // `_held` is never fired: a descendant keeps the pipe open for the
21125        // whole test.
21126        let (pump, _held) = held_pump(&ring, "parent exiting\n", "");
21127
21128        let started = Instant::now();
21129        settle_stderr_pump("orphaning", &ring, pump, BOUND).await;
21130        assert_eq!(
21131            started.elapsed(),
21132            BOUND,
21133            "the restart must wait exactly the bound for a pipe that stays open, no longer"
21134        );
21135
21136        let next = lock(&ring).begin_process();
21137        lock(&ring).push_line_from(next, "next process booting");
21138        tokio::time::sleep(Duration::from_secs(60)).await;
21139
21140        let snapshot = lock(&ring).snapshot(None, None);
21141        match &snapshot.capture {
21142            CaptureState::Incomplete { reason } => assert!(
21143                reason.contains("had not reached EOF") && reason.contains("250ms"),
21144                "the reason must say what is missing and after how long: {reason}"
21145            ),
21146            other => panic!("expected Incomplete while the pipe is held open, got {other:?}"),
21147        }
21148        assert_eq!(
21149            untimed(snapshot.entries),
21150            vec![
21151                line("parent exiting"),
21152                TailEntry::ProcessStart,
21153                line("next process booting"),
21154            ]
21155        );
21156    }
21157
21158    #[tokio::test(start_paused = true)]
21159    async fn a_reader_that_reaches_eof_within_the_bound_leaves_the_tail_captured() {
21160        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21161        let (pump, release) = held_pump(&ring, "one\n", "two\n");
21162        release.send(()).unwrap();
21163
21164        settle_stderr_pump("clean", &ring, pump, BOUND).await;
21165
21166        let snapshot = lock(&ring).snapshot(None, None);
21167        assert_eq!(snapshot.capture, CaptureState::Captured);
21168        assert_eq!(untimed(snapshot.entries), vec![line("one"), line("two")]);
21169    }
21170
21171    #[tokio::test(start_paused = true)]
21172    async fn stdout_buffered_past_the_exit_drain_bound_reaches_the_capture_file() {
21173        const BURST: usize = 150;
21174        let capture = cortexkit_test_support::ScratchDir::new("stdout-exit-drain");
21175        let path = capture.join("two-pipe.stderr.log");
21176        let sink = ChildOutputSink::open(&path, cortexkit_log::Retention::default()).unwrap();
21177        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21178        let generation = lock(&ring).begin_process();
21179        let stdout = (0..BURST)
21180            .map(|i| format!("out-{i:04}-{}\n", "o".repeat(64)))
21181            .collect::<String>();
21182        let stderr = (0..BURST)
21183            .map(|i| format!("err-{i:04}-{}\n", "e".repeat(64)))
21184            .collect::<String>();
21185        // Model a child that has written both bursts and exited. Hold the stdout
21186        // reader after one line and a partial prefix, as if pipe readiness or
21187        // capture-file writes had delayed it. The final line also needs EOF to
21188        // flush: neither complete nor partial buffered output may be discarded.
21189        let first_chunk = stdout.find('\n').unwrap() + 1 + "out-0001-".len();
21190        let (release, gate) = oneshot::channel();
21191        let reader = HeldReader {
21192            before: Some(stdout.as_bytes()[..first_chunk].to_vec()),
21193            gate: Some(gate),
21194            after: io::Cursor::new(stdout.as_bytes()[first_chunk..stdout.len() - 1].to_vec()),
21195        };
21196        let (finished, completion) = oneshot::channel();
21197        let stdout_sink = sink.clone();
21198        let pump = tokio::spawn(async move {
21199            pump_stdout_to(reader, stdout_sink).await;
21200            finished.send(()).unwrap();
21201        });
21202        pump_stderr_to(io::Cursor::new(stderr.into_bytes()), ring, generation, sink).await;
21203
21204        let started = Instant::now();
21205        settle_stdout_pump("two-pipe", pump, BOUND).await;
21206        assert_eq!(
21207            started.elapsed(),
21208            BOUND,
21209            "a late reader must not hold up restart"
21210        );
21211        assert_eq!(
21212            std::fs::read_to_string(&path).unwrap().lines().count(),
21213            BURST + 1
21214        );
21215
21216        release
21217            .send(())
21218            .expect("stdout reader must survive the exit drain bound");
21219        tokio::time::timeout(Duration::from_secs(1), completion)
21220            .await
21221            .expect("released stdout reader must reach EOF")
21222            .expect("stdout capture must finish at EOF, not be cancelled");
21223        let contents = std::fs::read_to_string(&path).unwrap();
21224        let mut lines = contents
21225            .lines()
21226            .map(|line| split_capture_stamp(line).expect("capture stamp").1)
21227            .collect::<Vec<_>>();
21228        let mut expected = (0..BURST)
21229            .flat_map(|i| {
21230                [
21231                    format!("out-{i:04}-{}", "o".repeat(64)),
21232                    format!("err-{i:04}-{}", "e".repeat(64)),
21233                ]
21234            })
21235            .collect::<Vec<_>>();
21236        lines.sort_unstable();
21237        expected.sort_unstable();
21238        assert_eq!(
21239            lines, expected,
21240            "both pipes must retain every complete line exactly once"
21241        );
21242    }
21243}
21244
21245/// Containment of a module's process tree (issue #109).
21246///
21247/// The behaviour these defend against is a module helper surviving its module:
21248/// on a real machine the Synapse embedding module's CUDA worker holds ~2.2 GB of
21249/// VRAM, so a leaked grandchild is a leaked GPU allocation, and a day of restarts
21250/// compounds it.
21251///
21252/// They run against the SUPERVISOR rather than the job-object crate because the
21253/// claim is about teardown: a crate-level test proves a job can reap a tree, not
21254/// that the daemon's drain path reaches it.
21255///
21256/// Windows-only, like the mechanism. On Unix this arm compiles out; the cgroup
21257/// lane there is a separate containment path with its own tests.
21258#[cfg(all(test, windows))]
21259mod job_containment_tests {
21260    use super::*;
21261    use cortexkit_test_support::ScratchDir;
21262    use std::{
21263        path::{Path, PathBuf},
21264        sync::{Arc, Mutex},
21265        time::{Duration, Instant},
21266    };
21267
21268    /// The stub, expected beside this test executable.
21269    ///
21270    /// The existence check is here for the reason its twin at `fake_aft_stub_path`
21271    /// documents: `--lib` does not build `[[bin]]` targets, and a bare spawn
21272    /// failure then reads as a broken test rather than an unbuilt dependency.
21273    fn stub_path() -> PathBuf {
21274        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
21275        assert!(
21276            path.exists(),
21277            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
21278             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
21279            path.display()
21280        );
21281        path
21282    }
21283
21284    /// Poll for the grandchild pid the stub records, and parse it.
21285    fn read_grandchild_pid(path: &Path) -> u32 {
21286        let deadline = Instant::now() + Duration::from_secs(10);
21287        loop {
21288            if let Ok(contents) = std::fs::read_to_string(path) {
21289                if let Ok(pid) = contents.trim().parse() {
21290                    return pid;
21291                }
21292            }
21293            assert!(
21294                Instant::now() < deadline,
21295                "the stub never recorded a grandchild pid at {}",
21296                path.display()
21297            );
21298            std::thread::sleep(Duration::from_millis(10));
21299        }
21300    }
21301
21302    /// Everything one fixture run needs, so the two tests below differ in exactly
21303    /// one place: whether the child is contained.
21304    struct Fixture {
21305        _dir: ScratchDir,
21306        _roster: ChildRoster,
21307        module_id: String,
21308        grandchild: u32,
21309        child: Option<SupervisedChild>,
21310        registry: Arc<Registry>,
21311        snapshot: Arc<Mutex<SupervisorSnapshot>>,
21312        terminal_ring: Arc<Mutex<TerminalRing>>,
21313        spawn_events: SpawnEventFeed,
21314    }
21315
21316    fn fixture(label: &str, module_id: &str) -> Fixture {
21317        fixture_with_carry(label, module_id, false)
21318    }
21319
21320    fn fixture_with_carry(label: &str, module_id: &str, carry_containment: bool) -> Fixture {
21321        let dir = ScratchDir::new(label);
21322        let pid_file = dir.join("grandchild.pid");
21323        let supervisor = Supervisor::new_for_test(
21324            Arc::new(Registry::default()),
21325            RestartPolicy::new(3, Duration::ZERO),
21326        );
21327        let runtime = supervisor.runtime_config();
21328        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21329        let spec = ModuleSpec {
21330            script: None,
21331            module_id: module_id.to_string(),
21332            program: stub_path(),
21333            // Zero args deliberately: a `--subc` argument would make the stub dial
21334            // a daemon that is not there, and the failure would land in the same
21335            // stderr ring this fixture exists to keep quiet.
21336            args: Vec::new(),
21337            env: vec![
21338                ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
21339                (
21340                    "FAKE_AFT_GRANDCHILD_PID_FILE".to_string(),
21341                    pid_file.display().to_string(),
21342                ),
21343            ],
21344            reserved: false,
21345            reserved_prefixes: Vec::new(),
21346            protocol: ModuleProtocol::Subc,
21347            overlap: Default::default(),
21348            carry_containment,
21349        };
21350        let child = spawn_and_mark_running(&spec, &runtime, &snapshot)
21351            .expect("spawn the supervised fixture");
21352        let grandchild = read_grandchild_pid(&pid_file);
21353        Fixture {
21354            _dir: dir,
21355            _roster: runtime.child_roster.clone(),
21356            module_id: module_id.to_string(),
21357            grandchild,
21358            child: Some(child),
21359            registry: Arc::new(Registry::default()),
21360            snapshot,
21361            terminal_ring: Arc::clone(&runtime.terminal_ring),
21362            spawn_events: SpawnEventFeed::default(),
21363        }
21364    }
21365
21366    async fn assert_admission_kill_reaps_grandchild(carry: bool) {
21367        let label = if carry {
21368            "admission-kill-carried-tree"
21369        } else {
21370            "admission-kill-plain-tree"
21371        };
21372        let mut fixture = fixture_with_carry(label, label, carry);
21373        let descendant = subc_os::Process::open(fixture.grandchild)
21374            .unwrap()
21375            .expect("the stub descendant must be alive before admission kill");
21376        assert!(descendant.observe().is_some());
21377        let child = fixture.child.as_mut().unwrap();
21378        assert_eq!(child.child.container().is_some(), carry);
21379        assert_eq!(child.job.is_some(), !carry);
21380
21381        child.start_admission_kill().unwrap();
21382        assert!(child.admission_kill_sent);
21383        let status = timeout(Duration::from_secs(10), child.wait())
21384            .await
21385            .unwrap()
21386            .unwrap();
21387        assert_eq!(
21388            status.code(),
21389            Some(admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE),
21390            "containment teardown must preserve the leader's distinctive status"
21391        );
21392        // Keep the child and its job/container alive: later exit finalization or
21393        // handle drop must not be what makes the descendant-death claim pass.
21394        assert!(
21395            descendant.wait_for_exit(Duration::from_secs(10)).unwrap(),
21396            "admission kill left a descendant running before exit finalization"
21397        );
21398        assert_eq!(child.child.container().is_some(), carry);
21399        assert_eq!(child.job.is_some(), !carry);
21400        child.finish_exit(false).await.unwrap();
21401    }
21402
21403    #[tokio::test]
21404    async fn admission_kill_reaps_grandchild_with_plain_job() {
21405        assert_admission_kill_reaps_grandchild(false).await;
21406    }
21407
21408    #[tokio::test]
21409    async fn admission_kill_reaps_grandchild_with_carried_job() {
21410        assert_admission_kill_reaps_grandchild(true).await;
21411    }
21412
21413    #[tokio::test]
21414    async fn admission_kill_retires_registration_before_wait() {
21415        let mut fixture = fixture("admission-registration", "admission-registration");
21416        let handle = SupervisorHandle::new();
21417        let spawn =
21418            RegistrationSpawn::new(&handle, "admission-registration", SpawnRole::Plain, None);
21419        spawn.ready();
21420        let child = fixture.child.as_mut().unwrap();
21421        child.registration_spawn = Some(spawn.clone());
21422        child.start_admission_kill().unwrap();
21423        assert!(
21424            !spawn.launch_ready(),
21425            "admission kill must retire before its caller can await the child"
21426        );
21427        timeout(Duration::from_secs(10), child.wait())
21428            .await
21429            .unwrap()
21430            .unwrap();
21431        child.finish_exit(false).await.unwrap();
21432    }
21433
21434    impl Fixture {
21435        /// Drain through the supervisor's own teardown path.
21436        async fn drain(&mut self) {
21437            let child = self
21438                .child
21439                .take()
21440                .expect("the fixture child is still present");
21441            drain_child_to_state(
21442                &self.module_id,
21443                ModuleProtocol::Subc,
21444                // No forwarding table in this fixture, so nothing reaches the
21445                // child over a connection.
21446                StopNotice::NotSent,
21447                &self.registry,
21448                None,
21449                &self.snapshot,
21450                &self.terminal_ring,
21451                &self.spawn_events,
21452                child,
21453                Duration::from_millis(500),
21454                ModuleState::Stopped,
21455                Some(false),
21456                &FailureContext::operator(),
21457            )
21458            .await
21459            .expect("drain the supervised fixture");
21460        }
21461    }
21462
21463    /// Teardown reaps the grandchild, not merely the direct child.
21464    ///
21465    /// This is the assertion the change exists for. Before containment the
21466    /// grandchild survived: it is a separate process, and `start_kill` is
21467    /// `TerminateProcess` scoped to one pid.
21468    #[tokio::test]
21469    async fn teardown_reaps_the_grandchild() {
21470        let mut fixture = fixture("teardown-grandchild", "tree-teardown");
21471        let grandchild = fixture.grandchild;
21472
21473        assert!(
21474            subc_jobobject::process_exists(grandchild),
21475            "grandchild {grandchild} must be alive before teardown, or this proves nothing"
21476        );
21477
21478        fixture.drain().await;
21479
21480        assert!(
21481            subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
21482            "grandchild {grandchild} outlived module teardown: the tree was not contained"
21483        );
21484    }
21485
21486    /// The mutation control: with containment withheld, the grandchild survives
21487    /// the same kill.
21488    ///
21489    /// This is the defect reproduction from #109 — a direct-child kill reaches
21490    /// one pid, and the grandchild is a different process. It spawns OUTSIDE the
21491    /// supervisor because `spawn_and_mark_running` now always contains on
21492    /// Windows, which is the point: there is no longer a path that spawns
21493    /// uncontained, so the control has to construct one.
21494    ///
21495    /// Its job is to keep `teardown_reaps_the_grandchild` honest. If the
21496    /// grandchild ever dies here, that test is passing for a reason unrelated to
21497    /// the job object and the containment claim is unproven.
21498    #[test]
21499    fn an_uncontained_grandchild_survives_a_direct_child_kill() {
21500        let dir = ScratchDir::new("teardown-uncontained");
21501        let pid_file = dir.join("grandchild.pid");
21502        let mut child = std::process::Command::new(stub_path())
21503            .env("FAKE_AFT_NEVER_CONNECT", "1")
21504            .env(
21505                "FAKE_AFT_GRANDCHILD_PID_FILE",
21506                pid_file.display().to_string(),
21507            )
21508            .stdin(std::process::Stdio::null())
21509            .stdout(std::process::Stdio::null())
21510            .stderr(std::process::Stdio::null())
21511            .spawn()
21512            .expect("spawn the uncontained fixture");
21513        let grandchild = read_grandchild_pid(&pid_file);
21514
21515        // Exactly what the pre-fix teardown did: kill the direct child.
21516        child.kill().expect("kill the direct child");
21517        let _ = child.wait();
21518
21519        assert!(
21520            subc_jobobject::process_exists(grandchild),
21521            "grandchild {grandchild} died with the direct child, so this control no longer \
21522             distinguishes contained from uncontained teardown and the regression test is \
21523             passing vacuously"
21524        );
21525
21526        // The orphan this control demonstrates is the leak the fix prevents, so
21527        // the control must not leave one behind.
21528        kill_tree(grandchild);
21529    }
21530
21531    /// Crash durability: closing the containment handle reaps the tree with no
21532    /// teardown code running at all.
21533    ///
21534    /// This is the case `taskkill /T` cannot cover — a daemon that dies cannot
21535    /// call anything — and it is why containment is a kernel property of the
21536    /// handle rather than a step in the drain. Discovered by getting the
21537    /// mutation control wrong: clearing `job` to "disable" containment instead
21538    /// killed the tree, which is the guarantee, not a mistake.
21539    #[tokio::test]
21540    async fn dropping_containment_reaps_the_grandchild() {
21541        let mut fixture = fixture("drop-containment", "tree-drop");
21542        let grandchild = fixture.grandchild;
21543
21544        assert!(subc_jobobject::process_exists(grandchild));
21545
21546        // No `drain` call, no kill: dropping the handle is the entire mechanism.
21547        fixture.child.as_mut().expect("child present").job = None;
21548
21549        assert!(
21550            subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
21551            "grandchild {grandchild} survived the containment handle closing, so a daemon \
21552             crash would leave the tree behind"
21553        );
21554    }
21555
21556    /// Kill a pid and its tree, then confirm it is gone.
21557    fn kill_tree(pid: u32) {
21558        let _ = std::process::Command::new("taskkill.exe")
21559            .args(["/PID", &pid.to_string(), "/T", "/F"])
21560            .stdin(std::process::Stdio::null())
21561            .stdout(std::process::Stdio::null())
21562            .stderr(std::process::Stdio::null())
21563            .status();
21564        assert!(
21565            subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10)),
21566            "could not clean up grandchild {pid}"
21567        );
21568    }
21569}
21570
21571#[cfg(test)]
21572mod privacy_trampoline_configuration_tests {
21573    #[tokio::test]
21574    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21575    async fn macos_spawn_without_a_configured_trampoline_refuses_by_name() {
21576        #[cfg(target_os = "macos")]
21577        {
21578            let supervisor = super::Supervisor::new(
21579                std::sync::Arc::new(crate::Registry::default()),
21580                super::RestartPolicy::default(),
21581            );
21582            let error = supervisor.spawn(spec()).unwrap_err();
21583            assert!(
21584                error
21585                    .to_string()
21586                    .contains("no privacy trampoline configured"),
21587                "{error}"
21588            );
21589        }
21590    }
21591
21592    #[tokio::test]
21593    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21594    async fn macos_wrong_trampoline_is_rejected_by_the_startup_probe() {
21595        #[cfg(target_os = "macos")]
21596        {
21597            let supervisor = super::Supervisor::new(
21598                std::sync::Arc::new(crate::Registry::default()),
21599                super::RestartPolicy::default(),
21600            )
21601            .with_privacy_trampoline(std::env::current_exe().unwrap());
21602            let error = supervisor.spawn(spec()).unwrap_err();
21603            assert!(
21604                error
21605                    .to_string()
21606                    .contains("binary does not implement the privacy trampoline protocol"),
21607                "{error}"
21608            );
21609        }
21610    }
21611
21612    #[cfg(target_os = "macos")]
21613    fn spec() -> super::ModuleSpec {
21614        super::ModuleSpec {
21615            module_id: "privacy-configuration".into(),
21616            program: "/bin/sleep".into(),
21617            args: vec!["30".into()],
21618            env: vec![],
21619            reserved: false,
21620            reserved_prefixes: vec![],
21621            protocol: subc_control::ModuleProtocol::None,
21622            overlap: super::ModuleOverlap::Exclusive,
21623            carry_containment: false,
21624            script: None,
21625        }
21626    }
21627}
21628
21629#[cfg(test)]
21630mod privacy_exec_boundary_tests {
21631    #[cfg(target_os = "macos")]
21632    use super::*;
21633    #[cfg(target_os = "macos")]
21634    use std::{
21635        io::{Read, Write},
21636        net::{TcpListener, TcpStream},
21637    };
21638
21639    /// Unit-test-only pause at the actual early image read, not at a later
21640    /// status read. Production supervisors never inspect this environment key.
21641    #[cfg(target_os = "macos")]
21642    pub(super) fn before_image_sample(spec: &ModuleSpec, pid: u32) {
21643        if let Some((_, path)) = spec
21644            .env
21645            .iter()
21646            .find(|(key, _)| key == "SUBC_TEST_PRIVACY_SAMPLE_BARRIER")
21647        {
21648            let mut barrier = TcpStream::connect(path).unwrap();
21649            barrier
21650                .set_read_timeout(Some(Duration::from_secs(30)))
21651                .unwrap();
21652            barrier.write_all(&pid.to_ne_bytes()).unwrap();
21653            let mut release = [0];
21654            barrier.read_exact(&mut release).unwrap();
21655            assert_eq!(&release, b"X");
21656        }
21657    }
21658
21659    #[cfg(target_os = "macos")]
21660    fn spec(program: &str, args: &[&str]) -> ModuleSpec {
21661        ModuleSpec {
21662            script: None,
21663            module_id: "privacy-boundary".into(),
21664            program: program.into(),
21665            args: args.iter().map(|arg| (*arg).into()).collect(),
21666            env: vec![],
21667            reserved: false,
21668            reserved_prefixes: vec![],
21669            protocol: ModuleProtocol::None,
21670            overlap: ModuleOverlap::Exclusive,
21671            carry_containment: false,
21672        }
21673    }
21674
21675    #[cfg(target_os = "macos")]
21676    async fn accept(listener: TcpListener) -> TcpStream {
21677        // Socket readiness, not elapsed time, establishes both pause points.
21678        let listener = tokio::net::TcpListener::from_std({
21679            listener.set_nonblocking(true).unwrap();
21680            listener
21681        })
21682        .unwrap();
21683        let (stream, _) = tokio::time::timeout(Duration::from_secs(30), listener.accept())
21684            .await
21685            .unwrap()
21686            .unwrap();
21687        let stream = stream.into_std().unwrap();
21688        stream.set_nonblocking(false).unwrap();
21689        stream
21690            .set_read_timeout(Some(Duration::from_secs(30)))
21691            .unwrap();
21692        stream
21693    }
21694
21695    #[tokio::test]
21696    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21697    async fn macos_roster_withholds_a_nonnull_trampoline_image_until_exec_confirmation() {
21698        #[cfg(target_os = "macos")]
21699        {
21700            let root = cortexkit_test_support::ScratchDir::new("privacy-roster-barrier");
21701            // Loopback sockets also work when the replay adapter's TMPDIR is
21702            // longer than Darwin's Unix-domain socket path limit.
21703            let exec_listener = TcpListener::bind("127.0.0.1:0").unwrap();
21704            let sample_listener = TcpListener::bind("127.0.0.1:0").unwrap();
21705            let record = root.join("live-children.json");
21706            let supervisor =
21707                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21708                    .with_live_children_record(&record);
21709            let runtime = supervisor.runtime_config();
21710            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21711            let mut spec = spec("/bin/sleep", &["30"]);
21712            spec.env = vec![
21713                (
21714                    "SUBC_TEST_PRIVACY_EXEC_BARRIER".into(),
21715                    exec_listener.local_addr().unwrap().to_string(),
21716                ),
21717                (
21718                    "SUBC_TEST_PRIVACY_SAMPLE_BARRIER".into(),
21719                    sample_listener.local_addr().unwrap().to_string(),
21720                ),
21721            ];
21722            let spawn = tokio::task::spawn_blocking(move || {
21723                spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap()
21724            });
21725            let mut sample = accept(sample_listener).await;
21726            let mut pid = [0; 4];
21727            sample.read_exact(&mut pid).unwrap();
21728            let pid = u32::from_ne_bytes(pid);
21729            let mut exec = accept(exec_listener).await;
21730            let mut ready = [0];
21731            exec.read_exact(&mut ready).unwrap();
21732            assert_eq!(&ready, b"R");
21733            // The early read is guaranteed to see a real, non-null trampoline
21734            // image: the fixture has reached its barrier and cannot exec yet.
21735            let trampoline = subc_os::file_identity(&test_privacy_trampoline()).unwrap();
21736            assert_eq!(
21737                observe_spawned_image(pid).unwrap().executable,
21738                Some(trampoline)
21739            );
21740            sample.write_all(b"X").unwrap();
21741            let mut child = spawn.await.unwrap();
21742            let early = crate::live_children::read_record(&record).unwrap();
21743            assert_eq!(early.len(), 1);
21744            assert_eq!(early[0].pid, pid);
21745            assert_eq!(
21746                early[0].executable, None,
21747                "unconfirmed trampoline image entered the roster"
21748            );
21749            assert!(child.report_ready.get().is_none());
21750            // The barrier's duration is unrelated to the production five-second
21751            // exec budget. Start the test's confirmation budget upon release.
21752            child.privacy_exec.as_mut().unwrap().deadline =
21753                tokio::time::Instant::now() + Duration::from_secs(30);
21754            exec.write_all(b"X").unwrap();
21755            child.confirm_privacy_exec().await;
21756            assert_eq!(child.spawn_failure, None);
21757            assert!(child.report_ready.get().is_some());
21758            let confirmed = crate::live_children::read_record(&record).unwrap();
21759            let module = subc_os::file_identity(std::path::Path::new("/bin/sleep")).unwrap();
21760            assert_ne!(module, trampoline);
21761            assert_eq!(confirmed[0].executable, Some(module.into()));
21762            child.start_kill().unwrap();
21763            child.wait().await.unwrap();
21764            child.release_roster();
21765        }
21766    }
21767
21768    #[tokio::test]
21769    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21770    async fn macos_unstamped_reexec_records_the_observed_native_image() {
21771        #[cfg(target_os = "macos")]
21772        {
21773            let root = cortexkit_test_support::ScratchDir::new("privacy-reexec");
21774            let record = root.join("live-children.json");
21775            let supervisor =
21776                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21777                    .with_live_children_record(&record);
21778            let runtime = supervisor.runtime_config();
21779            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21780            let fixture = crate::config_gate::program::native_fixture_for_test();
21781            let mut spec = spec(
21782                "/bin/sh",
21783                &["-c", "exec \"$1\" 600", "reexec", fixture.to_str().unwrap()],
21784            );
21785            spec.env
21786                .push(("SUBC_TEST_PRIVACY_IMAGE_DELAY_MS".into(), "5".into()));
21787            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21788            let native_image = subc_os::file_identity(&fixture).unwrap();
21789            // Native image installation, not shell startup speed, establishes
21790            // that this launch has crossed the re-exec boundary before sampling.
21791            let reexec = tokio::time::timeout(Duration::from_secs(5), async {
21792                while observe_spawned_image(child.pid).and_then(|image| image.executable)
21793                    != Some(native_image)
21794                {
21795                    tokio::time::sleep(Duration::from_millis(1)).await;
21796                }
21797            })
21798            .await;
21799            child.confirm_privacy_exec().await;
21800            let failure = child.spawn_failure.clone();
21801            let ready = child.report_ready.get().is_some();
21802            let confirmed = crate::live_children::read_record(&record).unwrap();
21803            child.start_kill().unwrap();
21804            tokio::time::timeout(Duration::from_secs(5), child.wait())
21805                .await
21806                .unwrap()
21807                .unwrap();
21808            child.release_roster();
21809
21810            reexec.expect("the shell must re-exec the native fixture");
21811            assert_eq!(
21812                failure, None,
21813                "an unstamped program may re-exec before observation"
21814            );
21815            assert!(ready);
21816            assert_eq!(confirmed.len(), 1);
21817            assert_eq!(confirmed[0].executable, Some(native_image.into()));
21818        }
21819    }
21820
21821    #[tokio::test]
21822    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21823    async fn macos_unstamped_ack_without_exec_still_refuses_the_trampoline() {
21824        #[cfg(target_os = "macos")]
21825        {
21826            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
21827            let supervisor =
21828                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
21829            let runtime = supervisor.runtime_config();
21830            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21831            let fixture = crate::config_gate::program::native_fixture_for_test();
21832            let mut spec = spec(fixture.to_str().unwrap(), &["600"]);
21833            spec.env.push((
21834                "SUBC_TEST_PRIVACY_EXEC_BARRIER".into(),
21835                listener.local_addr().unwrap().to_string(),
21836            ));
21837            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21838            let mut exec = accept(listener).await;
21839            let mut ready = [0];
21840            exec.read_exact(&mut ready).unwrap();
21841            assert_eq!(&ready, b"R");
21842            assert_eq!(
21843                observe_spawned_image(child.pid).unwrap().executable,
21844                subc_os::file_identity(&test_privacy_trampoline())
21845            );
21846            // Simulate a broken trampoline that acknowledges exec but keeps
21847            // running its own image, held at the fixture's pre-exec barrier.
21848            let (reader, writer) = std::io::pipe().unwrap();
21849            drop(writer);
21850            child.privacy_exec.as_mut().unwrap().reader =
21851                tokio::io::unix::AsyncFd::new(reader).unwrap();
21852            child.confirm_privacy_exec().await;
21853            let failure = child.spawn_failure.clone();
21854            let ready = child.report_ready.get().is_some();
21855            child.start_kill().unwrap();
21856            tokio::time::timeout(Duration::from_secs(5), child.wait())
21857                .await
21858                .unwrap()
21859                .unwrap();
21860            child.release_roster();
21861            assert_eq!(
21862                failure.as_deref(),
21863                Some("privacy identity trampoline did not exec the module")
21864            );
21865            assert!(!ready);
21866        }
21867    }
21868
21869    #[tokio::test]
21870    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21871    async fn macos_resumed_121_is_a_module_exit_not_a_trampoline_refusal() {
21872        #[cfg(target_os = "macos")]
21873        {
21874            let registry = Arc::new(Registry::default());
21875            let policy = RestartPolicy::new(0, Duration::ZERO);
21876            let fixture = crate::config_gate::program::native_fixture_for_test();
21877            let spec = spec(fixture.to_str().unwrap(), &["exit121"]);
21878            let scratch = cortexkit_test_support::ScratchDir::new("resumed-exit");
21879            let supervisor = Supervisor::new_for_test(Arc::clone(&registry), policy)
21880                .with_config_runtime(suspended_spawn_tests::gated_owner(&scratch, &spec, true));
21881            let runtime = supervisor.runtime_config();
21882            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21883            // A module cannot exit before suspended admission. After resume,
21884            // retain the real exit status even when it resembles a refusal.
21885            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21886            child.confirm_privacy_exec().await;
21887            assert_eq!(child.spawn_failure, None);
21888            assert!(child.report_ready.get().is_some());
21889            let pid = child.pid;
21890            tokio::task::spawn_blocking(move || {
21891                subc_os::fork_exec_test::wait_for_child_exit_without_reaping(pid)
21892            })
21893            .await
21894            .unwrap()
21895            .unwrap();
21896            let status = child.wait().await.unwrap();
21897            assert_eq!(status.code(), Some(121));
21898            assert!(child.privacy_exec.is_none());
21899            let report = classify_reaped_child_exit(&snapshot, &child, &status);
21900            on_child_exit(
21901                &spec,
21902                policy,
21903                &registry,
21904                &snapshot,
21905                &runtime.terminal_ring,
21906                &runtime.spawn_events,
21907                &runtime.child_roster,
21908                report,
21909                true,
21910            )
21911            .await;
21912            let state = lock_snapshot(&snapshot).unwrap();
21913            assert_eq!(state.state, ModuleState::Failed);
21914            assert_eq!(state.last_exit.as_ref().unwrap().code, Some(121));
21915            assert_eq!(state.reported_pid(), None);
21916            drop(state);
21917            let history = runtime.terminal_ring.lock().unwrap().snapshot();
21918            assert_eq!(history.entries.len(), 1);
21919            let terminal = &history.entries[0];
21920            assert_eq!(terminal.exit_code, Some(121));
21921            assert_eq!(terminal.exit_kind, subc_control::TerminalExitKind::Crash);
21922            assert_eq!(terminal.disposition, TerminalDisposition::Failed);
21923            assert_eq!(
21924                terminal.disposition_detail.as_deref(),
21925                Some(policy.budget_exhausted_detail().as_str()),
21926                "module exit 121 was classified as a trampoline refusal: {terminal:?}"
21927            );
21928            assert_eq!(child.spawn_failure, None);
21929            child.release_roster();
21930        }
21931    }
21932}
21933
21934#[cfg(all(test, target_os = "macos"))]
21935#[path = "supervise/suspended_spawn_tests.rs"]
21936mod suspended_spawn_tests;
21937
21938/// The daemon's real spawn path hands a subc-wire child its launch nonce on
21939/// descriptor 3, without an environment copy. The shell records the nonce
21940/// and its environment after exec so these tests observe the real handover.
21941#[cfg(all(test, unix))]
21942mod launch_nonce_descriptor_tests {
21943    use super::{ChildRoster, ModuleProtocol, ModuleSpec, SupervisorHandle};
21944    use crate::stderr_tail::{StderrRing, StderrTailConfig};
21945    use cortexkit_test_support::ScratchDir;
21946    use std::{
21947        path::PathBuf,
21948        sync::{Arc, Mutex},
21949        time::{Duration, Instant},
21950    };
21951
21952    async fn probe(role: super::SpawnRole) {
21953        let scratch = ScratchDir::new("launch-nonce-descriptor");
21954        let fd_copy = scratch.join("from-descriptor");
21955        let env_copy = scratch.join("environment");
21956        let script = format!(
21957            "env > '{env}.tmp' && mv '{env}.tmp' '{env}'; cat <&3 > '{fd}.tmp' && mv '{fd}.tmp' '{fd}'; sleep 30",
21958            fd = fd_copy.display(), env = env_copy.display(),
21959        );
21960        let xdg = |name: &str| (name.to_string(), scratch.join(name).display().to_string());
21961        let spec = ModuleSpec {
21962            script: None,
21963            module_id: "nonce-descriptor-probe".to_string(),
21964            program: PathBuf::from("/bin/sh"),
21965            args: vec!["-c".to_string(), script],
21966            env: vec![
21967                xdg("XDG_DATA_HOME"),
21968                xdg("XDG_RUNTIME_DIR"),
21969                xdg("XDG_CONFIG_HOME"),
21970                ("SUBC_LAUNCH_NONCE".to_string(), "must-not-leak".to_string()),
21971            ],
21972            reserved: true,
21973            reserved_prefixes: Vec::new(),
21974            protocol: ModuleProtocol::Subc,
21975            overlap: Default::default(),
21976            carry_containment: false,
21977        };
21978        let handle = SupervisorHandle::new();
21979        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21980        let roster = ChildRoster::default();
21981        #[cfg(target_os = "macos")]
21982        {
21983            let path = super::test_privacy_trampoline();
21984            roster.set_privacy_trampoline(super::probe_privacy_trampoline(&path).map(|()| path));
21985        }
21986        let child = super::spawn_child_in_slot(
21987            &spec,
21988            None,
21989            Some(&handle),
21990            &ring,
21991            None,
21992            &roster,
21993            None,
21994            #[cfg(target_os = "linux")]
21995            None,
21996            role,
21997            matches!(role, super::SpawnRole::SwapCandidate),
21998            super::DEFAULT_REGISTER_TIMEOUT,
21999        )
22000        .expect("spawn probe");
22001        let deadline = Instant::now() + Duration::from_secs(10);
22002        while !(fd_copy.exists() && env_copy.exists()) {
22003            assert!(Instant::now() < deadline, "probe never wrote its copies");
22004            tokio::time::sleep(Duration::from_millis(20)).await;
22005        }
22006        let nonce = std::fs::read_to_string(fd_copy).unwrap();
22007        assert!(!nonce.is_empty());
22008        let environment = std::fs::read_to_string(env_copy).unwrap();
22009        assert!(environment
22010            .lines()
22011            .any(|line| line.starts_with("SUBC_LAUNCH_NONCE_FD=3:")));
22012        let copy = environment
22013            .lines()
22014            .find_map(|line| line.strip_prefix("SUBC_LAUNCH_NONCE="));
22015        assert_eq!(
22016            copy, None,
22017            "Unix children must never receive the environment nonce"
22018        );
22019        if matches!(role, super::SpawnRole::Plain) {
22020            assert_eq!(
22021                handle.spawn_nonce(&spec.module_id).as_deref(),
22022                Some(nonce.as_str())
22023            );
22024        }
22025        drop(child);
22026    }
22027
22028    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
22029    async fn a_spawned_module_receives_its_nonce_only_on_descriptor_3() {
22030        probe(super::SpawnRole::Plain).await;
22031    }
22032
22033    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
22034    async fn swap_candidate_receives_its_nonce_only_on_descriptor_3() {
22035        probe(super::SpawnRole::SwapCandidate).await;
22036    }
22037}
22038
22039#[cfg(all(test, target_os = "linux"))]
22040#[path = "supervise/cgroup_reap_tests.rs"]
22041mod cgroup_reap_tests;
22042
22043#[cfg(all(test, target_os = "linux"))]
22044mod cgroup_containment_tests {
22045    use super::*;
22046    use cortexkit_test_support::ScratchDir;
22047
22048    #[tokio::test]
22049    async fn linux_subtree_memory_covers_module_children() {
22050        let dir = ScratchDir::new("subtree-memory");
22051        let root = PathBuf::from(format!(
22052            "/sys/fs/cgroup/subc-memory-test-{}-{}",
22053            std::process::id(),
22054            unix_ms_now()
22055        ));
22056        if let Err(error) = std::fs::create_dir(&root) {
22057            assert!(
22058                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
22059                "required cgroup test cannot execute: {error}"
22060            );
22061            eprintln!("SKIP linux_subtree_memory_covers_module_children: {error}");
22062            return;
22063        }
22064        let placement = subc_cgroup::prepare_at(&root)
22065            .unwrap()
22066            .expect("delegated cgroup");
22067        let supervisor = Supervisor::new_for_test(
22068            Arc::new(Registry::default()),
22069            RestartPolicy::new(3, Duration::ZERO),
22070        )
22071        .with_cgroup_placement(Some(placement));
22072        let ready = dir.join("ready");
22073        let module = supervisor
22074            .spawn(ModuleSpec {
22075                script: None,
22076                module_id: "memory-tree".into(),
22077                program: PathBuf::from("/bin/sh"),
22078                args: vec![
22079                    "-c".into(),
22080                    "sleep 600 & sleep 600 & sleep 600 & echo ready > \"$1\"; wait".into(),
22081                    "fixture".into(),
22082                    ready.display().to_string(),
22083                ],
22084                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
22085                    .into_iter()
22086                    .map(|key| (key.into(), dir.display().to_string()))
22087                    .collect(),
22088                reserved: false,
22089                reserved_prefixes: Vec::new(),
22090                protocol: ModuleProtocol::None,
22091                overlap: Default::default(),
22092                carry_containment: false,
22093            })
22094            .unwrap();
22095        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
22096        while !ready.exists() {
22097            assert!(
22098                tokio::time::Instant::now() < deadline,
22099                "children never started"
22100            );
22101            tokio::time::sleep(Duration::from_millis(10)).await;
22102        }
22103        let readings = crate::subtree_resources::read(vec![module.subtree_target()]).await;
22104        let reading = &readings[0];
22105        assert!(
22106            reading.process_count.is_some_and(|count| count >= 4),
22107            "{reading:?}"
22108        );
22109        assert!(
22110            reading.memory_bytes.is_some_and(|bytes| bytes > 0),
22111            "{reading:?}"
22112        );
22113        module.stop().await.unwrap();
22114        drop(module);
22115        std::fs::remove_dir(root.join("subc-modules")).unwrap();
22116        std::fs::remove_dir(&root).unwrap();
22117        eprintln!("EXECUTED linux_subtree_memory_covers_module_children: {reading:?}");
22118    }
22119
22120    fn running(pid: u32) -> bool {
22121        // An orphan can remain a zombie until the container init reaps it.
22122        std::fs::read_to_string(format!("/proc/{pid}/stat"))
22123            .ok()
22124            .and_then(|stat| {
22125                stat.rsplit_once(") ")
22126                    .map(|(_, rest)| rest.starts_with('Z'))
22127            })
22128            .is_some_and(|zombie| !zombie)
22129    }
22130
22131    #[tokio::test]
22132    async fn linux_teardown_reaps_the_grandchild() {
22133        teardown_tree("linux_teardown_reaps_the_grandchild", false).await;
22134    }
22135
22136    #[tokio::test]
22137    async fn linux_shutdown_straggler_reaps_the_grandchild() {
22138        teardown_tree("linux_shutdown_straggler_reaps_the_grandchild", true).await;
22139    }
22140
22141    async fn teardown_tree(test_name: &str, shutdown: bool) {
22142        let dir = ScratchDir::new(test_name);
22143        let root = PathBuf::from(format!(
22144            "/sys/fs/cgroup/subc-tree-test-{test_name}-{}-{}",
22145            std::process::id(),
22146            unix_ms_now()
22147        ));
22148        if let Err(error) = std::fs::create_dir(&root) {
22149            assert!(
22150                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
22151                "required cgroup test cannot execute: {error}"
22152            );
22153            eprintln!(
22154                "SKIP {test_name}: no writable delegated cgroup at {}: {error}",
22155                root.display()
22156            );
22157            return;
22158        }
22159        let placement = subc_cgroup::prepare_at(&root)
22160            .expect("prepare isolated kernel cgroup")
22161            .expect("isolated cgroup is delegated");
22162        let module_id = "tree-teardown";
22163        let module = placement
22164            .module_path(module_id)
22165            .expect("create isolated module cgroup");
22166        if !module.join("cgroup.kill").exists() {
22167            std::fs::remove_dir(&module).unwrap();
22168            std::fs::remove_dir(root.join("subc-modules")).unwrap();
22169            std::fs::remove_dir(&root).unwrap();
22170            assert!(
22171                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
22172                "required cgroup.kill interface unavailable"
22173            );
22174            eprintln!("SKIP {test_name}: cgroup.kill unavailable (kernel < 5.14)");
22175            return;
22176        }
22177        let supervisor = Supervisor::new_for_test(
22178            Arc::new(Registry::default()),
22179            RestartPolicy::new(3, Duration::ZERO),
22180        )
22181        .with_cgroup_placement(Some(placement));
22182        let mut runtime = supervisor.runtime_config();
22183        runtime.child_roster = runtime
22184            .child_roster
22185            .for_module(Arc::new(Mutex::new(Duration::from_millis(100))));
22186        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
22187        let pid_file = dir.join("grandchild.pid");
22188        let spec = ModuleSpec {
22189            script: None,
22190            module_id: module_id.to_string(),
22191            program: PathBuf::from("/bin/sh"),
22192            args: vec![
22193                "-c".into(),
22194                "trap '' TERM; sleep 600 & echo $! > \"$1\"; wait".into(),
22195                "fixture".into(),
22196                pid_file.display().to_string(),
22197            ],
22198            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
22199                .into_iter()
22200                .map(|key| (key.to_string(), dir.display().to_string()))
22201                .collect(),
22202            reserved: false,
22203            reserved_prefixes: Vec::new(),
22204            protocol: ModuleProtocol::None,
22205            overlap: Default::default(),
22206            carry_containment: false,
22207        };
22208        let child =
22209            spawn_and_mark_running(&spec, &runtime, &snapshot).expect("spawn supervised tree");
22210        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
22211        let grandchild: u32 = loop {
22212            if let Ok(contents) = std::fs::read_to_string(&pid_file) {
22213                if let Ok(pid) = contents.trim().parse() {
22214                    break pid;
22215                }
22216            }
22217            assert!(
22218                tokio::time::Instant::now() < deadline,
22219                "grandchild pid was not recorded"
22220            );
22221            tokio::time::sleep(Duration::from_millis(10)).await;
22222        };
22223        assert!(
22224            running(grandchild),
22225            "grandchild must be alive before teardown"
22226        );
22227        if shutdown {
22228            let mut child = child;
22229            crate::child_roster::end_children_for_daemon_shutdown(
22230                &runtime.child_roster,
22231                false,
22232                std::future::pending(),
22233            )
22234            .await;
22235            child.wait().await.expect("reap shutdown straggler");
22236        } else {
22237            drain_child_to_state(
22238                module_id,
22239                ModuleProtocol::None,
22240                StopNotice::NotSent,
22241                &Registry::default(),
22242                None,
22243                &snapshot,
22244                &runtime.terminal_ring,
22245                &SpawnEventFeed::default(),
22246                child,
22247                Duration::from_millis(100),
22248                ModuleState::Stopped,
22249                Some(false),
22250                &FailureContext::operator(),
22251            )
22252            .await
22253            .expect("real supervisor teardown");
22254        }
22255        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
22256        while running(grandchild) && tokio::time::Instant::now() < deadline {
22257            tokio::time::sleep(Duration::from_millis(10)).await;
22258        }
22259        let survived = running(grandchild);
22260        // Kill a surviving grandchild so a failed test does not leave it behind.
22261        if survived {
22262            let pid = rustix::process::Pid::from_raw(grandchild as i32).unwrap();
22263            let _ = rustix::process::kill_process(pid, rustix::process::Signal::KILL);
22264            tokio::time::sleep(Duration::from_millis(100)).await;
22265        }
22266        if module.exists() {
22267            std::fs::remove_dir(&module).expect("remove empty module cgroup");
22268        }
22269        std::fs::remove_dir(root.join("subc-modules")).unwrap();
22270        std::fs::remove_dir(&root).unwrap();
22271        assert!(
22272            !survived,
22273            "grandchild {grandchild} outlived module teardown"
22274        );
22275        eprintln!("EXECUTED {test_name}: grandchild {grandchild} killed in isolated cgroup");
22276    }
22277}
22278
22279/// A slow live-children record write on the restart path must not stop the
22280/// daemon from answering the replacement module's authentication handshake.
22281#[cfg(all(test, unix))]
22282mod record_write_stall_tests {
22283    use super::*;
22284    use std::sync::atomic::{AtomicBool, Ordering};
22285    use subc_transport::{authenticate_client, ConnectionInfo, Endpoint, SCHEMA_VERSION};
22286
22287    /// `subc-client-rs` gives the whole handshake this long before the module
22288    /// exits with `Timeout { stage: ServerProof }`.
22289    const MODULE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
22290    /// How long the replacement's admission write is held: longer than the
22291    /// module's deadline, standing in for the delay a busy disk can add
22292    /// across the two syncs in that write.
22293    const HELD_RECORD_WRITE: Duration = Duration::from_secs(3);
22294
22295    /// A module that runs `/bin/sleep` directly, not through `/bin/sh -c`.
22296    /// On macOS every module is launched through the privacy trampoline, and
22297    /// a module that is not a `#!` script is admitted only if its running
22298    /// image is the configured program. With `/bin/sh -c "exec sleep 600"`
22299    /// the shell soon replaces itself with `/bin/sleep`, which does not match
22300    /// the configured `/bin/sh`. The image is read only after the spawn's
22301    /// live-children record write, and here that write lasted long enough for
22302    /// the shell to have exec'd every time, so each process was refused and
22303    /// killed right after spawn, and the supervisor crash-looped it with
22304    /// backoff until its restart budget ran out. The restart this test
22305    /// measures would then never produce a module at all.
22306    fn sleeping_spec() -> ModuleSpec {
22307        ModuleSpec {
22308            script: None,
22309            module_id: "record-write-stall".into(),
22310            program: "/bin/sleep".into(),
22311            args: vec!["600".into()],
22312            env: vec![],
22313            reserved: false,
22314            reserved_prefixes: vec![],
22315            protocol: ModuleProtocol::None,
22316            overlap: Default::default(),
22317            carry_containment: false,
22318        }
22319    }
22320
22321    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
22322    async fn module_auth_completes_while_the_restart_waits_on_the_record_write() {
22323        let home = cortexkit_test_support::ScratchDir::new("record-write-stall");
22324        let supervisor =
22325            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
22326                .with_live_children_record(home.join("live-children.json"));
22327        let module = supervisor.spawn(sleeping_spec()).unwrap();
22328        // `reported_pid` names a process only once it is confirmed as the
22329        // module (on macOS, once the trampoline's image check has passed), so
22330        // a process the daemon is about to refuse and kill never counts as
22331        // the running module, here or in the final wait below.
22332        let old_pid = tokio::time::timeout(Duration::from_secs(10), async {
22333            loop {
22334                if let Some(pid) = lock_snapshot(&module.inner.snapshot)
22335                    .unwrap()
22336                    .reported_pid()
22337                {
22338                    return pid;
22339                }
22340                tokio::time::sleep(Duration::from_millis(10)).await;
22341            }
22342        })
22343        .await
22344        .expect("the first process was admitted as the module");
22345
22346        // The daemon's listener, served by this runtime's workers like the
22347        // supervisor's own tasks.
22348        let key = vec![0x42; 32];
22349        let daemon_id = [0x24; 16];
22350        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
22351        let port = listener.local_addr().unwrap().port();
22352        let server = tokio::spawn(crate::server::serve_listener(
22353            listener,
22354            Arc::new(crate::router::Router::with_default_self_handler()),
22355            crate::server::ServerAuth::with_limits(
22356                key.clone(),
22357                daemon_id,
22358                "test",
22359                crate::server::DEFAULT_AUTH_DEADLINE,
22360                4,
22361            ),
22362        ));
22363
22364        // Hold the write that admits the replacement, once, and say when it
22365        // has started.
22366        let (held_tx, held_rx) = std::sync::mpsc::channel();
22367        let armed = AtomicBool::new(true);
22368        supervisor
22369            .child_roster
22370            .set_record_write_hook_for_test(move |live| {
22371                let admitting_replacement = live.values().any(|entry| entry.pid != old_pid);
22372                if admitting_replacement && armed.swap(false, Ordering::SeqCst) {
22373                    let _ = held_tx.send(());
22374                    std::thread::sleep(HELD_RECORD_WRITE);
22375                }
22376            });
22377
22378        // The replacement module, as a separate process would be: its own
22379        // thread and runtime, so only the daemon's runtime can be stalled.
22380        let module_process = std::thread::spawn(move || {
22381            held_rx
22382                .recv_timeout(Duration::from_secs(30))
22383                .expect("the restart reached the replacement's record write");
22384            let conn = ConnectionInfo {
22385                schema: SCHEMA_VERSION,
22386                wire_version: None,
22387                endpoints: vec![Endpoint {
22388                    host: "127.0.0.1".to_owned(),
22389                    port,
22390                }],
22391                key,
22392                daemon_id,
22393                pid: std::process::id(),
22394                daemon_ver: "test".to_owned(),
22395            };
22396            tokio::runtime::Builder::new_current_thread()
22397                .enable_all()
22398                .build()
22399                .unwrap()
22400                .block_on(async {
22401                    let started = Instant::now();
22402                    let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
22403                        .await
22404                        .unwrap();
22405                    let result =
22406                        authenticate_client(&mut stream, &conn, MODULE_AUTH_DEADLINE).await;
22407                    (result, started.elapsed())
22408                })
22409        });
22410
22411        module.restart(Some(0)).await.unwrap();
22412        let (auth, elapsed) = tokio::task::spawn_blocking(move || module_process.join().unwrap())
22413            .await
22414            .unwrap();
22415        assert!(
22416            auth.is_ok(),
22417            "the daemon must answer a module's handshake while a restart waits on the \
22418             live-children record write; got {auth:?} after {elapsed:?}"
22419        );
22420
22421        tokio::time::timeout(Duration::from_secs(20), async {
22422            while lock_snapshot(&module.inner.snapshot)
22423                .unwrap()
22424                .reported_pid()
22425                .is_none_or(|pid| pid == old_pid)
22426            {
22427                tokio::time::sleep(Duration::from_millis(10)).await;
22428            }
22429        })
22430        .await
22431        .expect("the restart published its replacement");
22432        module.stop().await.unwrap();
22433        server.abort();
22434    }
22435}
22436
22437#[cfg(all(test, unix))]
22438mod retained_status_tests {
22439    use super::*;
22440
22441    #[tokio::test]
22442    async fn cached_container_block_is_visible_in_status_and_health_without_rechecking() {
22443        use crate::live_children::{ContainerIdentity, RetainedReason};
22444        for (reason, carried, expected) in [
22445            (
22446                RetainedReason::ContainerSurvivors(vec![4242]),
22447                true,
22448                Some("waiting: container survivors (pids [4242])".to_owned()),
22449            ),
22450            (
22451                RetainedReason::ContainerUnverifiable("member inspection denied".into()),
22452                true,
22453                Some(
22454                    "waiting: container survivors could not be verified: member inspection denied"
22455                        .to_owned(),
22456                ),
22457            ),
22458            (RetainedReason::Survived, false, None),
22459        ] {
22460            let supervisor =
22461                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
22462            let spec = ModuleSpec {
22463                script: None,
22464                module_id: "retained-status-fixture".into(),
22465                program: PathBuf::from("/not-spawned"),
22466                args: Vec::new(),
22467                env: Vec::new(),
22468                reserved: false,
22469                reserved_prefixes: Vec::new(),
22470                protocol: ModuleProtocol::None,
22471                overlap: ModuleOverlap::Exclusive,
22472                carry_containment: carried,
22473            };
22474            let module = supervisor
22475                .supervise_configured(spec.clone(), false)
22476                .unwrap();
22477            // No process is launched. Invalid group zero is deliberate: if a
22478            // status read wrongly rechecks, verification changes the reason
22479            // and fails the assertions without signalling any real process.
22480            let guard = supervisor
22481                .child_roster
22482                .admit(
22483                    spec.module_id,
22484                    0,
22485                    ModuleProtocol::None,
22486                    None,
22487                    crate::child_roster::RecordedIdentity {
22488                        container: carried.then_some(ContainerIdentity {
22489                            pgid: Some(0),
22490                            created_start_time: Some(0),
22491                            cgroup_path: None,
22492                            ..ContainerIdentity::test_metadata()
22493                        }),
22494                        ..crate::child_roster::RecordedIdentity::default()
22495                    },
22496                )
22497                .unwrap();
22498            guard.retain(reason);
22499            let status = module.status().unwrap();
22500            assert_eq!(status.waiting_for_previous_detail, expected.clone());
22501            assert_eq!(status.health.detail, expected);
22502            assert!(!status.process_alive);
22503        }
22504    }
22505}
22506
22507fn registration_child_is_running(child: &mut SupervisedChild) -> bool {
22508    child.try_wait().is_ok_and(|status| status.is_none())
22509}