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_output::StderrPump,
46    child_roster::ChildRoster,
47    daemon_config::{
48        CAPTURE_KEEP_ENV, CAPTURE_MAX_AGE_DAYS_ENV, CAPTURE_MAX_FILE_MB_ENV, CK_LOG_ENV,
49    },
50    forwarding::{
51        CloseReason, ForwardingError, ForwardingTable, GoodbyeTarget, ModuleControlRpcOutcome,
52        ModuleDrainTarget, PendingModuleControlRpc,
53    },
54    provenance::{ExecutableIdentityProbe, SpawnedFileIdentity},
55    registry::{ConnectionId, RegistrationEndReason, RegistryError},
56    stderr_tail::{ChildOutputSink, StderrRing, StderrTailConfig, StderrTailSnapshot},
57    terminal_ring::{TerminalHistorySnapshot, TerminalRecord, TerminalRing, TerminalRingConfig},
58    Frame, FrameSink, Registry,
59};
60
61#[cfg(not(windows))]
62use crate::provenance::spawned_file_identity;
63
64#[path = "supervise_swap.rs"]
65mod swap;
66
67#[path = "supervise_activity.rs"]
68mod activity;
69
70#[cfg(unix)]
71#[path = "supervise/admission.rs"]
72mod admission;
73mod admission_exit;
74#[cfg(all(test, target_os = "linux"))]
75mod async_spawn_tests;
76#[cfg(all(test, windows))]
77mod carried_job_tests;
78mod config_delivery;
79mod content_binding;
80mod program_binding;
81mod registration;
82pub(crate) mod script;
83/// Each launch nonce, mapped to its launch's module id and the launch.
84type NonceLaunches = HashMap<String, (String, std::sync::Weak<RegistrationSpawn>)>;
85pub(crate) use registration::NonceAttestation;
86#[cfg(all(test, unix))]
87pub(crate) use registration::RegistrationProof;
88pub(crate) use registration::RegistrationSpawn;
89pub(crate) use registration::REGISTRATION_CHANNEL_CLOSED;
90#[cfg(all(test, unix))]
91pub(crate) mod unix_channel_placement_tests;
92use program_binding::ProgramBindingPublication;
93mod config_exit_failure;
94#[cfg(all(test, any(target_os = "linux", windows)))]
95mod missing_path_tests;
96#[cfg(all(test, unix))]
97mod program_binding_tests;
98#[cfg(all(test, windows))]
99mod program_binding_windows_tests;
100#[cfg(all(test, windows))]
101mod windows_channel_tests;
102pub use config_exit_failure::ModuleStopReason;
103mod unregistered_stop;
104use unregistered_stop::stop_unregistered_child;
105#[cfg(target_os = "linux")]
106#[path = "supervise/cgroup_label.rs"]
107mod cgroup_label;
108#[cfg(all(test, unix))]
109mod config_exit_hold_tests;
110pub(crate) mod containment;
111#[cfg(all(test, unix))]
112mod containment_tests;
113#[cfg(target_os = "linux")]
114mod ordinary_cgroup;
115#[cfg(unix)]
116pub(crate) mod plain_group;
117#[cfg(all(test, target_os = "linux"))]
118mod plain_group_regression;
119mod slow_retry;
120use slow_retry::{FailedRetry, FailureContext};
121mod host_health;
122use host_health::HostHealth;
123
124#[cfg(test)]
125mod crash_admission_tests;
126mod crash_budget;
127#[cfg(all(test, unix))]
128mod mark_readiness_tests;
129#[cfg(all(test, unix))]
130mod slow_retry_tests;
131use crash_budget::{admit_running_child_async, spawn_and_mark_running_async};
132
133/// Command-line flag used by supervised modules to find subc.
134///
135/// subc launches module-mode children as `<module> --subc <connection-file-path>`.
136/// The path points at the TCP+key connection file; it is not an ambient signal and
137/// is never inherited by standalone children.
138pub const SUBC_ARG: &str = "--subc";
139
140const DEFAULT_MAX_RESTARTS: u32 = 3;
141const DEFAULT_BACKOFF: Duration = Duration::from_millis(100);
142const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
143/// The span `DEFAULT_MAX_RESTARTS` is counted over. Ten minutes is long enough
144/// to contain a real crash loop (which respawns in seconds) and short enough
145/// that unrelated crashes hours apart never accumulate into a permanent stop.
146const DEFAULT_RESTART_WINDOW: Duration = Duration::from_secs(600);
147/// How long a drain waits for already-dispatched requests to finalize before
148/// the child is torn down. Sized for TOOL-SCALE work (bash, inspect, builds),
149/// not RPC-scale: the original 2s value silently cut nearly every real tool
150/// call at the fence, making the wait-for-finalize design decorative for the
151/// workloads it existed for. Quiescence short-circuits, so an idle module
152/// restarts immediately regardless of this value; the budget is spent only
153/// when a genuine in-flight request is worth finishing. Per-module override:
154/// `drain_timeout_ms` in subc.jsonc; per-restart override: the operator's
155/// `supervisor.restart{drain_timeout_ms}` (0 = cut now, for wedge bounces
156/// where a stuck request will never settle).
157pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
158// Child admission durably records identity before exec. Disk pressure can make
159// fsync slow without implying a failed child start, so allow a generous budget.
160#[cfg(any(unix, feature = "test-support"))]
161const ADMISSION_TIMEOUT: Duration = Duration::from_secs(30);
162
163/// Daemon-side child-admission budget, for integration-test RPC deadlines.
164#[cfg(feature = "test-support")]
165pub const CHILD_ADMISSION_TIMEOUT: Duration = ADMISSION_TIMEOUT;
166
167pub(crate) const DEFAULT_REGISTER_TIMEOUT: Duration = Duration::from_secs(120);
168const REGISTRY_RELEASE_TIMEOUT: Duration = Duration::from_secs(1);
169const REGISTRY_RELEASE_POLL: Duration = Duration::from_millis(10);
170/// How long a drain waits after one busy-gauge probe completes before it asks
171/// again.
172///
173/// A drain re-probes on this short interval of its own rather than on the
174/// module's health cadence. The default cadence (30 s) equals the default
175/// drain ceiling, so a cadence-paced drain that found the module busy at its
176/// first probe never asked a second time: it waited out the whole ceiling and
177/// forced GOODBYE even after the gauges had read zero. The interval is counted
178/// from the moment the previous probe finished, and probes run one at a time,
179/// so a slow module is never asked more often than it can answer. Periodic
180/// health checks outside a drain keep using the configured cadence.
181const DRAIN_BUSY_REPROBE_INTERVAL: Duration = Duration::from_millis(250);
182/// How long a restart waits per pipe for queued capture to finish.
183///
184/// A reader and writer still running at the bound are left running. Stderr
185/// stays in the exited process's section of the ring. Its tail reports
186/// `Incomplete` until EOF has reached the writer, and stays incomplete if
187/// backpressure forced capture to drop lines. Late output from either pipe
188/// can reach the capture file after the successor starts.
189const STDERR_PUMP_DRAIN_TIMEOUT: Duration = Duration::from_millis(250);
190/// Maximum number of supervised process spawn/exit facts retained per daemon incarnation.
191pub const SPAWN_EVENT_RING_CAPACITY: usize = 4096;
192const SPAWN_SUBSCRIBER_BUFFER: usize = SPAWN_EVENT_RING_CAPACITY + 1;
193/// Terminal Error code for a `supervisor.spawn_subscribe` stream the daemon
194/// dropped because the subscriber stopped draining its frames. The detail's
195/// `first_undelivered_cursor` names the first event it did not receive; the
196/// client resubscribes from the last cursor it did receive.
197pub(crate) const SPAWN_SUBSCRIBER_LAGGED_CODE: &str = "spawn_subscriber_lagged";
198
199#[cfg(target_os = "macos")]
200struct PrivacyExec {
201    content_check: Option<tokio::task::JoinHandle<Result<(), crate::config_gate::GateError>>>,
202    gated: bool,
203    admission_binding: Option<ProgramBindingPublication>,
204    reader: tokio::io::unix::AsyncFd<std::io::PipeReader>,
205    deadline: tokio::time::Instant,
206    expected: Option<subc_os::FileIdentity>,
207    trampoline: Option<subc_os::FileIdentity>,
208    signature: Option<Arc<subc_os::privacy_identity::SuspendedSignature>>,
209    module_id: String,
210    #[cfg(test)]
211    confirmation_pause: Option<(String, Option<tokio::net::TcpStream>)>,
212    #[cfg(test)]
213    image_probe: Option<fn(u32) -> Option<subc_os::Observation>>,
214    #[cfg(test)]
215    image_read_delay: Option<Duration>,
216}
217
218#[cfg(all(test, target_os = "macos"))]
219pub(crate) fn test_privacy_trampoline() -> PathBuf {
220    // The fixture bin lives in the profile folder the unit-test executable was
221    // built into. This honors custom CARGO_TARGET_DIR too.
222    let path = cortexkit_test_support::cargo_profile_bin("privacy-trampoline-fixture");
223    // Without the fixture every macOS spawn is refused, and the tests that
224    // spawn fail later as a module in state Failed, which names the wrong
225    // cause. `cargo test -p subc-daemon --lib` alone does not build it.
226    assert!(
227        path.exists(),
228        "privacy-trampoline-fixture not built at {}: run `cargo build -p subc-daemon \
229         --bins --features test-support` or `cargo test -p subc-daemon` first",
230        path.display()
231    );
232    path
233}
234
235#[cfg(target_os = "macos")]
236fn probe_privacy_trampoline(path: &std::path::Path) -> Result<(), String> {
237    use std::io::Read;
238    let mut probe = subc_os::child_spawn::spawn(
239        std::process::Command::new(path)
240            .args(["__disclaim-exec", "--probe-suspended"])
241            .stdin(Stdio::null())
242            .stdout(Stdio::piped())
243            .stderr(Stdio::piped()),
244    )
245    .map_err(|error| {
246        format!(
247            "privacy trampoline probe failed for {}: {error}",
248            path.display()
249        )
250    })?;
251    let deadline = std::time::Instant::now() + Duration::from_secs(5);
252    let status = loop {
253        match probe.try_wait() {
254            Ok(Some(status)) => break status,
255            Ok(None) if std::time::Instant::now() < deadline => {
256                std::thread::sleep(Duration::from_millis(5))
257            }
258            result => {
259                let _ = probe.kill();
260                let _ = probe.wait();
261                return Err(format!(
262                    "privacy trampoline probe failed or timed out for {}: {result:?}",
263                    path.display()
264                ));
265            }
266        }
267    };
268    let mut answer = String::new();
269    if let Some(stdout) = probe.stdout.take() {
270        let _ = stdout.take(256).read_to_string(&mut answer);
271    }
272    if status.success() && answer.trim() == subc_os::privacy_identity::SUSPENDED_TRAMPOLINE_PROBE {
273        return Ok(());
274    }
275    let mut diagnostic = String::new();
276    if let Some(stderr) = probe.stderr.take() {
277        let _ = stderr.take(1024).read_to_string(&mut diagnostic);
278    }
279    let cause = diagnostic
280        .trim()
281        .strip_prefix("ck-subc: own privacy identity refused: ")
282        .unwrap_or("binary does not implement the privacy trampoline protocol");
283    Err(format!(
284        "{cause}: probe of {} exited {status}",
285        path.display()
286    ))
287}
288
289#[cfg(target_os = "macos")]
290fn privacy_command(
291    spec: &ModuleSpec,
292    binding: &SpawnProgramBinding,
293    roster: &ChildRoster,
294    gated: bool,
295) -> Result<
296    (
297        Command,
298        Option<PrivacyExec>,
299        subc_os::privacy_identity::ExecAcknowledgement,
300    ),
301    SuperviseError,
302> {
303    let failure = |cause: String| {
304        warn!(module_id = %spec.module_id, %cause, "privacy identity trampoline refused module spawn");
305        SuperviseError::Spawn {
306            program: spec.program.clone(),
307            source: io::Error::other(cause),
308            cgroup_path: None,
309        }
310    };
311    let trampoline = roster.privacy_trampoline().map_err(failure)?;
312    let expected = Some(binding.identity);
313    let trampoline_image = subc_os::file_identity(&trampoline);
314    let signature = gated
315        .then(|| {
316            subc_os::privacy_identity::SuspendedSignature::capture(&binding._file, &binding.path)
317                .map(Arc::new)
318        })
319        .transpose()
320        .map_err(|error| failure(error.to_string()))?;
321    if expected == trampoline_image {
322        return Err(failure(
323            "privacy identity module executable is missing or is the trampoline itself".to_string(),
324        ));
325    }
326    let (reader, ack) = subc_os::privacy_identity::ExecAcknowledgement::pipe()
327        .map_err(|error| failure(error.to_string()))?;
328    let reader =
329        tokio::io::unix::AsyncFd::new(reader).map_err(|error| failure(error.to_string()))?;
330    let mut command = Command::new(&trampoline);
331    command
332        .arg(if gated {
333            "__disclaim-exec-suspended"
334        } else {
335            "__disclaim-exec"
336        })
337        .arg(ack.fd().to_string())
338        .arg(&binding.path);
339    Ok((
340        command,
341        Some(PrivacyExec {
342            gated,
343            admission_binding: None,
344            content_check: None,
345            reader,
346            deadline: tokio::time::Instant::now() + Duration::from_secs(5),
347            expected,
348            trampoline: trampoline_image,
349            signature,
350            module_id: spec.module_id.clone(),
351            #[cfg(test)]
352            image_probe: None,
353            #[cfg(test)]
354            image_read_delay: spec
355                .env
356                .iter()
357                .find(|(key, _)| key == "SUBC_TEST_PRIVACY_IMAGE_DELAY_MS")
358                .map(|(_, millis)| Duration::from_millis(millis.parse().unwrap())),
359            #[cfg(test)]
360            confirmation_pause: spec
361                .env
362                .iter()
363                .find(|(key, _)| key == "SUBC_TEST_BEFORE_EXEC_CONFIRM")
364                .map(|(_, address)| (address.clone(), None)),
365        }),
366        ack,
367    ))
368}
369
370#[cfg(unix)]
371type SpawnRegistrationChannel = std::os::unix::net::UnixStream;
372#[cfg(windows)]
373type SpawnRegistrationChannel = subc_os::registration_channel::RegistrationPipe;
374#[cfg(test)]
375type CapturedRegistrationChannels =
376    Arc<Mutex<Option<Vec<(Arc<RegistrationSpawn>, CapturedRegistrationEndpoint)>>>>;
377#[cfg(test)]
378struct CapturedRegistrationEndpoint {
379    _channel: SpawnRegistrationChannel,
380}
381#[cfg(test)]
382impl fmt::Debug for CapturedRegistrationEndpoint {
383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384        f.write_str("CapturedRegistrationEndpoint")
385    }
386}
387
388struct SupervisedChild {
389    registration_spawn: Option<Arc<RegistrationSpawn>>,
390    /// Owned daemon endpoint, retained for the per-spawn registration service.
391    #[cfg(any(unix, windows))]
392    registration_channel: Option<SpawnRegistrationChannel>,
393    live_program_binding: Option<Arc<content_binding::LiveProgramBinding>>,
394    registered_config_connection: Option<ConnectionId>,
395    admission_base: Option<subc_config::Digest>,
396    registration_declaration: Option<String>,
397    _program_binding: Option<ProgramBindingPublication>,
398    subtree_target: crate::subtree_resources::Target,
399    child: containment::ProcessChild,
400    exec: crate::activity::ExecOwner,
401    #[cfg(windows)]
402    nonce_delivery: Option<subc_os::LaunchNoncePipeDelivery>,
403    #[cfg(target_os = "macos")]
404    privacy_exec: Option<PrivacyExec>,
405    /// Set once this launch's exec acknowledgement confirms the module image.
406    /// On macOS the pid first runs the `ck-subc` launch trampoline (see
407    /// `subc_os::privacy_identity`), which then replaces itself with the
408    /// module. The supervisor owns and can kill that pid from spawn, but
409    /// status readers report it only after this latch is set, so nothing
410    /// reports the trampoline's image as the module's.
411    #[cfg(target_os = "macos")]
412    report_ready: Arc<OnceLock<()>>,
413    /// Supervisor failure detail retained for the terminal record, including
414    /// image refusals and first-HELLO timeouts after a successful spawn.
415    spawn_failure: Option<String>,
416    /// Set only after a kill requested because launch admission failed was
417    /// accepted, never for an operator, health, or shutdown kill.
418    admission_kill_sent: bool,
419    /// The protocol this process was launched with. A reload can store a new
420    /// launch spec with a different protocol, but that takes effect only at the
421    /// next spawn, so this process keeps being handled by the protocol it
422    /// actually speaks.
423    protocol: ModuleProtocol,
424    /// This container's cgroup name: a bounded module/slot label followed by a
425    /// unique suffix (when cgroup placement is on). Carried replacements reuse
426    /// the name; ordinary launches each get a fresh container. A
427    /// retired process in a slot may still be draining when a later one is
428    /// spawned into that slot, so the suffix keeps the later process out of
429    /// the retired one's cgroup, which is the domain a kill applies to.
430    #[cfg(target_os = "linux")]
431    module_id: String,
432    #[cfg(target_os = "linux")]
433    cgroup_placement: Option<subc_cgroup::Placement>,
434    #[cfg(target_os = "linux")]
435    unresolved_cgroup: Option<ordinary_cgroup::Unresolved>,
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<tokio::sync::oneshot::Receiver<()>>,
461    stderr_pump: Option<StderrPump>,
462    #[cfg(unix)]
463    capture_stop: Option<crate::child_output::StopReaders>,
464    #[cfg(unix)]
465    late_output_lost: bool,
466    stderr_ring: Arc<Mutex<StderrRing>>,
467    /// Conservative monotonic bound sampled before `command.spawn()`, not when
468    /// identity recording finishes or the spawn generation is published.
469    spawned_at: Instant,
470    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
471    /// Ordinary spawns must send their first HELLO within this budget. Once
472    /// accepted, a later disconnect must not restart the registration clock.
473    registration_deadline: Option<Instant>,
474    registration_watch: Option<RegistrationWatch>,
475    spawned_at_ms: u64,
476    spawned_from: PathBuf,
477    launch_spec_digest: LaunchSpecDigest,
478    spawned_file_identity: Option<SpawnedFileIdentity>,
479    process_start_time: Option<u64>,
480    process_identity: Option<ProcessIdentity>,
481    pid: u32,
482    /// This process's entry in the daemon's child roster, released when the
483    /// process is reaped or this handle is dropped.
484    roster_guard: Option<crate::child_roster::RosterGuard>,
485}
486
487impl SupervisedChild {
488    fn retire_registration(&self) {
489        // All exit observers enter here before cleanup can await. The retired
490        // program-binding flag and the registration's Dead state make repeated
491        // observations harmless, even when another task observes the group
492        // leader retained unreaped to reserve its process-group id.
493        if let Some(spawn) = &self.registration_spawn {
494            spawn.retire();
495        } else if let Some(binding) = &self._program_binding {
496            binding.retire();
497        }
498        #[cfg(unix)]
499        if let Some(channel) = &self.registration_channel {
500            let _ = channel.shutdown(std::net::Shutdown::Both);
501        }
502        #[cfg(windows)]
503        if let Some(channel) = &self.registration_channel {
504            if let Ok(shutdown) = channel.shutdown_handle() {
505                shutdown.shutdown();
506            }
507        }
508    }
509    fn registered_since_spawn(&self) -> bool {
510        self.registration_watch
511            .as_ref()
512            .is_some_and(|watch| *watch.changes.borrow() != watch.baseline)
513    }
514
515    fn awaiting_registration(&self) -> bool {
516        // Admission failure retires the channel before its kill becomes
517        // waitable. That closure must not replace the admission failure with
518        // a registration failure and spend crash restart budget.
519        let admission_failed = self.admission_kill_sent && self.spawn_failure.is_some();
520        !admission_failed && !self.registered_since_spawn()
521    }
522
523    fn id(&self) -> Option<u32> {
524        Some(self.pid)
525    }
526
527    fn process_identity(&self) -> Option<ProcessIdentity> {
528        self.process_identity
529    }
530
531    fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
532        let result = self.child.try_wait();
533        if !matches!(result, Ok(None)) {
534            self.retire_registration();
535            #[cfg(any(unix, windows))]
536            self.registration_channel.take();
537            if let Some(binding) = &self._program_binding {
538                binding.retire();
539            }
540        }
541        result
542    }
543
544    async fn wait(&mut self) -> io::Result<ExitStatus> {
545        #[cfg(target_os = "macos")]
546        self.confirm_privacy_exec().await;
547        // The roster entry is NOT released here. A daemon shutdown waits for the
548        // roster to empty and then exits the process, so releasing at the reap
549        // let it exit before the exit handler wrote this child's terminal record
550        // (the stderr drain and snapshot update sit in between), and the
551        // shutdown's own `daemon_shutdown` record was intermittently lost. The
552        // caller releases it after recording the exit (`release_roster`), and
553        // dropping the handle releases it too.
554        let result = self.child.wait().await;
555        self.retire_registration();
556        #[cfg(any(unix, windows))]
557        self.registration_channel.take();
558        // All plain and swap waits pass here. Revoke the reaped child's nonce
559        // before cgroup cleanup, stderr draining or exit observation can await.
560        if let Some(binding) = &self._program_binding {
561            binding.retire();
562        }
563        #[cfg(all(test, target_os = "linux"))]
564        if let Some(binding) = &self._program_binding {
565            binding.pause_after_wait_for_test().await;
566        }
567        result
568    }
569
570    async fn finish_exit(&mut self, carry: bool) -> io::Result<()> {
571        self.retire_registration();
572        // Idempotent fallback for cleanup paths that did not call wait.
573        if let Some(binding) = self._program_binding.take() {
574            binding.retire();
575        }
576        if !carry && self.child.container().is_some() {
577            self.child.terminate_container().await;
578        }
579        self.child.reap().await?;
580        #[cfg(target_os = "linux")]
581        self.cleanup_ordinary_cgroup().await;
582        self.release_roster();
583        Ok(())
584    }
585
586    #[cfg(target_os = "macos")]
587    async fn confirm_privacy_exec(&mut self) {
588        if self
589            .privacy_exec
590            .as_ref()
591            .is_some_and(|pending| pending.content_check.is_some())
592        {
593            self.finish_privacy_content_check().await;
594            return;
595        }
596        let Some(pending) = &mut self.privacy_exec else {
597            return;
598        };
599        let result = tokio::time::timeout_at(pending.deadline, async {
600            let mut record = Vec::new();
601            loop {
602                let mut ready = pending.reader.readable().await?;
603                let read = ready.try_io(|reader| {
604                    use std::io::Read;
605                    let mut reader = reader.get_ref();
606                    let mut buffer = [0u8; 256];
607                    reader.read(&mut buffer).map(|count| (count, buffer))
608                });
609                match read {
610                    Ok(Ok((0, _))) => return Ok::<_, io::Error>(record),
611                    Ok(Ok((count, buffer))) => {
612                        if record.len() + count > 1024 {
613                            return Err(io::Error::other(
614                                "privacy exec refusal record is too long",
615                            ));
616                        }
617                        record.extend_from_slice(&buffer[..count]);
618                    }
619                    Ok(Err(error)) => return Err(error),
620                    Err(_) => continue,
621                }
622            }
623        })
624        .await;
625        #[cfg(test)]
626        let result = if let Some((address, stream)) = &mut pending.confirmation_pause {
627            use tokio::io::{AsyncReadExt, AsyncWriteExt};
628            if stream.is_none() {
629                *stream = Some(
630                    tokio::net::TcpStream::connect(address.as_str())
631                        .await
632                        .unwrap(),
633                );
634                stream.as_mut().unwrap().write_all(b"R").await.unwrap();
635                stream
636                    .as_mut()
637                    .unwrap()
638                    .write_all(&self.pid.to_ne_bytes())
639                    .await
640                    .unwrap();
641            }
642            let mut reply = [0];
643            stream
644                .as_mut()
645                .unwrap()
646                .read_exact(&mut reply)
647                .await
648                .unwrap();
649            pending.confirmation_pause = None;
650            if &reply == b"F" {
651                Ok(Err(io::Error::other("injected late exec refusal")))
652            } else {
653                assert_eq!(&reply, b"X");
654                result
655            }
656        } else {
657            result
658        };
659        // Keep the reader in self across await: select cancellation must not
660        // discard the handshake or reset its original five-second deadline.
661        // Use try_wait so a child reaped during confirmation has its program
662        // binding retired before another command can use its nonce.
663        let waited = if matches!(&result, Ok(Ok(record)) if record.is_empty()) {
664            Some(self.try_wait())
665        } else {
666            None
667        };
668        let pending = self.privacy_exec.as_ref().expect("pending exec");
669        let cause = match result {
670            Err(_) => Some("privacy identity trampoline did not exec within 5s".to_string()),
671            Ok(Err(error)) => Some(format!(
672                "privacy identity exec acknowledgement failed: {error}"
673            )),
674            Ok(Ok(record)) if !record.is_empty() => Some(
675                std::str::from_utf8(&record)
676                    .ok()
677                    .and_then(|record| {
678                        record
679                            .trim()
680                            .strip_prefix(subc_os::privacy_identity::EXEC_REFUSAL_TAG)
681                    })
682                    .filter(|cause| !cause.is_empty())
683                    .unwrap_or("invalid privacy exec refusal record")
684                    .to_string(),
685            ),
686            Ok(Ok(_)) if !pending.gated => match waited.expect("exec EOF checked child") {
687                Ok(Some(_)) => None,
688                Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
689                Ok(None) => {
690                    #[cfg(test)]
691                    if let Some(delay) = pending.image_read_delay {
692                        tokio::time::sleep(delay).await;
693                    }
694                    let image = observe_spawned_image(self.pid);
695                    #[cfg(test)]
696                    let image = pending.image_probe.map_or(image, |probe| probe(self.pid));
697                    // An unstamped module can re-exec before we wake to read its
698                    // image. Only the trampoline image proves exec never happened;
699                    // retain the observed image for later orphan identification.
700                    if let Some(image) = image.filter(|image| {
701                        image.executable.is_some() && image.executable != pending.trampoline
702                    }) {
703                        match self
704                            .roster_guard
705                            .as_ref()
706                            .map(|guard| guard.confirm_executable(image))
707                            .transpose()
708                        {
709                            Err(error) => Some(format!(
710                                "could not durably record confirmed module image: {error}"
711                            )),
712                            Ok(_) => {
713                                let _ = self.report_ready.set(());
714                                None
715                            }
716                        }
717                    } else if image.is_none()
718                        || image.is_some_and(|image| image.executable.is_none())
719                    {
720                        // Empty EOF acknowledged exec. An image disappearing
721                        // during observation is an ordinary module exit.
722                        match tokio::time::timeout_at(pending.deadline, self.child.wait()).await {
723                            Ok(result) => {
724                                self.retire_registration();
725                                self.registration_channel.take();
726                                if let Some(binding) = &self._program_binding {
727                                    binding.retire();
728                                }
729                                result.err().map(|error| format!("privacy identity trampoline wait failed: {error}"))
730                            }
731                            Err(_) => Some("privacy identity module executable remained unreadable until the 5s exec deadline".to_string()),
732                        }
733                    } else {
734                        Some("privacy identity trampoline did not exec the module".to_string())
735                    }
736                }
737            },
738            Ok(Ok(_)) => match waited.expect("exec EOF checked child") {
739                Ok(Some(_)) => {
740                    Some("privacy identity target exited before suspended admission".to_string())
741                }
742                Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
743                Ok(None) => {
744                    // CLOEXEC closes the ack just before the kernel reports the
745                    // suspended target. EOF alone must never admit a running image.
746                    let stopped = tokio::time::timeout_at(pending.deadline, async {
747                        loop {
748                            if subc_os::privacy_identity::SuspendedSignature::is_suspended(
749                                self.pid,
750                            )? {
751                                return Ok::<_, io::Error>(());
752                            }
753                            tokio::time::sleep(Duration::from_millis(1)).await;
754                        }
755                    })
756                    .await;
757                    match stopped {
758                        Err(_) => {
759                            Some("privacy identity target was not suspended within 5s".to_string())
760                        }
761                        Ok(Err(error)) => Some(format!(
762                            "privacy identity suspended target unavailable: {error}"
763                        )),
764                        Ok(Ok(())) => {
765                            let image = observe_spawned_image(self.pid);
766                            if image.is_some_and(|image| {
767                                image.executable.is_some()
768                                    && image.executable != pending.trampoline
769                                    && image.executable == pending.expected
770                            }) {
771                                None
772                            } else {
773                                Some("privacy identity trampoline executable mismatch: expected the suspended module program".to_string())
774                            }
775                        }
776                    }
777                }
778            },
779        };
780        #[cfg(test)]
781        if let Some(binding) = &self._program_binding {
782            binding.pause_after_wait_for_test().await;
783        }
784        if cause.is_none() && pending.gated {
785            let publication = pending.admission_binding.clone();
786            let live = self.live_program_binding.clone();
787            let signature = Arc::clone(pending.signature.as_ref().expect("gated signature"));
788            let pid = self.pid;
789            let gated = pending.gated;
790            self.privacy_exec
791                .as_mut()
792                .expect("pending exec")
793                .content_check = Some(tokio::task::spawn_blocking(move || {
794                signature.verify(pid).map_err(|error| {
795                    crate::config_gate::GateError::new("program_refused", error)
796                })?;
797                if !gated {
798                    return Ok(());
799                }
800                match (publication, live) {
801                    (Some(publication), _) => publication.verify(),
802                    (None, Some(live)) => live.check(),
803                    _ => Err(crate::config_gate::GateError::new(
804                        "config_delivery_deferred",
805                        "live program witness is unavailable",
806                    )),
807                }
808            }));
809            self.finish_privacy_content_check().await;
810        } else {
811            self.finish_privacy_exec(cause);
812        }
813    }
814
815    #[cfg(target_os = "macos")]
816    async fn finish_privacy_content_check(&mut self) {
817        let result = self
818            .privacy_exec
819            .as_mut()
820            .expect("pending exec")
821            .content_check
822            .as_mut()
823            .expect("pending content check")
824            .await;
825        let cause = match result {
826            Ok(Ok(())) => None,
827            Ok(Err(error)) => Some(format!("{}: {}", error.code, error.detail)),
828            Err(error) => Some(format!(
829                "config_delivery_deferred: content check stopped: {error}"
830            )),
831        };
832        self.finish_privacy_exec(cause);
833    }
834
835    #[cfg(target_os = "macos")]
836    fn finish_privacy_exec(&mut self, mut cause: Option<String>) {
837        let mut pending = self.privacy_exec.take().expect("pending exec");
838        if cause.is_none() && pending.gated {
839            let admission = (|| -> io::Result<()> {
840                let image = observe_spawned_image(self.pid)
841                    .filter(|image| image.executable == pending.expected)
842                    .ok_or_else(|| io::Error::other("suspended executable mismatch"))?;
843                if let Some(guard) = &self.roster_guard {
844                    guard.confirm_executable(image)?;
845                }
846                pending
847                    .signature
848                    .as_ref()
849                    .expect("gated signature")
850                    .resume(self.pid)?;
851                let _ = self.report_ready.set(());
852                info!(module_id = %pending.module_id, pid = self.pid,
853                    "verified suspended module resumed with own privacy identity");
854                Ok(())
855            })();
856            if let Err(error) = admission {
857                cause = Some(format!("program_refused: {error}"));
858            }
859        }
860        if cause.is_some() {
861            if let Some(spawn) = &self.registration_spawn {
862                spawn.refuse();
863            }
864            if let Some(binding) = &mut pending.admission_binding {
865                binding.reject();
866            }
867        } else if let Some(spawn) = &self.registration_spawn {
868            spawn.ready();
869        }
870        // Exec confirmation describes launch success, not roster retirement.
871        // Keep even a reaped child recorded until its terminal history exists.
872        self.exec.0.finish(if cause.is_some() {
873            crate::activity::ExecState::Refused
874        } else {
875            crate::activity::ExecState::CommittedExec
876        });
877        if let Some(cause) = cause {
878            warn!(module_id = %pending.module_id, pid = self.pid, %cause, "privacy identity trampoline refused module spawn");
879            self.spawn_failure = Some(
880                if pending.gated
881                    && (cause.contains("executable mismatch")
882                        || cause.starts_with("program_refused:"))
883                {
884                    format!("program_refused: {cause}")
885                } else if pending.gated {
886                    format!("config_delivery_deferred: {cause}")
887                } else {
888                    cause
889                },
890            );
891            // No resume signal is sent on failure; kill the entire fresh group
892            // even if a faulty trampoline did not honor the suspended protocol.
893            let _ = self.start_admission_kill();
894        }
895    }
896
897    /// Releases the leader's roster entry after recording and finalizing its
898    /// exit. A carried container retains its separate roster entry and, for a
899    /// Unix process group, its unreaped first leader that reserves the group ID.
900    fn release_roster(&mut self) {
901        let _guard = self.roster_guard.take();
902        #[cfg(target_os = "linux")]
903        if let (Some(unresolved), Some(guard)) = (self.unresolved_cgroup.take(), _guard) {
904            unresolved.retain(guard);
905        }
906    }
907
908    fn exit_cleanup_detail(&self, detail: Option<String>) -> Option<String> {
909        #[cfg(unix)]
910        let detail = if self.late_output_lost {
911            Some(match detail {
912                Some(detail) => {
913                    format!("{detail}; late child output lost: capture pipes did not close")
914                }
915                None => "late child output lost: capture pipes did not close".into(),
916            })
917        } else {
918            detail
919        };
920        #[cfg(target_os = "linux")]
921        if let Some(unresolved) = &self.unresolved_cgroup {
922            return Some(match detail {
923                Some(detail) => format!("{detail}; {}", unresolved.detail()),
924                None => unresolved.detail(),
925            });
926        }
927        detail
928    }
929
930    fn group_drain_budget(&self, budget: Duration, _notice: StopNotice) -> Duration {
931        #[cfg(unix)]
932        if self.child.plain_group.is_some() && _notice != StopNotice::SentOverConnection {
933            return budget.min(plain_group::TERM_GRACE);
934        }
935        budget
936    }
937
938    /// Kill the child and, where containment is available, its process tree.
939    ///
940    /// `Child::kill` is `TerminateProcess` scoped to one pid, so a module with a
941    /// helper process leaked the helper — the Synapse embedding module's CUDA
942    /// worker holds the GPU allocation, so the leak cost VRAM until the next
943    /// restart of something else. Terminating the job reaches grandchildren that
944    /// a tree walk cannot, including one whose parent has already exited and
945    /// been reparented away.
946    ///
947    /// Best-effort like `request_graceful_stop`: a job failure is logged and the
948    /// direct-child kill still decides the outcome, so containment can never
949    /// change whether a module is reported as stopped.
950    fn start_kill(&mut self) -> io::Result<()> {
951        self.retire_registration();
952        if let Some(container) = self.child.container() {
953            container.hard_kill();
954            return self.kill_leader();
955        }
956        #[cfg(windows)]
957        if let Some(job) = &self.job {
958            if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
959                debug!(
960                    error = %error,
961                    "job termination failed; the direct-child kill still owns the outcome"
962                );
963            }
964        }
965        #[cfg(target_os = "linux")]
966        kill_module_cgroup(self.cgroup_placement.as_ref(), &self.module_id);
967        self.child.start_kill()
968    }
969
970    fn kill_leader(&mut self) -> io::Result<()> {
971        self.retire_registration();
972        self.child.start_kill()
973    }
974
975    fn start_admission_kill(&mut self) -> io::Result<()> {
976        self.retire_registration();
977        #[cfg(windows)]
978        let result = {
979            // Preserve the leader's distinctive status before ending the whole
980            // container/job; descendants must not wait for exit finalization.
981            let result = self
982                .spawned_file_identity
983                .as_ref()
984                .and_then(|identity| identity.windows_image.as_ref())
985                .ok_or_else(|| io::Error::other("admission child handle unavailable"))
986                .and_then(|image| {
987                    image.process().terminate_with_exit_code(
988                        admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE as u32,
989                    )
990                });
991            if let Some(container) = self.child.container() {
992                container.hard_kill();
993            } else if let Some(job) = &self.job {
994                if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
995                    debug!(%error, "job termination failed after admission leader termination");
996                }
997            }
998            result
999        };
1000        #[cfg(not(windows))]
1001        let result = self.start_kill().map(|()| true);
1002        self.admission_kill_sent |= result?;
1003        Ok(())
1004    }
1005
1006    async fn drain_stderr(&mut self, module_id: &str) {
1007        #[cfg(unix)]
1008        if self.child.plain_group.is_some() {
1009            self.drain_plain_capture(module_id).await;
1010            return;
1011        }
1012        #[cfg(target_os = "linux")]
1013        self.cleanup_ordinary_cgroup().await;
1014        if let Some(pump) = self.stdout_pump.take() {
1015            settle_stdout_pump(module_id, pump, STDERR_PUMP_DRAIN_TIMEOUT).await;
1016        }
1017
1018        let Some(pump) = self.stderr_pump.take() else {
1019            return;
1020        };
1021        settle_stderr_pump(
1022            module_id,
1023            &self.stderr_ring,
1024            pump,
1025            STDERR_PUMP_DRAIN_TIMEOUT,
1026        )
1027        .await;
1028    }
1029}
1030
1031/// Bound the restart's wait. Dropping the completion future does not stop
1032/// the reader or the capture writer.
1033async fn settle_stdout_pump<E: std::fmt::Display>(
1034    module_id: &str,
1035    pump: impl std::future::Future<Output = Result<(), E>>,
1036    bound: Duration,
1037) {
1038    match timeout(bound, pump).await {
1039        Ok(Ok(())) => {}
1040        Ok(Err(error)) => {
1041            warn!(module_id, error = %error, "stdout pump ended unexpectedly");
1042        }
1043        Err(_) => {
1044            warn!(
1045                module_id,
1046                waited = ?bound,
1047                "stdout of the exited process has not finished capture; the reader and writer continue without delaying restart"
1048            );
1049        }
1050    }
1051}
1052
1053/// Retire an exited process's stderr reader and allow up to `bound` for its
1054/// output to reach the ring and sink. A late reader or writer keeps going,
1055/// and the tail reads `Incomplete` until it finishes.
1056async fn settle_stderr_pump<E: std::fmt::Display>(
1057    module_id: &str,
1058    ring: &Arc<Mutex<StderrRing>>,
1059    pump: StderrPump<impl std::future::Future<Output = Result<(), E>>>,
1060    bound: Duration,
1061) {
1062    let lock = || ring.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1063    let StderrPump { task, generation } = pump;
1064    lock().retire_pump(generation);
1065    match timeout(bound, task).await {
1066        Ok(Ok(())) => {}
1067        Ok(Err(err)) => {
1068            let mut ring = lock();
1069            ring.mark_incomplete_from(generation, format!("stderr pump ended unexpectedly: {err}"));
1070            ring.finish_pump(generation);
1071            warn!(module_id, error = %err, "stderr pump ended before clean EOF");
1072        }
1073        Err(_) => {
1074            lock().mark_pump_late(
1075                generation,
1076                format!(
1077                    "stderr of the exited process had not reached EOF or finished queued capture \
1078                     {bound:?} after it was retired; retained lines go in that process's section"
1079                ),
1080            );
1081            warn!(
1082                module_id,
1083                waited = ?bound,
1084                "stderr of the exited process has not finished capture; the reader and writer continue without delaying restart"
1085            );
1086        }
1087    }
1088}
1089
1090fn registration_release_events() -> &'static watch::Sender<u64> {
1091    static EVENTS: OnceLock<watch::Sender<u64>> = OnceLock::new();
1092    EVENTS.get_or_init(|| {
1093        let (sender, _receiver) = watch::channel(0);
1094        sender
1095    })
1096}
1097
1098pub(crate) fn notify_registration_release() {
1099    let events = registration_release_events();
1100    let next_generation = (*events.borrow()).wrapping_add(1);
1101    events.send_replace(next_generation);
1102}
1103
1104/// The installed companion that evaluates a script module.
1105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1106#[non_exhaustive]
1107pub enum ScriptRuntime {
1108    Bun,
1109    Python,
1110}
1111
1112impl ScriptRuntime {
1113    pub const fn as_str(self) -> &'static str {
1114        match self {
1115            Self::Bun => "bun",
1116            Self::Python => "python",
1117        }
1118    }
1119}
1120
1121/// Script content and the runtime approved to evaluate it.
1122#[derive(Debug, Clone, PartialEq, Eq)]
1123#[non_exhaustive]
1124pub struct ScriptEntry {
1125    pub runtime: ScriptRuntime,
1126    pub path: PathBuf,
1127}
1128
1129impl ScriptEntry {
1130    pub fn new(runtime: ScriptRuntime, path: PathBuf) -> Self {
1131        Self { runtime, path }
1132    }
1133}
1134
1135/// How to launch one singleton module process.
1136#[derive(Debug, Clone, PartialEq, Eq)]
1137pub struct ModuleSpec {
1138    pub module_id: String,
1139    pub program: PathBuf,
1140    /// Bundled script content. The program is always the installed runtime runner.
1141    pub script: Option<ScriptEntry>,
1142    pub args: Vec<String>,
1143    pub env: Vec<(String, String)>,
1144    /// When true this is a reserved module: each spawn gets a fresh one-time launch
1145    /// nonce that the child must echo in its HELLO, so only the daemon-spawned
1146    /// process can register this module_id (a security-boundary module like the
1147    /// credential vault must not be impersonable while it is down/restarting).
1148    pub reserved: bool,
1149    /// Module-id prefixes this supervised module owns for reserved HELLO checks.
1150    /// Prefixes come from daemon config and must end in `:` before they reach the
1151    /// supervisor; the owner module's current spawn nonce authorizes claims under
1152    /// each prefix.
1153    pub reserved_prefixes: Vec<String>,
1154    /// The wire protocol this module speaks, as DECLARED in daemon config.
1155    ///
1156    /// [`ModuleProtocol::None`] changes five things and nothing else: wire health
1157    /// probing is suppressed (an optional HTTP probe can replace it), teardown sends SIGTERM before waiting,
1158    /// `route.open` is refused, the spawn passes NO `--subc <path>` argument
1159    /// and NO launch nonce, and a clean exit the daemon did not request is
1160    /// restarted as a crash rather than recorded as a stop (see `on_child_exit`:
1161    /// a stock program exits 0 on a stray SIGTERM, and a stop would leave it
1162    /// down for good). `SUBC_MODULE_ID` still goes into the environment,
1163    /// because a process ignores an environment variable it does not read.
1164    ///
1165    /// The argument is the part that cannot be "harmless to a process that
1166    /// ignores it": a stock binary exits on an unknown flag before it listens
1167    /// (`nats-server`: "flag provided but not defined: -subc"), which is how the
1168    /// first conformance run against this mode found it. The nonce is withheld
1169    /// because a process that will never present it gains nothing from holding
1170    /// it, and a secret in the environment of a process that does not need it is
1171    /// a leak surface for no benefit.
1172    pub protocol: ModuleProtocol,
1173    /// Whether two processes of this module may run at once, which is what a
1174    /// blue/green swap does for the length of its overlap. Declared in daemon
1175    /// config because the daemon must be able to answer it while the module is
1176    /// down, and so a module cannot talk itself into it after registering.
1177    pub overlap: ModuleOverlap,
1178    /// Keep module-started helpers in the same container across replacements.
1179    /// This is a daemon-config policy, fixed for the lifetime of a container;
1180    /// stopping the module or losing its supervisor still destroys the container.
1181    pub carry_containment: bool,
1182}
1183
1184/// Only the configured launch inputs enter this value; spawned connection paths,
1185/// nonces and inherited environment never do. Its bytes remain daemon-private.
1186#[derive(Clone, PartialEq, Eq)]
1187pub(crate) struct LaunchSpecDigest([u8; 32]);
1188
1189impl fmt::Debug for LaunchSpecDigest {
1190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1191        f.write_str("LaunchSpecDigest([redacted])")
1192    }
1193}
1194
1195impl LaunchSpecDigest {
1196    pub(crate) fn from_spec(spec: &ModuleSpec) -> Self {
1197        fn field(hash: &mut Sha256, bytes: &[u8]) {
1198            hash.update((bytes.len() as u64).to_le_bytes());
1199            hash.update(bytes);
1200        }
1201        let mut hash = Sha256::new();
1202        if let Some(script) = &spec.script {
1203            field(
1204                &mut hash,
1205                match script.runtime {
1206                    ScriptRuntime::Bun => b"bun-script",
1207                    ScriptRuntime::Python => b"python-script",
1208                },
1209            );
1210            field(&mut hash, script.path.as_os_str().as_encoded_bytes());
1211        }
1212        if let Some(program) = spec.program.to_str() {
1213            field(&mut hash, b"utf8-program");
1214            field(&mut hash, program.as_bytes());
1215        } else {
1216            // The daemon config is UTF-8, but in-process callers may provide
1217            // native paths: lossy conversion would collapse distinct programs.
1218            #[cfg(unix)]
1219            {
1220                use std::os::unix::ffi::OsStrExt;
1221                field(&mut hash, b"unix-program");
1222                field(&mut hash, spec.program.as_os_str().as_bytes());
1223            }
1224            #[cfg(windows)]
1225            {
1226                use std::os::windows::ffi::OsStrExt;
1227                field(&mut hash, b"windows-program");
1228                let bytes = spec
1229                    .program
1230                    .as_os_str()
1231                    .encode_wide()
1232                    .flat_map(u16::to_le_bytes)
1233                    .collect::<Vec<_>>();
1234                field(&mut hash, &bytes);
1235            }
1236            #[cfg(not(any(unix, windows)))]
1237            field(&mut hash, spec.program.to_string_lossy().as_bytes());
1238        }
1239        hash.update((spec.args.len() as u64).to_le_bytes());
1240        for arg in &spec.args {
1241            field(&mut hash, arg.as_bytes());
1242        }
1243        let mut env = spec.env.iter().collect::<Vec<_>>();
1244        env.sort_unstable();
1245        hash.update((env.len() as u64).to_le_bytes());
1246        for (key, value) in env {
1247            field(&mut hash, key.as_bytes());
1248            field(&mut hash, value.as_bytes());
1249        }
1250        field(
1251            &mut hash,
1252            match spec.protocol {
1253                ModuleProtocol::Subc => b"subc",
1254                ModuleProtocol::None => b"none",
1255            },
1256        );
1257        Self(hash.finalize().into())
1258    }
1259}
1260
1261/// Whether a module tolerates a second process of itself running alongside.
1262///
1263/// Most modules are single-writer on their store (a WAL, a capture log, a
1264/// resident index behind a writer barrier), and two processes on one store
1265/// corrupt it. So a swap, which overlaps the old and new process by design,
1266/// is refused unless the module's config opts in with `overlap: "safe"`.
1267#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1268pub enum ModuleOverlap {
1269    /// Never run two processes of this module at once. The default.
1270    #[default]
1271    Exclusive,
1272    /// The module has said a second process of itself is harmless for the
1273    /// length of a swap.
1274    ///
1275    /// Declare it only if a second instance can run for a few seconds without
1276    /// touching ANY single-writer store: every database, WAL, index, projector
1277    /// and scheduled job the module owns. A lease on part of that state is not
1278    /// enough. broca's session lease guards WAL appends while its run index, its
1279    /// store projector and its archive fold timer (which unlinks live WAL files)
1280    /// stay single-writer, so broca is exclusive despite holding a lease. The
1281    /// refusal only fires after this has been decided, so the decision is the
1282    /// check.
1283    Safe,
1284}
1285
1286impl ModuleOverlap {
1287    pub fn as_str(self) -> &'static str {
1288        match self {
1289            Self::Exclusive => "exclusive",
1290            Self::Safe => "safe",
1291        }
1292    }
1293}
1294
1295/// Environment variable telling a spawned module which case it was started
1296/// for, before it sends HELLO. Only a swap candidate carries it, as
1297/// [`SPAWN_ROLE_SWAP_CANDIDATE`]; every other spawn has it removed.
1298///
1299/// It chooses a warm-up budget, nothing else: a swap candidate can warm for
1300/// longer because nobody waits on it, while a plain restart must flip ready
1301/// quickly because callers see `module_warming` until it does. Absence means
1302/// plain restart, the safe reading. The daemon trusts nothing about it; the
1303/// candidate is proven by its launch nonce at HELLO.
1304pub const SUBC_SPAWN_ROLE_ENV: &str = "SUBC_SPAWN_ROLE";
1305/// The one value of [`SUBC_SPAWN_ROLE_ENV`] the daemon sets.
1306pub const SPAWN_ROLE_SWAP_CANDIDATE: &str = "swap_candidate";
1307/// How long a swap waits for its candidate to register and declare itself
1308/// ready when the operator does not say. A module warming as a swap candidate
1309/// may take up to 90 s (aft's ceiling, the largest in the fleet), so the
1310/// daemon allows that plus time to start the process and send HELLO.
1311pub const DEFAULT_SWAP_READY_TIMEOUT: Duration = Duration::from_secs(100);
1312
1313/// Bounded restart policy for crash exits.
1314///
1315/// `max_restarts` is the number of replacement processes allowed after the
1316/// initial spawn WITHIN `window`. After that many crash restarts inside one
1317/// window the module enters [`ModuleState::Failed`] and the supervisor stops
1318/// the crash loop.
1319///
1320/// The budget is a RATE, not a lifetime total. It used to be a lifetime total,
1321/// and that only survived because crashes were rare: a module that crashed
1322/// three times across a week was disabled forever by crashes that had nothing
1323/// to do with each other. That stopped being survivable once modules began
1324/// exiting non-zero whenever the daemon's connection to them drops, because
1325/// then every daemon-side connection drop spends a unit of the same budget and
1326/// one flappy hour permanently stops a healthy module. Restarts older than
1327/// `window` release their slot, so a module that crashed twice yesterday has a
1328/// full budget today, while a genuine crash loop -- which is fast by
1329/// definition -- still reaches the cap and stops.
1330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1331pub struct RestartPolicy {
1332    pub max_restarts: u32,
1333    /// Base delay before a crash replacement. The actual delay escalates with
1334    /// the number of recent crash replacements and is capped by `max_backoff`.
1335    pub backoff: Duration,
1336    /// Maximum delay before a crash replacement.
1337    pub max_backoff: Duration,
1338    /// The span `max_restarts` is counted over. `Duration::ZERO` makes the
1339    /// budget effectively infinite (nothing is ever in-window), which is why
1340    /// daemon config refuses `window_secs: 0` rather than quietly accepting it.
1341    pub window: Duration,
1342}
1343
1344impl RestartPolicy {
1345    /// A policy with the default crash window. Callers that care about the
1346    /// window say so with [`Self::with_window`]; the ones that do not are
1347    /// asking for the standard rate limit, not for no limit.
1348    pub fn new(max_restarts: u32, backoff: Duration) -> Self {
1349        Self {
1350            max_restarts,
1351            backoff,
1352            max_backoff: DEFAULT_MAX_BACKOFF,
1353            window: DEFAULT_RESTART_WINDOW,
1354        }
1355    }
1356
1357    pub fn with_max_backoff(mut self, max_backoff: Duration) -> Self {
1358        self.max_backoff = max_backoff;
1359        self
1360    }
1361
1362    pub fn with_window(mut self, window: Duration) -> Self {
1363        self.window = window;
1364        self
1365    }
1366
1367    /// Calculate the capped exponential delay for the next crash replacement.
1368    /// `restart_in_window` is zero for the first replacement after an operator
1369    /// action (restart, reload, re-enable) cleared the crash ring, or after all
1370    /// older crash replacements have aged out of the window.
1371    fn delay_for_restart(&self, restart_in_window: u32) -> Duration {
1372        if self.backoff.is_zero() || self.max_backoff.is_zero() {
1373            return Duration::ZERO;
1374        }
1375
1376        let mut delay = self.backoff;
1377        for _ in 0..restart_in_window {
1378            if delay >= self.max_backoff {
1379                return self.max_backoff;
1380            }
1381            delay = delay
1382                .checked_mul(10)
1383                .unwrap_or(self.max_backoff)
1384                .min(self.max_backoff);
1385        }
1386        delay.min(self.max_backoff)
1387    }
1388
1389    /// The one sentence that explains a budget-exhausted stop, used for both the
1390    /// log line and the terminal record so the two cannot drift. It names the
1391    /// window because `max_restarts=3` alone reads as a lifetime cap, which is
1392    /// exactly what this budget is not.
1393    fn budget_exhausted_detail(&self) -> String {
1394        format!(
1395            "crash budget exhausted: max_restarts={} within window_secs={}",
1396            self.max_restarts,
1397            self.window.as_secs()
1398        )
1399    }
1400}
1401
1402impl Default for RestartPolicy {
1403    fn default() -> Self {
1404        Self {
1405            max_restarts: DEFAULT_MAX_RESTARTS,
1406            backoff: DEFAULT_BACKOFF,
1407            max_backoff: DEFAULT_MAX_BACKOFF,
1408            window: DEFAULT_RESTART_WINDOW,
1409        }
1410    }
1411}
1412
1413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1414struct CrashRestartSchedule {
1415    restart_in_window: u32,
1416    delay: Duration,
1417}
1418
1419/// Whether the daemon itself will bring this module back after the exit being
1420/// handled: it is enabled AND its in-window crash restarts are below the cap.
1421///
1422/// Takes `&mut` because reading the budget prunes it. Instants that fell out of
1423/// the window are dropped here rather than by a timer, so the count is right
1424/// the moment somebody asks and no bookkeeping runs for idle modules.
1425fn daemon_will_restart(
1426    state: &mut SupervisorSnapshot,
1427    policy: &RestartPolicy,
1428    now: Instant,
1429) -> bool {
1430    state.enabled && state.crash_restarts_in_window(policy.window, now) < policy.max_restarts
1431}
1432
1433const DEFAULT_HEALTH_CADENCE: Duration = Duration::from_secs(30);
1434const DEFAULT_HEALTH_DEADLINE: Duration = Duration::from_secs(5);
1435const DEFAULT_HEALTH_FAILURE_THRESHOLD: u32 = 3;
1436const MAX_HEALTH_METRICS_BYTES: usize = 16 * 1024;
1437
1438#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1439pub enum HealthAction {
1440    Report,
1441    Restart,
1442    Alert,
1443}
1444
1445impl fmt::Display for HealthAction {
1446    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1447        f.write_str(match self {
1448            Self::Report => "report",
1449            Self::Restart => "restart",
1450            Self::Alert => "alert",
1451        })
1452    }
1453}
1454
1455#[derive(Debug, Clone, PartialEq, Eq)]
1456pub struct HealthConfig {
1457    /// Optional loopback HTTP endpoint for a managed non-wire process.
1458    /// Changing it applies live on rescan; the process protocol changes only
1459    /// at its next spawn.
1460    pub http: Option<String>,
1461    pub cadence: Duration,
1462    pub deadline: Duration,
1463    pub failure_threshold: u32,
1464    pub on_degraded: HealthAction,
1465    pub on_failing: HealthAction,
1466    pub critical: bool,
1467}
1468
1469impl Default for HealthConfig {
1470    fn default() -> Self {
1471        Self {
1472            http: None,
1473            cadence: DEFAULT_HEALTH_CADENCE,
1474            deadline: DEFAULT_HEALTH_DEADLINE,
1475            failure_threshold: DEFAULT_HEALTH_FAILURE_THRESHOLD,
1476            on_degraded: HealthAction::Report,
1477            on_failing: HealthAction::Report,
1478            critical: false,
1479        }
1480    }
1481}
1482
1483/// The supervisor's view of one module's health, relayed to clients over
1484/// channel-0 and rendered by `ck health`.
1485///
1486/// THIS TYPE IS WHERE THE ABSENCE MEANINGS ARE CREATED, which is why they are
1487/// stated here rather than only at the wire type a consumer reads. A reader can
1488/// look up what `None` means; only a writer can silently change it, and the
1489/// writer has no reason to go looking at a downstream contract before editing.
1490///
1491/// `last_probe_ms: None` MEANS NEVER PROBED, not probed-long-ago. It is cleared
1492/// back to `None` on re-registration precisely so a respawned module does not
1493/// carry its predecessor's timestamp — so an old value and an absent one call for
1494/// opposite readings, and anything that defaulted this to a number would make a
1495/// never-probed module indistinguishable from one probed at the epoch.
1496///
1497/// `detail` and `metrics` are `None` when the module published none on this
1498/// probe, which does not mean it reported nothing wrong — it is also the shape
1499/// when the probe never reached it. `last_probe_ms` is what separates those.
1500#[derive(Debug, Clone, PartialEq)]
1501pub struct ModuleHealthStatus {
1502    pub status: SupervisorHealthStatus,
1503    pub last_probe_ms: Option<u64>,
1504    pub detail: Option<String>,
1505    pub metrics: Option<Value>,
1506    pub consecutive_failures: u32,
1507    /// Number of replies received after a recurring health probe's deadline.
1508    /// Unlike a timeout, every increment proves the module was alive.
1509    pub late_answer_count: u64,
1510    /// End-to-end latency of the newest late reply, measured from probe start.
1511    pub last_late_answer_latency_ms: Option<u64>,
1512    pub last_action: Option<String>,
1513    /// Set together with `last_action`; the pair moves as one, and both being
1514    /// absent means no escalation has ever been taken rather than that the last
1515    /// one succeeded.
1516    pub last_action_ms: Option<u64>,
1517}
1518
1519impl Default for ModuleHealthStatus {
1520    fn default() -> Self {
1521        Self {
1522            status: SupervisorHealthStatus::Unknown,
1523            last_probe_ms: None,
1524            detail: None,
1525            metrics: None,
1526            consecutive_failures: 0,
1527            late_answer_count: 0,
1528            last_late_answer_latency_ms: None,
1529            last_action: None,
1530            last_action_ms: None,
1531        }
1532    }
1533}
1534
1535/// Typed lifecycle state for a supervised module.
1536#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1537pub enum ModuleState {
1538    Starting,
1539    Running,
1540    Unresponsive,
1541    Restarting,
1542    Draining,
1543    Stopped,
1544    Failed,
1545    Disabled,
1546}
1547
1548impl fmt::Display for ModuleState {
1549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1550        f.write_str(match self {
1551            Self::Starting => "starting",
1552            Self::Running => "running",
1553            Self::Unresponsive => "unresponsive",
1554            Self::Restarting => "restarting",
1555            Self::Draining => "draining",
1556            Self::Stopped => "stopped",
1557            Self::Failed => "failed",
1558            Self::Disabled => "disabled",
1559        })
1560    }
1561}
1562
1563/// Supervisor classification of a child-process exit.
1564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1565pub enum ExitKind {
1566    Clean,
1567    Crash,
1568    DeliberateSeverance,
1569}
1570
1571impl From<ExitKind> for TerminalExitKind {
1572    fn from(kind: ExitKind) -> Self {
1573        match kind {
1574            ExitKind::Clean => Self::Clean,
1575            ExitKind::Crash => Self::Crash,
1576            ExitKind::DeliberateSeverance => Self::DeliberateSeverance,
1577        }
1578    }
1579}
1580
1581/// Exact process identity retained when a supervised module registers its
1582/// connection. PID reuse makes a PID alone insufficient evidence of ownership.
1583#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1584pub(crate) struct ProcessIdentity {
1585    pub(crate) pid: u32,
1586    pub(crate) start_time: u64,
1587}
1588
1589/// Last observed child exit, if any.
1590#[derive(Debug, Clone, PartialEq, Eq)]
1591pub struct ExitReport {
1592    pub kind: ExitKind,
1593    pub code: Option<i32>,
1594    pub signal: Option<i32>,
1595    pub at_ms: u64,
1596}
1597
1598/// Point-in-time module status answerable by subc without forwarding to the
1599/// module process.
1600#[derive(Debug, Clone, PartialEq)]
1601pub struct ModuleStatus {
1602    pub(crate) admission_refused: Option<String>,
1603    pub(crate) legacy_registration_spawn: bool,
1604    pub(crate) registration_declaration: Option<String>,
1605    pub module_id: String,
1606    /// Retained configuration-exit infrastructure failure. Cleared only after a
1607    /// successful launch; an ordinary stop has no infrastructure stop reason.
1608    pub stop_reason: Option<ModuleStopReason>,
1609    /// A previous daemon's unresolved process, not a child owned by this supervisor.
1610    pub waiting_for_previous_pid: Option<u32>,
1611    /// Why the previous instance still prevents a new start.
1612    pub waiting_for_previous_detail: Option<String>,
1613    /// The daemon's Windows per-spawn record: `pipe` after the process it
1614    /// spawned read all nonce bytes, otherwise `env` for the offered copy.
1615    /// List/status reports use this record, not the source the module sends
1616    /// in its registration message's manifest.provenance.launch_nonce_source.
1617    pub launch_nonce_source: Option<String>,
1618    pub state: ModuleState,
1619    pub enabled: bool,
1620    pub process_alive: bool,
1621    pub registration_active: bool,
1622    /// The module's declared wire protocol, carried beside `live` because it is
1623    /// what makes `live` readable: the two fields answer one question together.
1624    /// While a process is alive this is its launch declaration, not a later
1625    /// pending-reload edit. When down it is the configured next launch protocol.
1626    pub protocol: ModuleProtocol,
1627    /// Whether the module is serving, under the strongest definition the daemon
1628    /// can assert for its protocol.
1629    ///
1630    /// A subc module must also be REGISTERED: its process being alive says
1631    /// nothing about whether it can take a request. A `protocol: "none"` module
1632    /// never registers, so that term is dropped and this falls back to "enabled,
1633    /// running, and the process the daemon launched is alive" -- which is all
1634    /// the daemon observes about a process that speaks no subc wire. It stays a
1635    /// `bool` on the wire for compatibility; renderers pair it with `protocol`
1636    /// rather than printing it bare.
1637    pub live: bool,
1638    /// Crash restarts spent INSIDE `restart_window` as of this read. Older
1639    /// restarts have already released their slot, so this count can go down
1640    /// without anybody touching the module.
1641    pub restart_count: u32,
1642    /// Replacement processes spawned over this module's entire supervisor lifetime;
1643    /// unlike `restart_count`, this value is never reset by an operator action
1644    /// and never falls out of a window.
1645    pub lifetime_restarts: u32,
1646    pub spawn_generation: u64,
1647    /// Retained daemon-local outcome; the legacy control response omits it.
1648    pub swap_outcome: Option<SwapOutcome>,
1649    /// The budget `restart_count` is spent against. Carried alongside the count
1650    /// because the count alone does not say how close the module is to being
1651    /// disabled, and reporting one without the other is what makes an
1652    /// about-to-be-retired module look ordinary.
1653    pub max_restarts: u32,
1654    /// The span `restart_count` is counted over. Carried with the pair above for
1655    /// the same reason they are carried together: "2 of 3" means one thing for a
1656    /// ten-minute window and something else entirely for a lifetime.
1657    pub restart_window: Duration,
1658    /// Effective drain and restart timing policy used by this running module.
1659    /// These values are carried together with the restart budget so status
1660    /// readers can compare configured intent with what the supervisor applied.
1661    pub drain_timeout: Duration,
1662    pub restart_backoff: Duration,
1663    pub restart_max_backoff: Duration,
1664    /// The module's process. On macOS this stays absent while the `ck-subc`
1665    /// launch trampoline is still running in that pid, and appears once the
1666    /// exec acknowledgement confirms the module image has replaced it. Launch
1667    /// time and the supervisor's own hold on the process are unaffected.
1668    pub pid: Option<u32>,
1669    pub spawned_at_ms: Option<u64>,
1670    pub spawned_from: Option<PathBuf>,
1671    pub(crate) launch_spec_digest: Option<LaunchSpecDigest>,
1672    pub process_start_time: Option<u64>,
1673    pub last_exit: Option<ExitReport>,
1674    pub health: ModuleHealthStatus,
1675}
1676
1677#[cfg(test)]
1678#[derive(Debug, Clone, Copy, PartialEq)]
1679struct ActorSelectCheckpoint {
1680    generation: u64,
1681    turn: u64,
1682    registered_connection: Option<ConnectionId>,
1683    next_probe_at: Option<Instant>,
1684    wake_after: Option<Duration>,
1685}
1686
1687#[derive(Debug, Clone, PartialEq)]
1688struct SupervisorSnapshot {
1689    admission_refused: Option<String>,
1690    /// Distinguishes an admission-parked actor from an unrelated terminal exit.
1691    config_hold_parked: bool,
1692    /// Preserve daemon attribution for a paused start so a failing release can
1693    /// schedule the next slow retry instead of treating the start as operator work.
1694    config_hold_daemon_initiated: bool,
1695    /// The approval that owns the parked attempt, not whichever approval is latest.
1696    config_hold_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
1697    /// Retain an approved launch failure across competing reconciliation passes.
1698    approved_start_failure: Option<(crate::config_gate::runtime::ApprovalIdentity, String)>,
1699    legacy_registration_spawn: bool,
1700    registration_declaration: Option<String>,
1701    stop_reason: Option<ModuleStopReason>,
1702    config_exit_failed_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
1703    subtree_target: crate::subtree_resources::Target,
1704    failed_retry: FailedRetry,
1705    exec_outcome: Option<Arc<crate::activity::ExecOutcome>>,
1706    #[cfg(windows)]
1707    pipe_consumed: Option<Arc<OnceLock<()>>>,
1708    /// Counts running-child loop turns, not executor polls of a parked wait.
1709    #[cfg(test)]
1710    actor_turns: u64,
1711    /// Running select after exec confirmation and with no unconsumed registry
1712    /// event. Recording a spawn or starting a loop turn is not this barrier.
1713    #[cfg(test)]
1714    actor_select: Option<ActorSelectCheckpoint>,
1715    state: ModuleState,
1716    enabled: bool,
1717    process_alive: bool,
1718    spawned_protocol: Option<ModuleProtocol>,
1719    spawn_failure: Option<String>,
1720    waiting_for_previous_pid: Option<u32>,
1721    waiting_for_previous_detail: Option<String>,
1722    /// When each crash restart was spent, oldest first. This IS the crash
1723    /// budget: its in-window length is the count an operator sees and the count
1724    /// the restart decision is made against, so there is no second counter that
1725    /// can disagree with it. Bounded by `max_restarts`, and cleared by the same
1726    /// operator actions that used to zero the old lifetime counter.
1727    crash_restarts: VecDeque<Instant>,
1728    lifetime_restarts: u32,
1729    /// Successful child spawns in this daemon incarnation.
1730    ///
1731    /// `lifetime_restarts` was considered and rejected: it starts at zero
1732    /// (line 640), successful initial/operator spawns in `set_running` do not
1733    /// increment it (lines 5264-5274), and crash/deliberate retry bookkeeping
1734    /// increments before a successful replacement exists (lines 604, 3846,
1735    /// and 3921), so a failed spawn can consume it. This counter moves only
1736    /// when a live PID is accepted below.
1737    spawn_generation: u64,
1738    swap_outcome: Option<SwapOutcome>,
1739    pid: Option<u32>,
1740    #[cfg(target_os = "macos")]
1741    report_ready: Option<Arc<OnceLock<()>>>,
1742    /// Last reaped child, retained after current process facts are cleared.
1743    reaped_pid: Option<u32>,
1744    /// Whether a replacement has already been scheduled for the current process.
1745    respawn_pending: bool,
1746    /// A second restart is waiting for the replacement already scheduled.
1747    coalesced_restart_pending: bool,
1748    spawned_at_ms: Option<u64>,
1749    spawned_from: Option<PathBuf>,
1750    launch_spec_digest: Option<LaunchSpecDigest>,
1751    spawned_file_identity: Option<SpawnedFileIdentity>,
1752    process_start_time: Option<u64>,
1753    deliberate_severance: Option<ProcessIdentity>,
1754    last_exit: Option<ExitReport>,
1755    /// Diagnostic attached to the next drain's terminal record, if any.
1756    drain_disposition_detail: Option<String>,
1757    health: ModuleHealthStatus,
1758    last_probe_evidence: Option<HealthProbeEvidence>,
1759    /// Whether the current process was started as a swap candidate and so
1760    /// lives in the module's alternate cgroup. The next swap's candidate takes
1761    /// the other one, so the two processes of a swap never share a cgroup. A
1762    /// plain spawn always uses the primary cgroup.
1763    in_alternate_slot: bool,
1764    /// Whether the current `Draining` state ends in a replacement process
1765    /// (restart, reload, health restart) rather than a stop. Only meaningful
1766    /// while `state` is `Draining`; every entry into that state rewrites it.
1767    /// It is what lets route.open answer the retryable `module_reloading` to a
1768    /// consumer that reaches a still-registered process mid-restart, instead of
1769    /// the `supervisor_not_live` a stop or disable deserves.
1770    draining_to_replace: bool,
1771    /// Whether a configuration update has been applied since the current
1772    /// process was spawned, so that process runs an older spec than the one
1773    /// the supervisor now holds. A queued restart is only coalesced into a
1774    /// fresher process when this is false: a restart requested to pick up a
1775    /// new configuration must not be satisfied by a process that predates it.
1776    configuration_updated_since_spawn: bool,
1777}
1778
1779impl SupervisorSnapshot {
1780    /// The pid that status, provenance and resource readings may report. While
1781    /// the launch trampoline still runs in the pid, reading its executable or
1782    /// resource use would describe `ck-subc`, not the module, so none is
1783    /// reported until the exec acknowledgement confirms the module image.
1784    fn reported_pid(&self) -> Option<u32> {
1785        #[cfg(target_os = "macos")]
1786        if self
1787            .report_ready
1788            .as_ref()
1789            .is_some_and(|ready| ready.get().is_none())
1790        {
1791            return None;
1792        }
1793        self.pid
1794    }
1795
1796    fn starting() -> Self {
1797        Self::new(ModuleState::Starting, true)
1798    }
1799
1800    fn disabled() -> Self {
1801        Self::new(ModuleState::Disabled, false)
1802    }
1803
1804    /// Give the module its full budget back, as an operator restart, reload, or
1805    /// re-enable does. `lifetime_restarts` deliberately does not move: it is the
1806    /// ledger of what actually happened, and an operator action does not unmake
1807    /// replacements that already ran.
1808    fn clear_crash_restarts(&mut self) {
1809        self.crash_restarts.clear();
1810    }
1811
1812    fn new(state: ModuleState, enabled: bool) -> Self {
1813        Self {
1814            admission_refused: None,
1815            config_hold_parked: false,
1816            config_hold_daemon_initiated: false,
1817            config_hold_approval: None,
1818            approved_start_failure: None,
1819            legacy_registration_spawn: false,
1820            registration_declaration: None,
1821            stop_reason: None,
1822            config_exit_failed_approval: None,
1823            subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
1824            failed_retry: FailedRetry::default(),
1825            exec_outcome: None,
1826            #[cfg(test)]
1827            actor_turns: 0,
1828            #[cfg(test)]
1829            actor_select: None,
1830            state,
1831            enabled,
1832            process_alive: false,
1833            #[cfg(windows)]
1834            pipe_consumed: None,
1835            spawned_protocol: None,
1836            spawn_failure: None,
1837            waiting_for_previous_pid: None,
1838            waiting_for_previous_detail: None,
1839            crash_restarts: VecDeque::new(),
1840            lifetime_restarts: 0,
1841            spawn_generation: 0,
1842            swap_outcome: None,
1843            pid: None,
1844            #[cfg(target_os = "macos")]
1845            report_ready: None,
1846            reaped_pid: None,
1847            respawn_pending: false,
1848            coalesced_restart_pending: false,
1849            spawned_at_ms: None,
1850            spawned_from: None,
1851            launch_spec_digest: None,
1852            spawned_file_identity: None,
1853            process_start_time: None,
1854            deliberate_severance: None,
1855            last_exit: None,
1856            drain_disposition_detail: None,
1857            health: ModuleHealthStatus::default(),
1858            last_probe_evidence: None,
1859            in_alternate_slot: false,
1860            draining_to_replace: false,
1861            configuration_updated_since_spawn: false,
1862        }
1863    }
1864}
1865
1866type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
1867
1868type SpawnSubscriberKey = (ConnectionId, u64);
1869
1870#[derive(Debug)]
1871struct SpawnSubscriber {
1872    version: u8,
1873    frames: mpsc::Sender<Frame>,
1874    /// Tells this subscriber's forwarder that it was dropped for lagging, and
1875    /// from which event. The full frame channel cannot carry that news, so it
1876    /// travels beside it; see `SpawnEventFeed::subscribe`.
1877    lagged: Option<oneshot::Sender<SpawnCursor>>,
1878}
1879
1880#[derive(Debug)]
1881struct SpawnEventState {
1882    daemon_incarnation: String,
1883    seq: u64,
1884    capacity: usize,
1885    live: HashMap<String, LiveSpawn>,
1886    generations: HashMap<String, u64>,
1887    events: VecDeque<SpawnEvent>,
1888    subscribers: HashMap<SpawnSubscriberKey, SpawnSubscriber>,
1889    process_changes: HashMap<String, tokio::sync::watch::Sender<u64>>,
1890}
1891
1892impl Default for SpawnEventState {
1893    fn default() -> Self {
1894        Self {
1895            daemon_incarnation: "unconfigured".to_string(),
1896            seq: 0,
1897            capacity: SPAWN_EVENT_RING_CAPACITY,
1898            live: HashMap::new(),
1899            generations: HashMap::new(),
1900            events: VecDeque::new(),
1901            subscribers: HashMap::new(),
1902            process_changes: HashMap::new(),
1903        }
1904    }
1905}
1906
1907#[derive(Debug, Clone, Default)]
1908struct SpawnEventFeed(
1909    Arc<Mutex<SpawnEventState>>,
1910    #[cfg(test)] Arc<Mutex<Option<std::net::TcpStream>>>,
1911);
1912
1913#[derive(Debug, Clone, PartialEq, Eq)]
1914pub(crate) enum SpawnSubscribeRefusal {
1915    ForeignIncarnation { current: String },
1916    TooOld { oldest: SpawnCursor },
1917    Frame(String),
1918}
1919
1920impl SpawnEventFeed {
1921    fn configure_incarnation(&self, daemon_incarnation: String) {
1922        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1923        state.daemon_incarnation = daemon_incarnation;
1924        state.seq = 0;
1925        state.live.clear();
1926        state.generations.clear();
1927        state.events.clear();
1928        state.subscribers.clear();
1929        for changed in state.process_changes.values() {
1930            changed.send_replace(0);
1931        }
1932    }
1933
1934    fn cursor(state: &SpawnEventState) -> SpawnCursor {
1935        SpawnCursor {
1936            daemon_incarnation: state.daemon_incarnation.clone(),
1937            seq: state.seq,
1938        }
1939    }
1940
1941    fn snapshot(&self) -> SpawnSnapshot {
1942        let state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1943        let mut live = state.live.values().cloned().collect::<Vec<_>>();
1944        live.sort_by(|left, right| left.module_id.cmp(&right.module_id));
1945        SpawnSnapshot {
1946            cursor: Self::cursor(&state),
1947            ring_bound: state.capacity as u64,
1948            live,
1949        }
1950    }
1951
1952    fn allocate_generation_locked(state: &mut SpawnEventState, module_id: &str) -> u64 {
1953        let generation = state
1954            .generations
1955            .get(module_id)
1956            .copied()
1957            .unwrap_or(0)
1958            .checked_add(1)
1959            .expect("spawn generation exhausted");
1960        state.generations.insert(module_id.to_string(), generation);
1961        generation
1962    }
1963
1964    /// Allocate the spawn generation of a launch that is about to start, with
1965    /// the daemon incarnation it belongs to. The number names the launch from
1966    /// this moment, before its process runs; a launch that never runs keeps
1967    /// its number, so the generations a subscriber sees may skip.
1968    fn allocate_generation(&self, module_id: &str) -> (String, u64) {
1969        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1970        let generation = Self::allocate_generation_locked(&mut state, module_id);
1971        (state.daemon_incarnation.clone(), generation)
1972    }
1973
1974    /// Publish a running process. `allocated` is the generation its launch
1975    /// was given before it started; a launch without one (a process with no
1976    /// registration channel) is numbered here.
1977    fn emit_spawned(
1978        &self,
1979        module_id: &str,
1980        allocated: Option<u64>,
1981        pid: u32,
1982        spawned_at_ms: u64,
1983    ) -> u64 {
1984        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1985        let generation = match allocated {
1986            Some(generation) => generation,
1987            None => Self::allocate_generation_locked(&mut state, module_id),
1988        };
1989        let live = LiveSpawn {
1990            module_id: module_id.to_string(),
1991            spawn_generation: generation,
1992            pid,
1993            spawned_at_ms,
1994        };
1995        state.live.insert(module_id.to_string(), live);
1996        Self::emit_locked(
1997            &mut state,
1998            SpawnEventKind::Spawned,
1999            module_id.to_string(),
2000            generation,
2001            pid,
2002            None,
2003            None,
2004        );
2005        generation
2006    }
2007
2008    fn emit_exited(&self, module_id: &str, exit_code: Option<i32>, exit_signal: Option<i32>) {
2009        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2010        let Some(live) = state.live.remove(module_id) else {
2011            warn!(
2012                module_id,
2013                "terminal record had no live spawn event identity"
2014            );
2015            return;
2016        };
2017        Self::emit_locked(
2018            &mut state,
2019            SpawnEventKind::Exited,
2020            module_id.to_string(),
2021            live.spawn_generation,
2022            live.pid,
2023            exit_code,
2024            exit_signal,
2025        );
2026    }
2027
2028    /// Report the exit of a process that a swap has already replaced.
2029    ///
2030    /// `emit_exited` removes the module's live entry, which after a swap's
2031    /// cutover describes the promoted candidate, not the old process now
2032    /// exiting. This emits the old generation's exit and leaves the live entry
2033    /// alone unless it still names that generation.
2034    fn emit_superseded_exited(
2035        &self,
2036        module_id: &str,
2037        spawn_generation: u64,
2038        pid: u32,
2039        exit_code: Option<i32>,
2040        exit_signal: Option<i32>,
2041    ) {
2042        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2043        if state
2044            .live
2045            .get(module_id)
2046            .is_some_and(|live| live.spawn_generation == spawn_generation)
2047        {
2048            state.live.remove(module_id);
2049        }
2050        Self::emit_locked(
2051            &mut state,
2052            SpawnEventKind::Exited,
2053            module_id.to_string(),
2054            spawn_generation,
2055            pid,
2056            exit_code,
2057            exit_signal,
2058        );
2059    }
2060
2061    #[allow(clippy::too_many_arguments)]
2062    fn emit_locked(
2063        state: &mut SpawnEventState,
2064        kind: SpawnEventKind,
2065        module_id: String,
2066        spawn_generation: u64,
2067        pid: u32,
2068        exit_code: Option<i32>,
2069        exit_signal: Option<i32>,
2070    ) {
2071        state.seq = state
2072            .seq
2073            .checked_add(1)
2074            .expect("spawn event sequence exhausted");
2075        let event = SpawnEvent {
2076            cursor: Self::cursor(state),
2077            kind,
2078            module_id,
2079            spawn_generation,
2080            pid,
2081            exit_code,
2082            exit_signal,
2083        };
2084        state
2085            .process_changes
2086            .retain(|_, changed| changed.receiver_count() > 0);
2087        if let Some(changed) = state.process_changes.get(&event.module_id) {
2088            changed.send_replace(state.seq);
2089        }
2090        state.events.push_back(event.clone());
2091        while state.events.len() > state.capacity {
2092            state.events.pop_front();
2093        }
2094        let body = match serde_json::to_vec(&event) {
2095            Ok(body) => body,
2096            Err(error) => {
2097                error!(%error, "failed to serialize supervisor spawn event");
2098                return;
2099            }
2100        };
2101        state.subscribers.retain(|(connection_id, corr), subscriber| {
2102            let frame = Frame::build_with_version(
2103                subscriber.version,
2104                FrameType::StreamData,
2105                control_flags(),
2106                0,
2107                0,
2108                *corr,
2109                body.clone(),
2110            );
2111            match frame {
2112                Ok(frame) => {
2113                    if subscriber.frames.try_send(frame).is_ok() {
2114                        true
2115                    } else {
2116                        warn!(connection_id = connection_id.get(), corr, "dropping lagged supervisor spawn subscriber");
2117                        if let Some(lagged) = subscriber.lagged.take() {
2118                            let _ = lagged.send(event.cursor.clone());
2119                        }
2120                        false
2121                    }
2122                }
2123                Err(error) => {
2124                    warn!(connection_id = connection_id.get(), corr, %error, "dropping supervisor spawn subscriber after frame build failure");
2125                    false
2126                }
2127            }
2128        });
2129    }
2130
2131    fn subscribe(
2132        &self,
2133        connection_id: ConnectionId,
2134        corr: u64,
2135        version: u8,
2136        since: Option<SpawnCursor>,
2137        sink: FrameSink,
2138    ) -> Result<(), SpawnSubscribeRefusal> {
2139        let (frames, mut receiver) = mpsc::channel(SPAWN_SUBSCRIBER_BUFFER);
2140        let (lagged, mut lagged_rx) = oneshot::channel::<SpawnCursor>();
2141        {
2142            let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2143            let replay = if let Some(since) = since {
2144                if since.daemon_incarnation != state.daemon_incarnation {
2145                    return Err(SpawnSubscribeRefusal::ForeignIncarnation {
2146                        current: state.daemon_incarnation.clone(),
2147                    });
2148                }
2149                if let Some(oldest) = state.events.front().map(|event| event.cursor.clone()) {
2150                    if since.seq < oldest.seq.saturating_sub(1) {
2151                        return Err(SpawnSubscribeRefusal::TooOld { oldest });
2152                    }
2153                }
2154                state
2155                    .events
2156                    .iter()
2157                    .filter(|event| event.cursor.seq > since.seq)
2158                    .cloned()
2159                    .collect::<Vec<_>>()
2160            } else {
2161                Vec::new()
2162            };
2163            for event in replay {
2164                let body = serde_json::to_vec(&event)
2165                    .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2166                let frame = Frame::build_with_version(
2167                    version,
2168                    FrameType::StreamData,
2169                    control_flags(),
2170                    0,
2171                    0,
2172                    corr,
2173                    body,
2174                )
2175                .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2176                frames
2177                    .try_send(frame)
2178                    .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2179            }
2180            state.subscribers.insert(
2181                (connection_id, corr),
2182                SpawnSubscriber {
2183                    version,
2184                    frames,
2185                    lagged: Some(lagged),
2186                },
2187            );
2188        }
2189        // The lagged terminal is sent here, by the forwarder, rather than by
2190        // the emitter: at the moment of the drop the subscriber's own channel
2191        // is full, and writing to the connection sink directly from the emitter
2192        // would put the Error AHEAD of the events still queued in that channel
2193        // (and the emitter holds the feed lock, so it cannot await the sink).
2194        // Dropping the subscriber drops the only sender, so `recv` drains every
2195        // queued event and then returns `None`; only then is the Error sent, so
2196        // the client sees each event it can keep, then the reason it was cut.
2197        // Cancel and connection removal drop the oneshot unsent, so they end
2198        // the stream with no Error.
2199        tokio::spawn(async move {
2200            while let Some(frame) = receiver.recv().await {
2201                if sink.send(frame).await.is_err() {
2202                    return;
2203                }
2204            }
2205            let Ok(first_undelivered) = lagged_rx.try_recv() else {
2206                return;
2207            };
2208            match spawn_subscriber_lagged_frame(version, corr, first_undelivered) {
2209                Ok(frame) => {
2210                    let _ = sink.send(frame).await;
2211                }
2212                Err(error) => {
2213                    error!(%error, corr, "failed to build lagged spawn subscriber terminal frame");
2214                }
2215            }
2216        });
2217        Ok(())
2218    }
2219
2220    fn cancel(&self, connection_id: ConnectionId, corr: u64) -> bool {
2221        let Some(subscriber) = self
2222            .0
2223            .lock()
2224            .unwrap_or_else(|p| p.into_inner())
2225            .subscribers
2226            .remove(&(connection_id, corr))
2227        else {
2228            return false;
2229        };
2230        if let Ok(frame) = Frame::build_with_version(
2231            subscriber.version,
2232            FrameType::StreamEnd,
2233            control_flags(),
2234            0,
2235            0,
2236            corr,
2237            Vec::new(),
2238        ) {
2239            tokio::spawn(async move {
2240                let _ = subscriber.frames.send(frame).await;
2241            });
2242        }
2243        true
2244    }
2245
2246    fn remove_connection(&self, connection_id: ConnectionId) {
2247        self.0
2248            .lock()
2249            .unwrap_or_else(|p| p.into_inner())
2250            .subscribers
2251            .retain(|(subscriber_connection, _), _| *subscriber_connection != connection_id);
2252    }
2253
2254    #[cfg(any(test, feature = "test-support"))]
2255    fn set_capacity(&self, capacity: usize) {
2256        self.0.lock().unwrap_or_else(|p| p.into_inner()).capacity = capacity;
2257    }
2258
2259    #[cfg(any(test, feature = "test-support"))]
2260    fn subscriber_count(&self) -> usize {
2261        self.0
2262            .lock()
2263            .unwrap_or_else(|p| p.into_inner())
2264            .subscribers
2265            .len()
2266    }
2267}
2268
2269/// Narrow process-liveness signal published by supervisors and consumed by passive liveness polls.
2270/// The terminal Error a lagged spawn subscriber receives after its queued events.
2271fn spawn_subscriber_lagged_frame(
2272    version: u8,
2273    corr: u64,
2274    first_undelivered: SpawnCursor,
2275) -> Result<Frame, String> {
2276    // The daemon authors this terminal Error, so it carries the daemon-origin bit.
2277    let body = serde_json::to_vec(&subc_protocol::ErrorBody {
2278        code: SPAWN_SUBSCRIBER_LAGGED_CODE.to_string(),
2279        message: "spawn subscriber fell behind and was dropped; resubscribe from the last cursor received"
2280            .to_string(),
2281        detail: Some(serde_json::json!({
2282            "first_undelivered_cursor": first_undelivered
2283        })),
2284    })
2285    .map_err(|error| error.to_string())?;
2286    Frame::build_with_version(
2287        version,
2288        FrameType::Error,
2289        crate::router::daemon_error_flags(),
2290        0,
2291        0,
2292        corr,
2293        body,
2294    )
2295    .map_err(|error| error.to_string())
2296}
2297
2298pub trait ModuleProcessLiveness: Send + Sync {
2299    fn process_live(&self, module_id: &str) -> Option<bool>;
2300
2301    /// Whether the supervisor is replacing this module's process right now: an
2302    /// operator restart or reload, a health restart, or a crash respawn whose
2303    /// backoff is running. A module in that state is not live, but a consumer
2304    /// refused now should retry shortly rather than treat the target as gone.
2305    /// Stopped, failed, and disabled modules are not replacing.
2306    fn process_replacing(&self, _module_id: &str) -> bool {
2307        false
2308    }
2309}
2310
2311/// Shared process-liveness registry keyed by supervised `module_id`.
2312#[derive(Debug, Clone, Default)]
2313pub struct SupervisorProcessLiveness {
2314    snapshots: Arc<Mutex<HashMap<String, SharedSnapshot>>>,
2315}
2316
2317impl SupervisorProcessLiveness {
2318    pub fn new() -> Self {
2319        Self::default()
2320    }
2321
2322    fn track(&self, module_id: String, snapshot: SharedSnapshot) {
2323        let mut snapshots = self
2324            .snapshots
2325            .lock()
2326            .unwrap_or_else(|poisoned| poisoned.into_inner());
2327        snapshots.insert(module_id, snapshot);
2328    }
2329
2330    fn untrack_if_current(&self, module_id: &str, snapshot: &SharedSnapshot) {
2331        let mut snapshots = self
2332            .snapshots
2333            .lock()
2334            .unwrap_or_else(|poisoned| poisoned.into_inner());
2335        let is_current = snapshots
2336            .get(module_id)
2337            .map(|tracked| Arc::ptr_eq(tracked, snapshot))
2338            .unwrap_or(false);
2339        if is_current {
2340            snapshots.remove(module_id);
2341        }
2342    }
2343}
2344
2345impl ModuleProcessLiveness for SupervisorProcessLiveness {
2346    fn process_live(&self, module_id: &str) -> Option<bool> {
2347        let snapshot = {
2348            let snapshots = self
2349                .snapshots
2350                .lock()
2351                .unwrap_or_else(|poisoned| poisoned.into_inner());
2352            snapshots.get(module_id).cloned()
2353        }?;
2354        let snapshot = snapshot
2355            .lock()
2356            .unwrap_or_else(|poisoned| poisoned.into_inner());
2357        Some(snapshot.state == ModuleState::Running && snapshot.process_alive)
2358    }
2359
2360    fn process_replacing(&self, module_id: &str) -> bool {
2361        let Some(snapshot) = self
2362            .snapshots
2363            .lock()
2364            .unwrap_or_else(|poisoned| poisoned.into_inner())
2365            .get(module_id)
2366            .cloned()
2367        else {
2368            return false;
2369        };
2370        let snapshot = snapshot
2371            .lock()
2372            .unwrap_or_else(|poisoned| poisoned.into_inner());
2373        snapshot.enabled
2374            && match snapshot.state {
2375                ModuleState::Restarting => true,
2376                ModuleState::Draining => snapshot.draining_to_replace,
2377                ModuleState::Starting
2378                | ModuleState::Running
2379                | ModuleState::Unresponsive
2380                | ModuleState::Stopped
2381                | ModuleState::Failed
2382                | ModuleState::Disabled => false,
2383            }
2384    }
2385}
2386
2387#[cfg(test)]
2388#[derive(Debug, Default)]
2389struct ReloadExitRecordGate {
2390    reached: tokio::sync::Notify,
2391    resume: tokio::sync::Notify,
2392}
2393
2394#[derive(Debug, Clone, Copy)]
2395enum RespawnKind {
2396    Spawn,
2397    CrashRestart,
2398    Reload,
2399}
2400
2401#[derive(Debug, Clone)]
2402struct PendingRespawn {
2403    deadline: Instant,
2404    kind: RespawnKind,
2405    daemon_initiated: bool,
2406    approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
2407}
2408
2409impl PendingRespawn {
2410    fn failure_context(&self, runtime: &SupervisorRuntimeConfig) -> FailureContext {
2411        FailureContext {
2412            approval: self.approval.clone(),
2413            ..runtime.failure_context(self.daemon_initiated)
2414        }
2415    }
2416}
2417
2418type ReloadReply = oneshot::Sender<Result<(), SuperviseError>>;
2419
2420#[derive(Debug, Clone)]
2421struct SupervisorRuntimeConfig {
2422    registry: Arc<Registry>,
2423    config_delivery: Option<config_delivery::ConfigDelivery>,
2424    /// Retained across an operation's deferred backoff, until its child starts.
2425    recovery_is_daemon: bool,
2426    start_requester: Option<Principal>,
2427    pending_activity_restart: bool,
2428    provenance_probe: ExecutableIdentityProbe,
2429    /// Restart operations hand their backoff to the loop, which keeps serving commands.
2430    scheduled_respawn: Arc<Mutex<Option<PendingRespawn>>>,
2431    /// A reload acknowledges completion only after its replacement registers.
2432    deferred_reload_reply: Arc<Mutex<Option<ReloadReply>>>,
2433    restart_policy: RestartPolicy,
2434    register_timeout: Duration,
2435    /// This module's RESOLVED drain budget: per-module config when present,
2436    /// else `default_drain_timeout`.
2437    drain_timeout: Duration,
2438    /// Shared with the status handle so the attested value changes atomically
2439    /// when a rescan updates the running drain policy.
2440    effective_drain_timeout: Arc<Mutex<Duration>>,
2441    /// The supervisor-wide fallback, kept so a configuration update that
2442    /// REMOVES the per-module override can re-resolve to it.
2443    default_drain_timeout: Duration,
2444    health: HealthConfig,
2445    host_health: HostHealth,
2446    connection_file_path: Option<PathBuf>,
2447    capture_logs_dir: Option<PathBuf>,
2448    forwarding: Option<Arc<ForwardingTable>>,
2449    /// The shared handle, so every spawn path (initial, restart, reload) records the
2450    /// reserved-module launch nonce the HELLO verifier checks against.
2451    supervisor_handle: Option<SupervisorHandle>,
2452    /// This module's stderr tail, shared with the [`SupervisedModule`] that answers
2453    /// status queries.
2454    ///
2455    /// One ring per module, held across every respawn. The lines explaining an exit
2456    /// are written BEFORE that exit, so a ring recreated per process would be empty
2457    /// exactly when it is asked for.
2458    stderr_ring: Arc<Mutex<StderrRing>>,
2459    terminal_ring: Arc<Mutex<TerminalRing>>,
2460    spawn_events: SpawnEventFeed,
2461    child_roster: ChildRoster,
2462    #[cfg(target_os = "linux")]
2463    cgroup_placement: Option<subc_cgroup::Placement>,
2464    #[cfg(test)]
2465    test_seed_stale_facts_before_enable_spawn: bool,
2466    #[cfg(test)]
2467    test_reload_exit_record_gate: Option<Arc<ReloadExitRecordGate>>,
2468}
2469
2470impl SupervisorRuntimeConfig {
2471    fn failure_context(&self, daemon_initiated: bool) -> FailureContext {
2472        FailureContext {
2473            daemon_initiated,
2474            approval: None,
2475            shutdown: self.child_roster.shutdown_flag(),
2476        }
2477    }
2478}
2479
2480#[derive(Debug, Clone, PartialEq, Eq)]
2481struct SupervisedConfiguration {
2482    spec: ModuleSpec,
2483    enabled: bool,
2484    health: HealthConfig,
2485    register_timeout: Duration,
2486    restart_policy: RestartPolicy,
2487}
2488
2489/// Shared daemon lookup table for supervised module handles.
2490///
2491/// Shared by clone between the [`Supervisor`] (which spawns processes) and the
2492/// channel-0 control handler (which verifies HELLOs and consumer route opens), so
2493/// launch nonces recorded at spawn are checked by the same daemon instance.
2494#[derive(Debug, Clone, Default)]
2495pub struct SupervisorHandle {
2496    #[cfg(test)]
2497    resource_commit_pause: Arc<Mutex<Option<resource_launch::ResourceCommitPause>>>,
2498    #[cfg(test)]
2499    registration_test_channels: CapturedRegistrationChannels,
2500    registration_service: Arc<Mutex<Option<registration::RegistrationService>>>,
2501    registration_connections: Arc<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
2502    registration_launches: Arc<Mutex<Vec<std::sync::Weak<RegistrationSpawn>>>>,
2503    gate_runtime: Arc<Mutex<Option<std::sync::Weak<crate::config_gate::runtime::RuntimeOwner>>>>,
2504    program_bindings: program_binding::ProgramBindings,
2505    #[cfg(test)]
2506    identity_sample_pause: Arc<Mutex<Option<IdentitySamplePause>>>,
2507    #[cfg(all(test, unix))]
2508    plain_identity_policy_pause: Arc<Mutex<Option<(String, IdentitySamplePause)>>>,
2509    host_health: HostHealth,
2510    restart_intent: Arc<Mutex<DaemonRestartIntent>>,
2511    activity: Arc<Mutex<Option<crate::activity::ActivityLedger>>>,
2512    activity_images: Arc<Mutex<HashMap<String, activity::ActivityImage>>>,
2513    modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
2514    /// Module ids the supervisor has taken on. An id is added BEFORE the
2515    /// module's first process is spawned and removed only when the module
2516    /// leaves the roster (see [`Self::retire`]), so it is always a superset of
2517    /// the keys of `modules`.
2518    ///
2519    /// `modules` cannot answer "is this module configured?" on its own: a
2520    /// [`SupervisedModule`] only exists once its process has been spawned, and
2521    /// a fast child can connect, register, sync its scopes and ask about them
2522    /// before the supervisor has inserted it. Answering "not configured" in that
2523    /// gap makes scope admission refuse with the terminal "will never sync"
2524    /// instead of the retryable "has not synced yet".
2525    configured_ids: Arc<Mutex<HashSet<String>>>,
2526    spawn_events: SpawnEventFeed,
2527    /// The current expected launch nonce for each reserved module_id. Set when the
2528    /// supervisor spawns the reserved module; checked when a HELLO claims that id. A
2529    /// non-reserved module never has an entry here and is never nonce-checked.
2530    /// Reserved module ids and the nonce that authorizes their next HELLO.
2531    /// `None` means RESERVED WITH NO LEGITIMATE HOLDER — a reserved module that
2532    /// has never been spawned (e.g. configured `enabled: false`) — and refuses
2533    /// every HELLO. Before this was expressible, a reserved-but-never-spawned id
2534    /// had NO entry and admitted anyone: the reservation protected the nonce
2535    /// holder, not the NAME (found live by CKCRED's canary probe registering
2536    /// against a reserved scratch id).
2537    reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
2538    /// Reservations installed only to prevent HELLO for a protocol:none process.
2539    /// Replacement by a subc process releases them; explicitly reserved ids are
2540    /// never placed in this set and still require an operator release.
2541    implicit_protocol_none: Arc<Mutex<HashSet<String>>>,
2542    /// Module ids removed by an executed rescan and the unix-millisecond removal time.
2543    ///
2544    /// This is deliberately in-memory only: subc is state-free across daemon
2545    /// restarts, and the tombstone only explains the hours-after-removal window
2546    /// while this executing daemon is still alive. Do not persist it in a store.
2547    removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
2548    /// The current launch nonce for every supervised spawn. This is separate from
2549    /// reserved_nonces because consumer route.open attestation applies to all spawned
2550    /// modules, while HELLO id-squatting protection remains opt-in via `reserved`.
2551    spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
2552    /// The launch each live launch nonce was minted for, keyed by nonce, with
2553    /// the launch's module id, so a nonce-attested consumer or registration
2554    /// resolves to that launch's authority record. An entry whose launch has
2555    /// ended stays while its nonce still authorizes, so a nonce whose record
2556    /// is gone is told apart from one that never had a record.
2557    nonce_launches: Arc<Mutex<NonceLaunches>>,
2558    /// Reserved namespace prefixes mapped to the supervised owner module whose
2559    /// current spawn nonce authorizes HELLO claims below the prefix.
2560    ///
2561    /// Per §2.6 this is not a same-user security barrier: a same-user process can
2562    /// read the key file and launch nonce env. Like exact reserved ids, it prevents
2563    /// accidental collisions and lower-trust processes from squatting protected
2564    /// namespaces.
2565    reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
2566    /// Blue/green swaps in progress, by module id. An entry exists from just
2567    /// before the candidate process is spawned until the swap has failed, or
2568    /// has cut over and the old process is gone. While it exists, HELLO for the
2569    /// id is gated on the swap token (see [`Self::swap_hello_admission`]) and
2570    /// consumer attestation accepts both processes' nonces.
2571    swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
2572    /// Told when a swap promotes its candidate; see [`SwapPromotionObserver`].
2573    promotion_observer: PromotionObserverSlot,
2574    /// Serializes module-set reconciliation with operator lifecycle commands. Without
2575    /// this daemon-wide ordering, a rescan could retire or update a module while a
2576    /// concurrent reload still held its old handle and launch specification.
2577    operation_lock: Arc<AsyncMutex<()>>,
2578}
2579
2580#[cfg(test)]
2581#[derive(Debug)]
2582struct IdentitySamplePause {
2583    reached: std::sync::mpsc::Sender<()>,
2584    release: std::sync::mpsc::Receiver<()>,
2585}
2586
2587/// Told when a swap has promoted its candidate to be the module's active
2588/// registration.
2589///
2590/// An ordinary HELLO runs the control plane's registration side effects (the
2591/// capability cache, the deny census, the requirement recompute) as it
2592/// registers. A swap candidate's HELLO does not, because it is not routable;
2593/// promotion is when those must run instead, and promotion happens in the
2594/// supervisor, which has no other way into the control handler.
2595pub(crate) trait SwapPromotionObserver: Send + Sync {
2596    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration);
2597}
2598
2599/// The installed [`SwapPromotionObserver`], held weakly: the observer (the
2600/// control handler) owns this handle, so a strong reference back would be a
2601/// cycle that keeps both alive.
2602#[derive(Clone, Default)]
2603struct PromotionObserverSlot(Arc<Mutex<Option<std::sync::Weak<dyn SwapPromotionObserver>>>>);
2604
2605impl fmt::Debug for PromotionObserverSlot {
2606    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2607        f.write_str("PromotionObserverSlot")
2608    }
2609}
2610
2611/// The nonces of one open swap.
2612#[derive(Debug, Clone)]
2613struct OpenSwap {
2614    /// Legacy candidate token. A gated candidate has an empty lifecycle
2615    /// placeholder instead; only its own channel admits its HELLO.
2616    candidate_nonce: String,
2617    /// Incumbent token accepted before cutover, then cleared by promotion even
2618    /// while the incumbent's process is still draining.
2619    incumbent_nonce: Option<String>,
2620    /// Set once a HELLO has been admitted with the swap token, so the token
2621    /// admits one registration and cannot be replayed after cutover empties
2622    /// the candidate slot.
2623    candidate_admitted: bool,
2624}
2625
2626/// What the swap gate says about a HELLO. See
2627/// [`SupervisorHandle::swap_hello_admission`].
2628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2629pub(crate) enum SwapHelloAdmission {
2630    /// No swap is open for the id (or the HELLO carries the incumbent's own
2631    /// nonce); the ordinary gates decide.
2632    NotSwapping,
2633    /// The HELLO carries the swap token: register it into the candidate slot.
2634    Candidate,
2635    /// A swap is open and the HELLO carries a nonce the supervisor did not
2636    /// mint for this id, no nonce, or a token already used.
2637    Refused,
2638    /// The id belongs to a supervised `protocol: none` module. Such a module
2639    /// never registers, so no HELLO may claim its id, with or without a nonce.
2640    ProtocolNone,
2641    /// The id is gated. Its supervised child registers only over the
2642    /// registration channel it inherited at launch, never by HELLO alone.
2643    ChannelRequired,
2644}
2645
2646#[derive(Debug, Clone, PartialEq, Eq)]
2647pub(crate) enum ReservedHelloRejection {
2648    Exact {
2649        module_id: String,
2650    },
2651    Prefix {
2652        prefix: String,
2653        owner_module_id: String,
2654    },
2655}
2656
2657/// Identity facts established by the reserved-module policy for one HELLO.
2658#[derive(Debug, Default)]
2659pub(crate) struct ReservedHelloVerification {
2660    pub(crate) nonce_verified: bool,
2661    pub(crate) prefix_owner: Option<String>,
2662}
2663
2664#[derive(Debug)]
2665struct DaemonRestartIntent {
2666    expires: Option<Duration>,
2667    window: Duration,
2668}
2669
2670impl Default for DaemonRestartIntent {
2671    fn default() -> Self {
2672        Self {
2673            expires: None,
2674            window: Duration::from_secs(120),
2675        }
2676    }
2677}
2678
2679impl SupervisorHandle {
2680    pub(crate) fn module_is_gated(&self, module: &str) -> bool {
2681        let runtime = {
2682            let Ok(runtime) = self.gate_runtime.lock() else {
2683                return true;
2684            };
2685            runtime.clone()
2686        };
2687        runtime.is_some_and(|runtime| {
2688            runtime
2689                .upgrade()
2690                .is_none_or(|owner| owner.module_is_gated(module))
2691        })
2692    }
2693    pub(crate) fn announce_daemon_restart(&self) -> u64 {
2694        let mut intent = self
2695            .restart_intent
2696            .lock()
2697            .unwrap_or_else(|p| p.into_inner());
2698        intent.expires = Some(subc_uptime::suspend_inclusive_now() + intent.window);
2699        unix_ms_now().saturating_add(intent.window.as_millis() as u64)
2700    }
2701
2702    #[cfg(feature = "test-support")]
2703    pub(crate) fn set_shutdown_intent_window(&self, window: Duration) {
2704        self.restart_intent
2705            .lock()
2706            .unwrap_or_else(|p| p.into_inner())
2707            .window = window;
2708    }
2709
2710    #[cfg(unix)]
2711    fn take_daemon_shutdown_reason(&self) -> RouteCloseReason {
2712        let expiry = self
2713            .restart_intent
2714            .lock()
2715            .unwrap_or_else(|p| p.into_inner())
2716            .expires
2717            .take();
2718        if expiry.is_some_and(|expiry| subc_uptime::suspend_inclusive_now() < expiry) {
2719            RouteCloseReason::Restart
2720        } else {
2721            RouteCloseReason::Disable
2722        }
2723    }
2724
2725    pub fn new() -> Self {
2726        Self::default()
2727    }
2728
2729    pub(crate) fn spawn_snapshot(&self) -> SpawnSnapshot {
2730        self.spawn_events.snapshot()
2731    }
2732
2733    /// Subscribe before reading the bound process. A coalesced wake is enough:
2734    /// readers compare its exact generation and PID, not the last event kind.
2735    pub(crate) fn subscribe_process_changes(
2736        &self,
2737        module: &str,
2738    ) -> tokio::sync::watch::Receiver<u64> {
2739        let mut state = self
2740            .spawn_events
2741            .0
2742            .lock()
2743            .unwrap_or_else(|p| p.into_inner());
2744        state
2745            .process_changes
2746            .retain(|_, changed| changed.receiver_count() > 0);
2747        let seq = state.seq;
2748        state
2749            .process_changes
2750            .entry(module.into())
2751            .or_insert_with(|| tokio::sync::watch::channel(seq).0)
2752            .subscribe()
2753    }
2754
2755    pub(crate) fn current_spawn(&self, module: &str) -> Option<LiveSpawn> {
2756        self.spawn_events
2757            .0
2758            .lock()
2759            .unwrap_or_else(|p| p.into_inner())
2760            .live
2761            .get(module)
2762            .cloned()
2763    }
2764
2765    pub(crate) fn subscribe_spawns(
2766        &self,
2767        connection_id: ConnectionId,
2768        corr: u64,
2769        version: u8,
2770        since: Option<SpawnCursor>,
2771        sink: FrameSink,
2772    ) -> Result<(), SpawnSubscribeRefusal> {
2773        self.spawn_events
2774            .subscribe(connection_id, corr, version, since, sink)
2775    }
2776
2777    pub(crate) fn cancel_spawn_subscription(&self, connection_id: ConnectionId, corr: u64) -> bool {
2778        self.spawn_events.cancel(connection_id, corr)
2779    }
2780
2781    pub(crate) fn remove_spawn_subscribers(&self, connection_id: ConnectionId) {
2782        self.spawn_events.remove_connection(connection_id);
2783    }
2784
2785    #[cfg(any(test, feature = "test-support"))]
2786    pub fn set_spawn_event_capacity_for_test(&self, capacity: usize) {
2787        assert!(capacity > 0, "spawn event capacity must be non-zero");
2788        self.spawn_events.set_capacity(capacity);
2789    }
2790
2791    #[cfg(any(test, feature = "test-support"))]
2792    pub fn spawn_subscriber_count_for_test(&self) -> usize {
2793        self.spawn_events.subscriber_count()
2794    }
2795
2796    /// Record the launch nonce from a supervised spawn, replacing any prior nonce so
2797    /// a respawn invalidates stale consumer identities.
2798    pub fn set_spawn_nonce(&self, module_id: &str, nonce: String) {
2799        self.spawn_nonces
2800            .lock()
2801            .unwrap_or_else(|poisoned| poisoned.into_inner())
2802            .insert(module_id.to_string(), nonce);
2803        self.refresh_program_binding_nonces(module_id);
2804    }
2805
2806    /// Record the launch nonce expected from the next HELLO for a reserved module,
2807    /// replacing any prior nonce (a respawn invalidates the previous one).
2808    pub fn set_reserved_nonce(&self, module_id: &str, nonce: String) {
2809        {
2810            let mut reserved = self
2811                .reserved_nonces
2812                .lock()
2813                .unwrap_or_else(|p| p.into_inner());
2814            self.implicit_protocol_none
2815                .lock()
2816                .unwrap_or_else(|p| p.into_inner())
2817                .remove(module_id);
2818            reserved.insert(module_id.to_string(), Some(nonce));
2819        }
2820        self.refresh_program_binding_nonces(module_id);
2821    }
2822
2823    /// Record namespace prefixes owned by a supervised module.
2824    pub fn set_reserved_prefixes(&self, owner_module_id: &str, prefixes: &[String]) {
2825        let mut owners = self
2826            .reserved_prefix_owners
2827            .lock()
2828            .unwrap_or_else(|poisoned| poisoned.into_inner());
2829        owners.retain(|_, owner| owner != owner_module_id);
2830        for prefix in prefixes {
2831            owners.insert(prefix.clone(), owner_module_id.to_string());
2832        }
2833    }
2834
2835    /// The launch nonce most recently minted for a module's spawn, if any.
2836    pub(crate) fn spawn_nonce(&self, module_id: &str) -> Option<String> {
2837        if self.module_is_gated(module_id) {
2838            return None;
2839        }
2840        self.spawn_nonces
2841            .lock()
2842            .unwrap_or_else(|poisoned| poisoned.into_inner())
2843            .get(module_id)
2844            .cloned()
2845    }
2846
2847    #[cfg(all(test, unix))]
2848    pub(crate) fn legacy_nonce_present_for_test(&self, module: &str) -> bool {
2849        self.spawn_nonces.lock().unwrap().contains_key(module)
2850    }
2851
2852    pub(crate) fn apply_identity_configuration(&self, spec: &ModuleSpec) {
2853        // Prefix ownership follows staged configuration, not the running
2854        // child's launch settings. A respawn may still carry an older spec.
2855        self.set_reserved_prefixes(&spec.module_id, &spec.reserved_prefixes);
2856        let protocol = self
2857            .get(&spec.module_id)
2858            .and_then(|module| {
2859                let snapshot = module.inner.snapshot.lock().ok()?;
2860                snapshot
2861                    .process_alive
2862                    .then_some(snapshot.spawned_protocol.unwrap_or(spec.protocol))
2863            })
2864            .unwrap_or(spec.protocol);
2865        self.apply_identity_policy(spec, protocol);
2866    }
2867
2868    #[cfg(all(test, unix))]
2869    pub(crate) fn pause_plain_identity_policy_for_test(
2870        &self,
2871        module: &str,
2872    ) -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
2873        let (reached, waiting) = std::sync::mpsc::channel();
2874        let (release, paused) = std::sync::mpsc::channel();
2875        *self.plain_identity_policy_pause.lock().unwrap() = Some((
2876            module.to_owned(),
2877            IdentitySamplePause {
2878                reached,
2879                release: paused,
2880            },
2881        ));
2882        (waiting, release)
2883    }
2884
2885    fn apply_identity_policy(&self, spec: &ModuleSpec, protocol: ModuleProtocol) {
2886        let channel_only = self.module_is_gated(&spec.module_id);
2887        let mut current_nonces = self
2888            .spawn_nonces
2889            .lock()
2890            .unwrap_or_else(|poisoned| poisoned.into_inner());
2891        if protocol == ModuleProtocol::None || channel_only {
2892            current_nonces.remove(&spec.module_id);
2893        }
2894        let spawn_nonce = current_nonces.get(&spec.module_id).cloned();
2895        #[cfg(test)]
2896        if let Some(pause) = self.identity_sample_pause.lock().unwrap().take() {
2897            pause.reached.send(()).unwrap();
2898            pause.release.recv().unwrap();
2899        }
2900        let mut reserved_nonces = self
2901            .reserved_nonces
2902            .lock()
2903            .unwrap_or_else(|poisoned| poisoned.into_inner());
2904        let mut implicit = self
2905            .implicit_protocol_none
2906            .lock()
2907            .unwrap_or_else(|p| p.into_inner());
2908        if spec.reserved {
2909            implicit.remove(&spec.module_id);
2910        } else if protocol == ModuleProtocol::None {
2911            if !reserved_nonces.contains_key(&spec.module_id) {
2912                implicit.insert(spec.module_id.clone());
2913            }
2914        } else if implicit.remove(&spec.module_id) {
2915            reserved_nonces.remove(&spec.module_id);
2916        }
2917        if spec.reserved || protocol == ModuleProtocol::None {
2918            // `None` (no spawn nonce minted) is INSERTED, not skipped: a
2919            // reserved name whose module has never spawned has no legitimate
2920            // holder, and the entry's absence is what used to leave the name
2921            // open to the first claimant.
2922            reserved_nonces.insert(spec.module_id.clone(), spawn_nonce);
2923        }
2924        drop(implicit);
2925        drop(reserved_nonces);
2926        drop(current_nonces);
2927        self.refresh_program_binding_nonces(&spec.module_id);
2928        // A later unreserved declaration must not silently unreserve an id that
2929        // was retained after its reserved configuration was removed. The explicit
2930        // release ceremony is the only operation that retires that gate.
2931        self.removal_tombstones
2932            .lock()
2933            .unwrap_or_else(|poisoned| poisoned.into_inner())
2934            .remove(&spec.module_id);
2935    }
2936
2937    /// Whether a HELLO claiming `module_id` is authorized. An exact reserved id is
2938    /// authorized only by its expected nonce; otherwise a matching reserved prefix
2939    /// is authorized by the owner module's current spawn nonce. Non-reserved ids
2940    /// with no matching prefix are always authorized.
2941    pub fn reserved_hello_authorized(&self, module_id: &str, presented: Option<&str>) -> bool {
2942        self.reserved_hello_verification(module_id, presented)
2943            .is_ok()
2944    }
2945
2946    /// Whether HELLO passed a nonce check that was actually required by reserved
2947    /// module policy, or the refusal explaining why a required check failed.
2948    pub(crate) fn reserved_hello_verification(
2949        &self,
2950        module_id: &str,
2951        presented: Option<&str>,
2952    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
2953        if self.module_is_gated(module_id) {
2954            return Err(ReservedHelloRejection::Exact {
2955                module_id: module_id.into(),
2956            });
2957        }
2958        self.hello_verification(module_id, presented, false)
2959    }
2960
2961    pub(crate) fn channel_hello_verification(
2962        &self,
2963        module_id: &str,
2964    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
2965        if self
2966            .get(module_id)
2967            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
2968        {
2969            return Err(ReservedHelloRejection::Exact {
2970                module_id: module_id.into(),
2971            });
2972        }
2973        let mut verification = self.hello_verification(module_id, None, true)?;
2974        verification.nonce_verified = true;
2975        Ok(verification)
2976    }
2977
2978    pub(crate) fn prefix_claim_authorized(&self, owner: &str, module_id: &str) -> bool {
2979        self.prefix_claim_publication(owner, module_id).is_some()
2980    }
2981
2982    #[cfg(all(test, unix))]
2983    pub(crate) fn prefix_publication_locked_for_test(&self) -> bool {
2984        matches!(
2985            self.reserved_prefix_owners.try_lock(),
2986            Err(std::sync::TryLockError::WouldBlock)
2987        )
2988    }
2989
2990    // Keep this guard through registry/forwarding publication. Rescans replace
2991    // prefix owners without stopping their launches, so the spawn guard alone
2992    // cannot fence a reservation transfer.
2993    pub(crate) fn prefix_claim_publication(
2994        &self,
2995        owner: &str,
2996        module_id: &str,
2997    ) -> Option<std::sync::MutexGuard<'_, HashMap<String, String>>> {
2998        if subc_protocol::manifest::validate_module_id(module_id).is_err()
2999            || self.module_is_gated(module_id)
3000            || self
3001                .reserved_nonces
3002                .lock()
3003                .unwrap_or_else(|p| p.into_inner())
3004                .contains_key(module_id)
3005        {
3006            return None;
3007        }
3008        let owners = self
3009            .reserved_prefix_owners
3010            .lock()
3011            .unwrap_or_else(|p| p.into_inner());
3012        let authorized = owners
3013            .iter()
3014            .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
3015            .max_by_key(|(prefix, _)| prefix.len())
3016            .is_some_and(|(prefix, holder)| holder == owner && module_id.len() > prefix.len());
3017        authorized.then_some(owners)
3018    }
3019
3020    fn hello_verification(
3021        &self,
3022        module_id: &str,
3023        presented: Option<&str>,
3024        channel: bool,
3025    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
3026        let nonces = self
3027            .reserved_nonces
3028            .lock()
3029            .unwrap_or_else(|poisoned| poisoned.into_inner());
3030        if let Some(expected) = nonces.get(module_id) {
3031            // `None` = reserved with no legitimate holder: refuse every
3032            // presentation, because no process can hold a nonce that was never
3033            // minted. Only a real minted nonce admits, in constant time.
3034            let authorized = channel
3035                || match expected {
3036                    Some(expected) => presented.is_some_and(|p| {
3037                        !p.is_empty() && constant_time_eq(expected.as_bytes(), p.as_bytes())
3038                    }),
3039                    None => false,
3040                };
3041            if authorized {
3042                return Ok(ReservedHelloVerification {
3043                    nonce_verified: true,
3044                    prefix_owner: None,
3045                });
3046            }
3047            return Err(ReservedHelloRejection::Exact {
3048                module_id: module_id.to_string(),
3049            });
3050        }
3051        drop(nonces);
3052
3053        let matched_prefix = self
3054            .reserved_prefix_owners
3055            .lock()
3056            .unwrap_or_else(|poisoned| poisoned.into_inner())
3057            .iter()
3058            .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
3059            .max_by_key(|(prefix, _)| prefix.len())
3060            .map(|(prefix, owner)| (prefix.clone(), owner.clone()));
3061        let Some((prefix, owner_module_id)) = matched_prefix else {
3062            return Ok(ReservedHelloVerification::default());
3063        };
3064
3065        if module_id.len() == prefix.len()
3066            || (!channel
3067                && (self.module_is_gated(&owner_module_id) || self.protocol_none(&owner_module_id)))
3068        {
3069            return Err(ReservedHelloRejection::Prefix {
3070                prefix,
3071                owner_module_id,
3072            });
3073        }
3074
3075        let authorized = if channel {
3076            owner_module_id == module_id
3077        } else {
3078            presented.is_some_and(|presented| {
3079                self.spawn_nonces
3080                .lock()
3081                .unwrap_or_else(|poisoned| poisoned.into_inner())
3082                .get(&owner_module_id)
3083                .is_some_and(|expected| !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes()))
3084                // While the owner is being swapped, children started by
3085                // either of its two processes hold that process's nonce.
3086                || self.swap_nonce_matches(&owner_module_id, presented)
3087            })
3088        };
3089        if authorized {
3090            Ok(ReservedHelloVerification {
3091                nonce_verified: true,
3092                prefix_owner: (owner_module_id != module_id).then_some(owner_module_id),
3093            })
3094        } else {
3095            Err(ReservedHelloRejection::Prefix {
3096                prefix,
3097                owner_module_id,
3098            })
3099        }
3100    }
3101
3102    /// Whether a consumer connection proved it came from a daemon-spawned module.
3103    ///
3104    /// Absence of an expected spawn nonce is a hard failure: consumer_identity is
3105    /// accepted only for module ids the supervisor has spawned.
3106    pub fn spawned_consumer_authorized(&self, module_id: &str, presented: &str) -> bool {
3107        if self.module_is_gated(module_id) || self.protocol_none(module_id) {
3108            return false;
3109        }
3110        let nonces = self
3111            .spawn_nonces
3112            .lock()
3113            .unwrap_or_else(|poisoned| poisoned.into_inner());
3114        let current = nonces.get(module_id).is_some_and(|expected| {
3115            !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes())
3116        });
3117        drop(nonces);
3118        // Before cutover both launches may attest. Promotion removes the
3119        // incumbent's token even if its process still needs time to drain.
3120        current || self.swap_nonce_matches(module_id, presented)
3121    }
3122
3123    /// Whether `presented` is either nonce of an open swap for `module_id`.
3124    fn swap_nonce_matches(&self, module_id: &str, presented: &str) -> bool {
3125        if self.module_is_gated(module_id) || self.protocol_none(module_id) || presented.is_empty()
3126        {
3127            return false;
3128        }
3129        let swaps = self
3130            .swaps
3131            .lock()
3132            .unwrap_or_else(|poisoned| poisoned.into_inner());
3133        swaps.get(module_id).is_some_and(|swap| {
3134            constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes())
3135                || swap.incumbent_nonce.as_deref().is_some_and(|incumbent| {
3136                    constant_time_eq(incumbent.as_bytes(), presented.as_bytes())
3137                })
3138        })
3139    }
3140
3141    /// Open a swap for `module_id` with the candidate's freshly minted nonce.
3142    /// Called before the candidate process exists.
3143    pub(crate) fn open_swap(&self, module_id: &str, candidate_nonce: String) {
3144        let incumbent_nonce = self
3145            .spawn_nonces
3146            .lock()
3147            .unwrap_or_else(|poisoned| poisoned.into_inner())
3148            .get(module_id)
3149            .cloned();
3150        self.swaps
3151            .lock()
3152            .unwrap_or_else(|poisoned| poisoned.into_inner())
3153            .insert(
3154                module_id.to_string(),
3155                OpenSwap {
3156                    candidate_nonce,
3157                    incumbent_nonce,
3158                    candidate_admitted: false,
3159                },
3160            );
3161        self.refresh_program_binding_nonces(module_id);
3162    }
3163
3164    /// Close the swap for `module_id`, releasing whichever nonce is no longer
3165    /// the module's recorded one.
3166    pub(crate) fn close_swap(&self, module_id: &str) {
3167        self.swaps
3168            .lock()
3169            .unwrap_or_else(|poisoned| poisoned.into_inner())
3170            .remove(module_id);
3171        self.refresh_program_binding_nonces(module_id);
3172    }
3173
3174    /// Install the observer told about swap promotions, replacing any earlier
3175    /// one.
3176    pub(crate) fn set_swap_promotion_observer(
3177        &self,
3178        observer: std::sync::Weak<dyn SwapPromotionObserver>,
3179    ) {
3180        *self
3181            .promotion_observer
3182            .0
3183            .lock()
3184            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer);
3185    }
3186
3187    /// Tell the installed observer, if it is still alive, that a swap promoted
3188    /// `registration`.
3189    fn notify_swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
3190        let observer = self
3191            .promotion_observer
3192            .0
3193            .lock()
3194            .unwrap_or_else(|poisoned| poisoned.into_inner())
3195            .as_ref()
3196            .and_then(std::sync::Weak::upgrade);
3197        if let Some(observer) = observer {
3198            observer.swap_promoted(registration);
3199        }
3200    }
3201
3202    /// Whether a swap is open for `module_id`.
3203    pub(crate) fn swap_open(&self, module_id: &str) -> bool {
3204        self.swaps
3205            .lock()
3206            .unwrap_or_else(|poisoned| poisoned.into_inner())
3207            .contains_key(module_id)
3208    }
3209
3210    /// Make the candidate's nonce the module's recorded spawn nonce, as a plain
3211    /// respawn would, once cutover has made the candidate the module's process.
3212    /// Promotion revokes the incumbent's tokens; the swap record stays open
3213    /// only for lifecycle cleanup while the old process drains.
3214    fn promote_swap_nonce(&self, module_id: &str, reserved: bool) {
3215        let candidate_nonce = self
3216            .swaps
3217            .lock()
3218            .unwrap_or_else(|poisoned| poisoned.into_inner())
3219            .get_mut(module_id)
3220            .map(|swap| {
3221                swap.incumbent_nonce = None;
3222                swap.candidate_nonce.clone()
3223            });
3224        self.spawn_nonces
3225            .lock()
3226            .unwrap_or_else(|p| p.into_inner())
3227            .remove(module_id);
3228        {
3229            let mut nonces = self
3230                .reserved_nonces
3231                .lock()
3232                .unwrap_or_else(|p| p.into_inner());
3233            if reserved || nonces.contains_key(module_id) {
3234                nonces.insert(module_id.into(), None);
3235            }
3236        }
3237        if self.module_is_gated(module_id) {
3238            return;
3239        }
3240        let Some(nonce) = candidate_nonce.filter(|nonce| !nonce.is_empty()) else {
3241            return;
3242        };
3243        self.set_spawn_nonce(module_id, nonce.clone());
3244        if reserved {
3245            self.set_reserved_nonce(module_id, nonce);
3246        }
3247    }
3248
3249    /// The swap gate for a HELLO claiming `module_id`.
3250    ///
3251    /// This runs BEFORE the reserved-module gate. A reserved module's candidate
3252    /// presents the candidate nonce, which the reserved gate (holding the
3253    /// incumbent's nonce) would refuse as `reserved_module` before swap
3254    /// admission was ever reached. And it applies to unreserved ids too: for an
3255    /// unreserved id the only thing that ever stopped a second process claiming
3256    /// a live id was the `duplicate_module_id` refusal, which is exactly the
3257    /// refusal a swap lifts for its candidate.
3258    ///
3259    /// The incumbent's own nonce falls through to the ordinary gates, which
3260    /// treat it as they always have (a live incumbent is refused as a
3261    /// duplicate). Anything else while a swap is open is refused, including an
3262    /// absent nonce.
3263    pub(crate) fn swap_hello_admission(
3264        &self,
3265        module_id: &str,
3266        presented: Option<&str>,
3267    ) -> SwapHelloAdmission {
3268        if self.protocol_none(module_id) {
3269            return SwapHelloAdmission::ProtocolNone;
3270        }
3271        if self.module_is_gated(module_id) {
3272            return SwapHelloAdmission::ChannelRequired;
3273        }
3274        let swaps = self
3275            .swaps
3276            .lock()
3277            .unwrap_or_else(|poisoned| poisoned.into_inner());
3278        let Some(swap) = swaps.get(module_id) else {
3279            return SwapHelloAdmission::NotSwapping;
3280        };
3281        let Some(presented) = presented.filter(|nonce| !nonce.is_empty()) else {
3282            return SwapHelloAdmission::Refused;
3283        };
3284        if constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes()) {
3285            return if swap.candidate_admitted {
3286                SwapHelloAdmission::Refused
3287            } else {
3288                SwapHelloAdmission::Candidate
3289            };
3290        }
3291        if swap
3292            .incumbent_nonce
3293            .as_deref()
3294            .is_some_and(|incumbent| constant_time_eq(incumbent.as_bytes(), presented.as_bytes()))
3295        {
3296            return SwapHelloAdmission::NotSwapping;
3297        }
3298        SwapHelloAdmission::Refused
3299    }
3300
3301    fn protocol_none(&self, module: &str) -> bool {
3302        self.get(module)
3303            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
3304    }
3305
3306    /// Exclude swap closure through the short, synchronous candidate publication.
3307    pub(crate) fn with_swap_candidate_admission<T>(
3308        &self,
3309        module_id: &str,
3310        publish: impl FnOnce() -> (T, bool),
3311    ) -> Option<T> {
3312        let mut swaps = self.swaps.lock().unwrap_or_else(|p| p.into_inner());
3313        let swap = swaps
3314            .get_mut(module_id)
3315            .filter(|swap| !swap.candidate_admitted)?;
3316        let (result, admitted) = publish();
3317        swap.candidate_admitted = admitted;
3318        Some(result)
3319    }
3320
3321    /// Test/support lookup for the current launch nonce of a supervised spawn.
3322    pub fn spawn_launch_nonce_for(&self, module_id: &str) -> Option<String> {
3323        self.spawn_nonce(module_id)
3324    }
3325
3326    /// Test/support lookup for the HELLO-gating nonce of a reserved module.
3327    pub fn reserved_launch_nonce_for(&self, module_id: &str) -> Option<String> {
3328        if self.module_is_gated(module_id) {
3329            return None;
3330        }
3331        self.reserved_nonces
3332            .lock()
3333            .unwrap_or_else(|poisoned| poisoned.into_inner())
3334            .get(module_id)
3335            .cloned()
3336            .flatten()
3337    }
3338
3339    pub fn insert(&self, module: SupervisedModule) -> Option<SupervisedModule> {
3340        // Normally already marked before the process was spawned; marking here
3341        // too keeps `configured_ids` a superset of the roster for any caller
3342        // that inserts a module directly.
3343        self.mark_configured(module.module_id());
3344        let mut modules = self
3345            .modules
3346            .lock()
3347            .unwrap_or_else(|poisoned| poisoned.into_inner());
3348        modules.insert(module.module_id().to_string(), module)
3349    }
3350
3351    /// Record that the supervisor has taken on `module_id`. Called before the
3352    /// module's first process is spawned, so that by the time that process can
3353    /// register, [`Self::is_configured`] already answers true.
3354    fn mark_configured(&self, module_id: &str) {
3355        self.update_configured_ids(|ids| {
3356            ids.insert(module_id.to_string());
3357        });
3358    }
3359
3360    fn publish_configured_ids(&self, ids: Option<&HashSet<String>>) {
3361        let owner = self
3362            .gate_runtime
3363            .lock()
3364            .unwrap_or_else(|p| p.into_inner())
3365            .clone()
3366            .and_then(|owner| owner.upgrade());
3367        if let Some(owner) = owner {
3368            owner.observe_supervisor_configured_ids(ids, Arc::downgrade(&self.configured_ids));
3369        }
3370    }
3371
3372    fn update_configured_ids(&self, update: impl FnOnce(&mut HashSet<String>)) {
3373        match self.configured_ids.lock() {
3374            Ok(mut ids) => {
3375                update(&mut ids);
3376                // Publish while this roster mutation is serialized, so an
3377                // older snapshot can never overwrite a later configured id.
3378                self.publish_configured_ids(Some(&ids));
3379            }
3380            Err(poisoned) => {
3381                update(&mut poisoned.into_inner());
3382                self.publish_configured_ids(None);
3383            }
3384        }
3385    }
3386
3387    /// Undo [`Self::mark_configured`] for a module whose first spawn failed
3388    /// before it was ever put on the roster. A module already on the roster
3389    /// keeps its mark: only [`Self::retire`] takes a rostered module off.
3390    fn unmark_configured_unless_rostered(&self, module_id: &str) {
3391        let modules = self
3392            .modules
3393            .lock()
3394            .unwrap_or_else(|poisoned| poisoned.into_inner());
3395        if !modules.contains_key(module_id) {
3396            self.update_configured_ids(|ids| {
3397                ids.remove(module_id);
3398            });
3399        }
3400    }
3401
3402    /// Whether `module_id` is a module this daemon supervises: on the roster,
3403    /// or about to be (its process is being spawned right now).
3404    ///
3405    /// This, not `get(..).is_some()`, is what "the owner is configured" means
3406    /// for scopes: a supervised module's process can register and sync before
3407    /// [`Self::get`] can return it, and in that window it is still a module
3408    /// that will sync, not one that never will.
3409    pub(crate) fn is_configured(&self, module_id: &str) -> bool {
3410        self.configured_ids
3411            .lock()
3412            .unwrap_or_else(|poisoned| poisoned.into_inner())
3413            .contains(module_id)
3414    }
3415
3416    pub fn get(&self, module_id: &str) -> Option<SupervisedModule> {
3417        let modules = self
3418            .modules
3419            .lock()
3420            .unwrap_or_else(|poisoned| poisoned.into_inner());
3421        modules.get(module_id).cloned()
3422    }
3423
3424    pub(crate) fn record_late_health_answer(
3425        &self,
3426        module_id: &str,
3427        latency_ms: u64,
3428    ) -> Result<bool, SuperviseError> {
3429        let Some(module) = self.get(module_id) else {
3430            return Ok(false);
3431        };
3432        self.host_health.record_late_module(module_id);
3433        update_snapshot(&module.inner.snapshot, Some(module_id), |state| {
3434            state.health.late_answer_count = state.health.late_answer_count.saturating_add(1);
3435            state.health.last_late_answer_latency_ms = Some(latency_ms);
3436            // A late answer is an answer: the module served the probe, just past
3437            // the deadline. Leaving the miss streak in place while logging
3438            // "proves the module is alive" is how a CPU-starved module that
3439            // answers every probe a few seconds late still marches to the
3440            // threshold and gets killed — the exact kill class `NoAnswer` is
3441            // excluded from `is_proof_of_death` to prevent. Slow-but-answering
3442            // is degradation, and degradation reports; it does not restart.
3443            state.health.consecutive_failures = 0;
3444        })?;
3445        Ok(true)
3446    }
3447
3448    pub(crate) fn spawn_host_health_monitor(&self) -> JoinHandle<()> {
3449        self.host_health.spawn_monitor()
3450    }
3451
3452    /// Arm the one-shot marker for the module process that this caller
3453    /// deliberately initiated severance against. Generic connection teardown
3454    /// must not call this:
3455    /// a surviving process would otherwise retain an exemption for a later
3456    /// genuine crash.
3457    pub fn record_deliberate_severance(&self, module_id: &str) -> Result<bool, SuperviseError> {
3458        let Some(module) = self.get(module_id) else {
3459            return Ok(false);
3460        };
3461        let snapshot = lock_snapshot(&module.inner.snapshot)?;
3462        let Some((pid, start_time)) = snapshot.pid.zip(snapshot.process_start_time) else {
3463            return Ok(false);
3464        };
3465        drop(snapshot);
3466        module.record_deliberate_severance(ProcessIdentity { pid, start_time })
3467    }
3468
3469    pub fn list(&self) -> Vec<SupervisedModule> {
3470        let modules = self
3471            .modules
3472            .lock()
3473            .unwrap_or_else(|poisoned| poisoned.into_inner());
3474        let mut modules = modules.values().cloned().collect::<Vec<_>>();
3475        modules.sort_by(|left, right| left.module_id().cmp(right.module_id()));
3476        modules
3477    }
3478
3479    pub(crate) fn retire(&self, module_id: &str) -> Option<SupervisedModule> {
3480        self.activity_images
3481            .lock()
3482            .unwrap_or_else(|p| p.into_inner())
3483            .remove(module_id);
3484        self.spawn_nonces
3485            .lock()
3486            .unwrap_or_else(|poisoned| poisoned.into_inner())
3487            .remove(module_id);
3488        self.close_swap(module_id);
3489        let mut reserved_nonces = self
3490            .reserved_nonces
3491            .lock()
3492            .unwrap_or_else(|poisoned| poisoned.into_inner());
3493        if reserved_nonces.contains_key(module_id) {
3494            // The old nonce must die with the removed process, but the exact-id
3495            // gate remains until an operator explicitly releases it.
3496            reserved_nonces.insert(module_id.to_string(), None);
3497        }
3498        drop(reserved_nonces);
3499        self.reserved_prefix_owners
3500            .lock()
3501            .unwrap_or_else(|poisoned| poisoned.into_inner())
3502            .retain(|_, owner| owner != module_id);
3503        let removed = self
3504            .modules
3505            .lock()
3506            .unwrap_or_else(|poisoned| poisoned.into_inner())
3507            .remove(module_id);
3508        self.update_configured_ids(|ids| {
3509            ids.remove(module_id);
3510        });
3511        self.remove_program_binding_records(module_id);
3512        removed
3513    }
3514
3515    /// Remember a module removed by a non-preview rescan so route.open can
3516    /// distinguish that intentional removal from an unknown id.
3517    pub(crate) fn record_rescan_removal(&self, module_id: &str) {
3518        self.removal_tombstones
3519            .lock()
3520            .unwrap_or_else(|poisoned| poisoned.into_inner())
3521            .insert(module_id.to_string(), unix_ms_now());
3522    }
3523
3524    /// Return how long ago a rescan removed this module in milliseconds.
3525    pub(crate) fn removal_tombstone_age_ms(&self, module_id: &str) -> Option<u64> {
3526        self.removal_tombstones
3527            .lock()
3528            .unwrap_or_else(|poisoned| poisoned.into_inner())
3529            .get(module_id)
3530            .copied()
3531            .map(|removed_at_ms| unix_ms_now().saturating_sub(removed_at_ms))
3532    }
3533
3534    /// Retire a reserved-id gate only after its module has left supervision.
3535    ///
3536    /// A retained gate has no live nonce (`None`), so releasing any other entry
3537    /// would weaken a currently configured or otherwise active reservation.
3538    pub(crate) fn release_retained_reserved_gate(&self, module_id: &str) -> bool {
3539        if self.get(module_id).is_some() {
3540            return false;
3541        }
3542        let mut reserved_nonces = self
3543            .reserved_nonces
3544            .lock()
3545            .unwrap_or_else(|poisoned| poisoned.into_inner());
3546        if !matches!(reserved_nonces.get(module_id), Some(None)) {
3547            return false;
3548        }
3549        reserved_nonces.remove(module_id);
3550        self.implicit_protocol_none
3551            .lock()
3552            .unwrap_or_else(|p| p.into_inner())
3553            .remove(module_id);
3554        true
3555    }
3556
3557    pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
3558        Arc::clone(&self.operation_lock)
3559    }
3560}
3561
3562/// Process supervisor for subc-owned singleton modules.
3563#[derive(Debug, Clone)]
3564pub struct Supervisor {
3565    registry: Arc<Registry>,
3566    config_delivery: Option<config_delivery::ConfigDelivery>,
3567    restart_policy: RestartPolicy,
3568    drain_timeout: Duration,
3569    connection_file_path: Option<PathBuf>,
3570    capture_logs_dir: Option<PathBuf>,
3571    forwarding: Option<Arc<ForwardingTable>>,
3572    process_liveness: Arc<SupervisorProcessLiveness>,
3573    supervisor_handle: Option<SupervisorHandle>,
3574    health: HealthConfig,
3575    host_health: HostHealth,
3576    daemon_start_clock: crate::clock::StartClock,
3577    terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
3578    spawn_events: SpawnEventFeed,
3579    provenance_probe: ExecutableIdentityProbe,
3580    /// Every process spawned through this supervisor (and its clones) and not
3581    /// yet reaped, so daemon shutdown can end them.
3582    child_roster: ChildRoster,
3583    #[cfg(target_os = "linux")]
3584    cgroup_placement: Option<subc_cgroup::Placement>,
3585    #[cfg(test)]
3586    test_after_first_spawn: AfterFirstSpawnHook,
3587}
3588
3589/// A roster entry whose monitor and first process have not started yet.
3590/// Keeping the command receiver here lets discovery serve status immediately
3591/// while start/stop requests wait until bootstrap has published the connection file.
3592pub(crate) struct RegisteredConfiguredModule {
3593    spec: ModuleSpec,
3594    runtime: SupervisorRuntimeConfig,
3595    module: SupervisedModule,
3596    commands: mpsc::Receiver<SupervisorCommand>,
3597}
3598
3599/// Test-only hook run on the path that takes on a new module, right after its
3600/// first `spawn_child` returns (the process exists and could already be
3601/// registering) and before that process is handed to the module's supervise
3602/// loop and put on the roster. Lets a test observe what a fast child would see
3603/// in that window without racing a real one.
3604#[cfg(test)]
3605#[derive(Clone, Default)]
3606struct AfterFirstSpawnHook(Option<AfterFirstSpawnFn>);
3607
3608#[cfg(test)]
3609type AfterFirstSpawnFn = Arc<dyn Fn(&str) + Send + Sync>;
3610
3611#[cfg(test)]
3612impl fmt::Debug for AfterFirstSpawnHook {
3613    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3614        f.write_str("AfterFirstSpawnHook")
3615    }
3616}
3617
3618#[cfg(test)]
3619impl AfterFirstSpawnHook {
3620    fn run(&self, module_id: &str) {
3621        if let Some(hook) = &self.0 {
3622            hook(module_id);
3623        }
3624    }
3625}
3626
3627impl Supervisor {
3628    #[cfg(all(test, target_os = "linux"))]
3629    pub(crate) fn set_admission_hook_for_test(
3630        &self,
3631        hook: impl Fn(&str, &'static str, Option<u32>) -> bool + Send + Sync + 'static,
3632    ) {
3633        self.child_roster.set_admission_hook_for_test(hook);
3634    }
3635
3636    #[cfg(test)]
3637    pub(crate) fn new_for_test(registry: Arc<Registry>, policy: RestartPolicy) -> Self {
3638        let supervisor = Self::new(registry, policy);
3639        #[cfg(target_os = "macos")]
3640        let supervisor = supervisor.with_privacy_trampoline(test_privacy_trampoline());
3641        supervisor
3642    }
3643    /// Verify the trampoline once when configured. Missing private OS support
3644    /// refuses every macOS launch by name but does not stop the daemon's control
3645    /// server. Embedders must explicitly provide a binary with the subc-os hidden
3646    /// entry point; the library must not exec an arbitrary hosting program.
3647    pub fn with_privacy_trampoline(self, path: impl Into<PathBuf>) -> Self {
3648        let path = path.into();
3649        #[cfg(target_os = "macos")]
3650        {
3651            let result = probe_privacy_trampoline(&path).map(|()| path);
3652            if let Err(cause) = &result {
3653                error!(%cause, "macOS privacy identity unavailable; supervised launches will refuse");
3654            }
3655            self.child_roster.set_privacy_trampoline(result);
3656        }
3657        #[cfg(not(target_os = "macos"))]
3658        let _ = path;
3659        self
3660    }
3661    /// The flag [`Self::begin_daemon_shutdown`] sets, for the control handler's
3662    /// capability-requirement log to read.
3663    pub(crate) fn daemon_shutdown_flag(&self) -> crate::child_roster::DaemonShutdownFlag {
3664        self.child_roster.shutdown_flag()
3665    }
3666
3667    /// The first step of an announced daemon shutdown, before the notice and
3668    /// before any connection is closed.
3669    ///
3670    /// Sets the daemon-shutdown flag first: from here on no module is
3671    /// respawned (crash restart, operator restart, or swap), and every child
3672    /// exit is recorded as `daemon_shutdown` rather than as a crash, whether
3673    /// the module exits on the EOF this shutdown gives it or is signalled by a
3674    /// service manager that kills the whole cgroup. Queues the journal marker
3675    /// without waiting for disk I/O.
3676    #[cfg(unix)]
3677    pub(crate) fn begin_daemon_shutdown(&self) {
3678        self.child_roster.close();
3679        if let Some(journal) = &self.terminal_journal {
3680            journal.stamp_shutdown();
3681        }
3682    }
3683
3684    /// Announce a cut while established connections can still carry replies.
3685    /// These budgets bound the attempt to deliver notices and the wait for
3686    /// routes to drain; neither guarantees delivery or child completion, and
3687    /// they are local policy, not an estimate of launchd's unknown kill ceiling.
3688    #[cfg(unix)]
3689    pub(crate) async fn drain_for_daemon_shutdown(&self) -> Result<(), SuperviseError> {
3690        const NOTICE_BUDGET: Duration = Duration::from_millis(500);
3691        const DRAIN_BUDGET: Duration = Duration::from_secs(2);
3692        let Some(forwarding) = &self.forwarding else {
3693            return Ok(());
3694        };
3695        let notice_started = Instant::now();
3696        let modules = forwarding
3697            .begin_daemon_drain()
3698            .map_err(SuperviseError::Forwarding)?;
3699        let deadline_ms =
3700            unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
3701        let shutdown_reason = self
3702            .supervisor_handle
3703            .as_ref()
3704            .map(SupervisorHandle::take_daemon_shutdown_reason)
3705            .unwrap_or(RouteCloseReason::Disable);
3706        let mut modules_told = 0;
3707        let mut notices = tokio::task::JoinSet::new();
3708        let mut drains = Vec::new();
3709        for connection in forwarding
3710            .module_connections()
3711            .map_err(SuperviseError::Forwarding)?
3712        {
3713            let target = ModuleDrainTarget {
3714                endpoint: connection.endpoint,
3715                sink: connection.sink,
3716                negotiated_ver: connection.negotiated_ver,
3717                abandoned_bindings: Vec::new(),
3718                excluded_subscriptions: 0,
3719            };
3720            notices.spawn(async move {
3721                (
3722                    true,
3723                    send_module_draining(
3724                        &connection.module_id,
3725                        shutdown_reason,
3726                        deadline_ms,
3727                        &target,
3728                        true,
3729                    )
3730                    .await,
3731                )
3732            });
3733        }
3734        for (module_id, endpoint) in modules {
3735            let Some(target) = forwarding
3736                .begin_endpoint_drain(endpoint, RouteCloseReason::Restart)
3737                .map_err(SuperviseError::Forwarding)?
3738            else {
3739                continue;
3740            };
3741            let routes = forwarding
3742                .endpoint_routes(target.endpoint)
3743                .map_err(SuperviseError::Forwarding)?;
3744            // Only an announced restart promises that modules are coming back.
3745            // Client route notices retain their existing reconnect semantics.
3746            let mut recipients = Vec::new();
3747            let mut clients: Vec<(crate::forwarding::GoodbyeTarget, Vec<u16>)> = Vec::new();
3748            for route in routes {
3749                let client = route.goodbye_target;
3750                if let Some((_, channels)) = clients
3751                    .iter_mut()
3752                    .find(|(existing, _)| existing.connection_id == client.connection_id)
3753                {
3754                    channels.push(client.channel);
3755                } else {
3756                    let channel = client.channel;
3757                    clients.push((client, vec![channel]));
3758                }
3759            }
3760            for (client, mut channels) in clients {
3761                channels.sort_unstable();
3762                channels.dedup();
3763                let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
3764                    module_id: module_id.clone(),
3765                    channels,
3766                    reason: RouteCloseReason::Restart,
3767                })
3768                .expect("route closing serializes");
3769                recipients.push((client.sink, client.negotiated_ver, closing));
3770            }
3771            for (sink, version, body) in recipients {
3772                notices.spawn(async move {
3773                    let frame = Frame::build_with_version(
3774                        version,
3775                        FrameType::Push,
3776                        control_flags(),
3777                        0,
3778                        0,
3779                        0,
3780                        body,
3781                    )
3782                    .expect("bounded lifecycle notice frame builds");
3783                    (false, sink.send_flushed(frame).await.is_ok())
3784                });
3785            }
3786            let gauges = declared_busy_gauges(&self.registry, &module_id)?;
3787            drains.push((module_id, target.endpoint, gauges));
3788        }
3789        // A quiet forwarding table is not proof that queued notices reached the
3790        // socket. Wait for writer flush acknowledgements before testing quiescence.
3791        let notice_deadline = Instant::now() + NOTICE_BUDGET;
3792        while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
3793            match result {
3794                Ok((true, true)) => modules_told += 1,
3795                Ok((false, true)) => {}
3796                result => warn!(?result, "daemon shutdown notice delivery failed"),
3797            }
3798        }
3799        notices.abort_all();
3800        info!(
3801            ?shutdown_reason,
3802            modules_told, "daemon shutdown module notices delivered"
3803        );
3804        let notice_elapsed = notice_started.elapsed();
3805        let drain_started = Instant::now();
3806        let deadline = drain_started + DRAIN_BUDGET;
3807        let mut waits = tokio::task::JoinSet::new();
3808        for (module_id, endpoint, gauges) in drains {
3809            let forwarding = Arc::clone(forwarding);
3810            let mut runtime = self.runtime_config();
3811            runtime.health.cadence = Duration::from_millis(100);
3812            waits.spawn(async move {
3813                let wait_result = wait_for_forwarding_quiescence(
3814                    &forwarding,
3815                    &module_id,
3816                    &runtime,
3817                    endpoint,
3818                    deadline,
3819                    &gauges,
3820                    DrainScope::Endpoint(endpoint),
3821                    &mut DrainGaugeTrace::new(&gauges),
3822                )
3823                .await;
3824                // Store the measurement before the task returns: quiescence
3825                // may be reached just as the deadline stops the join loop from
3826                // collecting results. Unfinished or failed waits report false.
3827                forwarding
3828                    .record_daemon_drain_result(
3829                        endpoint,
3830                        drained_after_quiescence_wait(&wait_result),
3831                    )
3832                    .map_err(SuperviseError::Forwarding)?;
3833                wait_result
3834            });
3835        }
3836        while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
3837            if !matches!(result, Ok(Ok(true))) {
3838                warn!(?result, "daemon shutdown drain did not reach quiescence");
3839            }
3840        }
3841        // Measure only the forwarding drain, not child teardown or the caller's
3842        // signal delivery and process-reaping delays.
3843        info!(
3844            notice_elapsed_ms = notice_elapsed.as_millis() as u64,
3845            drain_elapsed_ms = drain_started.elapsed().as_millis() as u64,
3846            "daemon shutdown forwarding drain complete"
3847        );
3848        Ok(())
3849    }
3850
3851    /// The last step of a graceful daemon shutdown, after the notice and the
3852    /// drain: send every registered module a module GOODBYE, the same planned
3853    /// stop signal `ck module stop` gives, then close every connection so each
3854    /// subc module sees EOF and starts its own teardown, then end every
3855    /// supervised child that has not exited
3856    /// by its own deadline (its drain budget, capped). Modules lead their own
3857    /// process groups, so a
3858    /// service manager's group kill no longer reaches them; without this a
3859    /// child that does not stop on EOF (every `protocol: "none"` child, which
3860    /// has no connection) would outlive the daemon. Every wait is bounded (see
3861    /// `child_roster`), and `escalate` resolving (a second SIGTERM) cuts them.
3862    #[cfg(unix)]
3863    pub(crate) async fn end_children_for_daemon_shutdown(
3864        &self,
3865        already_escalated: bool,
3866        escalate: impl std::future::Future<Output = ()>,
3867    ) {
3868        tokio::pin!(escalate);
3869        let mut escalated = already_escalated;
3870        if let Some(forwarding) = &self.forwarding {
3871            let reason = CloseReason::new(
3872                "daemon_shutdown",
3873                "the daemon is exiting after its shutdown notice and drain",
3874            );
3875            if escalated {
3876                // The operator asked to stop waiting: queue the GOODBYEs but
3877                // do not wait for them to be written.
3878                send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, false).await;
3879            } else {
3880                tokio::select! {
3881                    biased;
3882                    _ = escalate.as_mut() => {
3883                        info!("second SIGTERM: abandoning module GOODBYE delivery");
3884                        escalated = true;
3885                    }
3886                    _ = send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, true) => {}
3887                }
3888            }
3889            let closed = forwarding.close_all_connections(&reason);
3890            debug!(closed, "closed established connections for daemon shutdown");
3891        }
3892        // If the second SIGTERM arrived during GOODBYE delivery, `escalate` has
3893        // already completed and must not be polled again; the child shutdown
3894        // wait is told it is escalated and gets a future that never fires.
3895        let escalated_here = escalated && !already_escalated;
3896        let remaining_escalate = async move {
3897            if escalated_here {
3898                std::future::pending::<()>().await;
3899            } else {
3900                escalate.await;
3901            }
3902        };
3903        crate::child_roster::end_children_for_daemon_shutdown(
3904            &self.child_roster,
3905            escalated,
3906            remaining_escalate,
3907        )
3908        .await;
3909        if let Some(journal) = &self.terminal_journal {
3910            journal.flush_shutdown().await;
3911        }
3912    }
3913
3914    pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
3915        Self {
3916            registry,
3917            config_delivery: None,
3918            restart_policy,
3919            drain_timeout: DEFAULT_DRAIN_TIMEOUT,
3920            connection_file_path: None,
3921            capture_logs_dir: None,
3922            forwarding: None,
3923            process_liveness: Arc::new(SupervisorProcessLiveness::default()),
3924            supervisor_handle: None,
3925            health: HealthConfig::default(),
3926            host_health: HostHealth::default(),
3927            daemon_start_clock: crate::clock::StartClock::capture(),
3928            terminal_journal: None,
3929            spawn_events: SpawnEventFeed::default(),
3930            provenance_probe: ExecutableIdentityProbe::default(),
3931            child_roster: ChildRoster::default(),
3932            #[cfg(target_os = "linux")]
3933            cgroup_placement: None,
3934            #[cfg(test)]
3935            test_after_first_spawn: AfterFirstSpawnHook::default(),
3936        }
3937    }
3938
3939    pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
3940        self.drain_timeout = drain_timeout;
3941        self
3942    }
3943
3944    /// The drain budget a module gets when its config entry sets none.
3945    pub(crate) fn default_drain_timeout(&self) -> Duration {
3946        self.drain_timeout
3947    }
3948
3949    pub fn with_process_liveness(
3950        mut self,
3951        process_liveness: Arc<SupervisorProcessLiveness>,
3952    ) -> Self {
3953        self.process_liveness = process_liveness;
3954        self
3955    }
3956
3957    /// Connect configuration delivery to observed process lifecycle events.
3958    pub fn with_config_runtime(
3959        mut self,
3960        owner: Arc<crate::config_gate::runtime::RuntimeOwner>,
3961    ) -> Self {
3962        if let Some(handle) = &self.supervisor_handle {
3963            handle.install_binding_retirement(&owner);
3964        }
3965        self.config_delivery = Some(config_delivery::ConfigDelivery(owner));
3966        self
3967    }
3968
3969    pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
3970        self.connection_file_path = Some(connection_file_path.into());
3971        self
3972    }
3973
3974    /// Enables daemon-owned capture files for supervised stdout and stderr.
3975    pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
3976        self.capture_logs_dir = Some(logs_dir.into());
3977        self
3978    }
3979
3980    /// Names this daemon lifetime in spawn events, independently of whether a
3981    /// terminal journal is configured.
3982    pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
3983        // A millisecond start stamp can repeat after clock rollback or a rapid
3984        // restart. Use the connection file's random daemon_id instead: it already
3985        // identifies this daemon lifetime independently of the wall clock.
3986        self.spawn_events.configure_incarnation(daemon_incarnation);
3987        self
3988    }
3989
3990    /// Enables best-effort history shared by every supervised module. Without
3991    /// it, terminal history is kept only in each module's in-memory ring.
3992    pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
3993        let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
3994        this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
3995            path,
3996            daemon_incarnation,
3997        )));
3998        this
3999    }
4000
4001    pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
4002        self.child_roster.counters = forwarding.counters();
4003        self.forwarding = Some(forwarding);
4004        self
4005    }
4006
4007    pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
4008        if let Some(delivery) = &self.config_delivery {
4009            supervisor_handle.install_binding_retirement(&delivery.0);
4010        }
4011        self.host_health = supervisor_handle.host_health.clone();
4012        self.spawn_events = supervisor_handle.spawn_events.clone();
4013        self.supervisor_handle = Some(supervisor_handle);
4014        self
4015    }
4016
4017    pub fn with_health_config(mut self, health: HealthConfig) -> Self {
4018        self.health = health;
4019        self
4020    }
4021
4022    /// Keeps a record of every live child at `path`, rewritten on each spawn and
4023    /// reap, for the orphan sweep a later daemon runs at boot. Without it no
4024    /// record is kept.
4025    pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
4026        self.child_roster.record_to(path.into());
4027        self
4028    }
4029
4030    #[cfg(target_os = "linux")]
4031    pub fn with_cgroup_placement(
4032        mut self,
4033        cgroup_placement: Option<subc_cgroup::Placement>,
4034    ) -> Self {
4035        self.child_roster
4036            .set_cgroup_placement(cgroup_placement.clone());
4037        self.cgroup_placement = cgroup_placement;
4038        self
4039    }
4040
4041    /// Spawn `spec.program` and start monitoring it.
4042    ///
4043    /// The child is expected to parse `--subc <connection-file-path>`, read the
4044    /// TCP+key connection file, authenticate to the already-running listener, and
4045    /// register with channel-0 `HELLO` using `spec.module_id` as its manifest id.
4046    ///
4047    /// This synchronous embedder API blocks on launch admission and store I/O.
4048    /// Do not call it on an async runtime thread; use [`Self::spawn_async`].
4049    pub fn spawn(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
4050        validate_spec(&spec)?;
4051        self.establish_identity(&spec);
4052
4053        let runtime = self.runtime_config();
4054        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
4055        let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4056        let registration_watch = watch_registration(&self.registry, &spec);
4057        let spawned = spawn_child(
4058            &spec,
4059            runtime.connection_file_path.as_deref(),
4060            self.supervisor_handle.as_ref(),
4061            &runtime.stderr_ring,
4062            runtime.capture_logs_dir.as_deref(),
4063            &runtime.child_roster,
4064            runtime.spawn_delivery(),
4065            #[cfg(target_os = "linux")]
4066            runtime.cgroup_placement.as_ref(),
4067            runtime.register_timeout,
4068        );
4069        #[cfg(test)]
4070        self.test_after_first_spawn.run(&spec.module_id);
4071        let mut child = match spawned {
4072            Ok(child) => child,
4073            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4074                defer_config_spawn(
4075                    &spec,
4076                    &runtime,
4077                    &snapshot,
4078                    RespawnKind::Spawn,
4079                    &runtime.failure_context(runtime.recovery_is_daemon),
4080                )?;
4081                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4082            }
4083            Err(SuperviseError::ConfigHeld { .. }) => {
4084                hold_config_spawn(
4085                    &spec,
4086                    &runtime,
4087                    &snapshot,
4088                    &runtime.failure_context(runtime.recovery_is_daemon),
4089                )?;
4090                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4091            }
4092            Err(err) => {
4093                // Unlike the configured paths, a failed `spawn` leaves nothing
4094                // on the roster, so the module must not stay marked configured.
4095                self.abandon_unrostered(&spec.module_id);
4096                return Err(err);
4097            }
4098        };
4099        arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
4100        self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
4101        if let Some(spawn) = activity_spawn {
4102            spawn.complete(&snapshot);
4103        }
4104
4105        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
4106    }
4107
4108    /// Spawn without running configuration integrity or keychain checks on the
4109    /// runtime thread. Cancellation during preparation cannot create a child.
4110    pub async fn spawn_async(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
4111        validate_spec(&spec)?;
4112        self.establish_identity(&spec);
4113        let mut identity = AsyncInitialIdentity {
4114            supervisor: self,
4115            module: spec.module_id.clone(),
4116            committed: false,
4117        };
4118        let runtime = self.runtime_config();
4119        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
4120        let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4121        let registration_watch = watch_registration(&self.registry, &spec);
4122        let spawned = spawn_child_async(&spec, &runtime).await;
4123        #[cfg(test)]
4124        self.test_after_first_spawn.run(&spec.module_id);
4125        let mut child = match spawned {
4126            Ok(child) => child,
4127            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4128                defer_config_spawn(
4129                    &spec,
4130                    &runtime,
4131                    &snapshot,
4132                    RespawnKind::Spawn,
4133                    &runtime.failure_context(runtime.recovery_is_daemon),
4134                )?;
4135                identity.committed = true;
4136                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4137            }
4138            Err(SuperviseError::ConfigHeld { .. }) => {
4139                hold_config_spawn(
4140                    &spec,
4141                    &runtime,
4142                    &snapshot,
4143                    &runtime.failure_context(runtime.recovery_is_daemon),
4144                )?;
4145                identity.committed = true;
4146                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4147            }
4148            Err(err) => {
4149                self.abandon_unrostered(&spec.module_id);
4150                return Err(err);
4151            }
4152        };
4153        arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
4154        self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
4155        if let Some(spawn) = activity_spawn {
4156            spawn.complete(&snapshot);
4157        }
4158        identity.committed = true;
4159        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
4160    }
4161
4162    /// Make `spec`'s module count as configured, with its identity gates
4163    /// (reserved id, reserved prefixes) in place, BEFORE any process of it
4164    /// exists.
4165    ///
4166    /// Every path that takes on a new module calls this before `spawn_child`.
4167    /// The order is the point: the child can connect, register, sync its
4168    /// scopes and ask about them as soon as it is spawned, and the module is
4169    /// only put on the roster after `spawn_child` returns. Were the mark set
4170    /// with the roster entry, a fast child would see its own owner reported
4171    /// as not configured, and a scoped `route.open` in that window would be
4172    /// refused as terminal `scope_not_live` ("will never sync") instead of
4173    /// retryable `scope_not_synced`.
4174    fn establish_identity(&self, spec: &ModuleSpec) {
4175        if let Some(supervisor_handle) = &self.supervisor_handle {
4176            supervisor_handle.apply_identity_configuration(spec);
4177            supervisor_handle.mark_configured(&spec.module_id);
4178        }
4179    }
4180
4181    /// Take back [`Self::establish_identity`]'s configured mark when the
4182    /// module will not be put on the roster after all.
4183    fn abandon_unrostered(&self, module_id: &str) {
4184        if let Some(supervisor_handle) = &self.supervisor_handle {
4185            supervisor_handle.unmark_configured_unless_rostered(module_id);
4186        }
4187    }
4188
4189    /// Record a freshly spawned first process as running. On failure the
4190    /// module never reaches the roster, so its configured mark is taken back.
4191    fn mark_first_process_running(
4192        &self,
4193        spec: &ModuleSpec,
4194        runtime: &SupervisorRuntimeConfig,
4195        snapshot: &SharedSnapshot,
4196        child: &mut SupervisedChild,
4197    ) -> Result<(), SuperviseError> {
4198        if let Err(err) = set_running(snapshot, child, &spec.module_id, &runtime.spawn_events) {
4199            containment::terminate_blocking(&runtime.child_roster.containment);
4200            self.abandon_unrostered(&spec.module_id);
4201            return Err(err);
4202        }
4203        self.process_liveness
4204            .track(spec.module_id.clone(), Arc::clone(snapshot));
4205        Ok(())
4206    }
4207
4208    /// Start supervising a module declared in daemon configuration.
4209    ///
4210    /// Unlike [`Self::spawn`], this records disabled modules and immediate spawn
4211    /// failures in the supervisor handle so operator-facing `supervisor.list`
4212    /// reflects every configured module while daemon startup continues.
4213    pub fn supervise_configured(
4214        &self,
4215        spec: ModuleSpec,
4216        enabled: bool,
4217    ) -> Result<SupervisedModule, SuperviseError> {
4218        self.supervise_configured_requested(
4219            spec,
4220            enabled,
4221            self.health.clone(),
4222            None,
4223            self.restart_policy,
4224            DEFAULT_REGISTER_TIMEOUT,
4225            None,
4226        )
4227    }
4228
4229    /// Supervise a configured module with its own health, drain, and crash
4230    /// budget. The restart policy is per-module because the config file is:
4231    /// `modules.<id>.restart` resolves to a full policy at parse time, and a
4232    /// module that is expensive to restart should not be forced onto the same
4233    /// budget as one that is cheap.
4234    pub fn supervise_configured_with_health(
4235        &self,
4236        spec: ModuleSpec,
4237        enabled: bool,
4238        health: HealthConfig,
4239        drain_timeout_ms: Option<u64>,
4240        restart_policy: RestartPolicy,
4241    ) -> Result<SupervisedModule, SuperviseError> {
4242        self.supervise_configured_requested(
4243            spec,
4244            enabled,
4245            health,
4246            drain_timeout_ms,
4247            restart_policy,
4248            DEFAULT_REGISTER_TIMEOUT,
4249            None,
4250        )
4251    }
4252
4253    #[allow(clippy::too_many_arguments)]
4254    pub(crate) fn supervise_configured_requested(
4255        &self,
4256        spec: ModuleSpec,
4257        enabled: bool,
4258        health: HealthConfig,
4259        drain_timeout_ms: Option<u64>,
4260        restart_policy: RestartPolicy,
4261        register_timeout: Duration,
4262        requester: Option<Principal>,
4263    ) -> Result<SupervisedModule, SuperviseError> {
4264        let registered = self.register_configured_with_health(
4265            spec,
4266            enabled,
4267            health,
4268            drain_timeout_ms,
4269            restart_policy,
4270            register_timeout,
4271        )?;
4272        let daemon_initiated = requester.is_none();
4273        self.start_registered_configured(registered, requester, daemon_initiated)
4274    }
4275
4276    #[allow(clippy::too_many_arguments)]
4277    pub(crate) async fn supervise_configured_requested_async(
4278        &self,
4279        spec: ModuleSpec,
4280        enabled: bool,
4281        health: HealthConfig,
4282        drain_timeout_ms: Option<u64>,
4283        restart_policy: RestartPolicy,
4284        register_timeout: Duration,
4285        requester: Option<Principal>,
4286    ) -> Result<SupervisedModule, SuperviseError> {
4287        let registered = self.register_configured_with_health(
4288            spec,
4289            enabled,
4290            health,
4291            drain_timeout_ms,
4292            restart_policy,
4293            register_timeout,
4294        )?;
4295        let daemon_initiated = requester.is_none();
4296        self.start_registered_configured_async(registered, requester, daemon_initiated)
4297            .await
4298    }
4299
4300    /// Record a configured module as starting or disabled, without launching a
4301    /// process or running its monitor. Bootstrap registers the entire roster
4302    /// before publishing discovery, then activates it once children can read
4303    /// the connection file passed in their `--subc` argument.
4304    pub(crate) fn register_configured_with_health(
4305        &self,
4306        spec: ModuleSpec,
4307        enabled: bool,
4308        health: HealthConfig,
4309        drain_timeout_ms: Option<u64>,
4310        restart_policy: RestartPolicy,
4311        register_timeout: Duration,
4312    ) -> Result<RegisteredConfiguredModule, SuperviseError> {
4313        validate_spec(&spec)?;
4314        self.establish_identity(&spec);
4315
4316        let mut runtime = self.runtime_config();
4317        runtime.health = health;
4318        runtime.restart_policy = restart_policy;
4319        runtime.register_timeout = register_timeout;
4320        if let Some(ms) = drain_timeout_ms {
4321            runtime.drain_timeout = Duration::from_millis(ms);
4322            *runtime
4323                .effective_drain_timeout
4324                .lock()
4325                .unwrap_or_else(|poisoned| poisoned.into_inner()) = runtime.drain_timeout;
4326        }
4327        let snapshot = if enabled {
4328            SupervisorSnapshot::starting()
4329        } else {
4330            SupervisorSnapshot::disabled()
4331        };
4332        let snapshot = {
4333            let mut snapshot = snapshot;
4334            if enabled {
4335                if let Some((pid, reason)) = runtime.child_roster.previous_instance(&spec.module_id)
4336                {
4337                    snapshot.waiting_for_previous_pid = Some(pid);
4338                    snapshot.waiting_for_previous_detail = Some(reason.waiting_message(pid));
4339                }
4340            }
4341            snapshot
4342        };
4343        let (module, commands) =
4344            self.register_module(&spec, &runtime, Arc::new(Mutex::new(snapshot)));
4345        Ok(RegisteredConfiguredModule {
4346            spec,
4347            runtime,
4348            module,
4349            commands,
4350        })
4351    }
4352
4353    /// Activate a previously registered module. Queued control requests are
4354    /// served by the monitor after the initial configured spawn has settled.
4355    pub(crate) fn start_registered_configured(
4356        &self,
4357        registered: RegisteredConfiguredModule,
4358        requester: Option<Principal>,
4359        daemon_initiated: bool,
4360    ) -> Result<SupervisedModule, SuperviseError> {
4361        let RegisteredConfiguredModule {
4362            spec,
4363            mut runtime,
4364            module,
4365            commands,
4366        } = registered;
4367        runtime.start_requester = requester;
4368        runtime.recovery_is_daemon = daemon_initiated;
4369        let snapshot = &module.inner.snapshot;
4370        let should_spawn = {
4371            let state = lock_snapshot(snapshot)?;
4372            state.enabled && state.waiting_for_previous_pid.is_none()
4373        };
4374        let child = if should_spawn {
4375            let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4376            let registration_watch = watch_registration(&self.registry, &spec);
4377            let spawned = spawn_child(
4378                &spec,
4379                runtime.connection_file_path.as_deref(),
4380                self.supervisor_handle.as_ref(),
4381                &runtime.stderr_ring,
4382                runtime.capture_logs_dir.as_deref(),
4383                &runtime.child_roster,
4384                runtime.spawn_delivery(),
4385                #[cfg(target_os = "linux")]
4386                runtime.cgroup_placement.as_ref(),
4387                runtime.register_timeout,
4388            );
4389            #[cfg(test)]
4390            self.test_after_first_spawn.run(&spec.module_id);
4391            match spawned {
4392                Ok(mut child) => {
4393                    arm_registration_deadline(
4394                        &mut child,
4395                        runtime.register_timeout,
4396                        registration_watch,
4397                    );
4398                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
4399                    if let Some(spawn) = activity_spawn {
4400                        spawn.complete(snapshot);
4401                    }
4402                    Some(child)
4403                }
4404                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4405                    defer_config_spawn(
4406                        &spec,
4407                        &runtime,
4408                        snapshot,
4409                        RespawnKind::Spawn,
4410                        &runtime.failure_context(daemon_initiated),
4411                    )?;
4412                    None
4413                }
4414                Err(mut err) => {
4415                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
4416                        match hold_config_spawn(
4417                            &spec,
4418                            &runtime,
4419                            snapshot,
4420                            &runtime.failure_context(daemon_initiated),
4421                        ) {
4422                            Ok(()) => {
4423                                self.start_monitor(spec, runtime, &module, None, commands);
4424                                return Ok(module);
4425                            }
4426                            Err(parking_error) => err = parking_error,
4427                        }
4428                    }
4429                    if runtime.health.critical {
4430                        error!(
4431                            module_id = %spec.module_id,
4432                            program = %spec.program.display(),
4433                            error = %err,
4434                            "critical configured module failed to spawn; marking failed and alerting"
4435                        );
4436                    } else {
4437                        error!(
4438                            module_id = %spec.module_id,
4439                            program = %spec.program.display(),
4440                            error = %err,
4441                            "configured module failed to spawn; marking failed and continuing"
4442                        );
4443                    }
4444                    fail_snapshot(
4445                        snapshot,
4446                        Some(&spec.module_id),
4447                        None,
4448                        &runtime.failure_context(daemon_initiated),
4449                    );
4450                    None
4451                }
4452            }
4453        } else {
4454            None
4455        };
4456        self.start_monitor(spec, runtime, &module, child, commands);
4457        Ok(module)
4458    }
4459
4460    pub(crate) async fn start_registered_configured_async(
4461        &self,
4462        registered: RegisteredConfiguredModule,
4463        requester: Option<Principal>,
4464        daemon_initiated: bool,
4465    ) -> Result<SupervisedModule, SuperviseError> {
4466        self.start_registered_with_failure_policy(registered, requester, daemon_initiated, None)
4467            .await
4468    }
4469
4470    pub(crate) async fn start_registered_approved_async(
4471        &self,
4472        registered: RegisteredConfiguredModule,
4473        requester: Principal,
4474        generation: crate::config_gate::runtime::ApprovalIdentity,
4475    ) -> Result<SupervisedModule, SuperviseError> {
4476        self.start_registered_with_failure_policy(
4477            registered,
4478            Some(requester),
4479            false,
4480            Some(generation),
4481        )
4482        .await
4483    }
4484
4485    async fn start_registered_with_failure_policy(
4486        &self,
4487        registered: RegisteredConfiguredModule,
4488        requester: Option<Principal>,
4489        daemon_initiated: bool,
4490        approved_generation: Option<crate::config_gate::runtime::ApprovalIdentity>,
4491    ) -> Result<SupervisedModule, SuperviseError> {
4492        let RegisteredConfiguredModule {
4493            spec,
4494            mut runtime,
4495            module,
4496            commands,
4497        } = registered;
4498        runtime.start_requester = requester;
4499        runtime.recovery_is_daemon = daemon_initiated;
4500        let snapshot = &module.inner.snapshot;
4501        let mut startup_error = None;
4502        let failure = FailureContext {
4503            approval: approved_generation.clone(),
4504            ..runtime.failure_context(daemon_initiated)
4505        };
4506        let should_spawn = {
4507            let state = lock_snapshot(snapshot)?;
4508            state.enabled && state.waiting_for_previous_pid.is_none()
4509        };
4510        let child = if should_spawn {
4511            let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4512            let registration_watch = watch_registration(&self.registry, &spec);
4513            let spawned = spawn_child_async(&spec, &runtime).await;
4514            #[cfg(test)]
4515            self.test_after_first_spawn.run(&spec.module_id);
4516            match spawned {
4517                Ok(mut child) => {
4518                    arm_registration_deadline(
4519                        &mut child,
4520                        runtime.register_timeout,
4521                        registration_watch,
4522                    );
4523                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
4524                    if let Some(spawn) = activity_spawn {
4525                        spawn.complete(snapshot);
4526                    }
4527                    Some(child)
4528                }
4529                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4530                    defer_config_spawn(&spec, &runtime, snapshot, RespawnKind::Spawn, &failure)?;
4531                    None
4532                }
4533                Err(mut err) => {
4534                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
4535                        match hold_config_spawn(&spec, &runtime, snapshot, &failure) {
4536                            Ok(()) => {
4537                                self.start_monitor(spec, runtime, &module, None, commands);
4538                                return Ok(module);
4539                            }
4540                            Err(parking_error) => err = parking_error,
4541                        }
4542                    }
4543                    if runtime.health.critical {
4544                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
4545                            "critical configured module failed to spawn; marking failed and alerting");
4546                    } else {
4547                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
4548                            "configured module failed to spawn; marking failed and continuing");
4549                    }
4550                    fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
4551                    if let Some(generation) = approved_generation {
4552                        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
4553                            state.approved_start_failure = Some((generation, err.to_string()));
4554                        });
4555                        startup_error = Some(err);
4556                    }
4557                    None
4558                }
4559            }
4560        } else {
4561            None
4562        };
4563        self.start_monitor(spec, runtime, &module, child, commands);
4564        // Applying an operator-approved configuration must report a spawn error
4565        // without removing the failed module or its monitor. Bootstrap instead
4566        // tolerates failed starts so other configured modules can still run.
4567        startup_error.map_or(Ok(module), Err)
4568    }
4569
4570    fn runtime_config(&self) -> SupervisorRuntimeConfig {
4571        let effective_drain_timeout = Arc::new(Mutex::new(self.drain_timeout));
4572        SupervisorRuntimeConfig {
4573            registry: self.registry.clone(),
4574            config_delivery: self.config_delivery.clone(),
4575            recovery_is_daemon: true,
4576            start_requester: None,
4577            pending_activity_restart: false,
4578            provenance_probe: self.provenance_probe.clone(),
4579            scheduled_respawn: Arc::default(),
4580            deferred_reload_reply: Arc::default(),
4581            restart_policy: self.restart_policy,
4582            register_timeout: DEFAULT_REGISTER_TIMEOUT,
4583            drain_timeout: self.drain_timeout,
4584            // Shared with this module's roster copy: daemon shutdown waits on
4585            // each child for the module's own drain budget, as resolved now.
4586            child_roster: self
4587                .child_roster
4588                .for_module(Arc::clone(&effective_drain_timeout)),
4589            effective_drain_timeout,
4590            default_drain_timeout: self.drain_timeout,
4591            health: self.health.clone(),
4592            host_health: self.host_health.clone(),
4593            connection_file_path: self.connection_file_path.clone(),
4594            capture_logs_dir: self.capture_logs_dir.clone(),
4595            forwarding: self.forwarding.clone(),
4596            supervisor_handle: self.supervisor_handle.clone(),
4597            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
4598            terminal_ring: Arc::new(Mutex::new(
4599                TerminalRing::new(
4600                    TerminalRingConfig::default(),
4601                    self.daemon_start_clock.started_at_ms(),
4602                )
4603                .with_start_clock(self.daemon_start_clock)
4604                .with_journal(self.terminal_journal.clone())
4605                .with_daemon_shutdown(self.child_roster.shutdown_flag()),
4606            )),
4607            spawn_events: self.spawn_events.clone(),
4608            #[cfg(target_os = "linux")]
4609            cgroup_placement: self.cgroup_placement.clone(),
4610            #[cfg(test)]
4611            test_seed_stale_facts_before_enable_spawn: false,
4612            #[cfg(test)]
4613            test_reload_exit_record_gate: None,
4614        }
4615    }
4616
4617    fn supervised_module(
4618        &self,
4619        spec: ModuleSpec,
4620        runtime: SupervisorRuntimeConfig,
4621        snapshot: SharedSnapshot,
4622        child: Option<SupervisedChild>,
4623    ) -> SupervisedModule {
4624        let (module, commands) = self.register_module(&spec, &runtime, snapshot);
4625        self.start_monitor(spec, runtime, &module, child, commands);
4626        module
4627    }
4628
4629    fn register_module(
4630        &self,
4631        spec: &ModuleSpec,
4632        runtime: &SupervisorRuntimeConfig,
4633        snapshot: SharedSnapshot,
4634    ) -> (SupervisedModule, mpsc::Receiver<SupervisorCommand>) {
4635        runtime.host_health.track(spec, &snapshot);
4636        let configuration = Arc::new(Mutex::new(SupervisedConfiguration {
4637            spec: spec.clone(),
4638            enabled: snapshot.lock().unwrap_or_else(|p| p.into_inner()).enabled,
4639            health: runtime.health.clone(),
4640            register_timeout: runtime.register_timeout,
4641            restart_policy: runtime.restart_policy,
4642        }));
4643        let stderr_ring = Arc::clone(&runtime.stderr_ring);
4644        let terminal_ring = Arc::clone(&runtime.terminal_ring);
4645        let effective_drain_timeout = Arc::clone(&runtime.effective_drain_timeout);
4646        let (tx, rx) = mpsc::channel(4);
4647        let module_id = spec.module_id.clone();
4648        let module = SupervisedModule {
4649            inner: Arc::new(SupervisedModuleInner {
4650                module_id: module_id.clone(),
4651                registry: Arc::clone(&self.registry),
4652                snapshot,
4653                configuration,
4654                stderr_ring,
4655                terminal_ring,
4656                commands: tx,
4657                monitor: Mutex::new(None),
4658                effective_drain_timeout,
4659                provenance_probe: self.provenance_probe.clone(),
4660                retained: runtime.child_roster.retained_view(),
4661            }),
4662        };
4663        // Identity gates and the configured mark must precede the roster entry,
4664        // so a client never sees a module without its admission policy.
4665        if let Some(supervisor_handle) = &self.supervisor_handle {
4666            supervisor_handle.insert(module.clone());
4667        }
4668        (module, rx)
4669    }
4670
4671    fn start_monitor(
4672        &self,
4673        spec: ModuleSpec,
4674        runtime: SupervisorRuntimeConfig,
4675        module: &SupervisedModule,
4676        child: Option<SupervisedChild>,
4677        commands: mpsc::Receiver<SupervisorCommand>,
4678    ) {
4679        let monitor = tokio::spawn(supervise_loop(
4680            spec,
4681            runtime,
4682            Arc::clone(&self.registry),
4683            Arc::clone(&self.process_liveness),
4684            Arc::clone(&module.inner.snapshot),
4685            child,
4686            commands,
4687        ));
4688        *module
4689            .inner
4690            .monitor
4691            .lock()
4692            .unwrap_or_else(|p| p.into_inner()) = Some(monitor);
4693    }
4694}
4695
4696impl Default for Supervisor {
4697    fn default() -> Self {
4698        Self::new(Arc::new(Registry::default()), RestartPolicy::default())
4699    }
4700}
4701
4702/// Handle to one supervised child process.
4703#[derive(Clone)]
4704pub struct SupervisedModule {
4705    inner: Arc<SupervisedModuleInner>,
4706}
4707
4708struct SupervisedModuleInner {
4709    retained: crate::child_roster::RetainedView,
4710    module_id: String,
4711    registry: Arc<Registry>,
4712    snapshot: SharedSnapshot,
4713    configuration: Arc<Mutex<SupervisedConfiguration>>,
4714    stderr_ring: Arc<Mutex<StderrRing>>,
4715    terminal_ring: Arc<Mutex<TerminalRing>>,
4716    commands: mpsc::Sender<SupervisorCommand>,
4717    monitor: Mutex<Option<JoinHandle<()>>>,
4718    effective_drain_timeout: Arc<Mutex<Duration>>,
4719    provenance_probe: ExecutableIdentityProbe,
4720}
4721
4722impl fmt::Debug for SupervisedModule {
4723    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4724        f.debug_struct("SupervisedModule")
4725            .field("module_id", &self.inner.module_id)
4726            .field("status", &self.status())
4727            .finish_non_exhaustive()
4728    }
4729}
4730
4731impl SupervisedModule {
4732    pub(crate) fn check_approved_start_failure(
4733        &self,
4734        generation: &crate::config_gate::runtime::ApprovalIdentity,
4735    ) -> Result<bool, SuperviseError> {
4736        let state = lock_snapshot(&self.inner.snapshot)?;
4737        if let Some((failed_generation, detail)) = &state.approved_start_failure {
4738            if failed_generation == generation {
4739                return Err(SuperviseError::ReloadFailed {
4740                    module_id: self.inner.module_id.clone(),
4741                    reason: detail.clone(),
4742                });
4743            }
4744        }
4745        Ok(state.approved_start_failure.is_some())
4746    }
4747
4748    pub(crate) fn has_approved_start_failure(
4749        &self,
4750        identity: &crate::config_gate::runtime::ApprovalIdentity,
4751    ) -> bool {
4752        lock_snapshot(&self.inner.snapshot).is_ok_and(|state| {
4753            state
4754                .approved_start_failure
4755                .as_ref()
4756                .is_some_and(|(failed, _)| failed == identity)
4757        })
4758    }
4759
4760    pub(crate) fn needs_approved_gate_restart(
4761        &self,
4762        approval: &crate::config_gate::runtime::ApprovalIdentity,
4763    ) -> bool {
4764        lock_snapshot(&self.inner.snapshot)
4765            .is_ok_and(|state| state.needs_approved_gate_restart(approval))
4766    }
4767
4768    #[cfg(all(test, unix))]
4769    pub(crate) fn config_hold_origin_for_test(
4770        &self,
4771    ) -> (bool, Option<crate::config_gate::runtime::ApprovalIdentity>) {
4772        let state = lock_snapshot(&self.inner.snapshot).unwrap();
4773        (
4774            state.config_hold_daemon_initiated,
4775            state.config_hold_approval.clone(),
4776        )
4777    }
4778
4779    pub(crate) async fn config_policy_probe(
4780        &self,
4781        connection: crate::ConnectionId,
4782        generation: u64,
4783        attempt: u64,
4784    ) -> Result<(), SuperviseError> {
4785        self.inner
4786            .commands
4787            .send(SupervisorCommand::ConfigPolicyProbe {
4788                connection,
4789                generation,
4790                attempt,
4791            })
4792            .await
4793            .map_err(|_| SuperviseError::CommandClosed {
4794                module_id: self.inner.module_id.clone(),
4795            })
4796    }
4797    pub(crate) async fn config_exit_hold(&self) -> Result<(), SuperviseError> {
4798        let (reply, result) = oneshot::channel();
4799        self.inner
4800            .commands
4801            .send(SupervisorCommand::ConfigExitHold { reply })
4802            .await
4803            .map_err(|_| SuperviseError::CommandClosed {
4804                module_id: self.module_id().to_string(),
4805            })?;
4806        result.await.map_err(|_| SuperviseError::CommandClosed {
4807            module_id: self.module_id().to_string(),
4808        })?
4809    }
4810    pub(crate) async fn config_delivery_failed(
4811        &self,
4812        connection: crate::ConnectionId,
4813        hold: bool,
4814    ) -> Result<(), SuperviseError> {
4815        self.inner
4816            .commands
4817            .send(SupervisorCommand::ConfigDeliveryFailed { connection, hold })
4818            .await
4819            .map_err(|_| SuperviseError::CommandClosed {
4820                module_id: self.module_id().to_string(),
4821            })
4822    }
4823
4824    pub(crate) async fn config_apply_restart(&self, generation: u64) -> Result<(), SuperviseError> {
4825        self.inner
4826            .commands
4827            .send(SupervisorCommand::ConfigApplyRestart {
4828                generation,
4829                supersedes_swap: false,
4830            })
4831            .await
4832            .map_err(|_| SuperviseError::CommandClosed {
4833                module_id: self.inner.module_id.clone(),
4834            })
4835    }
4836    pub fn module_id(&self) -> &str {
4837        &self.inner.module_id
4838    }
4839
4840    /// Test-only: put one probe miss on the streak, the way
4841    /// `handle_health_probe_failure` does, so tests can assert what a later
4842    /// event does to the streak without driving the whole probe loop.
4843    #[cfg(test)]
4844    pub(crate) fn record_health_probe_failure_for_test(
4845        &self,
4846        detail: &str,
4847    ) -> Result<(), SuperviseError> {
4848        update_snapshot(&self.inner.snapshot, Some(&self.inner.module_id), |state| {
4849            state.health.consecutive_failures = state.health.consecutive_failures.saturating_add(1);
4850            state.health.detail = Some(detail.to_string());
4851        })
4852    }
4853
4854    pub fn state(&self) -> Result<ModuleState, SuperviseError> {
4855        Ok(lock_snapshot(&self.inner.snapshot)?.state)
4856    }
4857
4858    pub(crate) fn registration_end_reason(
4859        &self,
4860    ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
4861        let snapshot = lock_snapshot(&self.inner.snapshot)?;
4862        Ok(match snapshot.state {
4863            ModuleState::Draining if snapshot.draining_to_replace => {
4864                Some(RegistrationEndReason::SupervisorRestart)
4865            }
4866            ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
4867            ModuleState::Restarting if snapshot.draining_to_replace => {
4868                Some(RegistrationEndReason::SupervisorRestart)
4869            }
4870            _ => None,
4871        })
4872    }
4873
4874    /// The module's retained stderr, newest lines last.
4875    ///
4876    /// Deliberately NOT on [`Self::status`]: a bounded tail is kilobytes per
4877    /// module, `supervisor.list` renders every module, and putting it in the
4878    /// shared snapshot would make each status read carry a payload almost nobody
4879    /// asked for. Callers that want the text ask for it.
4880    pub fn stderr_tail(
4881        &self,
4882        max_lines: Option<usize>,
4883        max_bytes: Option<usize>,
4884    ) -> StderrTailSnapshot {
4885        self.inner
4886            .stderr_ring
4887            .lock()
4888            .unwrap_or_else(|poisoned| poisoned.into_inner())
4889            .snapshot(max_lines, max_bytes)
4890    }
4891
4892    /// The module's bounded terminal history, oldest retained exit first.
4893    ///
4894    /// The daemon-start stamp distinguishes a quiet supervisor from a replacement
4895    /// daemon whose in-memory history was necessarily reset.
4896    pub fn terminal_history(&self) -> TerminalHistorySnapshot {
4897        self.inner
4898            .terminal_ring
4899            .lock()
4900            .unwrap_or_else(|poisoned| poisoned.into_inner())
4901            .snapshot()
4902    }
4903
4904    /// Retained observations from the current ring and all journal generations.
4905    ///
4906    /// Blocking: this reads the journal files. Async callers use
4907    /// `Self::read_durable_terminal_history`.
4908    pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
4909        durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
4910    }
4911
4912    /// [`Self::durable_terminal_history`] on a blocking thread, so the journal
4913    /// read (up to every retained generation) never occupies a runtime worker.
4914    /// Fails only if the blocking task could not finish (runtime shutdown or a
4915    /// panic in the read).
4916    pub(crate) async fn read_durable_terminal_history(
4917        &self,
4918    ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
4919        let terminal_ring = Arc::clone(&self.inner.terminal_ring);
4920        let module_id = self.inner.module_id.clone();
4921        tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
4922            .await
4923    }
4924
4925    pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
4926        self.status_with_snapshot_lock(&self.inner.snapshot, None)
4927            .map(|(status, _)| status)
4928    }
4929
4930    pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
4931        let state = lock_snapshot(&self.inner.snapshot)?;
4932        Ok(state
4933            .failed_retry
4934            .pending
4935            .filter(|_| state.state == ModuleState::Failed && state.enabled)
4936            .map(|retry| {
4937                unix_ms_now().saturating_add(
4938                    u64::try_from(
4939                        retry
4940                            .deadline
4941                            .saturating_duration_since(Instant::now())
4942                            .as_millis(),
4943                    )
4944                    .unwrap_or(u64::MAX),
4945                )
4946            }))
4947    }
4948
4949    #[cfg(all(test, unix))]
4950    pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
4951        lock_snapshot(&self.inner.snapshot)
4952            .unwrap()
4953            .failed_retry
4954            .pending
4955            .map(|retry| retry.deadline)
4956    }
4957
4958    pub(crate) fn record_deliberate_severance(
4959        &self,
4960        identity: ProcessIdentity,
4961    ) -> Result<bool, SuperviseError> {
4962        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
4963        if snapshot.pid != Some(identity.pid)
4964            || snapshot.process_start_time != Some(identity.start_time)
4965        {
4966            return Ok(false);
4967        }
4968        snapshot.deliberate_severance = Some(identity);
4969        Ok(true)
4970    }
4971
4972    /// Read status for a channel-0 renderer and report a contended snapshot lock.
4973    ///
4974    /// Internal supervision callers use [`Self::status`] so writer-side machinery
4975    /// does not produce reader-observability logs.
4976    pub(crate) fn status_for_control(
4977        &self,
4978        caller: &'static str,
4979    ) -> Result<ModuleStatus, SuperviseError> {
4980        self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
4981            .map(|(status, _)| status)
4982    }
4983
4984    fn status_with_snapshot_lock(
4985        &self,
4986        snapshot: &SharedSnapshot,
4987        caller: Option<&'static str>,
4988    ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
4989        let restart_policy = self
4990            .inner
4991            .configuration
4992            .lock()
4993            .map_err(|_| SuperviseError::StatePoisoned {
4994                module_id: Some(self.inner.module_id.clone()),
4995            })?
4996            .restart_policy;
4997        let mut guard = match caller {
4998            Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
4999            None => lock_snapshot(snapshot)?,
5000        };
5001        // Read the budget through the pruning path so a reader sees the same
5002        // in-window count the restart decision would use, not a stale total.
5003        let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
5004        let snapshot = guard.clone();
5005        drop(guard);
5006        let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
5007            SuperviseError::StatePoisoned {
5008                module_id: Some(self.inner.module_id.clone()),
5009            }
5010        })?;
5011        let registration_active = self
5012            .inner
5013            .registry
5014            .get_module(&self.inner.module_id)
5015            .map_err(SuperviseError::Registry)?
5016            .is_some();
5017        let protocol = snapshot
5018            .spawned_protocol
5019            .unwrap_or(self.declared_protocol()?);
5020        let running_process =
5021            snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
5022        // Registration is the difference between the two protocols and the only
5023        // one: a subc module that has not registered cannot serve a request even
5024        // though its process is up, and a `none` module never registers at all,
5025        // so requiring it there would pin `live` to false for the whole life of
5026        // a perfectly healthy process.
5027        let live = match protocol {
5028            ModuleProtocol::Subc => running_process && registration_active,
5029            ModuleProtocol::None => running_process,
5030        };
5031        // Read only the retained cache: a status read must not resend signals,
5032        // rewrite the record, or keep the containment resource alive.
5033        let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
5034        let carry_configured = self
5035            .inner
5036            .configuration
5037            .lock()
5038            .map_err(|_| SuperviseError::StatePoisoned {
5039                module_id: Some(self.inner.module_id.clone()),
5040            })?
5041            .spec
5042            .carry_containment;
5043        let recovery_block = carries_containment(
5044            carry_configured,
5045            self.inner
5046                .retained
5047                .has_carried_container(&self.inner.module_id),
5048        )
5049        .then(|| self.inner.retained.recovery_block())
5050        .flatten();
5051        let launch_nonce_source = observed_launch_nonce_source(&snapshot);
5052        let pid = snapshot.reported_pid();
5053        let mut health = snapshot.health;
5054        if let Some(detail) = recovery_block
5055            .as_ref()
5056            .or_else(|| retained.as_ref().map(|(_, detail)| detail))
5057        {
5058            health.detail = Some(match health.detail {
5059                Some(previous) => format!("{previous}; {detail}"),
5060                None => detail.clone(),
5061            });
5062        }
5063
5064        Ok((
5065            ModuleStatus {
5066                admission_refused: snapshot.admission_refused,
5067                legacy_registration_spawn: snapshot.legacy_registration_spawn,
5068                registration_declaration: snapshot.registration_declaration.clone(),
5069                stop_reason: snapshot.stop_reason,
5070                waiting_for_previous_pid: retained
5071                    .as_ref()
5072                    .map(|(pid, _)| *pid)
5073                    .filter(|pid| *pid > 0)
5074                    .or(snapshot.waiting_for_previous_pid),
5075                waiting_for_previous_detail: recovery_block
5076                    .or_else(|| retained.map(|(_, detail)| detail))
5077                    .or(snapshot.waiting_for_previous_detail),
5078                module_id: self.inner.module_id.clone(),
5079                launch_nonce_source,
5080                state: snapshot.state,
5081                enabled: snapshot.enabled,
5082                process_alive: snapshot.process_alive,
5083                registration_active,
5084                protocol,
5085                live,
5086                restart_count,
5087                lifetime_restarts: snapshot.lifetime_restarts,
5088                spawn_generation: snapshot.spawn_generation,
5089                swap_outcome: snapshot.swap_outcome,
5090                max_restarts: restart_policy.max_restarts,
5091                restart_window: restart_policy.window,
5092                drain_timeout,
5093                restart_backoff: restart_policy.backoff,
5094                restart_max_backoff: restart_policy.max_backoff,
5095                pid,
5096                spawned_at_ms: snapshot.spawned_at_ms,
5097                spawned_from: snapshot.spawned_from,
5098                launch_spec_digest: snapshot.launch_spec_digest,
5099                process_start_time: snapshot.process_start_time,
5100                last_exit: snapshot.last_exit,
5101                health,
5102            },
5103            snapshot.spawned_file_identity.clone(),
5104        ))
5105    }
5106
5107    #[cfg(test)]
5108    pub(crate) fn hold_snapshot_for_test(
5109        &self,
5110        acquired: std::sync::mpsc::Sender<()>,
5111        hold: Duration,
5112    ) -> std::thread::JoinHandle<()> {
5113        let snapshot = Arc::clone(&self.inner.snapshot);
5114        std::thread::spawn(move || {
5115            let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
5116            acquired
5117                .send(())
5118                .expect("test receiver waits for snapshot lock");
5119            std::thread::sleep(hold);
5120        })
5121    }
5122
5123    /// The status and the running-image check for `supervisor.provenance`,
5124    /// taken from one status read. The exec acknowledgement can land between
5125    /// two separate reads, and the reply would then pair "no pid yet" with an
5126    /// image observed after the module started, which describes no single
5127    /// moment.
5128    pub(crate) async fn status_and_running_image_agreement(
5129        &self,
5130    ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
5131        let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
5132        let image = self
5133            .inner
5134            .provenance_probe
5135            .observe(
5136                status.pid,
5137                status.spawned_from.as_deref(),
5138                identity,
5139                status.process_start_time,
5140            )
5141            .await;
5142        Ok((status, image))
5143    }
5144
5145    pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
5146        let snapshot = match lock_snapshot(&self.inner.snapshot) {
5147            Ok(snapshot) => snapshot.clone(),
5148            Err(_) => {
5149                return subc_control::RunningImageAgreement::Unavailable {
5150                    reason: subc_control::RunningImageUnavailableReason::NotRunning,
5151                };
5152            }
5153        };
5154        self.inner
5155            .provenance_probe
5156            .observe(
5157                snapshot.reported_pid(),
5158                snapshot.spawned_from.as_deref(),
5159                snapshot.spawned_file_identity.clone(),
5160                snapshot.process_start_time,
5161            )
5162            .await
5163    }
5164
5165    /// Memory and CPU time of the module's current process, read now. Only the
5166    /// process the supervisor spawned is read, not processes it has started.
5167    pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
5168        #[cfg(windows)]
5169        {
5170            let image = lock_snapshot(&self.inner.snapshot)
5171                .ok()
5172                .and_then(|snapshot| {
5173                    snapshot
5174                        .spawned_file_identity
5175                        .as_ref()
5176                        .and_then(|identity| identity.windows_image.clone())
5177                });
5178            match image {
5179                Some(image) => {
5180                    crate::child_resources::read_windows_handle(image.process(), image.start_time())
5181                }
5182                None => subc_control::ChildResourceUsage::Unavailable {
5183                    reason: subc_control::ChildResourceUnavailableReason::NotRunning,
5184                },
5185            }
5186        }
5187        #[cfg(not(windows))]
5188        {
5189            let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
5190                Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
5191                Err(_) => {
5192                    return subc_control::ChildResourceUsage::Unavailable {
5193                        reason: subc_control::ChildResourceUnavailableReason::Unreadable,
5194                    }
5195                }
5196            };
5197            crate::child_resources::read(pid, start_time)
5198        }
5199    }
5200
5201    #[cfg(all(test, any(target_os = "linux", windows)))]
5202    pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
5203        self.inner
5204            .snapshot
5205            .try_lock()
5206            .map(|snapshot| snapshot.subtree_target.clone())
5207            .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
5208    }
5209
5210    #[cfg(test)]
5211    pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
5212        self.inner.snapshot.lock().unwrap().subtree_target = target;
5213    }
5214
5215    pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
5216        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
5217        Ok(match snapshot.state {
5218            ModuleState::Restarting => true,
5219            ModuleState::Failed | ModuleState::Disabled => false,
5220            _ if snapshot.enabled && snapshot.respawn_pending => true,
5221            _ => daemon_will_restart(
5222                &mut snapshot,
5223                &self
5224                    .inner
5225                    .configuration
5226                    .lock()
5227                    .map_err(|_| SuperviseError::StatePoisoned {
5228                        module_id: Some(self.inner.module_id.clone()),
5229                    })?
5230                    .restart_policy,
5231                Instant::now(),
5232            ),
5233        })
5234    }
5235
5236    #[cfg(test)]
5237    pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
5238        self.is_warming_with_snapshot_lock(None)
5239    }
5240
5241    pub(crate) fn is_warming_for_control(
5242        &self,
5243        caller: &'static str,
5244    ) -> Result<bool, SuperviseError> {
5245        self.is_warming_with_snapshot_lock(Some(caller))
5246    }
5247
5248    fn is_warming_with_snapshot_lock(
5249        &self,
5250        caller: Option<&'static str>,
5251    ) -> Result<bool, SuperviseError> {
5252        let snapshot = match caller {
5253            Some(caller) => {
5254                lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
5255            }
5256            None => lock_snapshot(&self.inner.snapshot)?,
5257        }
5258        .clone();
5259        Ok(matches!(
5260            snapshot.state,
5261            ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
5262        ))
5263    }
5264
5265    /// Drain the module and stop monitoring it.
5266    pub async fn drain(&self) -> Result<(), SuperviseError> {
5267        self.stop().await
5268    }
5269
5270    pub(crate) async fn retire_requested(
5271        &self,
5272        requester: Option<Principal>,
5273    ) -> Result<(), SuperviseError> {
5274        match self.state()? {
5275            ModuleState::Stopped => return Ok(()),
5276            ModuleState::Failed
5277                if lock_snapshot(&self.inner.snapshot)?
5278                    .failed_retry
5279                    .pending
5280                    .is_none() =>
5281            {
5282                return Ok(())
5283            }
5284            ModuleState::Failed
5285            | ModuleState::Starting
5286            | ModuleState::Running
5287            | ModuleState::Unresponsive
5288            | ModuleState::Restarting
5289            | ModuleState::Draining
5290            | ModuleState::Disabled => {}
5291        }
5292
5293        let (reply_tx, reply_rx) = oneshot::channel();
5294        self.inner
5295            .commands
5296            .send(SupervisorCommand::Retire {
5297                requester,
5298                reply: reply_tx,
5299            })
5300            .await
5301            .map_err(|_| SuperviseError::CommandClosed {
5302                module_id: self.inner.module_id.clone(),
5303            })?;
5304        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5305            module_id: self.inner.module_id.clone(),
5306        })?
5307    }
5308
5309    pub async fn stop(&self) -> Result<(), SuperviseError> {
5310        self.stop_requested(None).await
5311    }
5312
5313    pub(crate) async fn stop_requested(
5314        &self,
5315        requester: Option<Principal>,
5316    ) -> Result<(), SuperviseError> {
5317        match self.state()? {
5318            ModuleState::Stopped => return Ok(()),
5319            ModuleState::Failed
5320                if lock_snapshot(&self.inner.snapshot)?
5321                    .failed_retry
5322                    .pending
5323                    .is_none() =>
5324            {
5325                return Ok(())
5326            }
5327            ModuleState::Failed
5328            | ModuleState::Starting
5329            | ModuleState::Running
5330            | ModuleState::Unresponsive
5331            | ModuleState::Restarting
5332            | ModuleState::Draining
5333            | ModuleState::Disabled => {}
5334        }
5335
5336        let (reply_tx, reply_rx) = oneshot::channel();
5337        self.inner
5338            .commands
5339            .send(SupervisorCommand::Drain {
5340                requester,
5341                reply: reply_tx,
5342            })
5343            .await
5344            .map_err(|_| SuperviseError::CommandClosed {
5345                module_id: self.inner.module_id.clone(),
5346            })?;
5347        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5348            module_id: self.inner.module_id.clone(),
5349        })?
5350    }
5351
5352    pub async fn restart(&self, drain_timeout_ms: Option<u64>) -> Result<(), SuperviseError> {
5353        self.restart_requested(drain_timeout_ms, None).await
5354    }
5355
5356    pub(crate) async fn restart_requested(
5357        &self,
5358        drain_timeout_ms: Option<u64>,
5359        requester: Option<Principal>,
5360    ) -> Result<(), SuperviseError> {
5361        let queued_at = Instant::now();
5362        let received_at_generation = lock_snapshot(&self.inner.snapshot)?.spawn_generation;
5363        let (reply_tx, reply_rx) = oneshot::channel();
5364        self.inner
5365            .commands
5366            .send(SupervisorCommand::Restart {
5367                requester,
5368                drain_timeout_ms,
5369                received_at_generation,
5370                queued_at,
5371                reply: reply_tx,
5372            })
5373            .await
5374            .map_err(|_| SuperviseError::CommandClosed {
5375                module_id: self.inner.module_id.clone(),
5376            })?;
5377        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5378            module_id: self.inner.module_id.clone(),
5379        })?
5380    }
5381
5382    /// Blue/green restart: see `SupervisorCommand::Swap` and the
5383    /// `supervisor_swap` module. Returns once the swap has cut over (the old
5384    /// process then drains in the background of the supervise loop), has been
5385    /// superseded by an approved configuration restart, or has failed. Both
5386    /// supersession and failure leave the old process serving until replacement.
5387    pub async fn swap(
5388        &self,
5389        ready_timeout: Option<Duration>,
5390    ) -> Result<SwapOutcome, SuperviseError> {
5391        self.swap_requested(ready_timeout, None).await
5392    }
5393
5394    pub(crate) async fn swap_requested(
5395        &self,
5396        ready_timeout: Option<Duration>,
5397        requester: Option<Principal>,
5398    ) -> Result<SwapOutcome, SuperviseError> {
5399        let (reply_tx, reply_rx) = oneshot::channel();
5400        self.inner
5401            .commands
5402            .send(SupervisorCommand::Swap {
5403                requester,
5404                ready_timeout,
5405                reply: reply_tx,
5406            })
5407            .await
5408            .map_err(|_| SuperviseError::CommandClosed {
5409                module_id: self.inner.module_id.clone(),
5410            })?;
5411        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5412            module_id: self.inner.module_id.clone(),
5413        })?
5414    }
5415
5416    pub async fn reload(&self) -> Result<(), SuperviseError> {
5417        self.reload_requested(None).await
5418    }
5419
5420    pub(crate) async fn reload_requested(
5421        &self,
5422        requester: Option<Principal>,
5423    ) -> Result<(), SuperviseError> {
5424        let (reply_tx, reply_rx) = oneshot::channel();
5425        self.inner
5426            .commands
5427            .send(SupervisorCommand::Reload {
5428                requester,
5429                reply: reply_tx,
5430            })
5431            .await
5432            .map_err(|_| SuperviseError::CommandClosed {
5433                module_id: self.inner.module_id.clone(),
5434            })?;
5435        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5436            module_id: self.inner.module_id.clone(),
5437        })?
5438    }
5439
5440    pub async fn set_enabled(&self, enabled: bool) -> Result<bool, SuperviseError> {
5441        self.set_enabled_requested(enabled, None).await
5442    }
5443
5444    pub(crate) async fn set_enabled_requested(
5445        &self,
5446        enabled: bool,
5447        requester: Option<Principal>,
5448    ) -> Result<bool, SuperviseError> {
5449        self.set_enabled_with_budget_policy(enabled, requester, true)
5450            .await
5451    }
5452
5453    pub(crate) async fn release_config_hold(&self) -> Result<bool, SuperviseError> {
5454        self.set_enabled_with_budget_policy(true, None, false).await
5455    }
5456
5457    #[cfg(all(test, unix))]
5458    pub(crate) fn seed_crash_budget_for_test(&self, count: u32) {
5459        let policy = self.inner.configuration.lock().unwrap().restart_policy;
5460        let mut state = self.inner.snapshot.lock().unwrap();
5461        for _ in 0..count {
5462            state.record_crash_restart(&policy, Instant::now());
5463        }
5464    }
5465
5466    async fn set_enabled_with_budget_policy(
5467        &self,
5468        enabled: bool,
5469        requester: Option<Principal>,
5470        reset_budget: bool,
5471    ) -> Result<bool, SuperviseError> {
5472        let (reply_tx, reply_rx) = oneshot::channel();
5473        self.inner
5474            .commands
5475            .send(SupervisorCommand::SetEnabled {
5476                requester,
5477                enabled,
5478                reset_budget,
5479                reply: reply_tx,
5480            })
5481            .await
5482            .map_err(|_| SuperviseError::CommandClosed {
5483                module_id: self.inner.module_id.clone(),
5484            })?;
5485        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5486            module_id: self.inner.module_id.clone(),
5487        })?
5488    }
5489
5490    /// The current process's protocol, or the configured protocol when down.
5491    /// A rescan stores the next launch spec without changing how an existing
5492    /// process registers, serves routes, is probed, or exits.
5493    pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
5494        let configured = self
5495            .inner
5496            .configuration
5497            .lock()
5498            .map_err(|_| SuperviseError::StatePoisoned {
5499                module_id: Some(self.inner.module_id.clone()),
5500            })?
5501            .spec
5502            .protocol;
5503        let state = lock_snapshot(&self.inner.snapshot)?;
5504        Ok(state.spawned_protocol.unwrap_or(configured))
5505    }
5506
5507    pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
5508        let configuration =
5509            self.inner
5510                .configuration
5511                .lock()
5512                .map_err(|_| SuperviseError::StatePoisoned {
5513                    module_id: Some(self.inner.module_id.clone()),
5514                })?;
5515        Ok((configuration.spec.clone(), configuration.health.clone()))
5516    }
5517
5518    pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
5519        self.inner
5520            .configuration
5521            .lock()
5522            .map(|configuration| configuration.register_timeout)
5523            .map_err(|_| SuperviseError::StatePoisoned {
5524                module_id: Some(self.inner.module_id.clone()),
5525            })
5526    }
5527
5528    pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
5529        self.inner
5530            .configuration
5531            .lock()
5532            .map(|configuration| configuration.enabled)
5533            .map_err(|_| SuperviseError::StatePoisoned {
5534                module_id: Some(self.inner.module_id.clone()),
5535            })
5536    }
5537
5538    /// Replace this module's launch spec, keeping its health and drain policy,
5539    /// the way a rescan does for a changed config entry. The running process is
5540    /// untouched; the next spawn (a restart, or a swap's candidate) uses it.
5541    #[cfg(any(test, feature = "test-support"))]
5542    pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
5543        let (_, health) = self.configuration()?;
5544        let drain_timeout_ms = u64::try_from(
5545            self.inner
5546                .effective_drain_timeout
5547                .lock()
5548                .unwrap_or_else(|poisoned| poisoned.into_inner())
5549                .as_millis(),
5550        )
5551        .ok();
5552        self.update_configuration(spec, health, drain_timeout_ms)
5553            .await
5554    }
5555
5556    pub(crate) async fn reconcile_approved_configuration(
5557        &self,
5558        approved: crate::config_gate::runtime::ApprovedDaemonConfiguration,
5559    ) -> Result<(), SuperviseError> {
5560        let entry = approved
5561            .module_entry(&self.inner.module_id)
5562            .map_err(|error| SuperviseError::InvalidSpec {
5563                reason: error.to_string(),
5564            })?;
5565        validate_spec(&entry.module_spec())?;
5566        let (reply, received) = oneshot::channel();
5567        self.inner
5568            .commands
5569            .send(SupervisorCommand::ApprovedConfiguration { approved, reply })
5570            .await
5571            .map_err(|_| SuperviseError::CommandClosed {
5572                module_id: self.inner.module_id.clone(),
5573            })?;
5574        received.await.map_err(|_| SuperviseError::CommandClosed {
5575            module_id: self.inner.module_id.clone(),
5576        })??;
5577        let mut configuration =
5578            self.inner
5579                .configuration
5580                .lock()
5581                .map_err(|_| SuperviseError::StatePoisoned {
5582                    module_id: Some(self.inner.module_id.clone()),
5583                })?;
5584        configuration.spec = entry.module_spec();
5585        configuration.enabled = entry.enabled;
5586        configuration.health = entry.health;
5587        configuration.register_timeout = entry.register_timeout;
5588        configuration.restart_policy = entry.restart;
5589        Ok(())
5590    }
5591
5592    pub(crate) async fn update_configuration(
5593        &self,
5594        spec: ModuleSpec,
5595        health: HealthConfig,
5596        drain_timeout_ms: Option<u64>,
5597    ) -> Result<(), SuperviseError> {
5598        if spec.module_id != self.inner.module_id {
5599            return Err(SuperviseError::InvalidSpec {
5600                reason: "a supervised module's module_id cannot be changed".to_string(),
5601            });
5602        }
5603        validate_spec(&spec)?;
5604        let (reply_tx, reply_rx) = oneshot::channel();
5605        self.inner
5606            .commands
5607            .send(SupervisorCommand::UpdateConfiguration {
5608                spec: spec.clone(),
5609                health: health.clone(),
5610                drain_timeout_ms,
5611                reply: reply_tx,
5612            })
5613            .await
5614            .map_err(|_| SuperviseError::CommandClosed {
5615                module_id: self.inner.module_id.clone(),
5616            })?;
5617        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5618            module_id: self.inner.module_id.clone(),
5619        })??;
5620        let mut configuration =
5621            self.inner
5622                .configuration
5623                .lock()
5624                .map_err(|_| SuperviseError::StatePoisoned {
5625                    module_id: Some(self.inner.module_id.clone()),
5626                })?;
5627        configuration.spec = spec;
5628        configuration.health = health;
5629        Ok(())
5630    }
5631}
5632
5633impl Drop for SupervisedModuleInner {
5634    fn drop(&mut self) {
5635        let Ok(mut monitor) = self.monitor.lock() else {
5636            return;
5637        };
5638        if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
5639            let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
5640                state.state = ModuleState::Stopped;
5641                clear_current_process_facts(state);
5642            });
5643            monitor.abort();
5644        }
5645        let _ = monitor.take();
5646    }
5647}
5648
5649#[derive(Debug)]
5650enum SupervisorCommand {
5651    ApprovedConfiguration {
5652        approved: crate::config_gate::runtime::ApprovedDaemonConfiguration,
5653        reply: oneshot::Sender<Result<(), SuperviseError>>,
5654    },
5655    ConfigPolicyProbe {
5656        connection: crate::ConnectionId,
5657        generation: u64,
5658        attempt: u64,
5659    },
5660    ConfigApplyRestart {
5661        generation: u64,
5662        supersedes_swap: bool,
5663    },
5664    ConfigExitHold {
5665        reply: oneshot::Sender<Result<(), SuperviseError>>,
5666    },
5667    ConfigDeliveryFailed {
5668        connection: crate::ConnectionId,
5669        hold: bool,
5670    },
5671    Drain {
5672        requester: Option<Principal>,
5673        reply: oneshot::Sender<Result<(), SuperviseError>>,
5674    },
5675    Retire {
5676        requester: Option<Principal>,
5677        reply: oneshot::Sender<Result<(), SuperviseError>>,
5678    },
5679    Restart {
5680        requester: Option<Principal>,
5681        /// Operator override for this one restart's drain budget, in ms. `None`
5682        /// uses the module's configured/default budget; `Some(0)` cuts
5683        /// immediately (wedge bounce: a stuck request never settles, so
5684        /// waiting only delays recovery).
5685        drain_timeout_ms: Option<u64>,
5686        /// The module's `spawn_generation` when the request was received, before
5687        /// it waited in the command queue. A queued restart whose module has
5688        /// since spawned a newer process is already satisfied (see the handler).
5689        received_at_generation: u64,
5690        /// When the request entered the command queue, so the handler can log
5691        /// how long it waited behind the loop's other work.
5692        queued_at: Instant,
5693        reply: oneshot::Sender<Result<(), SuperviseError>>,
5694    },
5695    Reload {
5696        requester: Option<Principal>,
5697        reply: oneshot::Sender<Result<(), SuperviseError>>,
5698    },
5699    SetEnabled {
5700        reset_budget: bool,
5701        requester: Option<Principal>,
5702        enabled: bool,
5703        reply: oneshot::Sender<Result<bool, SuperviseError>>,
5704    },
5705    UpdateConfiguration {
5706        spec: ModuleSpec,
5707        health: HealthConfig,
5708        /// Per-module drain override from the new config; `None` re-resolves to
5709        /// the supervisor-wide default.
5710        drain_timeout_ms: Option<u64>,
5711        reply: oneshot::Sender<Result<(), SuperviseError>>,
5712    },
5713    Swap {
5714        requester: Option<Principal>,
5715        /// How long the candidate may take to register and declare itself
5716        /// ready. `None` uses [`DEFAULT_SWAP_READY_TIMEOUT`].
5717        ready_timeout: Option<Duration>,
5718        /// Answered at cutover or failure; the incumbent's drain follows.
5719        reply: oneshot::Sender<Result<SwapOutcome, SuperviseError>>,
5720    },
5721}
5722
5723/// Successful daemon-local swap disposition. Supersession leaves the incumbent
5724/// serving until an approved replacement starts with the latest configured
5725/// command; the legacy control acknowledgment does not carry this disposition.
5726#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5727pub enum SwapOutcome {
5728    Cutover,
5729    SupersededByConfigRestart,
5730}
5731
5732impl SwapOutcome {
5733    pub fn as_str(self) -> &'static str {
5734        match self {
5735            Self::Cutover => "cutover",
5736            Self::SupersededByConfigRestart => "superseded_by_config_restart",
5737        }
5738    }
5739}
5740
5741#[derive(Debug)]
5742pub enum SuperviseError {
5743    ConfigHeld {
5744        module_id: String,
5745        code: String,
5746        detail: String,
5747    },
5748    ConfigDeliveryDeferred {
5749        module_id: String,
5750    },
5751    InvalidSpec {
5752        reason: String,
5753    },
5754    Spawn {
5755        program: PathBuf,
5756        source: io::Error,
5757        cgroup_path: Option<PathBuf>,
5758    },
5759    Cgroup {
5760        module_id: String,
5761        source: io::Error,
5762    },
5763    /// CSPRNG failure generating a reserved module's launch nonce. Fail loud rather
5764    /// than spawn a reserved module without its identity binding.
5765    LaunchNonce {
5766        reason: String,
5767    },
5768    Wait {
5769        module_id: String,
5770        source: io::Error,
5771    },
5772    Kill {
5773        module_id: String,
5774        source: io::Error,
5775    },
5776    Forwarding(ForwardingError),
5777    Registry(RegistryError),
5778    ReloadUnavailable {
5779        module_id: String,
5780        reason: String,
5781    },
5782    /// An operator restart/reload was requested for a module that is currently
5783    /// disabled. Restart/reload cycle a *running* module; a disabled module must
5784    /// be explicitly re-enabled (set_enabled(true)) rather than silently started
5785    /// by a restart, so these commands are rejected instead of re-enabling it.
5786    Disabled {
5787        module_id: String,
5788    },
5789    ReloadFailed {
5790        module_id: String,
5791        reason: String,
5792    },
5793    RegistrationStillActive {
5794        module_id: String,
5795        waited: Duration,
5796    },
5797    StatePoisoned {
5798        module_id: Option<String>,
5799    },
5800    CommandClosed {
5801        module_id: String,
5802    },
5803    /// A restart or reload arrived while a swap's candidate was warming. The
5804    /// swap owns the module until it cuts over or fails; a stop or disable
5805    /// would have aborted it instead.
5806    SwapInProgress {
5807        module_id: String,
5808    },
5809    /// A swap was refused before anything was spawned.
5810    SwapRefused {
5811        module_id: String,
5812        reason: SwapRefusal,
5813    },
5814    /// A swap spawned a candidate and gave up on it. The candidate has been
5815    /// killed and its slot freed; the incumbent was left serving and was never
5816    /// drained, except in the one `CutoverLost` case described on that arm.
5817    SwapFailed {
5818        module_id: String,
5819        arm: SwapFailureArm,
5820        detail: String,
5821        /// How the candidate exited, when it exited on its own before the
5822        /// supervisor gave up on it.
5823        candidate_exit: Option<ExitReport>,
5824    },
5825}
5826
5827/// Why a swap was refused before a candidate was spawned.
5828#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5829pub enum SwapRefusal {
5830    /// The module's config does not declare `overlap: "safe"`.
5831    OverlapExclusive,
5832    /// The module is not registered, so there is no incumbent to keep serving
5833    /// and nothing a swap would improve on; a plain restart is the tool.
5834    NotRegistered,
5835    /// The module does not speak the subc wire, so a candidate could never
5836    /// register or declare itself ready.
5837    ProtocolNone,
5838    /// The supervisor lacks the forwarding table (to cut routes over) or the
5839    /// shared handle (to admit the candidate's HELLO) that a swap needs.
5840    NotConfigured,
5841    /// A swap is already open for this module.
5842    AlreadySwapping,
5843}
5844
5845impl SwapRefusal {
5846    pub fn as_str(self) -> &'static str {
5847        match self {
5848            Self::OverlapExclusive => "overlap_exclusive",
5849            Self::NotRegistered => "not_registered",
5850            Self::ProtocolNone => "protocol_none",
5851            Self::NotConfigured => "not_configured",
5852            Self::AlreadySwapping => "already_swapping",
5853        }
5854    }
5855}
5856
5857/// Which failure arm ended a swap. Every arm but one leaves the incumbent
5858/// serving and undrained; see `CutoverLost`.
5859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5860pub enum SwapFailureArm {
5861    /// The candidate process could not be started.
5862    SpawnFailed,
5863    /// The candidate did not register within the readiness budget.
5864    NeverRegistered,
5865    /// The candidate registered but did not declare itself ready in time.
5866    NeverReady,
5867    /// The candidate exited before cutover.
5868    CandidateExited,
5869    /// The candidate declared itself ready but failed its health probe.
5870    CandidateUnhealthy,
5871    /// An operator stop, disable or retire arrived while the candidate warmed.
5872    /// The candidate was killed and the operator's command then carried out on
5873    /// the incumbent.
5874    Interrupted,
5875    /// The candidate's connection closed at the moment of cutover. If it
5876    /// closed before forwarding moved, the incumbent is untouched. If it closed
5877    /// between the forwarding and registry halves of cutover, forwarding can no
5878    /// longer route to the incumbent, so the module is restarted plainly.
5879    CutoverLost,
5880}
5881
5882impl SwapFailureArm {
5883    pub fn as_str(self) -> &'static str {
5884        match self {
5885            Self::SpawnFailed => "spawn_failed",
5886            Self::NeverRegistered => "never_registered",
5887            Self::NeverReady => "never_ready",
5888            Self::CandidateExited => "candidate_exited",
5889            Self::CandidateUnhealthy => "candidate_unhealthy",
5890            Self::Interrupted => "interrupted",
5891            Self::CutoverLost => "cutover_lost",
5892        }
5893    }
5894}
5895
5896impl SuperviseError {
5897    pub(crate) fn is_config_gate_error(&self) -> bool {
5898        match self {
5899            Self::ConfigHeld { .. } => true,
5900            Self::Spawn { source, .. } => source
5901                .get_ref()
5902                .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
5903            _ => false,
5904        }
5905    }
5906}
5907
5908impl fmt::Display for SuperviseError {
5909    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5910        match self {
5911            Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
5912            Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
5913            Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
5914            Self::Spawn {
5915                program,
5916                source,
5917                cgroup_path: Some(cgroup_path),
5918            } => write!(
5919                f,
5920                "failed to place module in cgroup '{}' while spawning '{}': {source}",
5921                cgroup_path.display(),
5922                program.display()
5923            ),
5924            Self::Spawn {
5925                program,
5926                source,
5927                cgroup_path: None,
5928            } => write!(
5929                f,
5930                "failed to spawn module '{}': {source}",
5931                program.display()
5932            ),
5933            Self::Cgroup { module_id, source } => {
5934                write!(
5935                    f,
5936                    "failed to prepare cgroup for module '{module_id}': {source}"
5937                )
5938            }
5939            Self::LaunchNonce { reason } => {
5940                write!(
5941                    f,
5942                    "failed to generate reserved-module launch nonce: {reason}"
5943                )
5944            }
5945            Self::Wait { module_id, source } => {
5946                write!(f, "failed to wait for module '{module_id}': {source}")
5947            }
5948            Self::Kill { module_id, source } => {
5949                write!(f, "failed to kill module '{module_id}': {source}")
5950            }
5951            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
5952            Self::Registry(err) => write!(f, "registry error: {err}"),
5953            Self::ReloadUnavailable { module_id, reason } => {
5954                write!(f, "reload unavailable for module '{module_id}': {reason}")
5955            }
5956            Self::Disabled { module_id } => {
5957                write!(
5958                    f,
5959                    "module '{module_id}' is disabled; enable it before restart or reload"
5960                )
5961            }
5962            Self::ReloadFailed { module_id, reason } => {
5963                write!(f, "reload failed for module '{module_id}': {reason}")
5964            }
5965            Self::RegistrationStillActive { module_id, waited } => write!(
5966                f,
5967                "module '{module_id}' registration remained active after waiting {waited:?}"
5968            ),
5969            Self::StatePoisoned { module_id } => match module_id {
5970                Some(module_id) => {
5971                    write!(f, "supervisor state for module '{module_id}' was poisoned")
5972                }
5973                None => write!(f, "supervisor state was poisoned"),
5974            },
5975            Self::CommandClosed { module_id } => {
5976                write!(
5977                    f,
5978                    "supervisor command channel for module '{module_id}' is closed"
5979                )
5980            }
5981            Self::SwapInProgress { module_id } => write!(
5982                f,
5983                "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
5984            ),
5985            Self::SwapRefused { module_id, reason } => match reason {
5986                SwapRefusal::OverlapExclusive => write!(
5987                    f,
5988                    "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"
5989                ),
5990                SwapRefusal::NotRegistered => write!(
5991                    f,
5992                    "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
5993                ),
5994                SwapRefusal::ProtocolNone => write!(
5995                    f,
5996                    "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
5997                ),
5998                SwapRefusal::NotConfigured => write!(
5999                    f,
6000                    "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
6001                ),
6002                SwapRefusal::AlreadySwapping => {
6003                    write!(f, "module '{module_id}' is already being swapped")
6004                }
6005            },
6006            Self::SwapFailed {
6007                module_id,
6008                arm,
6009                detail,
6010                ..
6011            } => write!(
6012                f,
6013                "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
6014                arm.as_str()
6015            ),
6016        }
6017    }
6018}
6019
6020impl Error for SuperviseError {
6021    fn source(&self) -> Option<&(dyn Error + 'static)> {
6022        match self {
6023            Self::Spawn { source, .. }
6024            | Self::Cgroup { source, .. }
6025            | Self::Wait { source, .. }
6026            | Self::Kill { source, .. } => Some(source),
6027            Self::Forwarding(err) => Some(err),
6028            Self::Registry(err) => Some(err),
6029            Self::LaunchNonce { .. }
6030            | Self::ConfigDeliveryDeferred { .. }
6031            | Self::ConfigHeld { .. }
6032            | Self::InvalidSpec { .. }
6033            | Self::ReloadUnavailable { .. }
6034            | Self::Disabled { .. }
6035            | Self::ReloadFailed { .. }
6036            | Self::RegistrationStillActive { .. }
6037            | Self::StatePoisoned { .. }
6038            | Self::CommandClosed { .. }
6039            | Self::SwapInProgress { .. }
6040            | Self::SwapRefused { .. }
6041            | Self::SwapFailed { .. } => None,
6042        }
6043    }
6044}
6045
6046pub(crate) fn validate_spec(spec: &ModuleSpec) -> Result<(), SuperviseError> {
6047    if spec.carry_containment && spec.overlap == ModuleOverlap::Safe {
6048        return Err(SuperviseError::InvalidSpec {
6049            reason: "carry_containment cannot be combined with overlap: safe".to_owned(),
6050        });
6051    }
6052    if spec.module_id.trim().is_empty() {
6053        return Err(SuperviseError::InvalidSpec {
6054            reason: "module_id must not be empty".to_string(),
6055        });
6056    }
6057
6058    Ok(())
6059}
6060
6061#[derive(Debug, Default)]
6062struct HealthProbeRuntime {
6063    spawn_generation: Option<u64>,
6064    configured_health: Option<HealthConfig>,
6065    registered_connection: Option<crate::ConnectionId>,
6066    advertised: bool,
6067    next_probe_at: Option<Instant>,
6068    probe_index: u64,
6069}
6070
6071fn running_protocol(spec: &ModuleSpec, snapshot: &SharedSnapshot) -> ModuleProtocol {
6072    lock_snapshot(snapshot)
6073        .ok()
6074        .and_then(|state| state.spawned_protocol)
6075        .unwrap_or(spec.protocol)
6076}
6077
6078impl HealthProbeRuntime {
6079    fn refresh_registration(
6080        &mut self,
6081        spec: &ModuleSpec,
6082        runtime: &SupervisorRuntimeConfig,
6083        registry: &Registry,
6084        snapshot: &SharedSnapshot,
6085    ) {
6086        let generation = lock_snapshot(snapshot)
6087            .ok()
6088            .map(|state| state.spawn_generation);
6089        if self.spawn_generation != generation {
6090            // A replacement cannot reuse a deadline that is already due for its
6091            // predecessor. HTTP children get a full cadence to start; wire
6092            // children still wait for their own health-advertising HELLO.
6093            *self = Self {
6094                spawn_generation: generation,
6095                ..Self::default()
6096            };
6097        }
6098        if self.configured_health.as_ref() != Some(&runtime.health) {
6099            self.configured_health = Some(runtime.health.clone());
6100            self.next_probe_at = None;
6101            self.registered_connection = None;
6102            self.probe_index = 0;
6103        }
6104        // A non-wire process never registers. Only an explicitly configured
6105        // HTTP endpoint can arm its health probe; an absent HELLO is not a
6106        // health failure for that kind of process.
6107        if running_protocol(spec, snapshot) == ModuleProtocol::None {
6108            self.registered_connection = None;
6109            self.advertised = runtime.health.http.is_some();
6110            if !self.advertised {
6111                self.next_probe_at = None;
6112                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6113                    let unknown = ModuleHealthStatus::default();
6114                    if state.health != unknown {
6115                        state.health = unknown;
6116                        state.last_probe_evidence = None;
6117                    }
6118                });
6119            } else if self.next_probe_at.is_none() {
6120                self.next_probe_at = Some(
6121                    Instant::now()
6122                        + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
6123                );
6124            }
6125            return;
6126        }
6127
6128        let registration = match registry.get_module(&spec.module_id) {
6129            Ok(registration) => registration,
6130            Err(err) => {
6131                warn!(module_id = %spec.module_id, error = %err, "health prober could not read registry");
6132                self.advertised = false;
6133                self.next_probe_at = None;
6134                return;
6135            }
6136        };
6137
6138        let Some(registration) = registration else {
6139            self.registered_connection = None;
6140            self.advertised = false;
6141            self.next_probe_at = None;
6142            return;
6143        };
6144
6145        let advertised = registration
6146            .control_ops
6147            .iter()
6148            .any(|op| op == MODULE_CONTROL_OP_HEALTH_CHECK);
6149        if !advertised {
6150            self.registered_connection = Some(registration.connection_id);
6151            self.advertised = false;
6152            self.next_probe_at = None;
6153            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6154                if state.health.status != SupervisorHealthStatus::Unknown
6155                    || state.health.consecutive_failures != 0
6156                    || state.health.last_probe_ms.is_some()
6157                    || state.health.detail.is_some()
6158                    || state.health.metrics.is_some()
6159                {
6160                    state.health.status = SupervisorHealthStatus::Unknown;
6161                    state.last_probe_evidence = None;
6162                    state.health.consecutive_failures = 0;
6163                    state.health.last_probe_ms = None;
6164                    state.health.detail = None;
6165                    state.health.metrics = None;
6166                }
6167            });
6168            return;
6169        }
6170
6171        let reregistered = self.registered_connection != Some(registration.connection_id);
6172        self.registered_connection = Some(registration.connection_id);
6173        self.advertised = true;
6174        if reregistered || self.next_probe_at.is_none() {
6175            self.probe_index = 0;
6176            self.next_probe_at = Some(
6177                Instant::now() + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
6178            );
6179            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6180                state.health.status = SupervisorHealthStatus::Unknown;
6181                state.last_probe_evidence = None;
6182                state.health.consecutive_failures = 0;
6183                state.health.detail = None;
6184                state.health.metrics = None;
6185            });
6186        }
6187    }
6188
6189    fn wake_at(&self) -> Option<Instant> {
6190        if !self.advertised {
6191            return None;
6192        }
6193        self.next_probe_at
6194    }
6195
6196    fn due(&self) -> bool {
6197        self.advertised
6198            && self
6199                .next_probe_at
6200                .is_some_and(|next| Instant::now() >= next)
6201    }
6202
6203    fn schedule_next(&mut self, spec: &ModuleSpec, cadence: Duration) {
6204        self.probe_index = self.probe_index.wrapping_add(1);
6205        self.next_probe_at = Some(
6206            Instant::now() + jittered_health_delay(&spec.module_id, self.probe_index, cadence),
6207        );
6208    }
6209}
6210
6211/// Evidence is separate from diagnostic prose so host starvation can hold only
6212/// silence-based restarts. A missing lane is still actionable during overload;
6213/// a timeout can instead mean the host has not scheduled a healthy module.
6214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6215enum HealthProbeEvidence {
6216    /// The module's control lane is gone. Proof of death.
6217    LaneDead,
6218    /// No reply within the deadline. Proves nothing about the module's state.
6219    NoAnswer,
6220    /// The module replied, but not with a usable health report. Proves it is alive.
6221    BadAnswer,
6222    /// The daemon could not ask. Says nothing about the module.
6223    Misconfigured,
6224}
6225
6226#[derive(Debug)]
6227struct HealthProbeError {
6228    evidence: HealthProbeEvidence,
6229    message: String,
6230}
6231
6232impl HealthProbeError {
6233    fn lane_dead(message: impl Into<String>) -> Self {
6234        Self::with(HealthProbeEvidence::LaneDead, message)
6235    }
6236
6237    fn no_answer(message: impl Into<String>) -> Self {
6238        Self::with(HealthProbeEvidence::NoAnswer, message)
6239    }
6240
6241    fn bad_answer(message: impl Into<String>) -> Self {
6242        Self::with(HealthProbeEvidence::BadAnswer, message)
6243    }
6244
6245    fn misconfigured(message: impl Into<String>) -> Self {
6246        Self::with(HealthProbeEvidence::Misconfigured, message)
6247    }
6248
6249    fn with(evidence: HealthProbeEvidence, message: impl Into<String>) -> Self {
6250        Self {
6251            evidence,
6252            message: message.into(),
6253        }
6254    }
6255
6256    /// Whether this observation is proof the module cannot serve.
6257    ///
6258    /// Only `LaneDead` qualifies. `NoAnswer` is deliberately excluded: it is the
6259    /// variant that fires under CPU starvation, and treating it as proof is the
6260    /// defect this enum exists to make impossible to reintroduce silently.
6261    ///
6262    /// Outside a host-overload hold, silence still reaches the normal failure
6263    /// threshold so an isolated, genuinely wedged module can recover.
6264    #[allow(dead_code)]
6265    fn is_proof_of_death(&self) -> bool {
6266        matches!(self.evidence, HealthProbeEvidence::LaneDead)
6267    }
6268
6269    /// Short stable label for logs and the health snapshot.
6270    ///
6271    /// An operator reading `ck health` currently cannot tell "the module is gone"
6272    /// from "the module did not answer in five seconds", because both render as
6273    /// prose in the same field. These labels are what make the two
6274    /// distinguishable at a glance, and they are what a later restart-policy
6275    /// change will be argued from.
6276    fn label(&self) -> &'static str {
6277        match self.evidence {
6278            HealthProbeEvidence::LaneDead => "lane-dead",
6279            HealthProbeEvidence::NoAnswer => "no-answer",
6280            HealthProbeEvidence::BadAnswer => "bad-answer",
6281            HealthProbeEvidence::Misconfigured => "daemon-misconfigured",
6282        }
6283    }
6284}
6285
6286impl fmt::Display for HealthProbeError {
6287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6288        f.write_str(&self.message)
6289    }
6290}
6291
6292async fn run_health_probe_cycle(
6293    spec: &ModuleSpec,
6294    runtime: &SupervisorRuntimeConfig,
6295    registry: &Registry,
6296    process_liveness: &SupervisorProcessLiveness,
6297    snapshot: &SharedSnapshot,
6298    child: &mut Option<SupervisedChild>,
6299) {
6300    let now_ms = unix_ms_now();
6301    let delivery_probe = match &runtime.config_delivery {
6302        Some(delivery) => {
6303            delivery
6304                .health_probe(&spec.module_id, runtime.forwarding.as_deref(), registry)
6305                .await
6306        }
6307        None => None,
6308    };
6309    let http = (running_protocol(spec, snapshot) == ModuleProtocol::None)
6310        .then_some(runtime.health.http.as_deref())
6311        .flatten();
6312    let result = match http {
6313        Some(url) => probe_http_health(url, runtime.health.deadline)
6314            .await
6315            .map(|report| (report, None)),
6316        None => probe_module_health_from(&spec.module_id, runtime, None)
6317            .await
6318            .map(|(report, probed)| (report, Some(probed))),
6319    };
6320    match result {
6321        Ok((report, probed)) => {
6322            handle_health_report(
6323                spec,
6324                runtime,
6325                registry,
6326                process_liveness,
6327                snapshot,
6328                child,
6329                report,
6330                now_ms,
6331                delivery_probe,
6332                probed,
6333            )
6334            .await;
6335        }
6336        Err(err) => {
6337            if http.is_some() {
6338                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6339                    state.health.status = SupervisorHealthStatus::Failing;
6340                });
6341            }
6342            handle_health_probe_failure(
6343                spec,
6344                runtime,
6345                registry,
6346                process_liveness,
6347                snapshot,
6348                child,
6349                err,
6350                now_ms,
6351                delivery_probe,
6352            )
6353            .await;
6354        }
6355    }
6356}
6357
6358pub(crate) struct HttpProbeTarget<'a> {
6359    address: std::net::SocketAddr,
6360    localhost: bool,
6361    authority: &'a str,
6362    path: String,
6363}
6364
6365/// Resolve only literal loopback endpoints, without DNS, redirects, proxies,
6366/// or TLS. A URL cannot turn a local health check into an outbound connection.
6367pub(crate) fn parse_http_probe_url(url: &str) -> Result<HttpProbeTarget<'_>, String> {
6368    if url.bytes().any(|b| b <= b' ' || b == 127) || url.contains('#') {
6369        return Err("must not contain whitespace, controls, or a fragment".into());
6370    }
6371    let rest = url
6372        .strip_prefix("http://")
6373        .ok_or("must use plain http://")?;
6374    let split = rest.find(['/', '?']).unwrap_or(rest.len());
6375    let (authority, suffix) = rest.split_at(split);
6376    let (host, port) = if let Some(rest) = authority.strip_prefix("[::1]") {
6377        ("::1", rest)
6378    } else {
6379        let split = authority.find(':').unwrap_or(authority.len());
6380        authority.split_at(split)
6381    };
6382    let ip: std::net::IpAddr = match host {
6383        "127.0.0.1" | "localhost" => std::net::Ipv4Addr::LOCALHOST.into(),
6384        "::1" => std::net::Ipv6Addr::LOCALHOST.into(),
6385        _ => return Err("host must be 127.0.0.1, [::1], or localhost".into()),
6386    };
6387    let port = if port.is_empty() {
6388        80
6389    } else {
6390        port.strip_prefix(':')
6391            .and_then(|p| p.parse::<u16>().ok())
6392            .filter(|p| *p > 0)
6393            .ok_or("must have a valid nonzero TCP port")?
6394    };
6395    let path = if suffix.is_empty() {
6396        "/".into()
6397    } else if suffix.starts_with('?') {
6398        format!("/{suffix}")
6399    } else {
6400        suffix.into()
6401    };
6402    Ok(HttpProbeTarget {
6403        address: std::net::SocketAddr::new(ip, port),
6404        localhost: host == "localhost",
6405        authority,
6406        path,
6407    })
6408}
6409
6410async fn probe_http_health(
6411    url: &str,
6412    deadline: Duration,
6413) -> Result<HealthReport, HealthProbeError> {
6414    use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
6415    let target = parse_http_probe_url(url).map_err(HealthProbeError::misconfigured)?;
6416    // Keep partial diagnostics outside the timed future so cancellation does
6417    // not discard a status line or body bytes already received.
6418    let mut response_status = String::new();
6419    let mut body = Vec::new();
6420    let probe = async {
6421        // Resolve localhost ourselves so a hosts-file override cannot turn
6422        // this into an outbound request, while IPv6-only local servers work.
6423        let connection = match tokio::net::TcpStream::connect(target.address).await {
6424            Err(_) if target.localhost => {
6425                tokio::net::TcpStream::connect((
6426                    std::net::Ipv6Addr::LOCALHOST,
6427                    target.address.port(),
6428                ))
6429                .await
6430            }
6431            result => result,
6432        };
6433        let mut stream = connection.map_err(|error| {
6434            HealthProbeError::no_answer(format!("HTTP connect failed: {error}"))
6435        })?;
6436        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
6437            .map_err(|error| HealthProbeError::no_answer(format!("HTTP write failed: {error}")))?;
6438        let mut reader = BufReader::new(stream);
6439        let mut budget = 16 * 1024;
6440        let status = http_line(&mut reader, &mut budget).await?;
6441        let mut words = status.split_ascii_whitespace();
6442        let version = words.next();
6443        let code = words
6444            .next()
6445            .filter(|word| word.len() == 3)
6446            .and_then(|word| word.parse::<u16>().ok());
6447        if !matches!(version, Some("HTTP/1.1" | "HTTP/1.0"))
6448            || !code.is_some_and(|code| (100..600).contains(&code))
6449        {
6450            return Err(HealthProbeError::bad_answer(format!(
6451                "invalid HTTP status: {status}"
6452            )));
6453        }
6454        let code = code.expect("validated status code");
6455        response_status = status.clone();
6456        let mut length = None;
6457        let mut chunked = false;
6458        loop {
6459            let line = http_line(&mut reader, &mut budget).await?;
6460            if line.is_empty() {
6461                break;
6462            }
6463            if let Some((name, value)) = line.split_once(':') {
6464                if name.eq_ignore_ascii_case("content-length") {
6465                    length = Some(value.trim().parse::<u64>().map_err(|_| {
6466                        HealthProbeError::bad_answer("invalid HTTP Content-Length")
6467                    })?);
6468                } else if name.eq_ignore_ascii_case("transfer-encoding") {
6469                    chunked = value.trim().eq_ignore_ascii_case("chunked");
6470                }
6471            }
6472        }
6473        if chunked {
6474            while body.len() < 200 {
6475                let line = http_line(&mut reader, &mut budget).await?;
6476                let size = u64::from_str_radix(line.split(';').next().unwrap_or("").trim(), 16)
6477                    .map_err(|_| HealthProbeError::bad_answer("invalid HTTP chunk size"))?;
6478                if size == 0 {
6479                    break;
6480                }
6481                let count = size.min((200 - body.len()) as u64) as usize;
6482                let start = body.len();
6483                (&mut reader)
6484                    .take(count as u64)
6485                    .read_to_end(&mut body)
6486                    .await
6487                    .map_err(|error| {
6488                        HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
6489                    })?;
6490                if body.len() - start != count {
6491                    return Err(HealthProbeError::bad_answer("truncated HTTP chunk"));
6492                }
6493                if size > count as u64 || body.len() == 200 {
6494                    break;
6495                }
6496                if !http_line(&mut reader, &mut budget).await?.is_empty() {
6497                    return Err(HealthProbeError::bad_answer("invalid HTTP chunk delimiter"));
6498                }
6499            }
6500        } else {
6501            reader
6502                .take(length.unwrap_or(200).min(200))
6503                .read_to_end(&mut body)
6504                .await
6505                .map_err(|error| {
6506                    HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
6507                })?;
6508        }
6509        if (200..300).contains(&code) {
6510            Ok(HealthReport::ok())
6511        } else {
6512            Err(HealthProbeError::bad_answer(
6513                "HTTP health endpoint returned non-2xx",
6514            ))
6515        }
6516    };
6517    let mut result = timeout(deadline, probe).await.unwrap_or_else(|_| {
6518        Err(HealthProbeError::no_answer(format!(
6519            "HTTP probe timed out after {deadline:?}"
6520        )))
6521    });
6522    if let Err(error) = &mut result {
6523        if !response_status.is_empty() {
6524            error.message = format!(
6525                "{}; {response_status}: {}",
6526                error.message,
6527                String::from_utf8_lossy(&body)
6528            );
6529        }
6530    }
6531    result
6532}
6533
6534async fn http_line(
6535    reader: &mut tokio::io::BufReader<tokio::net::TcpStream>,
6536    remaining: &mut usize,
6537) -> Result<String, HealthProbeError> {
6538    use tokio::io::{AsyncBufReadExt, AsyncReadExt};
6539    let mut line = Vec::new();
6540    (&mut *reader)
6541        .take(*remaining as u64)
6542        .read_until(b'\n', &mut line)
6543        .await
6544        .map_err(|error| {
6545            HealthProbeError::no_answer(format!("HTTP header read failed: {error}"))
6546        })?;
6547    *remaining -= line.len();
6548    if !line.ends_with(b"\r\n") {
6549        return Err(HealthProbeError::bad_answer(
6550            "HTTP headers are incomplete or exceed 16 KiB",
6551        ));
6552    }
6553    line.truncate(line.len() - 2);
6554    String::from_utf8(line).map_err(|_| HealthProbeError::bad_answer("HTTP header is not UTF-8"))
6555}
6556
6557async fn probe_module_health(
6558    module_id: &str,
6559    runtime: &SupervisorRuntimeConfig,
6560    drain_deadline: Option<Instant>,
6561) -> Result<HealthReport, HealthProbeError> {
6562    probe_module_health_from(module_id, runtime, drain_deadline)
6563        .await
6564        .map(|(report, _)| report)
6565}
6566
6567/// [`probe_module_health`], also returning the connection whose registration
6568/// answered, so its answer is credited to that registration and no other.
6569async fn probe_module_health_from(
6570    module_id: &str,
6571    runtime: &SupervisorRuntimeConfig,
6572    drain_deadline: Option<Instant>,
6573) -> Result<(HealthReport, ConnectionId), HealthProbeError> {
6574    let Some(forwarding) = runtime.forwarding.as_ref() else {
6575        return Err(HealthProbeError::misconfigured(
6576            "supervisor was not configured with a forwarding table",
6577        ));
6578    };
6579    let probe_started_at = Instant::now();
6580    let mut deadline = probe_started_at + runtime.health.deadline;
6581    if let Some(drain_deadline) = drain_deadline {
6582        deadline = deadline.min(drain_deadline);
6583    }
6584    let pending = if drain_deadline.is_some() {
6585        forwarding.begin_drain_health_probe_rpc_for(
6586            module_id,
6587            MODULE_CONTROL_OP_HEALTH_CHECK,
6588            probe_started_at,
6589            deadline,
6590        )
6591    } else {
6592        forwarding.begin_health_probe_rpc_for(
6593            module_id,
6594            MODULE_CONTROL_OP_HEALTH_CHECK,
6595            probe_started_at,
6596            deadline,
6597        )
6598    }
6599    .map_err(|err| {
6600        // The endpoint is not registered, so there is no live control lane to
6601        // ask. That is the module being absent, not slow.
6602        HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
6603    })?;
6604    let probed = pending.endpoint.connection_id;
6605    await_health_probe(forwarding, pending, deadline, runtime.health.deadline)
6606        .await
6607        .map(|report| (report, probed))
6608}
6609
6610/// [`probe_module_health`] for one endpoint rather than the id's active one.
6611///
6612/// A swap probes two processes that no by-id lookup reaches: its candidate
6613/// before cutover, and its superseded incumbent (for busy gauges) while the
6614/// incumbent drains. `deadline_cap` bounds the probe the way a drain deadline
6615/// bounds the by-id drain probe.
6616async fn probe_endpoint_health(
6617    endpoint: crate::ModuleEndpointId,
6618    runtime: &SupervisorRuntimeConfig,
6619    deadline_cap: Option<Instant>,
6620) -> Result<HealthReport, HealthProbeError> {
6621    let Some(forwarding) = runtime.forwarding.as_ref() else {
6622        return Err(HealthProbeError::misconfigured(
6623            "supervisor was not configured with a forwarding table",
6624        ));
6625    };
6626    let probe_started_at = Instant::now();
6627    let mut deadline = probe_started_at + runtime.health.deadline;
6628    if let Some(cap) = deadline_cap {
6629        deadline = deadline.min(cap);
6630    }
6631    let pending = forwarding
6632        .begin_endpoint_health_probe_rpc_for(
6633            endpoint,
6634            MODULE_CONTROL_OP_HEALTH_CHECK,
6635            probe_started_at,
6636            deadline,
6637        )
6638        .map_err(|err| {
6639            HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
6640        })?;
6641    await_health_probe(forwarding, pending, deadline, runtime.health.deadline).await
6642}
6643
6644/// Send a begun health probe and classify its answer.
6645async fn await_health_probe(
6646    forwarding: &ForwardingTable,
6647    pending: PendingModuleControlRpc,
6648    deadline: Instant,
6649    probe_budget: Duration,
6650) -> Result<HealthReport, HealthProbeError> {
6651    let PendingModuleControlRpc {
6652        endpoint,
6653        module_sink,
6654        negotiated_ver,
6655        corr,
6656        receiver,
6657    } = pending;
6658    let body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).map_err(|err| {
6659        HealthProbeError::misconfigured(format!("failed to encode health.check: {err}"))
6660    })?;
6661    let frame = Frame::build_with_version(
6662        negotiated_ver,
6663        FrameType::Request,
6664        control_flags(),
6665        0,
6666        0,
6667        corr,
6668        body,
6669    )
6670    .map_err(|err| {
6671        HealthProbeError::misconfigured(format!("failed to build health.check frame: {err}"))
6672    })?;
6673
6674    // The enqueue itself must be bounded by the probe deadline: FrameSink.send
6675    // blocks waiting for capacity when the module's egress queue is full, and an
6676    // unbounded await here freezes the whole supervision actor (it stops polling
6677    // Child::wait and supervisor commands), making the module unrecoverable
6678    // in-band. On timeout the probe fails like any transport failure.
6679    match timeout_at(deadline, module_sink.send(frame)).await {
6680        Ok(Ok(())) => {}
6681        Ok(Err(err)) => {
6682            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
6683            // A closed sink means the module's egress channel is gone -- the
6684            // receiving half is dropped when its connection tears down. Proof.
6685            return Err(HealthProbeError::lane_dead(format!(
6686                "failed to send health.check: {err}"
6687            )));
6688        }
6689        Err(_elapsed) => {
6690            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
6691            // A full egress queue means the module is not draining its socket, which
6692            // is consistent with a wedged module AND with one whose reader is merely
6693            // starved. Silence, not proof.
6694            return Err(HealthProbeError::no_answer(
6695                "health.check send timed out before enqueue (module egress full)",
6696            ));
6697        }
6698    }
6699
6700    match timeout_at(deadline, receiver).await {
6701        Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => Err(HealthProbeError::bad_answer(
6702            "health.check returned an unexpected config response",
6703        )),
6704        // Each arm records WHAT WAS OBSERVED. Four of them are the module
6705        // demonstrably answering -- rejected, non-health, malformed, wrong op --
6706        // and those prove it is alive even though the probe failed.
6707        Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
6708            response.health_report().ok_or_else(|| {
6709                HealthProbeError::bad_answer("health.check RPC returned a non-health response")
6710            })
6711        }
6712        Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => Err(HealthProbeError::bad_answer(
6713            format!("health.check rejected: {}", body.message),
6714        )),
6715        Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
6716            Err(HealthProbeError::lane_dead(message))
6717        }
6718        Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
6719            Err(HealthProbeError::bad_answer(message))
6720        }
6721        Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
6722            Err(HealthProbeError::bad_answer(format!(
6723                "expected module-control op '{expected}', got '{actual}'"
6724            )))
6725        }
6726        // A reply that crosses the deadline before this waiter observes it is
6727        // still proof of life. The forwarding path records its end-to-end latency
6728        // before delivering this classification.
6729        Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => Err(HealthProbeError::bad_answer(
6730            "module answered health.check after its daemon deadline",
6731        )),
6732        Ok(Err(_)) => Err(HealthProbeError::misconfigured(
6733            "health.check waiter was canceled before the module responded",
6734        )),
6735        Err(_) => {
6736            let _ = forwarding.tombstone_health_probe_rpc(endpoint, corr);
6737            Err(HealthProbeError::no_answer(format!(
6738                "module did not answer health.check within {probe_budget:?}"
6739            )))
6740        }
6741    }
6742}
6743
6744/// Act on a health probe's answer. `probed` is the connection whose
6745/// registration answered (`None` for an HTTP probe, which reaches no
6746/// registration); only that registration's spawn is credited with readiness.
6747#[allow(clippy::too_many_arguments)]
6748async fn handle_health_report(
6749    spec: &ModuleSpec,
6750    runtime: &SupervisorRuntimeConfig,
6751    registry: &Registry,
6752    process_liveness: &SupervisorProcessLiveness,
6753    snapshot: &SharedSnapshot,
6754    child: &mut Option<SupervisedChild>,
6755    report: HealthReport,
6756    now_ms: u64,
6757    delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
6758    probed: Option<ConnectionId>,
6759) {
6760    let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
6761        (Some(delivery), Some(probe)) => {
6762            delivery
6763                .health_result(
6764                    &spec.module_id,
6765                    runtime.forwarding.as_deref(),
6766                    registry,
6767                    probe,
6768                    report.status == HealthStatus::Ok,
6769                )
6770                .await
6771        }
6772        _ => false,
6773    };
6774    if let (Some(delivery), Some(spawn)) = (
6775        &runtime.config_delivery,
6776        child
6777            .as_ref()
6778            .and_then(|child| child.config_delivery.as_ref()),
6779    ) {
6780        delivery
6781            .mark_readiness(
6782                &spec.module_id,
6783                runtime.forwarding.as_deref(),
6784                probed,
6785                spawn,
6786                report.status == HealthStatus::Ok,
6787            )
6788            .await;
6789    }
6790    let status = supervisor_health_status(report.status);
6791    let detail = report.detail.clone();
6792    let metrics = truncate_health_metrics(report.metrics);
6793    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6794        state.health.status = status;
6795        state.last_probe_evidence = None;
6796        state.health.last_probe_ms = Some(now_ms);
6797        state.health.detail = detail.clone();
6798        state.health.metrics = metrics.clone();
6799        state.health.consecutive_failures = 0;
6800        state.failed_retry.observe_health(
6801            report.status == HealthStatus::Ok,
6802            runtime.restart_policy.window,
6803        );
6804    });
6805
6806    if delivery_failed {
6807        return;
6808    }
6809    let action = match report.status {
6810        HealthStatus::Ok => return,
6811        HealthStatus::Degraded => runtime.health.on_degraded,
6812        HealthStatus::Failing => runtime.health.on_failing,
6813    };
6814    apply_l3_health_action(
6815        spec,
6816        runtime,
6817        registry,
6818        process_liveness,
6819        snapshot,
6820        child,
6821        status,
6822        detail.as_deref(),
6823        action,
6824        now_ms,
6825    )
6826    .await;
6827}
6828
6829#[allow(clippy::too_many_arguments)]
6830async fn handle_health_probe_failure(
6831    spec: &ModuleSpec,
6832    runtime: &SupervisorRuntimeConfig,
6833    registry: &Registry,
6834    process_liveness: &SupervisorProcessLiveness,
6835    snapshot: &SharedSnapshot,
6836    child: &mut Option<SupervisedChild>,
6837    err: HealthProbeError,
6838    now_ms: u64,
6839    delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
6840) {
6841    let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
6842        (Some(delivery), Some(probe)) => {
6843            delivery
6844                .health_result(
6845                    &spec.module_id,
6846                    runtime.forwarding.as_deref(),
6847                    registry,
6848                    probe,
6849                    false,
6850                )
6851                .await
6852        }
6853        _ => false,
6854    };
6855    let threshold = runtime.health.failure_threshold.max(1);
6856    let held = if err.evidence == HealthProbeEvidence::NoAnswer {
6857        runtime.host_health.record_late_module(&spec.module_id)
6858    } else {
6859        false
6860    };
6861    let mut failures = 0;
6862    // Carry the evidence class into the operator-visible detail. Without it,
6863    // "module did not answer within 5s" and "the control lane is gone" are two
6864    // prose strings in the same field, and the reader has to know the codebase to
6865    // tell which one is proof of anything.
6866    let detail = if held {
6867        format!("[{}] {err}; host overloaded", err.label())
6868    } else {
6869        format!("[{}] {err}", err.label())
6870    };
6871    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6872        state.last_probe_evidence = Some(err.evidence);
6873        state
6874            .failed_retry
6875            .observe_health(false, runtime.restart_policy.window);
6876        // A failed wire probe invalidates the last report, even before the
6877        // restart threshold. HTTP probes already mark failures as Failing.
6878        if held {
6879            state.health.status = SupervisorHealthStatus::Degraded;
6880        } else if state.spawned_protocol.unwrap_or(spec.protocol) == ModuleProtocol::Subc {
6881            state.health.status = SupervisorHealthStatus::Unknown;
6882        }
6883        state.health.last_probe_ms = Some(now_ms);
6884        // Held silence breaks the streak: after the host recovers, only new
6885        // failures count. Replaying pre-overload misses would restart immediately.
6886        state.health.consecutive_failures = if held {
6887            0
6888        } else {
6889            state.health.consecutive_failures.saturating_add(1)
6890        };
6891        state.health.detail = Some(detail.clone());
6892        state.health.metrics = None;
6893        failures = state.health.consecutive_failures;
6894    });
6895
6896    if delivery_failed {
6897        return;
6898    }
6899    if held || failures < threshold {
6900        warn!(
6901            module_id = %spec.module_id,
6902            consecutive_failures = failures,
6903            threshold,
6904            evidence = err.label(),
6905            detail = %detail,
6906            "health.check probe failed"
6907        );
6908        return;
6909    }
6910
6911    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6912        state.state = ModuleState::Unresponsive;
6913        state.health.status = SupervisorHealthStatus::Unresponsive;
6914    });
6915    // The evidence class is logged at the kill site because this is the line an
6916    // operator reads after an unexplained restart. A streak of `no-answer` under
6917    // machine load is the known false-positive shape; a `lane-dead` is not.
6918    if runtime.health.critical {
6919        error!(
6920            module_id = %spec.module_id,
6921            status = "unresponsive",
6922            evidence = err.label(),
6923            detail = %detail,
6924            "critical module health alert"
6925        );
6926    } else {
6927        warn!(
6928            module_id = %spec.module_id,
6929            status = "unresponsive",
6930            evidence = err.label(),
6931            detail = %detail,
6932            "module health threshold breached"
6933        );
6934    }
6935    if let Err(err) = health_restart_child(
6936        spec,
6937        runtime,
6938        registry,
6939        process_liveness,
6940        snapshot,
6941        child,
6942        SupervisorHealthStatus::Unresponsive,
6943        Some(&detail),
6944        now_ms,
6945    )
6946    .await
6947    {
6948        error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
6949    }
6950}
6951
6952#[allow(clippy::too_many_arguments)]
6953async fn apply_l3_health_action(
6954    spec: &ModuleSpec,
6955    runtime: &SupervisorRuntimeConfig,
6956    registry: &Registry,
6957    process_liveness: &SupervisorProcessLiveness,
6958    snapshot: &SharedSnapshot,
6959    child: &mut Option<SupervisedChild>,
6960    status: SupervisorHealthStatus,
6961    detail: Option<&str>,
6962    action: HealthAction,
6963    now_ms: u64,
6964) {
6965    record_health_action(snapshot, &spec.module_id, action.to_string(), now_ms);
6966    match action {
6967        HealthAction::Report => {
6968            info!(
6969                module_id = %spec.module_id,
6970                status = ?status,
6971                detail,
6972                "module reported non-ok health"
6973            );
6974        }
6975        HealthAction::Alert => {
6976            error!(
6977                module_id = %spec.module_id,
6978                status = ?status,
6979                detail,
6980                "module health alert"
6981            );
6982        }
6983        HealthAction::Restart => {
6984            if let Err(err) = health_restart_child(
6985                spec,
6986                runtime,
6987                registry,
6988                process_liveness,
6989                snapshot,
6990                child,
6991                status,
6992                detail,
6993                now_ms,
6994            )
6995            .await
6996            {
6997                error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
6998            }
6999        }
7000    }
7001}
7002
7003#[allow(clippy::too_many_arguments)]
7004async fn health_restart_child(
7005    spec: &ModuleSpec,
7006    runtime: &SupervisorRuntimeConfig,
7007    registry: &Registry,
7008    process_liveness: &SupervisorProcessLiveness,
7009    snapshot: &SharedSnapshot,
7010    child: &mut Option<SupervisedChild>,
7011    status: SupervisorHealthStatus,
7012    detail: Option<&str>,
7013    now_ms: u64,
7014) -> Result<(), SuperviseError> {
7015    budgeted_restart_child(
7016        spec,
7017        runtime,
7018        registry,
7019        process_liveness,
7020        snapshot,
7021        child,
7022        status,
7023        detail,
7024        now_ms,
7025        true,
7026    )
7027    .await
7028}
7029
7030#[allow(clippy::too_many_arguments)]
7031async fn budgeted_restart_child(
7032    spec: &ModuleSpec,
7033    runtime: &SupervisorRuntimeConfig,
7034    registry: &Registry,
7035    process_liveness: &SupervisorProcessLiveness,
7036    snapshot: &SharedSnapshot,
7037    child: &mut Option<SupervisedChild>,
7038    status: SupervisorHealthStatus,
7039    detail: Option<&str>,
7040    now_ms: u64,
7041    health_failure: bool,
7042) -> Result<(), SuperviseError> {
7043    if let Some(error) = runtime
7044        .config_delivery
7045        .as_ref()
7046        .and_then(|delivery| delivery.0.check_module_hold(&spec.module_id).err())
7047        .filter(|error| error.code != "config_delivery_deferred")
7048    {
7049        return Err(config_delivery::gate_hold_error(
7050            spec,
7051            error,
7052            runtime.config_delivery.as_ref(),
7053        ));
7054    }
7055    let recovery_reason = if health_failure {
7056        "health_check"
7057    } else {
7058        "configuration_delivery"
7059    };
7060    let (enabled, schedule) = {
7061        let mut state = lock_snapshot(snapshot)?;
7062        let enabled = state.enabled;
7063        let schedule = if enabled {
7064            state.next_crash_restart(&runtime.restart_policy, Instant::now())
7065        } else {
7066            None
7067        };
7068        (enabled, schedule)
7069    };
7070
7071    if !enabled {
7072        return Err(SuperviseError::Disabled {
7073            module_id: spec.module_id.clone(),
7074        });
7075    }
7076
7077    if schedule.is_none() {
7078        if health_failure {
7079            record_health_action(snapshot, &spec.module_id, "failed".to_string(), now_ms);
7080        }
7081        error!(
7082            module_id = %spec.module_id,
7083            status = ?status,
7084            detail,
7085            max_restarts = runtime.restart_policy.max_restarts,
7086            window_secs = runtime.restart_policy.window.as_secs(),
7087            reason = %runtime.restart_policy.budget_exhausted_detail(),
7088            recovery_reason,
7089            "automatic restart budget exhausted; marking module failed"
7090        );
7091        let stop_notice = begin_forwarding_drain_if_configured(
7092            spec,
7093            runtime,
7094            registry,
7095            snapshot,
7096            Some(true),
7097            RouteCloseReason::Disable,
7098        )
7099        .await?;
7100        update_snapshot(snapshot, Some(&spec.module_id), |state| {
7101            state.drain_disposition_detail = Some(runtime.restart_policy.budget_exhausted_detail());
7102        })?;
7103        let result = drain_optional_child(
7104            &spec.module_id,
7105            spec.protocol,
7106            stop_notice,
7107            registry,
7108            runtime.forwarding.as_deref(),
7109            snapshot,
7110            &runtime.terminal_ring,
7111            &runtime.spawn_events,
7112            child,
7113            runtime.drain_timeout,
7114            ModuleState::Failed,
7115            Some(true),
7116            &runtime.failure_context(true),
7117        )
7118        .await;
7119        update_snapshot(snapshot, Some(&spec.module_id), |state| {
7120            if state.state == ModuleState::Failed && !runtime.child_roster.is_closed() {
7121                state.failed_retry.schedule(&spec.module_id);
7122            }
7123        })?;
7124        result?;
7125        process_liveness.untrack_if_current(&spec.module_id, snapshot);
7126        return Ok(());
7127    }
7128
7129    let schedule = schedule.expect("a health restart must have a crash-restart schedule");
7130    let mut restart_count = 0;
7131    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7132        restart_count = state.crash_restarts.len();
7133        state.state = ModuleState::Unresponsive;
7134        if health_failure {
7135            state.health.status = status;
7136            state.health.last_action = Some(HealthAction::Restart.to_string());
7137            state.health.last_action_ms = Some(now_ms);
7138        }
7139    })?;
7140    warn!(
7141        module_id = %spec.module_id,
7142        status = ?status,
7143        detail,
7144        restart_count,
7145        restart_in_window = schedule.restart_in_window,
7146        delay_ms = schedule.delay.as_millis() as u64,
7147        recovery_reason,
7148        "automatic module restart"
7149    );
7150
7151    let stop_notice = begin_forwarding_drain_if_configured(
7152        spec,
7153        runtime,
7154        registry,
7155        snapshot,
7156        Some(true),
7157        RouteCloseReason::Restart,
7158    )
7159    .await?;
7160    drain_optional_child(
7161        &spec.module_id,
7162        spec.protocol,
7163        stop_notice,
7164        registry,
7165        runtime.forwarding.as_deref(),
7166        snapshot,
7167        &runtime.terminal_ring,
7168        &runtime.spawn_events,
7169        child,
7170        runtime.drain_timeout,
7171        ModuleState::Restarting,
7172        Some(true),
7173        &runtime.failure_context(true),
7174    )
7175    .await?;
7176    schedule_respawn(
7177        runtime,
7178        snapshot,
7179        &spec.module_id,
7180        schedule.delay,
7181        RespawnKind::CrashRestart,
7182        true,
7183    )
7184}
7185
7186fn cancel_deferred_reload(runtime: &SupervisorRuntimeConfig, module_id: &str, reason: &str) {
7187    if let Some(reply) = runtime
7188        .deferred_reload_reply
7189        .lock()
7190        .unwrap_or_else(|p| p.into_inner())
7191        .take()
7192    {
7193        let _ = reply.send(Err(SuperviseError::ReloadFailed {
7194            module_id: module_id.to_string(),
7195            reason: reason.to_string(),
7196        }));
7197    }
7198}
7199
7200fn park_config_spawn(
7201    spec: &ModuleSpec,
7202    runtime: &SupervisorRuntimeConfig,
7203    snapshot: &SharedSnapshot,
7204    failure: &FailureContext,
7205    admission_refused: Option<String>,
7206) -> Result<(), SuperviseError> {
7207    *runtime
7208        .scheduled_respawn
7209        .lock()
7210        .unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
7211    if let Some(reply) = runtime
7212        .deferred_reload_reply
7213        .lock()
7214        .unwrap_or_else(|poisoned| poisoned.into_inner())
7215        .take()
7216    {
7217        let _ = reply.send(Err(SuperviseError::ConfigHeld {
7218            module_id: spec.module_id.clone(),
7219            code: "config_gated".into(),
7220            detail: "module is held by configuration admission".into(),
7221        }));
7222    }
7223    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7224        state.admission_refused = admission_refused;
7225        state.config_hold_daemon_initiated = failure.daemon_initiated;
7226        state.config_hold_approval = failure.approval.clone();
7227        state.config_hold_parked = true;
7228        state.state = ModuleState::Stopped;
7229        state.respawn_pending = false;
7230        state.failed_retry.pending = None;
7231        // Parking ends this attempt and discards its failure timestamp. If a
7232        // later release fails, its retry delay starts at that new failure.
7233        state.failed_retry.failed_at = None;
7234        clear_current_process_facts(state);
7235    })
7236}
7237
7238fn try_park_config_attempt(
7239    spec: &ModuleSpec,
7240    runtime: &SupervisorRuntimeConfig,
7241    snapshot: &SharedSnapshot,
7242    failure: &FailureContext,
7243    program_base: Option<&subc_config::Digest>,
7244) -> Result<bool, SuperviseError> {
7245    let result = (|| {
7246        if !lock_snapshot(snapshot)?.enabled {
7247            return Ok(false);
7248        }
7249        #[cfg(test)]
7250        if let Some(delivery) = &runtime.config_delivery {
7251            delivery.0.pause_before_config_park_for_test();
7252        }
7253        let Some(delivery) = &runtime.config_delivery else {
7254            return Ok(false);
7255        };
7256        let parked = delivery
7257            .0
7258            .with_recorded_admission_hold(&spec.module_id, program_base, |refusal| {
7259                park_config_spawn(spec, runtime, snapshot, failure, refusal)
7260            })
7261            .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(delivery)))?;
7262        if let Some(result) = parked {
7263            result?;
7264            Ok(true)
7265        } else {
7266            Ok(false)
7267        }
7268    })();
7269    if let Err(error) = &result {
7270        // A failed park still belongs to the attempt that tried to park. Mark it
7271        // Failed here, before the monitor can use a daemon/operator origin saved
7272        // for a different attempt to decide whether to schedule a slow retry.
7273        fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
7274        record_approved_attempt_failure(spec, snapshot, failure, error);
7275    }
7276    result
7277}
7278
7279fn record_approved_attempt_failure(
7280    spec: &ModuleSpec,
7281    snapshot: &SharedSnapshot,
7282    failure: &FailureContext,
7283    error: &SuperviseError,
7284) {
7285    let Some(approval) = &failure.approval else {
7286        return;
7287    };
7288    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
7289        if state.enabled
7290            && state.state == ModuleState::Failed
7291            && state
7292                .approved_start_failure
7293                .as_ref()
7294                .is_none_or(|(identity, _)| identity != approval)
7295        {
7296            state.approved_start_failure = Some((approval.clone(), error.to_string()));
7297        }
7298    });
7299}
7300
7301fn hold_config_spawn(
7302    spec: &ModuleSpec,
7303    runtime: &SupervisorRuntimeConfig,
7304    snapshot: &SharedSnapshot,
7305    failure: &FailureContext,
7306) -> Result<(), SuperviseError> {
7307    hold_config_respawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)
7308}
7309
7310fn hold_config_respawn(
7311    spec: &ModuleSpec,
7312    runtime: &SupervisorRuntimeConfig,
7313    snapshot: &SharedSnapshot,
7314    kind: RespawnKind,
7315    failure: &FailureContext,
7316) -> Result<(), SuperviseError> {
7317    if !lock_snapshot(snapshot)?.enabled {
7318        return Ok(());
7319    }
7320    if !try_park_config_attempt(spec, runtime, snapshot, failure, None)? {
7321        // This caller consumed an actual start attempt. If its hold ended before
7322        // parking, retain that attempt instead of waiting for a lost release.
7323        defer_config_spawn(spec, runtime, snapshot, kind, failure)?;
7324    }
7325    Ok(())
7326}
7327
7328fn schedule_respawn(
7329    runtime: &SupervisorRuntimeConfig,
7330    snapshot: &SharedSnapshot,
7331    module_id: &str,
7332    delay: Duration,
7333    kind: RespawnKind,
7334    daemon_initiated: bool,
7335) -> Result<(), SuperviseError> {
7336    cancel_deferred_reload(runtime, module_id, "respawn superseded by another restart");
7337    update_snapshot(snapshot, Some(module_id), |state| {
7338        state.respawn_pending = true
7339    })?;
7340    *runtime
7341        .scheduled_respawn
7342        .lock()
7343        .unwrap_or_else(|p| p.into_inner()) = Some(PendingRespawn {
7344        deadline: Instant::now() + delay,
7345        kind,
7346        daemon_initiated,
7347        approval: None,
7348    });
7349    Ok(())
7350}
7351
7352const CONFIG_ADMISSION_RETRY_DELAY: Duration = Duration::from_millis(100);
7353
7354fn defer_config_spawn(
7355    spec: &ModuleSpec,
7356    runtime: &SupervisorRuntimeConfig,
7357    snapshot: &SharedSnapshot,
7358    kind: RespawnKind,
7359    failure: &FailureContext,
7360) -> Result<(), SuperviseError> {
7361    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7362        state.state = ModuleState::Restarting;
7363        state.respawn_pending = true;
7364        clear_current_process_facts(state);
7365    })?;
7366    *runtime
7367        .scheduled_respawn
7368        .lock()
7369        .unwrap_or_else(|p| p.into_inner()) = Some(PendingRespawn {
7370        deadline: Instant::now() + CONFIG_ADMISSION_RETRY_DELAY,
7371        kind,
7372        daemon_initiated: failure.daemon_initiated,
7373        approval: failure.approval.clone(),
7374    });
7375    Ok(())
7376}
7377
7378fn record_health_action(snapshot: &SharedSnapshot, module_id: &str, action: String, now_ms: u64) {
7379    let _ = update_snapshot(snapshot, Some(module_id), |state| {
7380        state.health.last_action = Some(action);
7381        state.health.last_action_ms = Some(now_ms);
7382    });
7383}
7384
7385fn supervisor_health_status(status: HealthStatus) -> SupervisorHealthStatus {
7386    match status {
7387        HealthStatus::Ok => SupervisorHealthStatus::Ok,
7388        HealthStatus::Degraded => SupervisorHealthStatus::Degraded,
7389        HealthStatus::Failing => SupervisorHealthStatus::Failing,
7390    }
7391}
7392
7393/// Caps the metrics blob stored in the cached supervisor snapshot, which is
7394/// returned to every `supervisor.list` and `supervisor.health` caller.
7395///
7396/// This cap is deliberately NOT applied on the one-shot `supervisor.health_probe`
7397/// path: that request exists to return a module's complete metrics object, and
7398/// `ck health <module-id>` documents it as the way to see what the cached view
7399/// truncates. The asymmetry is the feature.
7400///
7401/// So a new caller must decide which side it is on rather than assume the cap is
7402/// universal. Reaching for it on a fresh-probe path would silently reintroduce
7403/// the truncation that path exists to avoid.
7404fn truncate_health_metrics(metrics: Option<Value>) -> Option<Value> {
7405    let metrics = metrics?;
7406    match serde_json::to_vec(&metrics) {
7407        Ok(encoded) if encoded.len() > MAX_HEALTH_METRICS_BYTES => Some(serde_json::json!({
7408            "truncated": true,
7409            "original_bytes": encoded.len(),
7410        })),
7411        Ok(_) | Err(_) => Some(metrics),
7412    }
7413}
7414
7415/// Spread health probes so a fleet-wide restart does not converge them.
7416///
7417/// The delay is derived from the module id and probe index rather than a random
7418/// source, so it is deterministic per module: a module keeps its own offset
7419/// across daemon restarts instead of re-rolling into a collision.
7420fn jittered_health_delay(module_id: &str, probe_index: u64, cadence: Duration) -> Duration {
7421    if cadence.is_zero() {
7422        return Duration::ZERO;
7423    }
7424    let cadence_ms = cadence.as_millis() as u64;
7425    // This early return is REDUNDANT, deliberately, and a mutation run will show
7426    // it surviving removal. Recording why here so the next person to notice does
7427    // not have to re-derive it:
7428    //
7429    // - It is unreachable in practice. `positive_millis` in daemon_config rejects
7430    //   a zero cadence and builds the Duration from whole milliseconds, so a
7431    //   sub-millisecond cadence cannot come from config.
7432    // - Even if reached it changes no answer. The `.max(1)` below makes the span
7433    //   1, and `hash % 1` is 0, so the fall-through returns `cadence` unchanged
7434    //   -- exactly what this returns.
7435    //
7436    // Kept as a guard against a future widening of the config parser (accepting
7437    // microseconds, say), which would make the sub-millisecond case reachable.
7438    // The `.max(1)` is the load-bearing half TODAY: remove it and the modulo
7439    // divides by zero. Remove this and nothing changes.
7440    if cadence_ms == 0 {
7441        return cadence;
7442    }
7443    // Note that this never returns less than one cadence, including for the FIRST
7444    // probe. So a freshly registered module reports health `unknown` for a full
7445    // cadence plus jitter -- 30-33s at the default -- no matter how quickly it is
7446    // ready to answer.
7447    //
7448    // That is a property of the supervisor's schedule, not of any module: an
7449    // operator watching a restart sees `unknown` and cannot tell it from a module
7450    // that is slow to warm. Measured on two unrelated modules, both flipping to
7451    // `ok` between 22s and 32s after restart.
7452    //
7453    // Left as-is because spreading the first probe is what keeps a fleet-wide
7454    // restart from firing fourteen simultaneous probes into a cold machine. The
7455    // alternative -- probe at t+0 and jitter only from the second onward -- trades
7456    // that thundering herd for a faster first reading.
7457    let jitter_span = (cadence_ms / 10).max(1);
7458    let hash = module_id.as_bytes().iter().fold(
7459        probe_index.wrapping_mul(0x9E37_79B9_7F4A_7C15),
7460        |acc, byte| {
7461            acc.wrapping_mul(1099511628211)
7462                .wrapping_add(u64::from(*byte))
7463        },
7464    );
7465    cadence + Duration::from_millis(hash % jitter_span)
7466}
7467
7468#[cfg(test)]
7469mod tests {
7470    use super::*;
7471
7472    #[test]
7473    fn registration_retirement_self_prefixed_owner_is_not_a_prefix_submodule() {
7474        let handle = SupervisorHandle::new();
7475        handle.set_spawn_nonce("prefix:owner", "owner-nonce".into());
7476        handle.set_reserved_prefixes("prefix:owner", &["prefix:".into()]);
7477        let owner = handle
7478            .reserved_hello_verification("prefix:owner", Some("owner-nonce"))
7479            .unwrap();
7480        assert!(owner.nonce_verified);
7481        assert!(
7482            owner.prefix_owner.is_none(),
7483            "an unreserved programmatic owner is not its own prefix child"
7484        );
7485        let child = handle
7486            .reserved_hello_verification("prefix:child", Some("owner-nonce"))
7487            .unwrap();
7488        assert!(child.nonce_verified);
7489        assert_eq!(child.prefix_owner.as_deref(), Some("prefix:owner"));
7490    }
7491
7492    #[test]
7493    fn readding_a_module_clears_its_rescan_removal_tombstone() {
7494        let handle = SupervisorHandle::new();
7495        let module_id = "readded-tombstone";
7496        handle.record_rescan_removal(module_id);
7497        assert!(handle.removal_tombstone_age_ms(module_id).is_some());
7498
7499        handle.apply_identity_configuration(&ModuleSpec {
7500            script: None,
7501            module_id: module_id.to_string(),
7502            program: PathBuf::from("/test/module"),
7503            args: Vec::new(),
7504            env: Vec::new(),
7505            reserved: false,
7506            reserved_prefixes: Vec::new(),
7507            protocol: ModuleProtocol::Subc,
7508            overlap: Default::default(),
7509            carry_containment: false,
7510        });
7511
7512        assert!(
7513            handle.removal_tombstone_age_ms(module_id).is_none(),
7514            "a re-added module must not retain a stale removal tombstone"
7515        );
7516    }
7517
7518    /// What one module's owner looked like from the control plane at the
7519    /// instant after its first process was spawned.
7520    #[derive(Debug, PartialEq, Eq)]
7521    struct OwnerInSpawnWindow {
7522        module_id: String,
7523        configured: bool,
7524        on_roster: bool,
7525        admission_refusal: Option<&'static str>,
7526    }
7527
7528    /// A supervised module's process can connect, register, sync its scopes
7529    /// and describe them as soon as it is spawned. A plain `spawn` does not put
7530    /// the module on the roster until afterward; configured supervision does
7531    /// so before spawning. In both cases the owner must
7532    /// already read as configured, so a scoped `route.open` against it is
7533    /// refused as retryable `scope_not_synced` and not as terminal
7534    /// `scope_not_live` ("will never sync").
7535    ///
7536    /// The hook runs just after each initial spawn attempt, before returning to
7537    /// the caller, so no race with a real child's registration is needed.
7538    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7539    async fn a_new_module_is_configured_before_its_first_process_can_register() {
7540        use crate::scopes::ScopeTable;
7541        use subc_protocol::{error_codes, scope::ScopeSelector, Principal};
7542
7543        let dir = cortexkit_test_support::ScratchDir::new("configured-before-spawn");
7544        let stub = |module_id: &str, program: PathBuf| ModuleSpec {
7545            script: None,
7546            module_id: module_id.to_string(),
7547            program,
7548            args: Vec::new(),
7549            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7550                .into_iter()
7551                .map(|key| (key.to_string(), dir.path().display().to_string()))
7552                .chain([("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())])
7553                .collect(),
7554            reserved: false,
7555            reserved_prefixes: Vec::new(),
7556            protocol: ModuleProtocol::Subc,
7557            overlap: Default::default(),
7558            carry_containment: false,
7559        };
7560        let live = super::terminal_history_tests::fake_aft_stub_path();
7561        let missing = dir.path().join("definitely-missing-module");
7562
7563        let handle = SupervisorHandle::new();
7564        let mut supervisor =
7565            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7566                .with_handle(handle.clone());
7567        let observed = Arc::new(Mutex::new(Vec::<OwnerInSpawnWindow>::new()));
7568        let hook_handle = handle.clone();
7569        let hook_observed = Arc::clone(&observed);
7570        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |module_id| {
7571            // Exactly what the control plane computes for a scoped route.open
7572            // naming this module as the owner of a scope it has not synced.
7573            let configured = hook_handle.is_configured(module_id);
7574            let selector = ScopeSelector::new(
7575                Principal::Reserved {
7576                    module_id: module_id.to_string(),
7577                },
7578                "s".to_string(),
7579                Some(1),
7580            );
7581            let carrier = Principal::Reserved {
7582                module_id: "carrier".to_string(),
7583            };
7584            let admission_refusal = match ScopeTable::new(Vec::<String>::new())
7585                .admit(&carrier, module_id, &selector, configured)
7586            {
7587                Ok(_) => None,
7588                Err(refusal) => Some(refusal.code),
7589            };
7590            hook_observed.lock().unwrap().push(OwnerInSpawnWindow {
7591                module_id: module_id.to_string(),
7592                configured,
7593                on_roster: hook_handle.get(module_id).is_some(),
7594                admission_refusal,
7595            });
7596        })));
7597
7598        let plain = supervisor.spawn(stub("plain", live.clone())).unwrap();
7599        let configured = supervisor
7600            .supervise_configured(stub("configured", live.clone()), true)
7601            .unwrap();
7602        let with_health = supervisor
7603            .supervise_configured_with_health(
7604                stub("with-health", live.clone()),
7605                true,
7606                HealthConfig::default(),
7607                None,
7608                RestartPolicy::default(),
7609            )
7610            .unwrap();
7611        // The failed-spawn path still puts the module on the roster (as
7612        // failed), so it is configured throughout.
7613        let failed = supervisor
7614            .supervise_configured_with_health(
7615                stub("failed-spawn", missing.clone()),
7616                true,
7617                HealthConfig::default(),
7618                None,
7619                RestartPolicy::default(),
7620            )
7621            .unwrap();
7622        // A failed plain `spawn` puts nothing on the roster, so its mark is
7623        // taken back once the spawn has failed.
7624        assert!(supervisor.spawn(stub("spawn-error", missing)).is_err());
7625
7626        let expected = [
7627            "plain",
7628            "configured",
7629            "with-health",
7630            "failed-spawn",
7631            "spawn-error",
7632        ]
7633        .into_iter()
7634        .map(|module_id| OwnerInSpawnWindow {
7635            module_id: module_id.to_string(),
7636            configured: true,
7637            on_roster: !matches!(module_id, "plain" | "spawn-error"),
7638            admission_refusal: Some(error_codes::SCOPE_NOT_SYNCED),
7639        })
7640        .collect::<Vec<_>>();
7641        assert_eq!(*observed.lock().unwrap(), expected);
7642
7643        for module_id in ["plain", "configured", "with-health", "failed-spawn"] {
7644            assert!(
7645                handle.get(module_id).is_some(),
7646                "{module_id} is on the roster"
7647            );
7648            assert!(
7649                handle.is_configured(module_id),
7650                "{module_id} stays configured"
7651            );
7652        }
7653        assert!(handle.get("spawn-error").is_none());
7654        assert!(
7655            !handle.is_configured("spawn-error"),
7656            "a plain spawn that failed must not leave its module marked configured"
7657        );
7658
7659        // Leaving the roster clears the mark with it.
7660        handle.retire("failed-spawn");
7661        assert!(!handle.is_configured("failed-spawn"));
7662
7663        for module in [plain, configured, with_health] {
7664            module.stop().await.unwrap();
7665        }
7666        drop(failed);
7667    }
7668
7669    /// A configured module reads as starting until the supervisor has admitted
7670    /// its first process (exec confirmed, identity durably recorded), even
7671    /// though that process is already running by then and can register over
7672    /// HELLO, which is what lists it in catalog.list. So a client that needs
7673    /// the supervisor state must wait for that state; seeing the module in
7674    /// the catalog does not mean supervisor.list already says running.
7675    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7676    async fn a_configured_module_reads_starting_while_its_first_process_already_runs() {
7677        let dir = cortexkit_test_support::ScratchDir::new("starting-while-spawned");
7678        let spec = ModuleSpec {
7679            script: None,
7680            module_id: "spawned-not-admitted".to_string(),
7681            program: super::terminal_history_tests::fake_aft_stub_path(),
7682            args: Vec::new(),
7683            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7684                .into_iter()
7685                .map(|key| (key.to_string(), dir.path().display().to_string()))
7686                .chain([("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())])
7687                .collect(),
7688            reserved: false,
7689            reserved_prefixes: Vec::new(),
7690            protocol: ModuleProtocol::Subc,
7691            overlap: Default::default(),
7692            carry_containment: false,
7693        };
7694        let handle = SupervisorHandle::new();
7695        let mut supervisor =
7696            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7697                .with_handle(handle.clone());
7698        let observed = Arc::new(Mutex::new(None));
7699        let hook_handle = handle.clone();
7700        let hook_observed = Arc::clone(&observed);
7701        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |module_id| {
7702            let state = hook_handle
7703                .get(module_id)
7704                .expect("a configured module is on the roster before it is spawned")
7705                .state()
7706                .unwrap();
7707            *hook_observed.lock().unwrap() = Some(state);
7708        })));
7709
7710        let module = supervisor.supervise_configured(spec, true).unwrap();
7711        assert_eq!(
7712            *observed.lock().unwrap(),
7713            Some(ModuleState::Starting),
7714            "between the spawn and its admission the supervisor still reports starting"
7715        );
7716        assert_eq!(module.state().unwrap(), ModuleState::Running);
7717        module.stop().await.unwrap();
7718    }
7719
7720    fn stale_process_snapshot(state: ModuleState, enabled: bool) -> SharedSnapshot {
7721        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(state, enabled)));
7722        update_snapshot(&snapshot, Some("stale-process-facts"), |snapshot| {
7723            snapshot.process_alive = true;
7724            snapshot.pid = Some(41);
7725            snapshot.spawned_at_ms = Some(42);
7726            snapshot.spawned_from = Some(PathBuf::from("/spawned/module"));
7727            snapshot.launch_spec_digest = Some(LaunchSpecDigest([0xA5; 32]));
7728            snapshot.spawned_file_identity = Some(SpawnedFileIdentity {
7729                device: 43,
7730                inode: 44,
7731                #[cfg(windows)]
7732                windows_image: None,
7733            });
7734        })
7735        .unwrap();
7736        snapshot
7737    }
7738
7739    fn assert_snapshot_process_facts_cleared(snapshot: &SharedSnapshot) {
7740        let snapshot = lock_snapshot(snapshot).unwrap();
7741        assert!(!snapshot.process_alive);
7742        assert_eq!(snapshot.pid, None);
7743        assert_eq!(snapshot.spawned_at_ms, None);
7744        assert_eq!(snapshot.spawned_from, None);
7745        assert_eq!(snapshot.launch_spec_digest, None);
7746        assert_eq!(snapshot.spawned_file_identity, None);
7747    }
7748
7749    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7750    async fn failed_enable_spawn_clears_preexisting_current_process_facts() {
7751        let supervisor =
7752            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7753        let mut runtime = supervisor.runtime_config();
7754        runtime.test_seed_stale_facts_before_enable_spawn = true;
7755        let snapshot = stale_process_snapshot(ModuleState::Disabled, false);
7756        let mut child = None;
7757        let spec = ModuleSpec {
7758            script: None,
7759            module_id: "failed-enable-clears-facts".to_string(),
7760            program: PathBuf::from("/definitely/missing/failed-enable-module"),
7761            args: Vec::new(),
7762            env: Vec::new(),
7763            reserved: false,
7764            reserved_prefixes: Vec::new(),
7765            protocol: ModuleProtocol::Subc,
7766            overlap: Default::default(),
7767            carry_containment: false,
7768        };
7769
7770        let result = set_child_enabled(
7771            &spec,
7772            &runtime,
7773            &supervisor.registry,
7774            &supervisor.process_liveness,
7775            &snapshot,
7776            &mut child,
7777            true,
7778            &runtime.failure_context(false),
7779        )
7780        .await;
7781
7782        assert!(matches!(result, Err(SuperviseError::Spawn { .. })));
7783        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
7784        assert_snapshot_process_facts_cleared(&snapshot);
7785    }
7786
7787    #[tokio::test]
7788    async fn start_revives_stranded_restarting_but_not_pending_backoff() {
7789        let supervisor =
7790            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7791        let runtime = supervisor.runtime_config();
7792        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
7793            ModuleState::Restarting,
7794            true,
7795        )));
7796        let spec = ModuleSpec {
7797            script: None,
7798            module_id: "start-stranded-restarting".to_string(),
7799            program: super::terminal_history_tests::fake_aft_stub_path(),
7800            args: Vec::new(),
7801            env: vec![("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())],
7802            reserved: false,
7803            reserved_prefixes: Vec::new(),
7804            protocol: ModuleProtocol::None,
7805            overlap: Default::default(),
7806            carry_containment: false,
7807        };
7808        let mut child = None;
7809        lock_snapshot(&snapshot).unwrap().respawn_pending = true;
7810        assert!(!super::set_child_enabled(
7811            &spec,
7812            &runtime,
7813            &Registry::default(),
7814            &supervisor.process_liveness,
7815            &snapshot,
7816            &mut child,
7817            true,
7818            &runtime.failure_context(false),
7819        )
7820        .await
7821        .unwrap());
7822        assert!(child.is_none());
7823        lock_snapshot(&snapshot).unwrap().respawn_pending = false;
7824        assert!(super::set_child_enabled(
7825            &spec,
7826            &runtime,
7827            &Registry::default(),
7828            &supervisor.process_liveness,
7829            &snapshot,
7830            &mut child,
7831            true,
7832            &runtime.failure_context(false),
7833        )
7834        .await
7835        .unwrap());
7836        assert_eq!(
7837            lock_snapshot(&snapshot).unwrap().state,
7838            ModuleState::Running
7839        );
7840        let mut child = child.unwrap();
7841        child.start_kill().unwrap();
7842        child.wait().await.unwrap();
7843    }
7844
7845    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7846    async fn failed_reload_spawn_clears_current_process_facts() {
7847        let supervisor =
7848            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7849        let mut runtime = supervisor.runtime_config();
7850        runtime.restart_policy = RestartPolicy::new(0, Duration::ZERO);
7851        let snapshot = stale_process_snapshot(ModuleState::Running, true);
7852        let mut child = None;
7853        let spec = ModuleSpec {
7854            script: None,
7855            module_id: "failed-reload-clears-facts".to_string(),
7856            program: PathBuf::from("/unused/failed-reload-module"),
7857            args: Vec::new(),
7858            env: Vec::new(),
7859            reserved: false,
7860            reserved_prefixes: Vec::new(),
7861            protocol: ModuleProtocol::Subc,
7862            overlap: Default::default(),
7863            carry_containment: false,
7864        };
7865
7866        let result = handle_reload_spawn_failure(
7867            &spec,
7868            &runtime,
7869            &supervisor.process_liveness,
7870            &snapshot,
7871            &mut child,
7872            "forced reload spawn failure".to_string(),
7873        )
7874        .await;
7875
7876        assert!(matches!(result, Err(SuperviseError::ReloadFailed { .. })));
7877        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
7878        assert_snapshot_process_facts_cleared(&snapshot);
7879    }
7880
7881    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7882    async fn dropping_a_module_with_an_active_monitor_clears_current_process_facts() {
7883        let supervisor =
7884            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7885        let snapshot = stale_process_snapshot(ModuleState::Running, true);
7886        let module = supervisor.supervised_module(
7887            ModuleSpec {
7888                script: None,
7889                module_id: "drop-clears-facts".to_string(),
7890                program: PathBuf::from("/unused/drop-module"),
7891                args: Vec::new(),
7892                env: Vec::new(),
7893                reserved: false,
7894                reserved_prefixes: Vec::new(),
7895                protocol: ModuleProtocol::Subc,
7896                overlap: Default::default(),
7897                carry_containment: false,
7898            },
7899            supervisor.runtime_config(),
7900            Arc::clone(&snapshot),
7901            None,
7902        );
7903        assert!(!module
7904            .inner
7905            .monitor
7906            .lock()
7907            .unwrap()
7908            .as_ref()
7909            .unwrap()
7910            .is_finished());
7911
7912        drop(module);
7913
7914        assert_eq!(
7915            lock_snapshot(&snapshot).unwrap().state,
7916            ModuleState::Stopped
7917        );
7918        assert_snapshot_process_facts_cleared(&snapshot);
7919    }
7920
7921    #[cfg(unix)]
7922    #[tokio::test]
7923    async fn rescan_preserves_running_protocol_until_respawn() {
7924        let dir = cortexkit_test_support::ScratchDir::new("rescan-protocol");
7925        let initial = ModuleSpec {
7926            script: None,
7927            module_id: "rescan-protocol".into(),
7928            program: PathBuf::from("/bin/sleep"),
7929            args: vec!["60".into()],
7930            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7931                .into_iter()
7932                .map(|key| (key.into(), dir.path().to_string_lossy().into_owned()))
7933                .collect(),
7934            reserved: false,
7935            reserved_prefixes: vec![],
7936            protocol: ModuleProtocol::None,
7937            overlap: Default::default(),
7938            carry_containment: false,
7939        };
7940        let supervisor =
7941            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7942        let module = supervisor.spawn(initial.clone()).unwrap();
7943        assert!(module.status().unwrap().live);
7944        let mut next = initial;
7945        next.protocol = ModuleProtocol::Subc;
7946        module
7947            .update_configuration(next.clone(), HealthConfig::default(), None)
7948            .await
7949            .unwrap();
7950        assert!(
7951            module.status().unwrap().live,
7952            "rescan must not require HELLO from the old non-wire process"
7953        );
7954        let runtime = supervisor.runtime_config();
7955        let action = on_child_exit(
7956            &next,
7957            RestartPolicy::default(),
7958            &supervisor.registry,
7959            &module.inner.snapshot,
7960            &runtime.terminal_ring,
7961            &runtime.spawn_events,
7962            &runtime.child_roster,
7963            ExitReport {
7964                kind: ExitKind::Clean,
7965                code: Some(0),
7966                signal: None,
7967                at_ms: unix_ms_now(),
7968            },
7969            true,
7970        )
7971        .await;
7972        assert!(
7973            matches!(action, NextAction::Restart { .. }),
7974            "the old non-wire process's clean exit must restart"
7975        );
7976        module.drain().await.unwrap();
7977    }
7978
7979    #[cfg(unix)]
7980    #[tokio::test]
7981    async fn orphan_identity_matches_path_names_and_shebang_interpreters() {
7982        use std::os::unix::fs::PermissionsExt;
7983        let dir = cortexkit_test_support::ScratchDir::new("spawn-image-identity");
7984        let script = dir.join("module.sh");
7985        std::fs::write(&script, "#!/bin/sh\nwhile :; do sleep 0.1; done\n").unwrap();
7986        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
7987        let record_path = dir.join("live-children.json");
7988        let supervisor =
7989            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7990                .with_live_children_record(&record_path);
7991        for (program, args) in [
7992            (PathBuf::from("sleep"), vec!["60".into()]),
7993            (script, vec![]),
7994        ] {
7995            let spec = ModuleSpec {
7996                script: None,
7997                module_id: "image-identity".into(),
7998                program: program.clone(),
7999                args,
8000                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
8001                    .into_iter()
8002                    .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
8003                    .collect(),
8004                reserved: false,
8005                reserved_prefixes: vec![],
8006                protocol: ModuleProtocol::None,
8007                overlap: Default::default(),
8008                carry_containment: false,
8009            };
8010            let module = supervisor.spawn(spec).unwrap();
8011            #[cfg(target_os = "macos")]
8012            {
8013                // SETEXEC confirmation is asynchronous; the orphan record must
8014                // identify the final image, never the intermediate trampoline.
8015                let deadline = Instant::now() + Duration::from_secs(5);
8016                while crate::live_children::read_record(&record_path)
8017                    .unwrap()
8018                    .iter()
8019                    .all(|entry| entry.executable.is_none())
8020                {
8021                    assert!(Instant::now() < deadline, "module image was not confirmed");
8022                    tokio::time::sleep(Duration::from_millis(5)).await;
8023                }
8024            }
8025            let entry = crate::live_children::read_record(&record_path)
8026                .unwrap()
8027                .pop()
8028                .unwrap();
8029            let observed = subc_os::Process::open(entry.pid)
8030                .unwrap()
8031                .unwrap()
8032                .observe()
8033                .unwrap();
8034            let verdict = crate::live_children::identity_verdict(&entry, entry.pid, &observed);
8035            module.drain().await.unwrap();
8036            assert_eq!(
8037                verdict,
8038                crate::live_children::IdentityVerdict::Matches,
8039                "program {program:?}: recorded {entry:?}, observed {observed:?}"
8040            );
8041        }
8042    }
8043
8044    #[cfg(unix)]
8045    fn http_fixture(
8046        dir: &std::path::Path,
8047        url: &str,
8048        threshold: u32,
8049    ) -> crate::daemon_config::ConfiguredModule {
8050        let path = dir.join("subc.jsonc");
8051        std::fs::write(&path, serde_json::json!({"version": 1, "modules": {"http-process": {
8052            "program": "/bin/sleep", "args": ["60"], "protocol": "none",
8053            "env": {"XDG_DATA_HOME":dir,"XDG_RUNTIME_DIR":dir,"XDG_CONFIG_HOME":dir},
8054            "health": {"http":url,"cadence_ms":20,"deadline_ms":200,"failure_threshold":threshold},
8055            "restart": {"backoff_ms":1,"max_backoff_ms":1}, "drain_timeout_ms":10
8056        }}}).to_string()).unwrap();
8057        crate::daemon_config::load(&path)
8058            .unwrap()
8059            .unwrap()
8060            .modules
8061            .pop()
8062            .unwrap()
8063    }
8064
8065    #[cfg(unix)]
8066    async fn wait_http_health(module: &SupervisedModule, status: SupervisorHealthStatus) {
8067        timeout(Duration::from_secs(5), async {
8068            loop {
8069                if module.status().unwrap().health.status == status {
8070                    break;
8071                }
8072                sleep(Duration::from_millis(5)).await;
8073            }
8074        })
8075        .await
8076        .unwrap_or_else(|_| {
8077            panic!(
8078                "expected {status:?}, got {:?}",
8079                module.status().unwrap().health
8080            )
8081        });
8082    }
8083
8084    #[cfg(unix)]
8085    #[tokio::test]
8086    async fn http_health_status_flips_ok_failing_ok() {
8087        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8088        let dir = cortexkit_test_support::ScratchDir::new("http-status-flips");
8089        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8090        let status = Arc::new(std::sync::atomic::AtomicU16::new(200));
8091        let serving_status = status.clone();
8092        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8093        let server = tokio::spawn(async move {
8094            loop {
8095                let (mut stream, _) = listener.accept().await.unwrap();
8096                let mut request = [0u8; 2048];
8097                let count = stream.read(&mut request).await.unwrap();
8098                assert!(count > 0, "a probe must send an HTTP request");
8099                let code = serving_status.load(std::sync::atomic::Ordering::SeqCst);
8100                let body = if code == 200 {
8101                    "ready"
8102                } else {
8103                    "{\"status\":\"unavailable\",\"error\":\"scratch failure\"}"
8104                };
8105                let response = format!("HTTP/1.1 {code} scratch\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
8106                let _ = stream.write_all(response.as_bytes()).await;
8107            }
8108        });
8109        let configured = http_fixture(&dir, &url, 1000);
8110        let module =
8111            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8112                .supervise_configured_with_health(
8113                    configured.module_spec(),
8114                    true,
8115                    configured.health,
8116                    configured.drain_timeout_ms,
8117                    configured.restart,
8118                )
8119                .unwrap();
8120        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8121        status.store(503, std::sync::atomic::Ordering::SeqCst);
8122        wait_http_health(&module, SupervisorHealthStatus::Failing).await;
8123        assert!(module
8124            .status()
8125            .unwrap()
8126            .health
8127            .detail
8128            .unwrap()
8129            .contains("scratch failure"));
8130        status.store(200, std::sync::atomic::Ordering::SeqCst);
8131        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8132        assert_eq!(module.status().unwrap().health.consecutive_failures, 0);
8133        let before = module.status().unwrap();
8134        let (spec, mut health) = module.configuration().unwrap();
8135        health.http = None;
8136        module
8137            .update_configuration(spec.clone(), health.clone(), Some(10))
8138            .await
8139            .unwrap();
8140        wait_http_health(&module, SupervisorHealthStatus::Unknown).await;
8141        health.http = Some(url);
8142        module
8143            .update_configuration(spec, health, Some(10))
8144            .await
8145            .unwrap();
8146        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8147        assert_eq!(
8148            module.status().unwrap().pid,
8149            before.pid,
8150            "changing a probe must apply live, not restart its process"
8151        );
8152        let (spec, mut health) = module.configuration().unwrap();
8153        health.failure_threshold = 2;
8154        module
8155            .update_configuration(spec, health, Some(10))
8156            .await
8157            .unwrap();
8158        status.store(503, std::sync::atomic::Ordering::SeqCst);
8159        timeout(Duration::from_secs(5), async {
8160            while module.status().unwrap().spawn_generation == before.spawn_generation {
8161                sleep(Duration::from_millis(5)).await;
8162            }
8163        })
8164        .await
8165        .expect("sustained HTTP 503 responses must trigger the health restart policy");
8166        module.drain().await.unwrap();
8167        server.abort();
8168    }
8169
8170    #[cfg(unix)]
8171    #[tokio::test]
8172    async fn http_health_replacement_recovers_after_one_restart() {
8173        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8174        let dir = cortexkit_test_support::ScratchDir::new("http-replacement-recovers");
8175        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8176        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8177        let mut configured = http_fixture(&dir, &url, 2);
8178        configured.restart.max_restarts = 2;
8179        let module =
8180            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8181                .supervise_configured_with_health(
8182                    configured.module_spec(),
8183                    true,
8184                    configured.health,
8185                    configured.drain_timeout_ms,
8186                    configured.restart,
8187                )
8188                .unwrap();
8189        let first_generation = module.status().unwrap().spawn_generation;
8190        let observed = module.clone();
8191        let (healthy_tx, mut healthy_rx) = mpsc::channel(8);
8192        let server = tokio::spawn(async move {
8193            let mut generation = first_generation;
8194            let mut probes = 0;
8195            loop {
8196                let (mut stream, _) = listener.accept().await.unwrap();
8197                let mut request = [0; 2048];
8198                assert!(stream.read(&mut request).await.unwrap() > 0);
8199                let current = observed.status().unwrap().spawn_generation;
8200                if current != generation {
8201                    generation = current;
8202                    probes = 0;
8203                }
8204                probes += 1;
8205                // The original process never recovers. Each replacement has one
8206                // transient miss, then answers successfully for its remaining life.
8207                let healthy = generation != first_generation && probes > 1;
8208                let code = if healthy { 200 } else { 503 };
8209                let response = format!(
8210                    "HTTP/1.1 {code} scratch\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
8211                );
8212                let _ = stream.write_all(response.as_bytes()).await;
8213                if healthy {
8214                    healthy_tx.send(()).await.unwrap();
8215                }
8216            }
8217        });
8218        timeout(Duration::from_secs(5), async {
8219            let mut healthy_probes = 0;
8220            loop {
8221                if module.state().unwrap() == ModuleState::Failed {
8222                    break;
8223                }
8224                while healthy_rx.try_recv().is_ok() {
8225                    healthy_probes += 1;
8226                }
8227                if healthy_probes >= 3
8228                    && module.status().unwrap().health.status == SupervisorHealthStatus::Ok
8229                {
8230                    break;
8231                }
8232                sleep(Duration::from_millis(5)).await;
8233            }
8234        })
8235        .await
8236        .expect("the replacement must settle healthy without exhausting its restart budget");
8237        let status = module.status().unwrap();
8238        module.drain().await.unwrap();
8239        server.abort();
8240        assert_eq!(status.state, ModuleState::Running);
8241        assert_eq!(status.health.status, SupervisorHealthStatus::Ok);
8242        assert_eq!(status.health.consecutive_failures, 0);
8243        assert_eq!(status.lifetime_restarts, 1);
8244        assert_eq!(status.restart_count, 1);
8245    }
8246
8247    #[cfg(unix)]
8248    #[tokio::test]
8249    async fn http_health_sustained_failure_exhausts_restart_budget() {
8250        use std::collections::BTreeMap;
8251        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8252        let dir = cortexkit_test_support::ScratchDir::new("http-health-budget");
8253        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8254        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8255        let mut configured = http_fixture(&dir, &url, 2);
8256        configured.restart.max_restarts = 2;
8257        let module =
8258            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8259                .supervise_configured_with_health(
8260                    configured.module_spec(),
8261                    true,
8262                    configured.health,
8263                    configured.drain_timeout_ms,
8264                    configured.restart,
8265                )
8266                .unwrap();
8267        let observed = module.clone();
8268        let probes = Arc::new(Mutex::new(BTreeMap::<u64, u32>::new()));
8269        let served = probes.clone();
8270        let server = tokio::spawn(async move {
8271            loop {
8272                let (mut stream, _) = listener.accept().await.unwrap();
8273                let mut request = [0; 2048];
8274                assert!(stream.read(&mut request).await.unwrap() > 0);
8275                *served
8276                    .lock()
8277                    .unwrap()
8278                    .entry(observed.status().unwrap().spawn_generation)
8279                    .or_default() += 1;
8280                let _ = stream
8281                    .write_all(b"HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
8282                    .await;
8283            }
8284        });
8285        timeout(Duration::from_secs(5), async {
8286            while module.state().unwrap() != ModuleState::Failed {
8287                sleep(Duration::from_millis(5)).await;
8288            }
8289        })
8290        .await
8291        .expect("sustained failures must still exhaust the health restart budget");
8292        let status = module.status().unwrap();
8293        server.abort();
8294        assert_eq!(status.restart_count, 2);
8295        assert_eq!(status.lifetime_restarts, 2);
8296        assert!(!status.process_alive);
8297        assert_eq!(
8298            probes.lock().unwrap().values().copied().collect::<Vec<_>>(),
8299            vec![2, 2, 2]
8300        );
8301    }
8302
8303    #[cfg(unix)]
8304    #[tokio::test]
8305    async fn spawn_clears_the_previous_process_health() {
8306        let dir = cortexkit_test_support::ScratchDir::new("spawn-fresh-health");
8307        let mut configured = http_fixture(&dir, "http://127.0.0.1:1/healthz", 2);
8308        configured.health.cadence = Duration::from_secs(3600);
8309        let module =
8310            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8311                .supervise_configured_with_health(
8312                    configured.module_spec(),
8313                    false,
8314                    configured.health,
8315                    configured.drain_timeout_ms,
8316                    configured.restart,
8317                )
8318                .unwrap();
8319        update_snapshot(&module.inner.snapshot, Some(module.module_id()), |state| {
8320            state.health.status = SupervisorHealthStatus::Unresponsive;
8321            state.health.consecutive_failures = 3;
8322            state.health.detail = Some("old process refused connections".into());
8323            state.health.metrics = Some(serde_json::json!({"old": true}));
8324            state.health.last_probe_ms = Some(123);
8325            state.health.last_action = Some("restart".into());
8326            state.health.last_action_ms = Some(124);
8327        })
8328        .unwrap();
8329        module.set_enabled(true).await.unwrap();
8330        let health = module.status().unwrap().health;
8331        module.drain().await.unwrap();
8332        assert_eq!(health.consecutive_failures, 0);
8333        assert_eq!(health.status, SupervisorHealthStatus::Unknown);
8334        assert_eq!(health.detail, None);
8335        assert_eq!(health.metrics, None);
8336        assert_eq!(health.last_probe_ms, None);
8337        assert_eq!(health.last_action.as_deref(), Some("restart"));
8338        assert_eq!(health.last_action_ms, Some(124));
8339    }
8340
8341    #[cfg(unix)]
8342    #[tokio::test]
8343    async fn http_health_no_listener_restarts_after_consecutive_failures() {
8344        let dir = cortexkit_test_support::ScratchDir::new("http-refused");
8345        let unused = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8346        let url = format!("http://{}/healthz", unused.local_addr().unwrap());
8347        drop(unused);
8348        let configured = http_fixture(&dir, &url, 2);
8349        let module =
8350            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8351                .supervise_configured_with_health(
8352                    configured.module_spec(),
8353                    true,
8354                    configured.health,
8355                    configured.drain_timeout_ms,
8356                    configured.restart,
8357                )
8358                .unwrap();
8359        let before = module.status().unwrap().spawn_generation;
8360        timeout(Duration::from_secs(5), async {
8361            loop {
8362                let status = module.status().unwrap();
8363                if status.spawn_generation > before {
8364                    assert!(status.lifetime_restarts > 0);
8365                    break;
8366                }
8367                sleep(Duration::from_millis(5)).await;
8368            }
8369        })
8370        .await
8371        .expect("sustained HTTP refusal must trigger the health restart policy");
8372        module.drain().await.unwrap();
8373    }
8374
8375    #[cfg(unix)]
8376    #[tokio::test]
8377    async fn http_health_timeout_honours_deadline() {
8378        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8379        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8380        let server = tokio::spawn(async move {
8381            let _held = listener.accept().await.unwrap();
8382            std::future::pending::<()>().await;
8383        });
8384        let error = timeout(
8385            Duration::from_secs(1),
8386            probe_http_health(&url, Duration::from_millis(10)),
8387        )
8388        .await
8389        .expect("the probe must enforce its own deadline")
8390        .unwrap_err();
8391        server.abort();
8392        assert!(error.to_string().contains("timed out"));
8393    }
8394
8395    #[cfg(unix)]
8396    #[tokio::test]
8397    async fn http_health_localhost_reaches_an_ipv6_only_listener() {
8398        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8399        let listener = tokio::net::TcpListener::bind("[::1]:0").await.unwrap();
8400        let url = format!(
8401            "http://localhost:{}/healthz",
8402            listener.local_addr().unwrap().port()
8403        );
8404        let server = tokio::spawn(async move {
8405            let (mut stream, _) = listener.accept().await.unwrap();
8406            let mut request = [0u8; 2048];
8407            assert!(stream.read(&mut request).await.unwrap() > 0);
8408            stream
8409                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
8410                .await
8411                .unwrap();
8412        });
8413        // The deadline only bounds a hang. A probe that never tried the IPv6
8414        // address would be refused on 127.0.0.1 and fail at once, so a longer
8415        // deadline does not weaken the assertion; one second timed out under a
8416        // loaded parallel test run.
8417        assert_eq!(
8418            probe_http_health(&url, Duration::from_secs(10))
8419                .await
8420                .unwrap()
8421                .status,
8422            HealthStatus::Ok
8423        );
8424        server.await.unwrap();
8425    }
8426
8427    #[cfg(unix)]
8428    #[tokio::test]
8429    async fn http_health_timeout_keeps_partial_status_and_body() {
8430        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8431        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8432        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8433        let server = tokio::spawn(async move {
8434            let (mut stream, _) = listener.accept().await.unwrap();
8435            let mut request = [0u8; 2048];
8436            assert!(stream.read(&mut request).await.unwrap() > 0);
8437            stream
8438                .write_all(
8439                    b"HTTP/1.1 503 Unavailable\r\nContent-Length: 100\r\n\r\npartial diagnostic",
8440                )
8441                .await
8442                .unwrap();
8443            std::future::pending::<()>().await;
8444        });
8445        let error = probe_http_health(&url, Duration::from_secs(1))
8446            .await
8447            .unwrap_err()
8448            .to_string();
8449        server.abort();
8450        assert!(
8451            error.contains("timed out")
8452                && error.contains("503 Unavailable")
8453                && error.contains("partial diagnostic"),
8454            "{error}"
8455        );
8456    }
8457
8458    #[cfg(unix)]
8459    #[tokio::test]
8460    async fn http_health_diagnostic_body_is_bounded_to_200_bytes() {
8461        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8462        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8463        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8464        let server = tokio::spawn(async move {
8465            let (mut stream, _) = listener.accept().await.unwrap();
8466            let mut request = [0u8; 2048];
8467            assert!(stream.read(&mut request).await.unwrap() > 0);
8468            let body = format!("{}not-in-diagnostic", "x".repeat(400));
8469            let response = format!(
8470                "HTTP/1.1 503 Unavailable\r\nContent-Length: {}\r\n\r\n{body}",
8471                body.len()
8472            );
8473            stream.write_all(response.as_bytes()).await.unwrap();
8474        });
8475        let error = probe_http_health(&url, Duration::from_secs(1))
8476            .await
8477            .unwrap_err()
8478            .to_string();
8479        server.await.unwrap();
8480        assert!(error.ends_with(&"x".repeat(200)), "{error}");
8481        assert_eq!(error.split(": ").last().unwrap().len(), 200);
8482        assert!(!error.contains("not-in-diagnostic"));
8483    }
8484
8485    #[cfg(unix)]
8486    #[tokio::test]
8487    async fn http_health_real_nats_server_monitoring() {
8488        if std::process::Command::new("nats-server")
8489            .arg("--version")
8490            .env("XDG_DATA_HOME", std::env::temp_dir())
8491            .env("XDG_RUNTIME_DIR", std::env::temp_dir())
8492            .env("XDG_CONFIG_HOME", std::env::temp_dir())
8493            .output()
8494            .is_err()
8495        {
8496            eprintln!(
8497                "skipped: http_health_real_nats_server_monitoring (nats-server is not on PATH)"
8498            );
8499            return;
8500        }
8501        let dir = cortexkit_test_support::ScratchDir::new("nats-http-monitoring");
8502        let monitor = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8503        let port = monitor.local_addr().unwrap().port();
8504        let client = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8505        let client_port = client.local_addr().unwrap().port();
8506        let config = dir.join("server.conf");
8507        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();
8508        let mut configured = http_fixture(&dir, &format!("http://127.0.0.1:{port}/healthz"), 1000);
8509        configured.program = PathBuf::from("nats-server");
8510        configured.args = vec!["-c".into(), config.to_string_lossy().into_owned()];
8511        drop(monitor);
8512        drop(client);
8513        let module =
8514            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8515                .supervise_configured_with_health(
8516                    configured.module_spec(),
8517                    true,
8518                    configured.health,
8519                    configured.drain_timeout_ms,
8520                    configured.restart,
8521                )
8522                .unwrap();
8523        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8524        module.drain().await.unwrap();
8525    }
8526
8527    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8528    async fn configuration_update_does_not_replace_captured_running_process_facts() {
8529        let supervisor =
8530            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
8531        let snapshot = stale_process_snapshot(ModuleState::Running, true);
8532        let initial = ModuleSpec {
8533            script: None,
8534            module_id: "rescan-preserves-spawn-facts".to_string(),
8535            program: PathBuf::from("/spawned/module"),
8536            args: Vec::new(),
8537            env: Vec::new(),
8538            reserved: false,
8539            reserved_prefixes: Vec::new(),
8540            protocol: ModuleProtocol::Subc,
8541            overlap: Default::default(),
8542            carry_containment: false,
8543        };
8544        let module = supervisor.supervised_module(
8545            initial.clone(),
8546            supervisor.runtime_config(),
8547            snapshot,
8548            None,
8549        );
8550        let before = module.status().unwrap();
8551        let mut replacement = initial;
8552        replacement.program = PathBuf::from("/rescanned/replacement-module");
8553
8554        module
8555            .update_configuration(replacement, HealthConfig::default(), None)
8556            .await
8557            .unwrap();
8558
8559        let after = module.status().unwrap();
8560        assert_eq!(after.pid, before.pid);
8561        assert_eq!(after.spawned_at_ms, before.spawned_at_ms);
8562        assert_eq!(after.spawned_from, before.spawned_from);
8563        drop(module);
8564    }
8565}
8566
8567fn unix_ms_now() -> u64 {
8568    SystemTime::now()
8569        .duration_since(UNIX_EPOCH)
8570        .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
8571        .unwrap_or(0)
8572}
8573
8574async fn supervise_loop(
8575    mut spec: ModuleSpec,
8576    mut runtime: SupervisorRuntimeConfig,
8577    registry: Arc<Registry>,
8578    process_liveness: Arc<SupervisorProcessLiveness>,
8579    snapshot: SharedSnapshot,
8580    mut child: Option<SupervisedChild>,
8581    mut commands: mpsc::Receiver<SupervisorCommand>,
8582) {
8583    let mut health_probe = HealthProbeRuntime::default();
8584    // Registry writes (including embedded callers) notify this module only.
8585    // Subscribe before the first refresh; watch retains changes that arrive
8586    // while commands or probes are running. No polling fallback is needed.
8587    let mut registration_changes = match registry.subscribe_module_changes(&spec.module_id) {
8588        Ok(changes) => Some(changes),
8589        Err(err) => {
8590            // A poisoned registry cannot accept further writes, so it cannot
8591            // recover via a timer. Keep exit and command handling alive.
8592            warn!(module_id = %spec.module_id, error = %err, "health prober could not subscribe to registry");
8593            None
8594        }
8595    };
8596    // All restart backoffs run here, including health and operator requests.
8597    // While one is pending the loop serves commands, so disable or drain can
8598    // cancel the replacement without spawning a process just to stop it.
8599    let mut pending_respawn: Option<PendingRespawn> = None;
8600    // Commands a swap handed back to run next (see `swap::SwapEnd`). Served
8601    // before anything else so a stop that interrupted a swap runs at once.
8602    let mut requeued: VecDeque<SupervisorCommand> = VecDeque::new();
8603    let mut previous_instance_recheck = tokio::time::interval_at(
8604        Instant::now() + Duration::from_secs(5),
8605        Duration::from_secs(5),
8606    );
8607    previous_instance_recheck.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
8608    'supervision: loop {
8609        #[cfg(test)]
8610        {
8611            lock_snapshot(&snapshot).unwrap().actor_select = None;
8612        }
8613        #[cfg(target_os = "macos")]
8614        if let Some(active) = child.as_mut() {
8615            active.confirm_privacy_exec().await;
8616        }
8617        if let Some(scheduled) = runtime
8618            .scheduled_respawn
8619            .lock()
8620            .unwrap_or_else(|p| p.into_inner())
8621            .take()
8622        {
8623            runtime.recovery_is_daemon = scheduled.daemon_initiated;
8624            pending_respawn = Some(scheduled);
8625        }
8626        if pending_respawn.is_some() && (child.is_some() || !respawn_still_pending(&snapshot)) {
8627            pending_respawn = None;
8628            cancel_deferred_reload(
8629                &runtime,
8630                &spec.module_id,
8631                "respawn cancelled by a supervisor command",
8632            );
8633        }
8634        if child.is_none()
8635            && pending_respawn.is_none()
8636            && lock_snapshot(&snapshot).is_ok_and(|state| state.waiting_for_previous_pid.is_none())
8637        {
8638            cancel_deferred_reload(
8639                &runtime,
8640                &spec.module_id,
8641                "respawn cancelled before a replacement was spawned",
8642            );
8643            let mut stranded = false;
8644            let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8645                state.respawn_pending = false;
8646                state.coalesced_restart_pending = false;
8647                if matches!(
8648                    state.state,
8649                    ModuleState::Restarting
8650                        | ModuleState::Starting
8651                        | ModuleState::Draining
8652                        | ModuleState::Unresponsive
8653                ) {
8654                    error!(module_id = %spec.module_id, state = ?state.state,
8655                        "supervision operation ended without a child or pending respawn; marking failed so start can retry");
8656                    stranded = true;
8657                }
8658            });
8659            if stranded {
8660                fail_snapshot(
8661                    &snapshot,
8662                    Some(&spec.module_id),
8663                    None,
8664                    &runtime.failure_context(runtime.recovery_is_daemon),
8665                );
8666            }
8667        }
8668        if child.is_none()
8669            && (runtime.child_roster.is_closed()
8670                || pending_respawn.is_none()
8671                || !lock_snapshot(&snapshot)
8672                    .is_ok_and(|state| state.enabled && state.state == ModuleState::Restarting))
8673        {
8674            containment::terminate(&runtime.child_roster.containment).await;
8675        }
8676        if let Some(command) = requeued.pop_front() {
8677            if !handle_supervisor_command(
8678                command,
8679                &mut spec,
8680                &mut runtime,
8681                &registry,
8682                &process_liveness,
8683                &snapshot,
8684                &mut child,
8685                &mut commands,
8686                &mut requeued,
8687            )
8688            .await
8689            {
8690                containment::terminate(&runtime.child_roster.containment).await;
8691                return;
8692            }
8693            if child.is_some() || !respawn_still_pending(&snapshot) {
8694                pending_respawn = None;
8695                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8696                    state.respawn_pending = false
8697                });
8698            }
8699            continue;
8700        }
8701        if child.is_some() {
8702            runtime.recovery_is_daemon = true;
8703            #[cfg(test)]
8704            {
8705                lock_snapshot(&snapshot).unwrap().actor_turns += 1;
8706            }
8707            health_probe.refresh_registration(&spec, &runtime, &registry, &snapshot);
8708            let active = child.as_mut().expect("child checked above");
8709            if active.registered_since_spawn() {
8710                if let Some(delivery) = &runtime.config_delivery {
8711                    delivery.queue_registered(
8712                        &spec.module_id,
8713                        runtime.forwarding.as_ref(),
8714                        &registry,
8715                        active,
8716                    );
8717                }
8718            }
8719            if runtime.child_roster.is_closed() || !active.awaiting_registration() {
8720                active.registration_deadline = None;
8721            }
8722            let registration_deadline = active.registration_deadline;
8723            let no_checks = runtime.health.http.is_none()
8724                && (running_protocol(&spec, &snapshot) == ModuleProtocol::None
8725                    || (health_probe.registered_connection.is_some() && !health_probe.advertised));
8726            let uptime_reset = lock_snapshot(&snapshot).ok().and_then(|mut state| {
8727                state
8728                    .failed_retry
8729                    .uptime_reset_at(no_checks, runtime.restart_policy.window)
8730            });
8731            let wake_at = match (health_probe.wake_at(), uptime_reset) {
8732                (probe, Some(reset)) => Some(probe.map_or(reset, |probe| probe.min(reset))),
8733                (probe, None) => probe,
8734            };
8735            let wake_at = match (wake_at, registration_deadline) {
8736                (Some(wake), Some(register)) => Some(wake.min(register)),
8737                (wake, register) => wake.or(register),
8738            };
8739            #[cfg(test)]
8740            let wake_after = wake_at.map(|at| at.saturating_duration_since(Instant::now()));
8741            let probe_sleep = supervisor_sleep(wake_at);
8742            tokio::pin!(probe_sleep);
8743            // A `protocol: "none"` child (a plain process that never registers
8744            // over the subc wire, such as nats-server) with no HTTP health
8745            // check has nothing to probe, so it waits only for its exit or a
8746            // supervisor command. A rescan that adds an HTTP check is a command.
8747            let wire_child = running_protocol(&spec, &snapshot) == ModuleProtocol::Subc;
8748            #[cfg(test)]
8749            {
8750                let registration_pending = wire_child
8751                    && registration_changes
8752                        .as_ref()
8753                        .is_some_and(|changes| changes.has_changed().unwrap());
8754                let mut state = lock_snapshot(&snapshot).unwrap();
8755                state.actor_select = (!registration_pending).then_some(ActorSelectCheckpoint {
8756                    generation: state.spawn_generation,
8757                    turn: state.actor_turns,
8758                    registered_connection: health_probe.registered_connection,
8759                    next_probe_at: health_probe.next_probe_at,
8760                    wake_after,
8761                });
8762            }
8763            let registration = active
8764                .awaiting_registration()
8765                .then(|| active.registration_spawn.clone())
8766                .flatten();
8767            #[cfg(all(test, target_os = "linux"))]
8768            let registration_before_exit = !runtime.child_roster.admission_event_for_test(
8769                &spec.module_id,
8770                "observe_registration_before_exit",
8771                Some(active.pid),
8772            ) && registration.is_some();
8773            #[cfg(not(all(test, target_os = "linux")))]
8774            let registration_before_exit = false;
8775            #[cfg(all(test, target_os = "linux"))]
8776            let registration_child_is_running = |child: &mut SupervisedChild| {
8777                // Model the interval after SIGKILL is accepted but before the
8778                // child becomes waitable, without delaying the actual kill.
8779                registration_before_exit || registration_child_is_running(child)
8780            };
8781            let registration_failed = async {
8782                match &registration {
8783                    Some(spawn) => spawn.wait_registration_failure().await,
8784                    None => std::future::pending().await,
8785                }
8786            };
8787            let active_child = child.as_mut().expect("child checked above");
8788            tokio::select! {
8789                _ = registration_failed => {
8790                    if !active_child.registered_since_spawn() && registration_child_is_running(active_child) {
8791                        active_child.registration_deadline = None;
8792                        active_child.spawn_failure = Some("registration_channel_closed".into());
8793                        if let Err(error) = stop_unregistered_child(active_child).await {
8794                            fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
8795                                &runtime.spawn_events, format!("registration_channel_closed: {error}"),
8796                                &runtime.failure_context(true));
8797                            child = None;
8798                        }
8799                    }
8800                    continue;
8801                }
8802                wait_result = active_child.wait(), if !registration_before_exit => {
8803                    if let Ok(mut state) = lock_snapshot(&snapshot) {
8804                        state.failed_retry.uptime_reset_at(no_checks, runtime.restart_policy.window);
8805                    }
8806                    #[cfg(test)]
8807                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8808                    // Every arm below that gives up on the CHILD must keep the
8809                    // supervision task itself alive (child = None, loop
8810                    // continues into command-serving mode). Returning here
8811                    // closes the command channel, which makes the module
8812                    // permanently unrestartable in-band: a clean child exit
8813                    // of an enabled module once wedged the fleet this way
8814                    // ('supervisor command channel is closed') and required a
8815                    // full daemon restart to recover.
8816                    let exit_report = match wait_result {
8817                        Ok(status) => classify_reaped_child_exit(&snapshot, active_child, &status),
8818                        Err(err) => {
8819                            active_child.drain_stderr(&spec.module_id).await;
8820                            fail_after_wait_error(
8821                                &spec.module_id,
8822                                &snapshot,
8823                                &runtime.terminal_ring,
8824                                &runtime.spawn_events,
8825                                format!("failed to wait for supervised module: {err}"),
8826                            &runtime.failure_context(true),
8827                            );
8828                            untrack_if_registration_released(
8829                                &process_liveness,
8830                                &registry,
8831                                &spec.module_id,
8832                                &snapshot,
8833                            );
8834                            error!(module_id = %spec.module_id, error = %err, "failed to wait for supervised module");
8835                            child = None;
8836                            continue;
8837                        }
8838                    };
8839                    active_child.drain_stderr(&spec.module_id).await;
8840
8841                    let delivery=runtime.config_delivery.clone();
8842                    let exited_spawn=active_child.spawned_at;
8843                    let spawn=active_child.config_delivery.clone();
8844                    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())));
8845                    let module_id=spec.module_id.clone();
8846                    // Publication may own the store mutex for local durable I/O.
8847                    // Keep commands selectable until the child's exit is recorded;
8848                    // no respawn disposition is chosen before that observation.
8849                    let observed=async move {
8850                        if let Some(delivery)=delivery {
8851                            delivery.0.on_blocking(move |owner| {
8852                                if let Some(spawn)=spawn { owner.delivery_child_exited(&spawn)?; }
8853                                if let Some((base,identity))=refusal {owner.record_program_refusal(&module_id,&base,identity)?;}
8854                                Ok(())
8855                            }).await
8856                        } else {Ok(())}
8857                    };
8858                    tokio::pin!(observed);
8859                    loop {
8860                        tokio::select! {
8861                            result=&mut observed=>{
8862                                if let Err(error)=result {warn!(module_id=%spec.module_id,%error,"configuration exit observation failed");}
8863                                break;
8864                            }
8865                            command=commands.recv()=>{
8866                                let Some(command)=command else {containment::terminate(&runtime.child_roster.containment).await;return;};
8867                                let deferred=||SuperviseError::ConfigDeliveryDeferred {module_id:spec.module_id.clone()};
8868                                let command=match command {
8869                                    SupervisorCommand::Restart {reply,..}|SupervisorCommand::Reload {reply,..}=>{let _=reply.send(Err(deferred()));continue;}
8870                                    SupervisorCommand::Swap {reply,..}=>{let _=reply.send(Err(deferred()));continue;}
8871                                    command @ (SupervisorCommand::ConfigApplyRestart {..}|SupervisorCommand::ConfigPolicyProbe {..}|SupervisorCommand::ConfigDeliveryFailed {..})=>{requeued.push_back(command);continue;}
8872                                    command=>command,
8873                                };
8874                                if !handle_supervisor_command(command,&mut spec,&mut runtime,&registry,&process_liveness,&snapshot,&mut child,&mut commands,&mut requeued).await {
8875                                    containment::terminate(&runtime.child_roster.containment).await;return;
8876                                }
8877                                if child.as_ref().is_none_or(|current|current.spawned_at!=exited_spawn) {continue 'supervision;}
8878                            }
8879                        }
8880                    }
8881                    let active_child=child.as_mut().expect("exit observation retained its child");
8882                    // An unavailable image can race the program's own exit.
8883                    // Only the admission kill is budget-free; another exit must
8884                    // retain its ordinary crash/clean-exit accounting.
8885                    let admission_kill = admission_exit::is_admission_kill(active_child.admission_kill_sent, &exit_report);
8886                    let deferred_spawn=admission_kill && active_child.spawn_failure.as_deref().is_some_and(|detail|detail.starts_with("config_delivery_deferred:"));
8887                    let refused_program = active_child.live_program_binding.as_ref().is_some_and(|binding| binding.is_refused());
8888                    let exit_held = !deferred_spawn && (refused_program || runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.exit_is_held(&spec.module_id)));
8889                    let parked = exit_held && (!refused_program || active_child.admission_base.is_some())
8890                        && try_park_config_attempt(&spec, &runtime, &snapshot, &runtime.failure_context(true),
8891                            if refused_program { active_child.admission_base.as_ref() } else { None })
8892                            .unwrap_or_else(|error| { warn!(module_id=%spec.module_id, %error, "exit hold could not be recorded; using ordinary exit accounting"); false });
8893                    let next = if deferred_spawn {
8894                        record_terminal_with_detail(&spec.module_id,&runtime.terminal_ring,&runtime.spawn_events,&exit_report,TerminalDisposition::Restarting,active_child.exit_cleanup_detail(active_child.spawn_failure.clone()));
8895                        let _=update_snapshot(&snapshot,Some(&spec.module_id),|state| {
8896                            state.state=ModuleState::Restarting;
8897                            clear_current_process_facts(state);
8898                            state.last_exit=Some(exit_report.clone());
8899                        });
8900                        NextAction::Restart {schedule:None}
8901                    } else if parked {
8902                        record_terminal_with_detail(&spec.module_id, &runtime.terminal_ring, &runtime.spawn_events, &exit_report, TerminalDisposition::Stopped, active_child.exit_cleanup_detail(active_child.spawn_failure.clone().or_else(|| Some("config_gated".into()))));
8903                        NextAction::Stop { registration_released: registry.get_module(&spec.module_id).ok().flatten().is_none() }
8904                    } else { on_child_exit_with_detail(
8905                        &spec,
8906                        runtime.restart_policy,
8907                        &registry,
8908                        &snapshot,
8909                        &runtime.terminal_ring,
8910                        &runtime.spawn_events,
8911                        &runtime.child_roster,
8912                        exit_report,
8913                        true,
8914                        active_child.exit_cleanup_detail(None),
8915                    ).await };
8916                    runtime.start_requester = None;
8917                    runtime.pending_activity_restart = false;
8918                    // The exit is recorded, so a daemon shutdown may stop
8919                    // waiting for this child (see `SupervisedChild::wait`).
8920                    let carry = matches!(next, NextAction::Restart { .. })
8921                        && active_child.spawn_failure.is_none()
8922                        && !runtime.child_roster.is_closed();
8923                    if let Err(error) = active_child.finish_exit(carry).await {
8924                        containment::terminate(&runtime.child_roster.containment).await;
8925                        fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
8926                            &runtime.spawn_events, format!("failed to reap classified exit: {error}"),
8927                            &runtime.failure_context(true));
8928                        child = None;
8929                        continue;
8930                    }
8931                    match next {
8932                        NextAction::Stop { registration_released } => {
8933                            if registration_released {
8934                                process_liveness.untrack_if_current(&spec.module_id, &snapshot);
8935                            }
8936                            child = None;
8937                        }
8938                        NextAction::Restart { schedule } => {
8939                            let delay = if deferred_spawn {CONFIG_ADMISSION_RETRY_DELAY} else {schedule.map_or(
8940                                runtime.restart_policy.delay_for_restart(0),
8941                                |schedule| schedule.delay,
8942                            )};
8943                            if let Some(schedule) = schedule {
8944                                log_crash_respawn(&spec.module_id, schedule);
8945                            }
8946                            // The exited child is fully recorded at this point,
8947                            // so release it and count the backoff down in the
8948                            // command-serving branch below rather than sleeping
8949                            // here: commands cannot be received from inside this
8950                            // select arm, and an operator disable or drain that
8951                            // arrives during the backoff must cancel the pending
8952                            // respawn instead of waiting for it to spawn first.
8953                            child = None;
8954                            pending_respawn = Some(PendingRespawn { deadline: Instant::now() + delay, kind: RespawnKind::after_exit(schedule), daemon_initiated: true, approval: None });
8955                             let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = true);
8956                        }
8957                    }
8958                }
8959                command = commands.recv() => {
8960                    #[cfg(test)]
8961                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8962                    let Some(command) = command else {
8963                        containment::terminate(&runtime.child_roster.containment).await;
8964                        return;
8965                    };
8966                    if !handle_supervisor_command(
8967                        command,
8968                        &mut spec,
8969                        &mut runtime,
8970                        &registry,
8971                        &process_liveness,
8972                        &snapshot,
8973                        &mut child,
8974                        &mut commands,
8975                        &mut requeued,
8976                    ).await {
8977                        containment::terminate(&runtime.child_roster.containment).await;
8978                        return;
8979                    }
8980                }
8981                _ = async {
8982                    match registration_changes.as_mut() {
8983                        Some(changes) => { let _ = changes.changed().await; }
8984                        None => std::future::pending().await,
8985                    }
8986                }, if wire_child => {
8987                    #[cfg(test)]
8988                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8989                }
8990                _ = &mut probe_sleep => {
8991                    #[cfg(test)]
8992                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8993                    if registration_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
8994                        // Recheck after the wake: HELLO, exit or shutdown may
8995                        // have become ready in the same executor tick.
8996                        active_child.registration_deadline = None;
8997                        if !runtime.child_roster.is_closed()
8998                            && !active_child.registered_since_spawn()
8999                            && registration_child_is_running(active_child)
9000                        {
9001                            warn!(module_id = %spec.module_id, pid = active_child.pid,
9002                                wait_secs = runtime.register_timeout.as_secs(),
9003                                "supervised module registration_timeout: first HELLO deadline expired; stopping child");
9004                            active_child.spawn_failure = Some("registration_timeout".into());
9005                            if let Err(error) = stop_unregistered_child(active_child).await {
9006                                error!(module_id = %spec.module_id, %error, "failed to stop unregistered child");
9007                                fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
9008                                    &runtime.spawn_events, format!("registration_timeout: {error}"),
9009                                    &runtime.failure_context(true));
9010                                child = None;
9011                            }
9012                            // The ordinary exit handler records the child's exit,
9013                            // spends crash budget, and schedules recovery.
9014                            continue;
9015                        }
9016                    }
9017                    if health_probe.due() {
9018                        run_health_probe_cycle(
9019                            &spec,
9020                            &runtime,
9021                            &registry,
9022                            &process_liveness,
9023                            &snapshot,
9024                            &mut child,
9025                        ).await;
9026                        if child.is_none() {
9027                            runtime.start_requester = None;
9028                            runtime.pending_activity_restart = false;
9029                        }
9030                        if child.is_some() {
9031                            health_probe.schedule_next(&spec, runtime.health.cadence);
9032                        }
9033                    }
9034                }
9035            }
9036        } else if let Some(pending) = pending_respawn.clone() {
9037            tokio::select! {
9038                _ = runtime.child_roster.closed() => {
9039                    pending_respawn = None;
9040                    let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9041                        state.state = ModuleState::Stopped;
9042                        state.respawn_pending = false;
9043                    });
9044                    containment::terminate(&runtime.child_roster.containment).await;
9045                }
9046                _ = async {
9047                    sleep_until(pending.deadline).await;
9048                    #[cfg(target_os = "linux")]
9049                    ordinary_cgroup::await_clear(&runtime.child_roster, &spec.module_id).await;
9050                    if let Some(delivery) = &runtime.config_delivery {
9051                        delivery.unfenced(&spec.module_id).await;
9052                    }
9053                } => {
9054                    pending_respawn = None;
9055                    let failure = pending.failure_context(&runtime);
9056                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = false);
9057                    // A command handled below while the backoff elapsed may
9058                    // have stopped the module; never respawn past an operator's
9059                    // disable or drain.
9060                    if !respawn_still_pending(&snapshot) {
9061                        continue;
9062                    }
9063                    // The daemon began shutting down during the backoff: the
9064                    // spawn would be refused anyway, and refusing it here
9065                    // leaves the module stopped instead of reporting a
9066                    // failed restart.
9067                    if runtime.child_roster.is_closed() {
9068                        let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9069                            state.state = ModuleState::Stopped;
9070                        });
9071                        debug!(module_id = %spec.module_id, "crash respawn cancelled by daemon shutdown");
9072                        continue;
9073                    }
9074                    if let Err(err) = release_dead_registration(
9075                        &registry,
9076                        runtime.forwarding.as_deref(),
9077                        &snapshot,
9078                        &spec.module_id,
9079                        &failure,
9080                    ).await {
9081                        record_approved_attempt_failure(&spec, &snapshot, &failure, &err);
9082                        error!(module_id = %spec.module_id, error = %err, "registration did not release before restart");
9083                        continue;
9084                    }
9085
9086                    if matches!(pending.kind, RespawnKind::Reload) {
9087                        let reply = runtime.deferred_reload_reply.lock().unwrap_or_else(|p| p.into_inner()).take();
9088                        let result = finish_reload_child(&spec, &runtime, &registry, &process_liveness, &snapshot, &mut child).await;
9089                        if matches!(result, Err(SuperviseError::ConfigDeliveryDeferred { .. })) {
9090                            *runtime.deferred_reload_reply.lock().unwrap_or_else(|p| p.into_inner()) = reply;
9091                            continue;
9092                        }
9093                        if result.is_ok() && runtime.pending_activity_restart {
9094                            runtime.record_activity_transition("subc.module_restarted", &spec.module_id, runtime.start_requester.clone());
9095                        }
9096                        runtime.pending_activity_restart = false;
9097                        if let Some(reply) = reply { let _ = reply.send(result); }
9098                        continue;
9099                    }
9100                    process_liveness.track(spec.module_id.clone(), Arc::clone(&snapshot));
9101                    match admit_running_child_async(&spec, &runtime, &snapshot, pending.kind).await {
9102                        Ok(next_child) => {
9103                            child = Some(next_child);
9104                            if runtime.pending_activity_restart {
9105                                runtime.record_activity_transition("subc.module_restarted", &spec.module_id, runtime.start_requester.clone());
9106                                runtime.pending_activity_restart = false;
9107                            }
9108                            debug!(module_id = %spec.module_id, "supervised module restarted after crash");
9109                        }
9110                        Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9111                            pending_respawn = Some(PendingRespawn { deadline:Instant::now()+CONFIG_ADMISSION_RETRY_DELAY, ..pending });
9112                            let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = true);
9113                        }
9114                        Err(SuperviseError::ConfigHeld { .. }) => {
9115                            let _ = hold_config_respawn(&spec, &runtime, &snapshot, pending.kind, &failure);
9116                            runtime.pending_activity_restart = false;
9117                            process_liveness.untrack_if_current(&spec.module_id, &snapshot);
9118                        }
9119                        Err(err) => {
9120                            fail_snapshot(&snapshot, Some(&spec.module_id), None, &failure);
9121                            record_approved_attempt_failure(&spec, &snapshot, &failure, &err);
9122                            process_liveness.untrack_if_current(&spec.module_id, &snapshot);
9123                            error!(module_id = %spec.module_id, error = %err, "failed to restart supervised module");
9124                        }
9125                    }
9126                }
9127                command = commands.recv() => {
9128                    let Some(command) = command else {
9129                        containment::terminate(&runtime.child_roster.containment).await;
9130                        return;
9131                    };
9132                    if !handle_supervisor_command(
9133                        command,
9134                        &mut spec,
9135                        &mut runtime,
9136                        &registry,
9137                        &process_liveness,
9138                        &snapshot,
9139                        &mut child,
9140                        &mut commands,
9141                        &mut requeued,
9142                    ).await {
9143                        containment::terminate(&runtime.child_roster.containment).await;
9144                        return;
9145                    }
9146                    // Reconcile the pending respawn with what the command did:
9147                    // a start may already have spawned a fresh child,
9148                    // while a disable or drain moved the snapshot out of the
9149                    // state the respawn was counting down from.
9150                    if child.is_some() || !respawn_still_pending(&snapshot) {
9151                        pending_respawn = None;
9152                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = false);
9153                    }
9154                }
9155            }
9156        } else {
9157            let slow_retry = lock_snapshot(&snapshot).ok().and_then(|state| {
9158                (state.enabled && state.state == ModuleState::Failed)
9159                    .then_some(state.failed_retry.pending)
9160                    .flatten()
9161            });
9162            let command = if lock_snapshot(&snapshot)
9163                .is_ok_and(|state| state.waiting_for_previous_pid.is_some())
9164            {
9165                tokio::select! {
9166                    command = commands.recv() => command,
9167                    _ = previous_instance_recheck.tick() => {
9168                        if runtime.child_roster.previous_instance_pid(&spec.module_id).is_none() {
9169                            let enabled = lock_snapshot(&snapshot).is_ok_and(|state| state.enabled);
9170                            if enabled && !runtime.child_roster.is_closed() {
9171                                process_liveness.track(spec.module_id.clone(), Arc::clone(&snapshot));
9172                                match spawn_and_mark_running_async(&spec, &runtime, &snapshot).await {
9173                                    Ok(next_child) => child = Some(next_child),
9174                                    Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9175                                        let _ = defer_config_spawn(&spec, &runtime, &snapshot, RespawnKind::Spawn, &runtime.failure_context(true));
9176                                    }
9177                                    Err(SuperviseError::ConfigHeld { .. }) => {
9178                                        let _ = hold_config_spawn(&spec, &runtime, &snapshot, &runtime.failure_context(true));
9179                                    }
9180                                    Err(error) => {
9181                                        fail_snapshot(&snapshot, Some(&spec.module_id), None, &runtime.failure_context(true));
9182                                        error!(module_id = %spec.module_id, %error, "failed to start module after its previous instance exited");
9183                                    }
9184                                }
9185                            } else {
9186                                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9187                                    state.waiting_for_previous_pid = None;
9188                                    state.waiting_for_previous_detail = None;
9189                                });
9190                            }
9191                        }
9192                        continue;
9193                    }
9194                }
9195            } else {
9196                tokio::select! {
9197                    biased;
9198                    command = commands.recv() => command,
9199                    _ = async {
9200                        match slow_retry {
9201                            Some(retry) => sleep_until(retry.deadline).await,
9202                            None => std::future::pending().await,
9203                        }
9204                    } => {
9205                        let retry = slow_retry.expect("only a scheduled slow retry can wake");
9206                        let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9207                            state.failed_retry.pending = None;
9208                        });
9209                        if runtime.child_roster.is_closed() {
9210                            continue;
9211                        }
9212                        info!(module_id = %spec.module_id, attempt = retry.attempt,
9213                            delay_secs = retry.delay.as_secs(), "starting failed module retry");
9214                        if let Err(error) = set_child_enabled(
9215                            &spec, &runtime, &registry, &process_liveness, &snapshot, &mut child, true,
9216                            &runtime.failure_context(true),
9217                        ).await {
9218                            error!(module_id = %spec.module_id, %error, "failed module retry could not start");
9219                        }
9220                        continue;
9221                    }
9222                }
9223            };
9224            let Some(command) = command else {
9225                containment::terminate(&runtime.child_roster.containment).await;
9226                return;
9227            };
9228            if !handle_supervisor_command(
9229                command,
9230                &mut spec,
9231                &mut runtime,
9232                &registry,
9233                &process_liveness,
9234                &snapshot,
9235                &mut child,
9236                &mut commands,
9237                &mut requeued,
9238            )
9239            .await
9240            {
9241                containment::terminate(&runtime.child_roster.containment).await;
9242                return;
9243            }
9244        }
9245    }
9246}
9247
9248// Preserve the deadline until the future is polled. Starting a relative sleep
9249// after the executor yields would restart part of the countdown.
9250async fn supervisor_sleep(wake_at: Option<Instant>) {
9251    match wake_at {
9252        Some(deadline) => sleep_until(deadline).await,
9253        None => std::future::pending().await,
9254    }
9255}
9256
9257fn log_crash_respawn(module_id: &str, schedule: CrashRestartSchedule) {
9258    info!(
9259        module_id,
9260        restart_in_window = schedule.restart_in_window,
9261        delay_ms = schedule.delay.as_millis() as u64,
9262        "respawning after crash"
9263    );
9264}
9265
9266/// Whether the respawn a backoff was counting down to is still wanted. A
9267/// disable or drain handled while the backoff elapsed moves the snapshot out
9268/// of `Restarting`, and the operator's stop must win over the pending respawn,
9269/// so every sleep-then-spawn path re-validates against the live snapshot
9270/// instead of assuming the state it left behind still holds.
9271fn respawn_still_pending(snapshot: &SharedSnapshot) -> bool {
9272    matches!(
9273        lock_snapshot(snapshot),
9274        Ok(state) if state.enabled && state.state == ModuleState::Restarting
9275    )
9276}
9277
9278enum NextAction {
9279    Stop {
9280        registration_released: bool,
9281    },
9282    Restart {
9283        schedule: Option<CrashRestartSchedule>,
9284    },
9285}
9286
9287#[allow(clippy::too_many_arguments)]
9288async fn handle_supervisor_command(
9289    command: SupervisorCommand,
9290    spec: &mut ModuleSpec,
9291    runtime: &mut SupervisorRuntimeConfig,
9292    registry: &Arc<Registry>,
9293    process_liveness: &SupervisorProcessLiveness,
9294    snapshot: &SharedSnapshot,
9295    child: &mut Option<SupervisedChild>,
9296    commands: &mut mpsc::Receiver<SupervisorCommand>,
9297    requeued: &mut VecDeque<SupervisorCommand>,
9298) -> bool {
9299    if let SupervisorCommand::SetEnabled {
9300        enabled: true,
9301        reset_budget: false,
9302        reply,
9303        ..
9304    } = command
9305    {
9306        let parked = lock_snapshot(snapshot).ok().and_then(|state| {
9307            (state.config_hold_parked
9308                && state.enabled
9309                && !state.process_alive
9310                && child.is_none()
9311                && state.state == ModuleState::Stopped)
9312                .then(|| {
9313                    (
9314                        state.config_hold_daemon_initiated,
9315                        state.config_hold_approval.clone(),
9316                    )
9317                })
9318        });
9319        // Clearing a configuration-delivery block must not restart a child that
9320        // exited on its own or exhausted its crash budget. Resume only an actor
9321        // stopped by a configuration hold; otherwise leave its slow retry alone.
9322        let result = if let Some((daemon_initiated, approval)) = parked {
9323            runtime.recovery_is_daemon = daemon_initiated;
9324            let failure = FailureContext {
9325                approval,
9326                ..runtime.failure_context(daemon_initiated)
9327            };
9328            let result = set_child_enabled_with_budget_policy(
9329                spec,
9330                runtime,
9331                registry,
9332                process_liveness,
9333                snapshot,
9334                child,
9335                true,
9336                &failure,
9337                false,
9338            )
9339            .await;
9340            if let Err(error) = &result {
9341                record_approved_attempt_failure(spec, snapshot, &failure, error);
9342            }
9343            result
9344        } else {
9345            Ok(false)
9346        };
9347        let _ = reply.send(result);
9348        return true;
9349    }
9350    let blocked = runtime
9351        .config_delivery
9352        .as_ref()
9353        .and_then(|delivery| delivery.0.check_module_hold(&spec.module_id).err())
9354        .filter(|error| error.code != "config_delivery_deferred")
9355        .map(|error| {
9356            config_delivery::gate_hold_error(spec, error, runtime.config_delivery.as_ref())
9357        })
9358        .or_else(|| recovery_block_error(spec, &runtime.child_roster))
9359        .or_else(|| {
9360            runtime
9361                .child_roster
9362                .previous_instance(&spec.module_id)
9363                .map(|(pid, reason)| previous_instance_error(spec, pid, reason))
9364        });
9365    let command = if let Some(error) = blocked {
9366        match command {
9367            SupervisorCommand::Restart { reply, .. } | SupervisorCommand::Reload { reply, .. } => {
9368                let _ = reply.send(Err(error));
9369                return true;
9370            }
9371            SupervisorCommand::Swap { reply, .. } => {
9372                let _ = reply.send(Err(error));
9373                return true;
9374            }
9375            SupervisorCommand::ConfigApplyRestart { .. } => return true,
9376            SupervisorCommand::SetEnabled {
9377                enabled: true,
9378                requester,
9379                reply,
9380                ..
9381            } => {
9382                if matches!(error, SuperviseError::ConfigHeld { .. })
9383                    && lock_snapshot(snapshot).is_ok_and(|state| !state.enabled)
9384                    && runtime
9385                        .config_delivery
9386                        .as_ref()
9387                        .is_some_and(|delivery| delivery.0.can_stage_unstamp_enable())
9388                {
9389                    // Stage only the pending unstamp's desired state. A stamped
9390                    // unapproved actor stays refused; admission release starts
9391                    // an unstamped actor only after reconciliation completes.
9392                    let mut changed = false;
9393                    let result = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9394                        changed = !state.enabled;
9395                        state.enabled = true;
9396                        if child.is_none() && state.waiting_for_previous_pid.is_none() {
9397                            state.state = ModuleState::Starting;
9398                            state.failed_retry.cancel();
9399                        }
9400                    })
9401                    .and_then(|_| {
9402                        if child.is_none()
9403                            && lock_snapshot(snapshot)?.waiting_for_previous_pid.is_none()
9404                        {
9405                            hold_config_spawn(
9406                                spec,
9407                                runtime,
9408                                snapshot,
9409                                &runtime.failure_context(false),
9410                            )?;
9411                        }
9412                        Ok(changed)
9413                    });
9414                    if result.is_ok() && changed {
9415                        runtime.start_requester = requester;
9416                    }
9417                    let _ = reply.send(result);
9418                    return true;
9419                }
9420                let _ = reply.send(Err(error));
9421                return true;
9422            }
9423            other => other,
9424        }
9425    } else {
9426        command
9427    };
9428    // A refused start or restart leaves the Failed actor's existing recovery
9429    // deadline intact. Cancel only after the command passes admission.
9430    if matches!(
9431        command,
9432        SupervisorCommand::Drain { .. }
9433            | SupervisorCommand::Retire { .. }
9434            | SupervisorCommand::SetEnabled { .. }
9435            | SupervisorCommand::Restart { .. }
9436    ) {
9437        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9438            state.failed_retry.cancel();
9439        });
9440    }
9441    match command {
9442        SupervisorCommand::ApprovedConfiguration { approved, reply } => {
9443            let result = async {
9444                let next = approved.module_entry(&spec.module_id).map_err(|error| {
9445                    SuperviseError::InvalidSpec { reason: error.to_string() }
9446                })?;
9447                let retry_approved_failure = {
9448                    let mut state = lock_snapshot(snapshot)?;
9449                    if let Some((generation, detail)) = &state.approved_start_failure {
9450                        if *generation == approved.identity() && next.enabled {
9451                            return Err(SuperviseError::Spawn {
9452                                program: spec.program.clone(),
9453                                source: std::io::Error::other(detail.clone()),
9454                                cgroup_path: None,
9455                            });
9456                        }
9457                    }
9458                    let retry = state.approved_start_failure.is_some();
9459                    state.approved_start_failure = None;
9460                    retry
9461                };
9462                stage_supervisor_configuration(
9463                    spec, runtime, snapshot, next.module_spec(), next.health,
9464                    next.drain_timeout_ms,
9465                );
9466                runtime.restart_policy = next.restart;
9467                runtime.register_timeout = next.register_timeout;
9468                if let Some(active) = child.as_mut()
9469                    .filter(|child| child.registration_deadline.is_some())
9470                {
9471                    active.registration_deadline = Some(active.spawned_at + next.register_timeout);
9472                }
9473                let enabled = lock_snapshot(snapshot)?.enabled;
9474                // An approval retries a changed failed entry or its own earlier
9475                // failed start, not an unrelated crash-budget failure. For an
9476                // unchanged entry, reconciled means the approved configuration
9477                // is effective; it does not claim the process has recovered.
9478                // A terminal gate stop is different: a new approval owns its
9479                // recovery even when the daemon entry itself did not change.
9480                let retry_gate_stopped = lock_snapshot(snapshot)?
9481                    .needs_approved_gate_restart(&approved.identity());
9482                let retry_failed = enabled && child.is_none()
9483                    && ((lock_snapshot(snapshot)?.state == ModuleState::Failed
9484                        && (retry_approved_failure || approved.changes_entry(&spec.module_id)))
9485                        || retry_gate_stopped);
9486                if retry_failed {
9487                    // This approval owns a new start, so the failed attempt's
9488                    // daemon retry must not survive either result of that start.
9489                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
9490                        state.failed_retry.cancel();
9491                        if retry_gate_stopped {
9492                            state.stop_reason = None;
9493                            state.config_exit_failed_approval = None;
9494                        }
9495                    })?;
9496                }
9497                if enabled != next.enabled || retry_failed {
9498                    let failure = FailureContext {
9499                        approval: next.enabled.then(|| approved.identity()),
9500                        ..runtime.failure_context(false)
9501                    };
9502                    let held = next.enabled && runtime.config_delivery.as_ref()
9503                        .is_some_and(|delivery| delivery.0.has_recorded_admission_hold(&spec.module_id)
9504                            || delivery.0.check_module_hold(&spec.module_id).is_err_and(|error| error.code == "config_delivery_deferred"));
9505                    if held {
9506                        // Preserve module-delivery failure/recovery holds. The
9507                        // admission release starts the actor when its own hold ends.
9508                        reset_restart_count(snapshot, &spec.module_id)?;
9509                        update_snapshot(snapshot, Some(&spec.module_id), |state| {
9510                            state.enabled = true;
9511                            if child.is_none() && state.waiting_for_previous_pid.is_none() {
9512                                state.state = ModuleState::Starting;
9513                            }
9514                        })?;
9515                        if child.is_none() && lock_snapshot(snapshot)?.waiting_for_previous_pid.is_none() {
9516                            hold_config_spawn(spec, runtime, snapshot, &failure)?;
9517                        }
9518                    } else {
9519                        match set_child_enabled_with_budget_policy(
9520                            spec, runtime, registry, process_liveness, snapshot, child,
9521                            next.enabled, &failure, true,
9522                        ).await {
9523                            Ok(_) => {},
9524                            Err(SuperviseError::ConfigHeld { .. }) if next.enabled => {},
9525                            Err(error) => return Err(error),
9526                        }
9527                        if !next.enabled {
9528                            containment::terminate(&runtime.child_roster.containment).await;
9529                        }
9530                    }
9531                }
9532                if (child.as_ref().is_some_and(|child| child.registration_spawn.is_some() && child.admission_base.is_none())
9533                        || (child.is_none() && lock_snapshot(snapshot)?.state == ModuleState::Restarting
9534                            && runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.stamp_channel_cutover_pending())))
9535                    && runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.module_is_gated(&spec.module_id))
9536                {
9537                    let failure = FailureContext {
9538                        approval: Some(approved.identity()),
9539                        ..runtime.failure_context(false)
9540                    };
9541                    // A stamp cannot adopt an unverified legacy process, even
9542                    // when its approved replacement no longer speaks subc.
9543                    // Stopping that process spends no crash restart budget.
9544                    if child.is_some() {
9545                        restart_child_with_budget_policy(spec, runtime, registry,
9546                            process_liveness, snapshot, child, runtime.drain_timeout, false).await?;
9547                    }
9548                    // The stamp is already committed. A deferred or held launch
9549                    // belongs to the normal retry/hold loop, not a failed apply.
9550                    update_snapshot(snapshot, Some(&spec.module_id), |state| state.respawn_pending = false)?;
9551                    match spawn_and_mark_running_async(spec, runtime, snapshot).await {
9552                        Ok(replacement) => *child = Some(replacement),
9553                        Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9554                            defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, &failure)?;
9555                        }
9556                        Err(SuperviseError::ConfigHeld { .. }) => hold_config_spawn(spec, runtime, snapshot, &failure)?,
9557                        Err(error) => {
9558                            fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
9559                            return Err(error);
9560                        }
9561                    }
9562                }
9563                info!(module_id=%spec.module_id, config_generation=approved.generation(), "approved daemon entry reconciled");
9564                Ok(())
9565            }
9566            .await;
9567            if let Err(error) = &result {
9568                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9569                    if state.enabled
9570                        && state.state == ModuleState::Failed
9571                        && state
9572                            .approved_start_failure
9573                            .as_ref()
9574                            .is_none_or(|(generation, _)| *generation != approved.identity())
9575                    {
9576                        state.approved_start_failure =
9577                            Some((approved.identity(), error.to_string()));
9578                    }
9579                });
9580            }
9581            let _ = reply.send(result);
9582            true
9583        }
9584        SupervisorCommand::ConfigPolicyProbe {
9585            connection,
9586            generation,
9587            attempt,
9588        } => {
9589            let Some(delivery) = &runtime.config_delivery else {
9590                return true;
9591            };
9592            let Ok(gate) = delivery.0.module_gate(&spec.module_id) else {
9593                return true;
9594            };
9595            let guard = gate.lock().await;
9596            let pending = delivery
9597                .0
9598                .on_blocking(move |owner| {
9599                    owner.policy_probe_pending(connection, generation, attempt)
9600                })
9601                .await
9602                .unwrap_or(false)
9603                && child.is_some()
9604                && registry
9605                    .get_module(&spec.module_id)
9606                    .ok()
9607                    .flatten()
9608                    .is_some_and(|registration| registration.connection_id == connection);
9609            drop(guard);
9610            if pending {
9611                run_health_probe_cycle(spec, runtime, registry, process_liveness, snapshot, child)
9612                    .await;
9613            }
9614            true
9615        }
9616        SupervisorCommand::ConfigApplyRestart {
9617            generation,
9618            supersedes_swap,
9619        } => {
9620            let Some(owner) = runtime
9621                .config_delivery
9622                .as_ref()
9623                .map(|delivery| delivery.0.clone())
9624            else {
9625                return true;
9626            };
9627            let Ok(gate) = owner.module_gate(&spec.module_id) else {
9628                return true;
9629            };
9630            let _guard = gate.lock().await;
9631            let spawn = child
9632                .as_ref()
9633                .and_then(|child| child.config_delivery.clone());
9634            let module = spec.module_id.clone();
9635            let current = owner
9636                .on_blocking(move |owner| {
9637                    Ok((supersedes_swap
9638                        || owner
9639                            .pending_config_restarts()?
9640                            .contains(&(module.clone(), generation)))
9641                        && owner.requires_fresher_spawn(&module, spawn.as_ref())?
9642                            == Some(generation))
9643                })
9644                .await
9645                .unwrap_or(false);
9646            if !current
9647                || !lock_snapshot(snapshot).is_ok_and(|state| {
9648                    state.enabled && !state.respawn_pending && state.process_alive
9649                })
9650            {
9651                return true;
9652            }
9653            drop(_guard);
9654            info!(module_id=%spec.module_id, config_generation=generation, "approved configuration restart preserves the crash budget");
9655            if let Err(error) = restart_child_with_budget_policy(
9656                spec,
9657                runtime,
9658                registry,
9659                process_liveness,
9660                snapshot,
9661                child,
9662                runtime.drain_timeout,
9663                false,
9664            )
9665            .await
9666            {
9667                warn!(module_id=%spec.module_id, %error, "approved configuration restart could not be scheduled");
9668            }
9669            true
9670        }
9671        SupervisorCommand::ConfigExitHold { reply } => {
9672            // A notification owns no start, backoff, reload reply or previous-
9673            // instance wait. Only an idle, registered initial start has no work
9674            // to preserve; its initialized startup context can be parked here.
9675            let idle_start = child.is_none()
9676                && lock_snapshot(snapshot).is_ok_and(|state| {
9677                    state.enabled
9678                        && state.state == ModuleState::Starting
9679                        && !state.process_alive
9680                        && !state.respawn_pending
9681                        && state.waiting_for_previous_pid.is_none()
9682                        && state.waiting_for_previous_detail.is_none()
9683                        && state.failed_retry.pending.is_none()
9684                })
9685                && runtime
9686                    .scheduled_respawn
9687                    .lock()
9688                    .unwrap_or_else(|p| p.into_inner())
9689                    .is_none()
9690                && runtime
9691                    .deferred_reload_reply
9692                    .lock()
9693                    .unwrap_or_else(|p| p.into_inner())
9694                    .is_none();
9695            let result = if idle_start {
9696                try_park_config_attempt(
9697                    spec,
9698                    runtime,
9699                    snapshot,
9700                    &runtime.failure_context(runtime.recovery_is_daemon),
9701                    None,
9702                )
9703                .map(|_| ())
9704            } else {
9705                Ok(())
9706            };
9707            let _ = reply.send(result);
9708            true
9709        }
9710        SupervisorCommand::ConfigDeliveryFailed { connection, hold } => {
9711            if registry
9712                .get_module(&spec.module_id)
9713                .ok()
9714                .flatten()
9715                .is_none_or(|registration| registration.connection_id != connection)
9716            {
9717                return true;
9718            }
9719            runtime.recovery_is_daemon = true;
9720            // With a recoverable generation, delivery-failure recovery spends
9721            // one crash-budget entry: the module rejected its configuration.
9722            // Approved configuration restarts spend none.
9723            if hold {
9724                let notice = begin_forwarding_drain_if_configured(
9725                    spec,
9726                    runtime,
9727                    registry,
9728                    snapshot,
9729                    Some(true),
9730                    RouteCloseReason::Disable,
9731                )
9732                .await;
9733                if let Ok(notice) = notice {
9734                    let drained = drain_optional_child(
9735                        &spec.module_id,
9736                        spec.protocol,
9737                        notice,
9738                        registry,
9739                        runtime.forwarding.as_deref(),
9740                        snapshot,
9741                        &runtime.terminal_ring,
9742                        &runtime.spawn_events,
9743                        child,
9744                        runtime.drain_timeout,
9745                        ModuleState::Failed,
9746                        Some(true),
9747                        &runtime.failure_context(true),
9748                    )
9749                    .await;
9750                    if drained.is_ok() {
9751                        match try_park_config_attempt(
9752                            spec,
9753                            runtime,
9754                            snapshot,
9755                            &runtime.failure_context(true),
9756                            None,
9757                        ) {
9758                            Ok(true) => {}
9759                            Ok(false) => {
9760                                if let Err(error) = budgeted_restart_child(
9761                                    spec,
9762                                    runtime,
9763                                    registry,
9764                                    process_liveness,
9765                                    snapshot,
9766                                    child,
9767                                    SupervisorHealthStatus::Unknown,
9768                                    Some("configuration delivery failed after its hold ended"),
9769                                    unix_ms_now(),
9770                                    false,
9771                                )
9772                                .await
9773                                {
9774                                    warn!(module_id=%spec.module_id, %error, "configuration failure restart could not be scheduled");
9775                                }
9776                            }
9777                            Err(error) => {
9778                                warn!(module_id=%spec.module_id, %error, "configuration failure could not be parked")
9779                            }
9780                        }
9781                    }
9782                }
9783            } else if let Err(error) = budgeted_restart_child(
9784                spec,
9785                runtime,
9786                registry,
9787                process_liveness,
9788                snapshot,
9789                child,
9790                SupervisorHealthStatus::Unknown,
9791                Some("configuration delivery failed"),
9792                unix_ms_now(),
9793                false,
9794            )
9795            .await
9796            {
9797                warn!(module_id=%spec.module_id, %error, "configuration failure restart could not be scheduled");
9798            }
9799            true
9800        }
9801        SupervisorCommand::Drain { requester, reply } => {
9802            // A plain stop runs no forwarding drain, so nothing reaches the
9803            // module over its connection before the wait: ask by signal.
9804            let result = drain_optional_child(
9805                &spec.module_id,
9806                spec.protocol,
9807                StopNotice::NotSent,
9808                registry,
9809                runtime.forwarding.as_deref(),
9810                snapshot,
9811                &runtime.terminal_ring,
9812                &runtime.spawn_events,
9813                child,
9814                runtime.drain_timeout,
9815                ModuleState::Stopped,
9816                None,
9817                &FailureContext::operator(),
9818            )
9819            .await;
9820            containment::terminate(&runtime.child_roster.containment).await;
9821            let registration_released = result.is_ok();
9822            if registration_released {
9823                runtime.record_activity_transition(
9824                    "subc.module_stopped",
9825                    &spec.module_id,
9826                    requester,
9827                );
9828            }
9829            let _ = reply.send(result);
9830            if registration_released {
9831                process_liveness.untrack_if_current(&spec.module_id, snapshot);
9832            }
9833            false
9834        }
9835        SupervisorCommand::Retire { requester, reply } => {
9836            let result = async {
9837                let stop_notice = begin_forwarding_drain_if_configured(
9838                    spec,
9839                    runtime,
9840                    registry,
9841                    snapshot,
9842                    None,
9843                    RouteCloseReason::Disable,
9844                )
9845                .await?;
9846                drain_optional_child(
9847                    &spec.module_id,
9848                    spec.protocol,
9849                    stop_notice,
9850                    registry,
9851                    runtime.forwarding.as_deref(),
9852                    snapshot,
9853                    &runtime.terminal_ring,
9854                    &runtime.spawn_events,
9855                    child,
9856                    runtime.drain_timeout,
9857                    ModuleState::Stopped,
9858                    None,
9859                    &FailureContext::operator(),
9860                )
9861                .await
9862            }
9863            .await;
9864            containment::terminate(&runtime.child_roster.containment).await;
9865            let registration_released = result.is_ok();
9866            if registration_released {
9867                runtime.record_activity_transition(
9868                    "subc.module_stopped",
9869                    &spec.module_id,
9870                    requester,
9871                );
9872            }
9873            let _ = reply.send(result);
9874            if registration_released {
9875                process_liveness.untrack_if_current(&spec.module_id, snapshot);
9876            }
9877            false
9878        }
9879        SupervisorCommand::Restart {
9880            requester,
9881            drain_timeout_ms,
9882            received_at_generation,
9883            queued_at,
9884            reply,
9885        } => {
9886            // Without this line a restart that waited in the queue (behind a
9887            // health probe cycle or another command) was invisible: the log
9888            // showed only the drain timing out, minutes after the operator's call.
9889            info!(
9890                module_id = %spec.module_id,
9891                queued_ms = u64::try_from(queued_at.elapsed().as_millis()).unwrap_or(u64::MAX),
9892                "restart command dequeued"
9893            );
9894            // ACK AT INITIATION, not completion. The blocking form deadlocked any
9895            // caller whose own request lane rides the module being restarted: the
9896            // caller's in-flight request keeps the drain from quiescing, the drain
9897            // keeps the restart from completing, and the completion keeps the reply
9898            // from releasing the caller — so the drain always timed out and cut the
9899            // initiator with a GOODBYE, even on a healthy module. Replying once the
9900            // restart is validated lets a self-lane caller settle, which is exactly
9901            // what makes the drain succeed. Completion is observable via
9902            // supervisor.list / module status; a post-ack failure lands the module
9903            // in a visible terminal state below rather than in a reply nobody can
9904            // receive.
9905            let validation = match lock_snapshot(snapshot) {
9906                Ok(state) if !state.enabled => Err(SuperviseError::Disabled {
9907                    module_id: spec.module_id.clone(),
9908                }),
9909                Ok(_) => Ok(()),
9910                Err(err) => Err(err),
9911            };
9912            let initiated = validation.is_ok();
9913            let _ = reply.send(validation);
9914            // A restart asks for a fresh process. Commands run one at a time,
9915            // so a restart queued behind another restart (two operator calls
9916            // in quick succession) is dequeued the moment the first one has
9917            // spawned its replacement -- before that process has sent HELLO.
9918            // Running it would drain and kill the process the first restart
9919            // just produced, which is the opposite of what both callers asked
9920            // for. If a process spawned after this request was received is
9921            // still supervised, the request is already satisfied. Not when the
9922            // configuration changed since that spawn: then the newer process
9923            // predates the spec this restart may exist to apply.
9924            // Generation publication can lag a child that is already serving
9925            // while its identity is recorded. Only process creation after request
9926            // receipt satisfies a restart, not publication after receipt.
9927            let satisfied_by_generation = if initiated
9928                && child
9929                    .as_ref()
9930                    .is_some_and(|child| child.spawned_at > queued_at)
9931            {
9932                lock_snapshot(snapshot).ok().and_then(|state| {
9933                    (!state.configuration_updated_since_spawn).then_some(state.spawn_generation)
9934                })
9935            } else {
9936                None
9937            };
9938            let satisfied_by_pending = initiated
9939                && child.is_none()
9940                && lock_snapshot(snapshot).ok().is_some_and(|mut state| {
9941                    // No child exists yet, so this replacement will necessarily
9942                    // be created after the queued request, unlike a published
9943                    // generation whose process may already have been serving.
9944                    let pending = state.respawn_pending && !state.configuration_updated_since_spawn;
9945                    if pending {
9946                        state.coalesced_restart_pending = true;
9947                    }
9948                    pending
9949                });
9950            if satisfied_by_pending {
9951                debug!(module_id = %spec.module_id, "restart coalesced into the pending replacement");
9952            } else if let Some(generation) = satisfied_by_generation {
9953                info!(
9954                    module_id = %spec.module_id,
9955                    received_at_generation,
9956                    "restart already satisfied by generation {generation}; not restarting again"
9957                );
9958            } else if initiated {
9959                // Precedence: this restart's operator override, else the module's
9960                // configured budget (already resolved into the runtime).
9961                let drain_timeout = drain_timeout_ms
9962                    .map(Duration::from_millis)
9963                    .unwrap_or(runtime.drain_timeout);
9964                if let Err(err) = restart_child(
9965                    spec,
9966                    runtime,
9967                    registry,
9968                    process_liveness,
9969                    snapshot,
9970                    child,
9971                    drain_timeout,
9972                )
9973                .await
9974                {
9975                    warn!(
9976                        module_id = %spec.module_id,
9977                        error = %err,
9978                        "operator restart failed after initiation ack; module state carries the outcome"
9979                    );
9980                    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9981                        state.state = ModuleState::Failed;
9982                        clear_current_process_facts(state);
9983                    });
9984                } else {
9985                    runtime.start_requester = requester;
9986                    runtime.pending_activity_restart = true;
9987                }
9988            }
9989            true
9990        }
9991        SupervisorCommand::Reload { requester, reply } => {
9992            let result =
9993                reload_child(spec, runtime, registry, process_liveness, snapshot, child).await;
9994            if result.is_ok() {
9995                runtime.start_requester = requester;
9996                runtime.pending_activity_restart = true;
9997            }
9998            if result.is_ok()
9999                && runtime
10000                    .scheduled_respawn
10001                    .lock()
10002                    .unwrap_or_else(|p| p.into_inner())
10003                    .as_ref()
10004                    .is_some_and(|pending| matches!(pending.kind, RespawnKind::Reload))
10005            {
10006                *runtime
10007                    .deferred_reload_reply
10008                    .lock()
10009                    .unwrap_or_else(|p| p.into_inner()) = Some(reply);
10010            } else {
10011                let _ = reply.send(result);
10012            }
10013            true
10014        }
10015        SupervisorCommand::SetEnabled {
10016            enabled,
10017            requester,
10018            reply,
10019            reset_budget,
10020        } => {
10021            let previous_requester = runtime.start_requester.clone();
10022            if enabled {
10023                runtime.start_requester = requester.clone();
10024            }
10025            let result = set_child_enabled_with_budget_policy(
10026                spec,
10027                runtime,
10028                registry,
10029                process_liveness,
10030                snapshot,
10031                child,
10032                enabled,
10033                &runtime.failure_context(false),
10034                reset_budget,
10035            )
10036            .await;
10037            if !enabled {
10038                containment::terminate(&runtime.child_roster.containment).await;
10039            }
10040            if matches!(result, Ok(true)) {
10041                runtime.pending_activity_restart = false;
10042                if enabled {
10043                    runtime.start_requester = requester;
10044                } else {
10045                    runtime.start_requester = None;
10046                    runtime.record_activity_transition(
10047                        "subc.module_disabled",
10048                        &spec.module_id,
10049                        requester,
10050                    );
10051                }
10052            } else {
10053                runtime.start_requester = previous_requester;
10054            }
10055            let _ = reply.send(result);
10056            true
10057        }
10058        SupervisorCommand::UpdateConfiguration {
10059            spec: next_spec,
10060            health,
10061            drain_timeout_ms,
10062            reply,
10063        } => {
10064            if runtime
10065                .config_delivery
10066                .as_ref()
10067                .is_some_and(|delivery| delivery.0.file_configuration_is_gated(&spec.module_id))
10068            {
10069                let _ = reply.send(Err(SuperviseError::ConfigHeld {
10070                    module_id: spec.module_id.clone(),
10071                    code: "config_gated".into(),
10072                    detail: "live file reconfiguration cannot replace stamped authority".into(),
10073                }));
10074                return true;
10075            }
10076            stage_supervisor_configuration(
10077                spec,
10078                runtime,
10079                snapshot,
10080                next_spec,
10081                health,
10082                drain_timeout_ms,
10083            );
10084            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10085                state.configuration_updated_since_spawn = true;
10086            });
10087            let _ = reply.send(Ok(()));
10088            true
10089        }
10090        SupervisorCommand::Swap {
10091            requester,
10092            ready_timeout,
10093            reply,
10094        } => {
10095            if spec.carry_containment
10096                || containment::current(&runtime.child_roster.containment).is_some()
10097            {
10098                let _ = reply.send(Err(SuperviseError::InvalidSpec {
10099                    reason: "a carried container cannot overlap a swap candidate".to_owned(),
10100                }));
10101                return true;
10102            }
10103            let mut swap_runtime = runtime.clone();
10104            swap_runtime.start_requester = requester;
10105            let before = lock_snapshot(snapshot)
10106                .ok()
10107                .map(|state| state.spawn_generation);
10108            let end = swap::run_swap(
10109                spec,
10110                &swap_runtime,
10111                registry,
10112                process_liveness,
10113                snapshot,
10114                child,
10115                commands,
10116                ready_timeout.unwrap_or(DEFAULT_SWAP_READY_TIMEOUT),
10117                reply,
10118            )
10119            .await;
10120            if before
10121                != lock_snapshot(snapshot)
10122                    .ok()
10123                    .map(|state| state.spawn_generation)
10124            {
10125                runtime.start_requester = swap_runtime.start_requester;
10126            }
10127            requeued.extend(end.requeue);
10128            true
10129        }
10130    }
10131}
10132
10133fn stage_supervisor_configuration(
10134    spec: &mut ModuleSpec,
10135    runtime: &mut SupervisorRuntimeConfig,
10136    snapshot: &SharedSnapshot,
10137    next_spec: ModuleSpec,
10138    health: HealthConfig,
10139    drain_timeout_ms: Option<u64>,
10140) {
10141    if let Some(handle) = &runtime.supervisor_handle {
10142        handle.apply_identity_configuration(&next_spec);
10143    }
10144    let launch_changed = *spec != next_spec;
10145    *spec = next_spec;
10146    if launch_changed {
10147        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10148            state.configuration_updated_since_spawn = true
10149        });
10150    }
10151    let health_changed = runtime.health != health;
10152    runtime.health = health;
10153    // Reset the cadence and old endpoint's failure streak on a live
10154    // health-policy change rather than waiting for its old deadline.
10155    if health_changed {
10156        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10157            state.health = ModuleHealthStatus::default();
10158            state.last_probe_evidence = None;
10159        });
10160    }
10161    runtime.drain_timeout = drain_timeout_ms
10162        .map(Duration::from_millis)
10163        .unwrap_or(runtime.default_drain_timeout);
10164    *runtime
10165        .effective_drain_timeout
10166        .lock()
10167        .unwrap_or_else(|p| p.into_inner()) = runtime.drain_timeout;
10168}
10169
10170async fn restart_child(
10171    spec: &ModuleSpec,
10172    runtime: &SupervisorRuntimeConfig,
10173    registry: &Registry,
10174    process_liveness: &SupervisorProcessLiveness,
10175    snapshot: &SharedSnapshot,
10176    child: &mut Option<SupervisedChild>,
10177    drain_timeout: Duration,
10178) -> Result<(), SuperviseError> {
10179    restart_child_with_budget_policy(
10180        spec,
10181        runtime,
10182        registry,
10183        process_liveness,
10184        snapshot,
10185        child,
10186        drain_timeout,
10187        true,
10188    )
10189    .await
10190}
10191
10192#[allow(clippy::too_many_arguments)]
10193async fn restart_child_with_budget_policy(
10194    spec: &ModuleSpec,
10195    runtime: &SupervisorRuntimeConfig,
10196    registry: &Registry,
10197    process_liveness: &SupervisorProcessLiveness,
10198    snapshot: &SharedSnapshot,
10199    child: &mut Option<SupervisedChild>,
10200    drain_timeout: Duration,
10201    reset_budget: bool,
10202) -> Result<(), SuperviseError> {
10203    // Restart cycles a running module; it must not silently start a disabled one.
10204    if !lock_snapshot(snapshot)?.enabled {
10205        return Err(SuperviseError::Disabled {
10206            module_id: spec.module_id.clone(),
10207        });
10208    }
10209    let stop_notice = begin_forwarding_drain_with_timeout(
10210        spec,
10211        runtime,
10212        registry,
10213        snapshot,
10214        None,
10215        RouteCloseReason::Restart,
10216        drain_timeout,
10217    )
10218    .await?;
10219
10220    if child.is_some() {
10221        drain_optional_child(
10222            &spec.module_id,
10223            spec.protocol,
10224            stop_notice,
10225            registry,
10226            runtime.forwarding.as_deref(),
10227            snapshot,
10228            &runtime.terminal_ring,
10229            &runtime.spawn_events,
10230            child,
10231            drain_timeout,
10232            ModuleState::Restarting,
10233            Some(true),
10234            &FailureContext::operator(),
10235        )
10236        .await?;
10237    } else {
10238        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10239            state.enabled = true;
10240            state.state = ModuleState::Restarting;
10241            clear_current_process_facts(state);
10242        })?;
10243        release_dead_registration(
10244            registry,
10245            runtime.forwarding.as_deref(),
10246            snapshot,
10247            &spec.module_id,
10248            &runtime.failure_context(false),
10249        )
10250        .await?;
10251    }
10252
10253    if reset_budget {
10254        reset_restart_count(snapshot, &spec.module_id)?;
10255    }
10256    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10257    schedule_respawn(
10258        runtime,
10259        snapshot,
10260        &spec.module_id,
10261        runtime.restart_policy.backoff,
10262        RespawnKind::Spawn,
10263        false,
10264    )
10265}
10266
10267async fn reload_child(
10268    spec: &ModuleSpec,
10269    runtime: &SupervisorRuntimeConfig,
10270    registry: &Registry,
10271    process_liveness: &SupervisorProcessLiveness,
10272    snapshot: &SharedSnapshot,
10273    child: &mut Option<SupervisedChild>,
10274) -> Result<(), SuperviseError> {
10275    // Reload cycles a running module; it must not silently start a disabled one.
10276    if !lock_snapshot(snapshot)?.enabled {
10277        return Err(SuperviseError::Disabled {
10278            module_id: spec.module_id.clone(),
10279        });
10280    }
10281    let stop_notice = begin_forwarding_drain(
10282        spec,
10283        runtime,
10284        registry,
10285        snapshot,
10286        Some(true),
10287        RouteCloseReason::Reload,
10288    )
10289    .await?;
10290
10291    if child.is_some() {
10292        drain_optional_child(
10293            &spec.module_id,
10294            spec.protocol,
10295            stop_notice,
10296            registry,
10297            runtime.forwarding.as_deref(),
10298            snapshot,
10299            &runtime.terminal_ring,
10300            &runtime.spawn_events,
10301            child,
10302            runtime.drain_timeout,
10303            ModuleState::Restarting,
10304            Some(true),
10305            &FailureContext::operator(),
10306        )
10307        .await?;
10308    } else {
10309        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10310            state.enabled = true;
10311            state.state = ModuleState::Restarting;
10312            clear_current_process_facts(state);
10313        })?;
10314        release_dead_registration(
10315            registry,
10316            runtime.forwarding.as_deref(),
10317            snapshot,
10318            &spec.module_id,
10319            &runtime.failure_context(false),
10320        )
10321        .await?;
10322    }
10323
10324    reset_restart_count(snapshot, &spec.module_id)?;
10325    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10326    schedule_respawn(
10327        runtime,
10328        snapshot,
10329        &spec.module_id,
10330        runtime.restart_policy.backoff,
10331        RespawnKind::Reload,
10332        false,
10333    )
10334}
10335
10336async fn finish_reload_child(
10337    spec: &ModuleSpec,
10338    runtime: &SupervisorRuntimeConfig,
10339    registry: &Registry,
10340    process_liveness: &SupervisorProcessLiveness,
10341    snapshot: &SharedSnapshot,
10342    child: &mut Option<SupervisedChild>,
10343) -> Result<(), SuperviseError> {
10344    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10345    let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
10346        Ok(next_child) => next_child,
10347        Err(error @ SuperviseError::ConfigDeliveryDeferred { .. }) => {
10348            defer_config_spawn(
10349                spec,
10350                runtime,
10351                snapshot,
10352                RespawnKind::Reload,
10353                &runtime.failure_context(runtime.recovery_is_daemon),
10354            )?;
10355            return Err(error);
10356        }
10357        Err(error @ SuperviseError::ConfigHeld { .. }) => {
10358            let failure = runtime.failure_context(runtime.recovery_is_daemon);
10359            if try_park_config_attempt(spec, runtime, snapshot, &failure, None)? {
10360                return Err(error);
10361            }
10362            defer_config_spawn(spec, runtime, snapshot, RespawnKind::Reload, &failure)?;
10363            return Err(SuperviseError::ConfigDeliveryDeferred {
10364                module_id: spec.module_id.clone(),
10365            });
10366        }
10367        Err(err) => {
10368            return handle_reload_spawn_failure(
10369                spec,
10370                runtime,
10371                process_liveness,
10372                snapshot,
10373                child,
10374                format!("new child failed to spawn: {err}"),
10375            )
10376            .await;
10377        }
10378    };
10379    *child = Some(next_child);
10380
10381    let wait_outcome = {
10382        let active_child = child.as_mut().expect("new reload child was just stored");
10383        wait_for_registration_after_reload(
10384            registry,
10385            &spec.module_id,
10386            snapshot,
10387            active_child,
10388            REGISTRY_RELEASE_TIMEOUT,
10389        )
10390        .await?
10391    };
10392
10393    match wait_outcome {
10394        RegistrationWaitOutcome::Registered => {
10395            child
10396                .as_mut()
10397                .expect("registered reload child")
10398                .registration_deadline = None;
10399            debug!(module_id = %spec.module_id, "supervised module reloaded and registered");
10400            Ok(())
10401        }
10402        RegistrationWaitOutcome::Exited(exit_report) => {
10403            if let Some(active_child) = child.as_mut() {
10404                active_child.drain_stderr(&spec.module_id).await;
10405            }
10406            // Keep the exited child's roster guard until its terminal is written.
10407            // Shutdown waits on that guard, not on the child Option used for respawn.
10408            let mut exited_child = child.take().expect("exited reload child is still stored");
10409            #[cfg(test)]
10410            if let Some(gate) = &runtime.test_reload_exit_record_gate {
10411                gate.reached.notify_one();
10412                gate.resume.notified().await;
10413            }
10414            let result = handle_reload_child_registration_failure(
10415                spec,
10416                runtime,
10417                registry,
10418                process_liveness,
10419                snapshot,
10420                child,
10421                ReloadRegistrationFailure {
10422                    exit_report: registration_failure_exit_report(exit_report),
10423                    cleanup_detail: exited_child.exit_cleanup_detail(None),
10424                    reason: exited_child
10425                        .spawn_failure
10426                        .clone()
10427                        .unwrap_or_else(|| "new child exited before registering".to_string()),
10428                },
10429            )
10430            .await;
10431            exited_child
10432                .finish_exit(false)
10433                .await
10434                .map_err(|source| SuperviseError::Wait {
10435                    module_id: spec.module_id.clone(),
10436                    source,
10437                })?;
10438            result
10439        }
10440        RegistrationWaitOutcome::TimedOut => {
10441            let mut timed_out_child = child
10442                .take()
10443                .expect("timed-out reload child is still running");
10444            timed_out_child
10445                .start_kill()
10446                .map_err(|source| SuperviseError::Kill {
10447                    module_id: spec.module_id.clone(),
10448                    source,
10449                })?;
10450            let status = timed_out_child
10451                .wait()
10452                .await
10453                .map_err(|source| SuperviseError::Wait {
10454                    module_id: spec.module_id.clone(),
10455                    source,
10456                })?;
10457            timed_out_child.drain_stderr(&spec.module_id).await;
10458            let result = handle_reload_child_registration_failure(
10459                spec,
10460                runtime,
10461                registry,
10462                process_liveness,
10463                snapshot,
10464                child,
10465                ReloadRegistrationFailure {
10466                    exit_report: registration_failure_exit_report(classify_reaped_child_exit(
10467                        snapshot,
10468                        &timed_out_child,
10469                        &status,
10470                    )),
10471                    cleanup_detail: timed_out_child.exit_cleanup_detail(None),
10472                    reason: format!(
10473                        "new child did not register within {:?}",
10474                        REGISTRY_RELEASE_TIMEOUT
10475                    ),
10476                },
10477            )
10478            .await;
10479            timed_out_child
10480                .finish_exit(false)
10481                .await
10482                .map_err(|source| SuperviseError::Wait {
10483                    module_id: spec.module_id.clone(),
10484                    source,
10485                })?;
10486            result
10487        }
10488    }
10489}
10490
10491#[allow(clippy::too_many_arguments)]
10492async fn set_child_enabled(
10493    spec: &ModuleSpec,
10494    runtime: &SupervisorRuntimeConfig,
10495    registry: &Registry,
10496    process_liveness: &SupervisorProcessLiveness,
10497    snapshot: &SharedSnapshot,
10498    child: &mut Option<SupervisedChild>,
10499    enabled: bool,
10500    failure: &FailureContext,
10501) -> Result<bool, SuperviseError> {
10502    set_child_enabled_with_budget_policy(
10503        spec,
10504        runtime,
10505        registry,
10506        process_liveness,
10507        snapshot,
10508        child,
10509        enabled,
10510        failure,
10511        true,
10512    )
10513    .await
10514}
10515
10516#[allow(clippy::too_many_arguments)]
10517async fn set_child_enabled_with_budget_policy(
10518    spec: &ModuleSpec,
10519    runtime: &SupervisorRuntimeConfig,
10520    registry: &Registry,
10521    process_liveness: &SupervisorProcessLiveness,
10522    snapshot: &SharedSnapshot,
10523    child: &mut Option<SupervisedChild>,
10524    enabled: bool,
10525    failure: &FailureContext,
10526    reset_budget: bool,
10527) -> Result<bool, SuperviseError> {
10528    let (current_enabled, current_state, respawn_pending) = {
10529        let state = lock_snapshot(snapshot)?;
10530        (state.enabled, state.state, state.respawn_pending)
10531    };
10532    // `start` (enable on an already-enabled module) heals TERMINAL states instead
10533    // of no-op'ing: a module whose restart budget exhausted (Failed) or that exited
10534    // clean (Stopped) has no live process and no other in-band recovery — the
10535    // operator's start is the explicit recovery act and resets the budget. Without
10536    // this arm the only revival was subc-probe --supervisor-restart in a terminal,
10537    // which the 2026-07-14 aft outage proved is a trap when the failed module is
10538    // the one providing every agent's shell.
10539    let revive_terminal = enabled
10540        && current_enabled
10541        && child.is_none()
10542        && (matches!(current_state, ModuleState::Failed | ModuleState::Stopped)
10543            || (current_state == ModuleState::Restarting && !respawn_pending));
10544    if current_enabled == enabled && !revive_terminal {
10545        return Ok(false);
10546    }
10547
10548    if enabled {
10549        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10550            state.enabled = true;
10551            state.state = ModuleState::Starting;
10552            clear_current_process_facts(state);
10553        })?;
10554        #[cfg(test)]
10555        if runtime.test_seed_stale_facts_before_enable_spawn {
10556            update_snapshot(snapshot, Some(&spec.module_id), |state| {
10557                state.process_alive = true;
10558                state.pid = Some(41);
10559                state.spawned_at_ms = Some(42);
10560                state.spawned_from = Some(PathBuf::from("/spawned/module"));
10561                state.spawned_file_identity = Some(SpawnedFileIdentity {
10562                    device: 43,
10563                    inode: 44,
10564                    #[cfg(windows)]
10565                    windows_image: None,
10566                });
10567            })?;
10568        }
10569        release_dead_registration(
10570            registry,
10571            runtime.forwarding.as_deref(),
10572            snapshot,
10573            &spec.module_id,
10574            failure,
10575        )
10576        .await?;
10577        if reset_budget {
10578            reset_restart_count(snapshot, &spec.module_id)?;
10579        }
10580        process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10581        let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
10582            Ok(next_child) => next_child,
10583            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
10584                defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
10585                return Ok(true);
10586            }
10587            Err(error @ SuperviseError::ConfigHeld { .. }) => {
10588                if let Err(parking_error) = hold_config_spawn(spec, runtime, snapshot, failure) {
10589                    process_liveness.untrack_if_current(&spec.module_id, snapshot);
10590                    return Err(parking_error);
10591                }
10592                return Err(error);
10593            }
10594            Err(err) => {
10595                fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
10596                process_liveness.untrack_if_current(&spec.module_id, snapshot);
10597                return Err(err);
10598            }
10599        };
10600        *child = Some(next_child);
10601        debug!(module_id = %spec.module_id, "supervised module enabled");
10602        Ok(true)
10603    } else {
10604        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10605            state.config_hold_parked = false;
10606            state.config_hold_daemon_initiated = false;
10607            state.config_hold_approval = None;
10608        })?;
10609        let stop_notice = begin_forwarding_drain_if_configured(
10610            spec,
10611            runtime,
10612            registry,
10613            snapshot,
10614            Some(false),
10615            RouteCloseReason::Disable,
10616        )
10617        .await?;
10618        drain_optional_child(
10619            &spec.module_id,
10620            spec.protocol,
10621            stop_notice,
10622            registry,
10623            runtime.forwarding.as_deref(),
10624            snapshot,
10625            &runtime.terminal_ring,
10626            &runtime.spawn_events,
10627            child,
10628            runtime.drain_timeout,
10629            ModuleState::Disabled,
10630            Some(false),
10631            failure,
10632        )
10633        .await?;
10634        debug!(module_id = %spec.module_id, "supervised module disabled");
10635        Ok(true)
10636    }
10637}
10638
10639#[allow(clippy::too_many_arguments)]
10640#[cfg(test)]
10641async fn on_child_exit(
10642    spec: &ModuleSpec,
10643    policy: RestartPolicy,
10644    registry: &Registry,
10645    snapshot: &SharedSnapshot,
10646    terminal_ring: &Arc<Mutex<TerminalRing>>,
10647    spawn_events: &SpawnEventFeed,
10648    roster: &ChildRoster,
10649    exit_report: ExitReport,
10650    daemon_initiated: bool,
10651) -> NextAction {
10652    on_child_exit_with_detail(
10653        spec,
10654        policy,
10655        registry,
10656        snapshot,
10657        terminal_ring,
10658        spawn_events,
10659        roster,
10660        exit_report,
10661        daemon_initiated,
10662        None,
10663    )
10664    .await
10665}
10666
10667#[allow(clippy::too_many_arguments)]
10668async fn on_child_exit_with_detail(
10669    spec: &ModuleSpec,
10670    policy: RestartPolicy,
10671    registry: &Registry,
10672    snapshot: &SharedSnapshot,
10673    terminal_ring: &Arc<Mutex<TerminalRing>>,
10674    spawn_events: &SpawnEventFeed,
10675    roster: &ChildRoster,
10676    exit_report: ExitReport,
10677    daemon_initiated: bool,
10678    detail: Option<String>,
10679) -> NextAction {
10680    // Once the daemon has begun shutting down, no exit is a crash to recover
10681    // from: the module is exiting because the daemon is going away (EOF on its
10682    // connection, or a service manager signalling the whole cgroup). Record it
10683    // as such and never schedule a respawn, which would only start a process
10684    // for the shutdown to end again.
10685    if roster.is_closed() {
10686        return on_child_exit_during_daemon_shutdown(
10687            spec,
10688            registry,
10689            snapshot,
10690            terminal_ring,
10691            spawn_events,
10692            exit_report,
10693            detail,
10694        )
10695        .await;
10696    }
10697    // Deliberate stops the supervisor asks for (operator stop, disable,
10698    // restart, reload, swap, a health restart, a drain that runs out of budget)
10699    // takes the child out of the supervise loop and reaps it in
10700    // `drain_child_to_state`, and daemon shutdown is handled above. So an exit
10701    // that reaches this point is either unrequested or a first-HELLO timeout,
10702    // which is deliberately classified as a crash even after a clean TERM exit.
10703    //
10704    // For a subc-wire module a clean exit is still a stop: those modules are
10705    // written to re-raise SIGTERM, so a stray outside signal already reads as a
10706    // crash, and exiting 0 is a deliberate choice the module made. A
10707    // `protocol: "none"` module is a stock program we cannot change, and many
10708    // of them (nats-server among them) exit 0 on SIGTERM. Treating that as a
10709    // stop would leave the module down for good after any stray signal, so it
10710    // goes through the crash path instead: it spends restart budget, respawns
10711    // with the crash backoff, and ends `failed` when the budget runs out.
10712    let unrequested_clean_exit_of_protocol_none = exit_report.kind == ExitKind::Clean
10713        && running_protocol(spec, snapshot) == ModuleProtocol::None;
10714    match exit_report.kind {
10715        ExitKind::Clean if !unrequested_clean_exit_of_protocol_none => {
10716            info!(
10717                module_id = %spec.module_id,
10718                exit_code = ?exit_report.code,
10719                exit_signal = ?exit_report.signal,
10720                "supervised module exited cleanly"
10721            );
10722            if let Err(err) = publish_after_terminal_record(
10723                &spec.module_id,
10724                || {
10725                    record_terminal_with_detail(
10726                        &spec.module_id,
10727                        terminal_ring,
10728                        spawn_events,
10729                        &exit_report,
10730                        TerminalDisposition::Stopped,
10731                        detail,
10732                    )
10733                },
10734                || {
10735                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10736                        state.state = ModuleState::Stopped;
10737                        clear_current_process_facts(state);
10738                        state.last_exit = Some(exit_report.clone());
10739                    })
10740                },
10741            ) {
10742                error!(module_id = %spec.module_id, error = %err, "failed to publish clean module exit");
10743            }
10744            let registration_released = match wait_for_registration_release(
10745                registry,
10746                &spec.module_id,
10747                REGISTRY_RELEASE_TIMEOUT,
10748            )
10749            .await
10750            {
10751                Ok(()) => true,
10752                Err(err) => {
10753                    warn!(module_id = %spec.module_id, error = %err, "registration still active after clean exit");
10754                    false
10755                }
10756            };
10757            NextAction::Stop {
10758                registration_released,
10759            }
10760        }
10761        ExitKind::Clean | ExitKind::Crash => {
10762            if unrequested_clean_exit_of_protocol_none {
10763                warn!(
10764                    module_id = %spec.module_id,
10765                    exit_code = ?exit_report.code,
10766                    exit_signal = ?exit_report.signal,
10767                    "protocol-none module exited cleanly without a stop request; handling it as a crash"
10768                );
10769            } else {
10770                warn!(
10771                    module_id = %spec.module_id,
10772                    exit_code = ?exit_report.code,
10773                    exit_signal = ?exit_report.signal,
10774                    "supervised module exited abnormally (crash)"
10775                );
10776            }
10777            let mut restart_schedule = None;
10778            let mut disposition = TerminalDisposition::Disabled;
10779            let mut final_state = ModuleState::Disabled;
10780            // Set only when the budget is what stopped the module, so the
10781            // terminal record says which limit was hit rather than leaving
10782            // `failed` to be read as "crashed once, badly".
10783            let mut disposition_detail = lock_snapshot(snapshot)
10784                .ok()
10785                .and_then(|mut state| state.spawn_failure.take());
10786            if let Some(detail) = detail {
10787                disposition_detail = Some(
10788                    disposition_detail
10789                        .map_or_else(|| detail.clone(), |cause| format!("{cause}; {detail}")),
10790                );
10791            }
10792            let now = Instant::now();
10793            if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10794                if state.enabled {
10795                    if let Some(schedule) = state.next_crash_restart(&policy, now) {
10796                        // Route close checks this flag so clients can retry even
10797                        // before terminal recording publishes Restarting.
10798                        state.respawn_pending = true;
10799                        final_state = ModuleState::Restarting;
10800                        restart_schedule = Some(schedule);
10801                        disposition = TerminalDisposition::Restarting;
10802                    } else {
10803                        final_state = ModuleState::Failed;
10804                        disposition = TerminalDisposition::Failed;
10805                        let budget = policy.budget_exhausted_detail();
10806                        disposition_detail =
10807                            Some(disposition_detail.take().map_or_else(
10808                                || budget.clone(),
10809                                |cause| format!("{cause}; {budget}"),
10810                            ));
10811                    }
10812                } else {
10813                    disposition = TerminalDisposition::Disabled;
10814                }
10815            }) {
10816                error!(module_id = %spec.module_id, error = %err, "failed to record crashed module exit");
10817                return NextAction::Stop {
10818                    registration_released: false,
10819                };
10820            }
10821            if disposition == TerminalDisposition::Failed {
10822                // The window is in the message, not only in the fields: this line
10823                // is read in a scrollback where a bare `max_restarts=3` reads as a
10824                // lifetime cap and sends the operator looking for three crashes
10825                // that never happened together.
10826                error!(
10827                    module_id = %spec.module_id,
10828                    max_restarts = policy.max_restarts,
10829                    window_secs = policy.window.as_secs(),
10830                    "module stopped: {}",
10831                    policy.budget_exhausted_detail()
10832                );
10833            }
10834            if let Err(err) = publish_after_terminal_record(
10835                &spec.module_id,
10836                || {
10837                    record_terminal_with_detail(
10838                        &spec.module_id,
10839                        terminal_ring,
10840                        spawn_events,
10841                        &exit_report,
10842                        disposition,
10843                        disposition_detail,
10844                    )
10845                },
10846                || {
10847                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10848                        state.state = final_state;
10849                        clear_current_process_facts(state);
10850                        if final_state == ModuleState::Failed
10851                            && daemon_initiated
10852                            && !roster.is_closed()
10853                        {
10854                            state.failed_retry.schedule(&spec.module_id);
10855                        }
10856                        state.last_exit = Some(exit_report.clone());
10857                    })
10858                },
10859            ) {
10860                error!(module_id = %spec.module_id, error = %err, "failed to publish crashed module exit");
10861            }
10862
10863            if let Some(schedule) = restart_schedule {
10864                NextAction::Restart {
10865                    schedule: Some(schedule),
10866                }
10867            } else {
10868                let registration_released = match wait_for_registration_release(
10869                    registry,
10870                    &spec.module_id,
10871                    REGISTRY_RELEASE_TIMEOUT,
10872                )
10873                .await
10874                {
10875                    Ok(()) => true,
10876                    Err(err) => {
10877                        warn!(module_id = %spec.module_id, error = %err, "registration still active after failed module");
10878                        false
10879                    }
10880                };
10881                NextAction::Stop {
10882                    registration_released,
10883                }
10884            }
10885        }
10886        ExitKind::DeliberateSeverance => {
10887            warn!(
10888                module_id = %spec.module_id,
10889                exit_code = ?exit_report.code,
10890                exit_signal = ?exit_report.signal,
10891                "supervised module exited after deliberate connection severance"
10892            );
10893            let should_restart = match lock_snapshot(snapshot) {
10894                Ok(state) => state.enabled,
10895                Err(err) => {
10896                    error!(module_id = %spec.module_id, error = %err, "failed to read deliberately severed module state");
10897                    return NextAction::Stop {
10898                        registration_released: false,
10899                    };
10900                }
10901            };
10902            let final_state = if should_restart {
10903                ModuleState::Restarting
10904            } else {
10905                ModuleState::Disabled
10906            };
10907            if let Err(err) = publish_after_terminal_record(
10908                &spec.module_id,
10909                || {
10910                    record_terminal_with_detail(
10911                        &spec.module_id,
10912                        terminal_ring,
10913                        spawn_events,
10914                        &exit_report,
10915                        terminal_disposition(final_state),
10916                        detail,
10917                    )
10918                },
10919                || {
10920                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10921                        state.state = final_state;
10922                        clear_current_process_facts(state);
10923                        state.last_exit = Some(exit_report.clone());
10924                        state.lifetime_restarts += 1;
10925                    })
10926                },
10927            ) {
10928                error!(module_id = %spec.module_id, error = %err, "failed to publish deliberately severed module exit");
10929                return NextAction::Stop {
10930                    registration_released: false,
10931                };
10932            }
10933
10934            if should_restart {
10935                NextAction::Restart { schedule: None }
10936            } else {
10937                let registration_released = match wait_for_registration_release(
10938                    registry,
10939                    &spec.module_id,
10940                    REGISTRY_RELEASE_TIMEOUT,
10941                )
10942                .await
10943                {
10944                    Ok(()) => true,
10945                    Err(err) => {
10946                        warn!(module_id = %spec.module_id, error = %err, "registration still active after deliberately severed module exit");
10947                        false
10948                    }
10949                };
10950                NextAction::Stop {
10951                    registration_released,
10952                }
10953            }
10954        }
10955    }
10956}
10957
10958async fn on_child_exit_during_daemon_shutdown(
10959    spec: &ModuleSpec,
10960    registry: &Registry,
10961    snapshot: &SharedSnapshot,
10962    terminal_ring: &Arc<Mutex<TerminalRing>>,
10963    spawn_events: &SpawnEventFeed,
10964    exit_report: ExitReport,
10965    detail: Option<String>,
10966) -> NextAction {
10967    info!(
10968        module_id = %spec.module_id,
10969        exit_code = ?exit_report.code,
10970        exit_signal = ?exit_report.signal,
10971        exit_kind = ?exit_report.kind,
10972        "supervised module exited during daemon shutdown; not restarting it"
10973    );
10974    if let Err(err) = publish_after_terminal_record(
10975        &spec.module_id,
10976        || {
10977            record_terminal_with_detail(
10978                &spec.module_id,
10979                terminal_ring,
10980                spawn_events,
10981                &exit_report,
10982                TerminalDisposition::DaemonShutdown,
10983                detail,
10984            )
10985        },
10986        || {
10987            update_snapshot(snapshot, Some(&spec.module_id), |state| {
10988                state.state = ModuleState::Stopped;
10989                clear_current_process_facts(state);
10990                state.last_exit = Some(exit_report.clone());
10991            })
10992        },
10993    ) {
10994        error!(module_id = %spec.module_id, error = %err, "failed to publish module exit during daemon shutdown");
10995    }
10996    let registration_released =
10997        wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT)
10998            .await
10999            .is_ok();
11000    NextAction::Stop {
11001        registration_released,
11002    }
11003}
11004
11005// Keep the status lock out of terminal I/O. Readers may observe the previous
11006// state while recording is in progress, but never a completed exit without its
11007// history. Journal errors are logged by the journal and retained in the ring;
11008// a recording panic still publishes the final state before resuming the unwind.
11009fn publish_after_terminal_record<T>(
11010    module_id: &str,
11011    record: impl FnOnce(),
11012    publish: impl FnOnce() -> T,
11013) -> T {
11014    let recorded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(record));
11015    let published = publish();
11016    if let Err(panic) = recorded {
11017        error!(
11018            module_id,
11019            "terminal recording panicked; published final state before resuming unwind"
11020        );
11021        std::panic::resume_unwind(panic);
11022    }
11023    published
11024}
11025
11026fn fail_after_wait_error(
11027    module_id: &str,
11028    snapshot: &SharedSnapshot,
11029    terminal_ring: &Arc<Mutex<TerminalRing>>,
11030    spawn_events: &SpawnEventFeed,
11031    detail: String,
11032    failure: &FailureContext,
11033) {
11034    let report = wait_error_exit_report();
11035    publish_after_terminal_record(
11036        module_id,
11037        || {
11038            record_terminal_with_detail(
11039                module_id,
11040                terminal_ring,
11041                spawn_events,
11042                &report,
11043                TerminalDisposition::Failed,
11044                Some(detail),
11045            )
11046        },
11047        || fail_snapshot(snapshot, Some(module_id), Some(report.clone()), failure),
11048    );
11049}
11050
11051#[cfg(test)]
11052fn record_wait_error_terminal(
11053    module_id: &str,
11054    terminal_ring: &Arc<Mutex<TerminalRing>>,
11055    spawn_events: &SpawnEventFeed,
11056) {
11057    record_terminal(
11058        module_id,
11059        terminal_ring,
11060        spawn_events,
11061        &wait_error_exit_report(),
11062        TerminalDisposition::Failed,
11063    );
11064}
11065
11066#[cfg(test)]
11067fn record_terminal(
11068    module_id: &str,
11069    terminal_ring: &Arc<Mutex<TerminalRing>>,
11070    spawn_events: &SpawnEventFeed,
11071    exit_report: &ExitReport,
11072    disposition: TerminalDisposition,
11073) {
11074    record_terminal_with_detail(
11075        module_id,
11076        terminal_ring,
11077        spawn_events,
11078        exit_report,
11079        disposition,
11080        None,
11081    );
11082}
11083
11084/// Copy the ring under its lock; pin and read the journal files without it.
11085fn durable_terminal_history_of(
11086    terminal_ring: &Mutex<TerminalRing>,
11087    module_id: &str,
11088) -> subc_control::TerminalHistory {
11089    let read = terminal_ring
11090        .lock()
11091        .unwrap_or_else(|p| p.into_inner())
11092        .capture_durable_history();
11093    read.read(module_id)
11094}
11095
11096fn record_terminal_with_detail(
11097    module_id: &str,
11098    terminal_ring: &Arc<Mutex<TerminalRing>>,
11099    spawn_events: &SpawnEventFeed,
11100    exit_report: &ExitReport,
11101    disposition: TerminalDisposition,
11102    disposition_detail: Option<String>,
11103) {
11104    #[cfg(test)]
11105    terminal_history_tests::before_terminal_record(spawn_events);
11106    spawn_events.emit_exited(module_id, exit_report.code, exit_report.signal);
11107    let record = TerminalRecord {
11108        exit_code: exit_report.code,
11109        exit_signal: exit_report.signal,
11110        at_ms: exit_report.at_ms,
11111        disposition,
11112        exit_kind: exit_report.kind.into(),
11113        disposition_detail,
11114    };
11115    terminal_ring
11116        .lock()
11117        .unwrap_or_else(|poisoned| poisoned.into_inner())
11118        .record_exit(module_id, record);
11119}
11120
11121fn untrack_if_registration_released(
11122    process_liveness: &SupervisorProcessLiveness,
11123    registry: &Registry,
11124    module_id: &str,
11125    snapshot: &SharedSnapshot,
11126) {
11127    match registry.get_module(module_id) {
11128        Ok(None) => process_liveness.untrack_if_current(module_id, snapshot),
11129        Ok(Some(_)) => {}
11130        Err(err) => {
11131            warn!(module_id, error = %err, "could not determine whether supervisor liveness can be untracked");
11132        }
11133    }
11134}
11135
11136/// The child's environment plan: inherit the parent's, drop ambient `CK_LOG`,
11137/// then apply the module's configured entries minus daemon-private capture keys.
11138///
11139/// Separated from `spawn_child` only so it can be asserted without spawning a
11140/// process — a duplicate of this logic in a test would pass while the real one
11141/// drifted, which is the defect class this function exists to avoid.
11142/// The subc-wire half of a spawn: `--subc <connection file>` and the launch
11143/// nonce. A `protocol: "none"` module gets neither, because it cannot use
11144/// either and the argument would stop a stock binary from starting at all.
11145/// `SUBC_MODULE_ID` is set on every path since an unread variable is inert.
11146///
11147/// The plain-spawn form, kept for the tests that assert its plan; spawns go
11148/// through [`apply_wire_spawn_args_for_admission`].
11149#[cfg(test)]
11150fn apply_wire_spawn_args(
11151    command: &mut Command,
11152    spec: &ModuleSpec,
11153    connection_file_path: Option<&std::path::Path>,
11154    handle: Option<&SupervisorHandle>,
11155) -> Result<Option<NonceHandoff>, SuperviseError> {
11156    apply_wire_spawn_args_for_role(
11157        command,
11158        spec,
11159        connection_file_path,
11160        handle,
11161        SpawnRole::Plain,
11162    )
11163}
11164
11165/// The read end of a spawn's launch-nonce pipe, prepared by
11166/// [`apply_wire_spawn_args_for_admission`] and installed as the child's descriptor 3
11167/// by the last pre-exec step, just before `spawn()`. Windows prepares a named
11168/// server before spawn and authenticates its client after the child exists.
11169#[cfg(unix)]
11170type NonceHandoff = subc_os::LaunchNonceHandoff;
11171#[cfg(windows)]
11172type NonceHandoff = subc_os::LaunchNoncePipeHandoff;
11173#[cfg(not(any(unix, windows)))]
11174type NonceHandoff = std::convert::Infallible;
11175
11176/// Create the launch nonce that a new module process must present when it
11177/// registers or opens a consumer connection, including a replacement process
11178/// started alongside a still-serving module.
11179///
11180/// A plain spawn replaces the module's recorded nonce. A swap candidate records
11181/// a separate candidate token so the still-serving incumbent and its consumers
11182/// keep their nonce. Both records are installed before the process exists, so
11183/// the child's initial HELLO registration cannot arrive ahead of its nonce.
11184///
11185/// On Unix the nonce is delivered only through a pipe. It is written into
11186/// a pipe whose read end the child gets as descriptor 3, named by
11187/// `SUBC_LAUNCH_NONCE_FD=3:<pipe inode>`: unlike the environment, another
11188/// process of the same user cannot read it with `ps eww`. That handoff is
11189/// returned rather than installed here. The combined descriptor placement runs
11190/// after the cgroup callback and placement barrier, so replacing slots 3-5
11191/// cannot close a descriptor either callback still needs.
11192/// Windows keeps SUBC_LAUNCH_NONCE as well until every module reads the named pipe.
11193#[cfg(test)]
11194fn apply_wire_spawn_args_for_role(
11195    command: &mut Command,
11196    spec: &ModuleSpec,
11197    connection_file_path: Option<&std::path::Path>,
11198    handle: Option<&SupervisorHandle>,
11199    role: SpawnRole,
11200) -> Result<Option<NonceHandoff>, SuperviseError> {
11201    apply_wire_spawn_args_for_admission(command, spec, connection_file_path, handle, role, None)
11202}
11203
11204fn apply_wire_spawn_args_for_admission(
11205    command: &mut Command,
11206    spec: &ModuleSpec,
11207    connection_file_path: Option<&std::path::Path>,
11208    handle: Option<&SupervisorHandle>,
11209    role: SpawnRole,
11210    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
11211) -> Result<Option<NonceHandoff>, SuperviseError> {
11212    command.env(SUBC_MODULE_ID_ENV, &spec.module_id);
11213    // SUBC_LAUNCH_NONCE_FD is removed for every child, `protocol: "none"`
11214    // included: a daemon started from a module's process tree inherits it,
11215    // and passing it on would point the child at a descriptor it does not
11216    // have.
11217    command.env_remove(subc_os::LAUNCH_NONCE_FD_ENV);
11218    #[cfg(windows)]
11219    {
11220        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_ENV);
11221        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV);
11222    }
11223    // Remove inherited or configured copies too: withholding must mean absent.
11224    command.env_remove(SUBC_LAUNCH_NONCE_ENV);
11225    command.env_remove(subc_os::registration_channel::REGISTRATION_FD_ENV);
11226    command.env_remove(subc_os::registration_channel::REGISTRATION_PIPE_ENV);
11227    command.env_remove(subc_os::registration_channel::DAEMON_PID_ENV);
11228    if role == SpawnRole::Plain {
11229        if let Some(handle) = handle {
11230            #[cfg(all(test, unix))]
11231            {
11232                let pause = {
11233                    let mut slot = handle.plain_identity_policy_pause.lock().unwrap();
11234                    if slot
11235                        .as_ref()
11236                        .is_some_and(|(module, _)| module == &spec.module_id)
11237                    {
11238                        slot.take().map(|(_, pause)| pause)
11239                    } else {
11240                        None
11241                    }
11242                };
11243                if let Some(pause) = pause {
11244                    pause.reached.send(()).unwrap();
11245                    pause.release.recv().unwrap();
11246                }
11247            }
11248            // A rescan preserves the running child's nonce and reservation.
11249            // Replacement spawn preparation applies the new protocol now,
11250            // before protocol:none can return without minting a nonce.
11251            handle.apply_identity_policy(spec, spec.protocol);
11252        }
11253    }
11254    if spec.protocol == ModuleProtocol::None {
11255        return Ok(None);
11256    }
11257    if let Some(connection_file_path) = connection_file_path {
11258        command.arg(SUBC_ARG).arg(connection_file_path);
11259    }
11260
11261    if admission.is_some_and(|admission| admission.launch.is_some()) {
11262        if let Some(handle) = handle {
11263            match role {
11264                SpawnRole::Plain => {
11265                    handle
11266                        .spawn_nonces
11267                        .lock()
11268                        .unwrap_or_else(|p| p.into_inner())
11269                        .remove(&spec.module_id);
11270                    if spec.reserved {
11271                        handle
11272                            .reserved_nonces
11273                            .lock()
11274                            .unwrap_or_else(|p| p.into_inner())
11275                            .insert(spec.module_id.clone(), None);
11276                    }
11277                }
11278                // Swaps still need their lifecycle record, but the empty value
11279                // is not a bearer token and is never accepted by nonce HELLO.
11280                SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, String::new()),
11281            }
11282        }
11283        return Ok(None);
11284    }
11285    // Every subc-wire spawn receives a fresh one-time launch nonce for consumer
11286    // route.open attestation. Reserved modules additionally use the same nonce
11287    // for HELLO id-squatting protection. A respawn rotates both records.
11288    let nonce = generate_launch_nonce()?;
11289    if let Some(handle) = handle {
11290        match role {
11291            SpawnRole::Plain => {
11292                handle.set_spawn_nonce(&spec.module_id, nonce.clone());
11293                if spec.reserved {
11294                    handle.set_reserved_nonce(&spec.module_id, nonce.clone());
11295                }
11296            }
11297            SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, nonce.clone()),
11298        }
11299    }
11300    #[cfg(unix)]
11301    let handoff = {
11302        let handoff =
11303            subc_os::LaunchNonceHandoff::new(&nonce).map_err(|source| SuperviseError::Spawn {
11304                program: spec.program.clone(),
11305                source,
11306                cgroup_path: None,
11307            })?;
11308        command.env(subc_os::LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
11309        Some(handoff)
11310    };
11311    #[cfg(windows)]
11312    let handoff = prepare_windows_nonce_pipe(command, spec, &nonce);
11313    #[cfg(not(any(unix, windows)))]
11314    let handoff = None;
11315    // Older modules still read SUBC_LAUNCH_NONCE to register. Keep that copy
11316    // until the daemon's per-spawn delivery records show that every running
11317    // Windows module has read its secret from the named pipe.
11318    #[cfg(not(unix))]
11319    command.env(SUBC_LAUNCH_NONCE_ENV, nonce);
11320    Ok(handoff)
11321}
11322
11323pub(crate) fn apply_child_env(command: &mut Command, spec: &ModuleSpec) {
11324    command.env_remove(CK_LOG_ENV);
11325    // The spawn role is the supervisor's to set, and only on a swap candidate
11326    // (see `apply_spawn_role`). Removing it here, rather than just not setting
11327    // it, is what makes it absent on a plain spawn: the daemon's own
11328    // environment could carry it, and so could a spec built outside daemon
11329    // config (config refuses it as an `env` key). A module reading it on a
11330    // plain restart would pick the long swap budget and leave callers waiting.
11331    command.env_remove(SUBC_SPAWN_ROLE_ENV);
11332    for (key, value) in &spec.env {
11333        // cortexkit-log currently exposes retention only as a Rust struct, not
11334        // environment names. These values are daemon-private sink metadata and
11335        // must never become a public child-process contract by being inherited.
11336        if matches!(
11337            key.as_str(),
11338            CAPTURE_MAX_FILE_MB_ENV | CAPTURE_KEEP_ENV | CAPTURE_MAX_AGE_DAYS_ENV
11339        ) || key == SUBC_SPAWN_ROLE_ENV
11340        {
11341            continue;
11342        }
11343        command.env(key, value);
11344    }
11345}
11346
11347#[cfg(windows)]
11348fn prepare_windows_registration_pipe(
11349    command: &mut Command,
11350    spec: &ModuleSpec,
11351) -> Result<Option<SpawnRegistrationChannel>, SuperviseError> {
11352    if spec.protocol == ModuleProtocol::None {
11353        return Ok(None);
11354    }
11355    let pipe = subc_os::registration_channel::RegistrationPipe::new().map_err(|source| {
11356        SuperviseError::Spawn {
11357            program: spec.program.clone(),
11358            source,
11359            cgroup_path: None,
11360        }
11361    })?;
11362    command
11363        .env(
11364            subc_os::registration_channel::REGISTRATION_PIPE_ENV,
11365            pipe.name(),
11366        )
11367        .env(
11368            subc_os::registration_channel::DAEMON_PID_ENV,
11369            std::process::id().to_string(),
11370        );
11371    Ok(Some(pipe))
11372}
11373
11374#[cfg(windows)]
11375fn prepare_windows_nonce_pipe(
11376    command: &mut Command,
11377    spec: &ModuleSpec,
11378    nonce: &str,
11379) -> Option<NonceHandoff> {
11380    match subc_os::LaunchNoncePipeHandoff::new(nonce) {
11381        Ok(handoff) => {
11382            command.env(subc_os::LAUNCH_NONCE_PIPE_ENV, handoff.name());
11383            // Let a failed pipe read use SUBC_LAUNCH_NONCE so the process can
11384            // still register until every module reads the pipe. A reader without
11385            // this variable set to env returns the pipe error instead of using
11386            // an inherited or configured environment copy.
11387            command.env(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV, "env");
11388            Some(handoff)
11389        }
11390        Err(error) => {
11391            warn!(module_id = %spec.module_id, %error, "could not prepare launch nonce pipe; retaining the environment handoff");
11392            None
11393        }
11394    }
11395}
11396
11397#[cfg(windows)]
11398fn start_windows_nonce_pipe(
11399    handoff: Option<NonceHandoff>,
11400    pid: u32,
11401    spec: &ModuleSpec,
11402) -> Option<subc_os::LaunchNoncePipeDelivery> {
11403    // Close an unread pipe after REGISTRY_RELEASE_TIMEOUT (one second), the
11404    // same maximum wait used for registration during a reload. Older modules
11405    // may register using SUBC_LAUNCH_NONCE without ever connecting to the pipe.
11406    handoff.and_then(|handoff| match handoff.serve(pid, REGISTRY_RELEASE_TIMEOUT) {
11407        Ok(delivery) => Some(delivery),
11408        Err(error) => {
11409            warn!(module_id = %spec.module_id, %error, "could not serve launch nonce pipe; retaining the environment handoff");
11410            None
11411        }
11412    })
11413}
11414
11415fn observed_launch_nonce_source(snapshot: &SupervisorSnapshot) -> Option<String> {
11416    #[cfg(windows)]
11417    if snapshot.process_alive && snapshot.spawned_protocol == Some(ModuleProtocol::Subc) {
11418        return Some(
11419            if snapshot
11420                .pipe_consumed
11421                .as_ref()
11422                .is_some_and(|consumed| consumed.get().is_some())
11423            {
11424                "pipe"
11425            } else {
11426                "env"
11427            }
11428            .to_owned(),
11429        );
11430    }
11431    let _ = snapshot;
11432    None
11433}
11434
11435/// Which slot a spawn fills: the module's ordinary one, or the candidate slot
11436/// of a blue/green swap.
11437#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11438enum SpawnRole {
11439    Plain,
11440    SwapCandidate,
11441}
11442
11443/// Set the spawn role for a swap candidate. A plain spawn gets nothing here;
11444/// `apply_child_env` has already removed the variable for every spawn.
11445fn apply_spawn_role(command: &mut Command, role: SpawnRole) {
11446    if role == SpawnRole::SwapCandidate {
11447        command.env(SUBC_SPAWN_ROLE_ENV, SPAWN_ROLE_SWAP_CANDIDATE);
11448    }
11449}
11450
11451fn previous_instance_error(
11452    spec: &ModuleSpec,
11453    pid: u32,
11454    reason: crate::live_children::RetainedReason,
11455) -> SuperviseError {
11456    SuperviseError::Spawn {
11457        program: spec.program.clone(),
11458        source: io::Error::new(io::ErrorKind::WouldBlock, reason.waiting_message(pid)),
11459        cgroup_path: None,
11460    }
11461}
11462
11463fn carries_containment(configured: bool, has_container: bool) -> bool {
11464    configured || has_container
11465}
11466
11467fn recovery_block_error(spec: &ModuleSpec, roster: &ChildRoster) -> Option<SuperviseError> {
11468    if !carries_containment(
11469        spec.carry_containment,
11470        containment::current(&roster.containment).is_some(),
11471    ) {
11472        return None;
11473    }
11474    Some(SuperviseError::Spawn {
11475        program: spec.program.clone(),
11476        source: io::Error::new(io::ErrorKind::WouldBlock, roster.recovery_block()?),
11477        cgroup_path: None,
11478    })
11479}
11480
11481#[allow(clippy::too_many_arguments)]
11482fn spawn_child(
11483    spec: &ModuleSpec,
11484    connection_file_path: Option<&std::path::Path>,
11485    handle: Option<&SupervisorHandle>,
11486    ring: &Arc<Mutex<StderrRing>>,
11487    capture_logs_dir: Option<&std::path::Path>,
11488    roster: &ChildRoster,
11489    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11490    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11491    register_timeout: Duration,
11492) -> Result<SupervisedChild, SuperviseError> {
11493    #[cfg(all(test, unix))]
11494    if let Some(source) = containment_tests::join_failure(spec, roster) {
11495        containment::terminate_blocking(&roster.containment);
11496        return Err(SuperviseError::Spawn {
11497            program: spec.program.clone(),
11498            source,
11499            cgroup_path: None,
11500        });
11501    }
11502    let result = spawn_child_in_slot(
11503        spec,
11504        connection_file_path,
11505        handle,
11506        ring,
11507        capture_logs_dir,
11508        roster,
11509        config_delivery,
11510        #[cfg(target_os = "linux")]
11511        cgroup_placement,
11512        SpawnRole::Plain,
11513        false,
11514        register_timeout,
11515    );
11516    if result
11517        .as_ref()
11518        .is_err_and(|error| !is_launch_deferral(error))
11519    {
11520        if roster.admission_pending(&spec.module_id) {
11521            containment::terminate_deferred(&roster.containment);
11522        } else {
11523            containment::terminate_blocking(&roster.containment);
11524        }
11525    }
11526    result
11527}
11528
11529/// A configuration deferral means the launch never started: the module gate
11530/// or the configuration owner was briefly busy, and every caller schedules
11531/// the same launch again shortly. A carried container stays for that retry,
11532/// as it does across a restart backoff; ending it here would kill the
11533/// module's helpers and give up the group the retry is meant to join.
11534fn is_launch_deferral(error: &SuperviseError) -> bool {
11535    matches!(error, SuperviseError::ConfigDeliveryDeferred { .. })
11536}
11537
11538/// Spawn one process of `spec` into a slot.
11539///
11540/// `alternate_slot` picks the process's cgroup label on Linux (see `swap::cgroup_name`).
11541/// A swap candidate needs a different cgroup from the process it is replacing,
11542/// which is still alive: in the same cgroup the two would be one kill domain,
11543/// and killing a failed candidate could take the incumbent with it.
11544///
11545/// The stderr capture file is `<module_id>.stderr.log` for every process of
11546/// the module, whichever slot it is in, because that is the one file
11547/// `ck module logs` reads. During a swap's overlap both processes append to it;
11548/// the daemon writes whole lines, so the two interleave by line, which is also
11549/// the merged view an operator wants while a swap runs.
11550#[allow(clippy::too_many_arguments)]
11551fn spawn_child_in_slot(
11552    spec: &ModuleSpec,
11553    connection_file_path: Option<&std::path::Path>,
11554    handle: Option<&SupervisorHandle>,
11555    ring: &Arc<Mutex<StderrRing>>,
11556    capture_logs_dir: Option<&std::path::Path>,
11557    roster: &ChildRoster,
11558    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11559    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11560    role: SpawnRole,
11561    alternate_slot: bool,
11562    register_timeout: Duration,
11563) -> Result<SupervisedChild, SuperviseError> {
11564    let prepared = prepare_child_in_slot(
11565        spec,
11566        connection_file_path,
11567        handle,
11568        capture_logs_dir,
11569        roster,
11570        config_delivery,
11571        #[cfg(target_os = "linux")]
11572        cgroup_placement,
11573        role,
11574        alternate_slot,
11575        false,
11576    )?;
11577    let gate = config_delivery
11578        .map(|delivery| delivery.module_gate(spec))
11579        .transpose()?;
11580    let _gate = gate
11581        .as_ref()
11582        .map(|gate| {
11583            gate.try_lock()
11584                .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
11585                    module_id: spec.module_id.clone(),
11586                })
11587        })
11588        .transpose()?;
11589    if let (Some(delivery), Some(admission)) = (config_delivery, &prepared.spawn_admission) {
11590        delivery.check(spec, admission)?;
11591    }
11592    let checked_base = prepared
11593        .spawn_admission
11594        .as_ref()
11595        .and_then(|admission| admission.approved_base())
11596        .cloned();
11597    let mut result = launch_child_in_slot(spec, ring, roster, prepared, register_timeout);
11598    drop(_gate);
11599    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
11600        (config_delivery, &result)
11601    {
11602        if let Some(base) = checked_base.as_ref().filter(|_| code == "program_refused") {
11603            if !delivery.record_refusal(spec, base, detail)? {
11604                result = Err(spawn_plan_stale(spec));
11605            }
11606        }
11607    }
11608    result
11609}
11610
11611struct AsyncInitialIdentity<'a> {
11612    supervisor: &'a Supervisor,
11613    module: String,
11614    committed: bool,
11615}
11616impl Drop for AsyncInitialIdentity<'_> {
11617    fn drop(&mut self) {
11618        if !self.committed {
11619            self.supervisor.abandon_unrostered(&self.module);
11620        }
11621    }
11622}
11623
11624/// Child-free preparation can be abandoned without orphaning a process. After
11625/// this value returns, the async caller validates its launch witness and creates
11626/// and publishes the child without another await.
11627struct PreparedChild {
11628    script_delivery: Option<script::Delivery>,
11629    registration_spawn: Option<Arc<RegistrationSpawn>>,
11630    registration_handle: Option<SupervisorHandle>,
11631    #[cfg(any(unix, windows))]
11632    registration_channel: Option<SpawnRegistrationChannel>,
11633    config_context: Option<config_delivery::ConfigDelivery>,
11634    binding_publication: Option<ProgramBindingPublication>,
11635    launch_spec: ModuleSpec,
11636    spawn_admission: Option<crate::config_gate::runtime::SpawnAdmission>,
11637    command: Command,
11638    carrying: bool,
11639    carried: Option<Arc<containment::CarriedContainment>>,
11640    #[cfg(unix)]
11641    launch_identity: Option<containment::LaunchIdentity>,
11642    #[cfg(unix)]
11643    group_target: containment::GroupTarget,
11644    #[cfg(target_os = "linux")]
11645    cgroup_placement: Option<subc_cgroup::Placement>,
11646    #[cfg(target_os = "linux")]
11647    cgroup_name: String,
11648    #[cfg(target_os = "linux")]
11649    cgroup_cleanup: PreparedCgroup,
11650    cgroup_path: Option<PathBuf>,
11651    #[cfg(unix)]
11652    admission_gate: Option<admission::Gate>,
11653    output_sink: ChildOutputSink,
11654    #[cfg(target_os = "macos")]
11655    privacy_exec: Option<PrivacyExec>,
11656    #[cfg(windows)]
11657    image_capture: subc_os::ExecutableCapture,
11658    #[cfg(windows)]
11659    nonce_handoff: Option<NonceHandoff>,
11660    spawned_at: Instant,
11661    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
11662    delivery_registration: Option<config_delivery::RegistrationGuard>,
11663    program_binding: Option<SpawnProgramBinding>,
11664}
11665
11666#[cfg(target_os = "linux")]
11667struct PreparedCgroup(Option<(subc_cgroup::Placement, String)>);
11668#[cfg(target_os = "linux")]
11669impl Drop for PreparedCgroup {
11670    fn drop(&mut self) {
11671        if let Some((placement, name)) = &self.0 {
11672            remove_module_cgroup(placement, name);
11673        }
11674    }
11675}
11676
11677pub(crate) struct SpawnProgramBinding {
11678    pub(crate) path: PathBuf,
11679    // Keep the inode alive if the configured name is replaced while preparation
11680    // is suspended, so replacement cannot pass through inode reuse.
11681    _file: std::fs::File,
11682    pub(crate) identity: subc_os::RetainedFileIdentity,
11683}
11684
11685impl SpawnProgramBinding {
11686    pub(crate) fn capture(spec: &ModuleSpec) -> Result<Self, SuperviseError> {
11687        Self::capture_after_resolution(spec, |_| {})
11688    }
11689
11690    fn capture_after_resolution(
11691        spec: &ModuleSpec,
11692        before_open: impl FnOnce(&std::path::Path),
11693    ) -> Result<Self, SuperviseError> {
11694        require_program_search_path(spec)?;
11695        #[cfg(windows)]
11696        let windows_capture =
11697            windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
11698                program: spec.program.clone(),
11699                source,
11700                cgroup_path: None,
11701            })?;
11702        #[cfg(windows)]
11703        let path = windows_capture.path().to_path_buf();
11704        #[cfg(not(windows))]
11705        let path = if spec.program.is_absolute() || spec.program.components().count() > 1 {
11706            spec.program.clone()
11707        } else {
11708            let path = spec
11709                .env
11710                .iter()
11711                .rev()
11712                .find(|(key, _)| key == "PATH")
11713                .map(|(_, path)| std::ffi::OsString::from(path))
11714                .or_else(|| std::env::var_os("PATH"))
11715                .unwrap_or_else(|| {
11716                    if cfg!(target_os = "macos") {
11717                        // Match Darwin's spawn search when PATH is absent, not
11718                        // the current-directory search of an explicitly empty PATH.
11719                        "/usr/bin:/bin".into()
11720                    } else {
11721                        Default::default()
11722                    }
11723                });
11724            std::env::split_paths(&path)
11725                .map(|dir| dir.join(&spec.program))
11726                .find(|path| {
11727                    if !path.is_file() {
11728                        return false;
11729                    }
11730                    #[cfg(unix)]
11731                    {
11732                        rustix::fs::accessat(
11733                            rustix::fs::CWD,
11734                            path,
11735                            rustix::fs::Access::EXEC_OK,
11736                            rustix::fs::AtFlags::EACCESS,
11737                        )
11738                        .is_ok()
11739                    }
11740                    #[cfg(not(unix))]
11741                    {
11742                        true
11743                    }
11744                })
11745                .ok_or_else(|| SuperviseError::Spawn {
11746                    program: spec.program.clone(),
11747                    source: io::Error::new(io::ErrorKind::NotFound, "executable not found in PATH"),
11748                    cgroup_path: None,
11749                })?
11750        };
11751        let resolved = std::fs::canonicalize(&path).map_err(|source| SuperviseError::Spawn {
11752            program: spec.program.clone(),
11753            source,
11754            cgroup_path: None,
11755        })?;
11756        before_open(&resolved);
11757        // Resolving links does not open their target. The descriptor open must
11758        // remain nonblocking and no-follow if that resolved name is substituted.
11759        let file =
11760            subc_os::open_regular_nofollow(&resolved).map_err(|source| SuperviseError::Spawn {
11761                program: spec.program.clone(),
11762                source: io::Error::other(source),
11763                cgroup_path: None,
11764            })?;
11765        let identity =
11766            subc_os::retained_file_identity(&file).map_err(|source| SuperviseError::Spawn {
11767                program: spec.program.clone(),
11768                source,
11769                cgroup_path: None,
11770            })?;
11771        Ok(Self {
11772            path,
11773            _file: file,
11774            identity,
11775        })
11776    }
11777    fn current(&self) -> bool {
11778        #[cfg(unix)]
11779        {
11780            subc_os::file_identity(&self.path) == Some(self.identity)
11781        }
11782        #[cfg(windows)]
11783        {
11784            std::fs::canonicalize(&self.path)
11785                .ok()
11786                .and_then(|path| subc_os::open_regular_nofollow(&path).ok())
11787                .and_then(|file| subc_os::retained_file_identity(&file).ok())
11788                == Some(self.identity)
11789        }
11790    }
11791}
11792
11793fn spawn_plan_stale(spec: &ModuleSpec) -> SuperviseError {
11794    SuperviseError::ConfigDeliveryDeferred {
11795        module_id: spec.module_id.clone(),
11796    }
11797}
11798
11799fn require_program_search_path(spec: &ModuleSpec) -> Result<(), SuperviseError> {
11800    if !cfg!(target_os = "macos")
11801        && !spec.program.is_absolute()
11802        && spec.program.components().count() == 1
11803        && !spec.env.iter().any(|(key, _)| {
11804            if cfg!(windows) {
11805                key.eq_ignore_ascii_case("PATH")
11806            } else {
11807                key == "PATH"
11808            }
11809        })
11810        && std::env::var_os("PATH").is_none()
11811    {
11812        // The OS default search is not a current-directory search. Refusing an
11813        // unspecified search path prevents approving a decoy in the current directory.
11814        return Err(SuperviseError::Spawn {
11815            program: spec.program.clone(),
11816            source: io::Error::new(io::ErrorKind::InvalidInput, "bare program requires PATH"),
11817            cgroup_path: None,
11818        });
11819    }
11820    Ok(())
11821}
11822
11823async fn spawn_child_async(
11824    spec: &ModuleSpec,
11825    runtime: &SupervisorRuntimeConfig,
11826) -> Result<SupervisedChild, SuperviseError> {
11827    #[cfg(all(test, unix))]
11828    if let Some(source) = containment_tests::join_failure(spec, &runtime.child_roster) {
11829        containment::terminate_blocking(&runtime.child_roster.containment);
11830        return Err(SuperviseError::Spawn {
11831            program: spec.program.clone(),
11832            source,
11833            cgroup_path: None,
11834        });
11835    }
11836    let result = spawn_child_in_slot_async(spec, runtime, SpawnRole::Plain, false).await;
11837    if result
11838        .as_ref()
11839        .is_err_and(|error| !is_launch_deferral(error))
11840    {
11841        if runtime.child_roster.admission_pending(&spec.module_id) {
11842            containment::terminate_deferred(&runtime.child_roster.containment);
11843        } else {
11844            containment::terminate_blocking(&runtime.child_roster.containment);
11845        }
11846    }
11847    result
11848}
11849
11850async fn spawn_child_in_slot_async(
11851    spec: &ModuleSpec,
11852    runtime: &SupervisorRuntimeConfig,
11853    role: SpawnRole,
11854    alternate_slot: bool,
11855) -> Result<SupervisedChild, SuperviseError> {
11856    let gate = runtime
11857        .config_delivery
11858        .as_ref()
11859        .map(|delivery| delivery.0.module_gate(&spec.module_id))
11860        .transpose()
11861        .map_err(|error| SuperviseError::InvalidSpec {
11862            reason: error.to_string(),
11863        })?;
11864    if gate.as_ref().is_some_and(|gate| gate.try_lock().is_err()) {
11865        return Err(SuperviseError::ConfigDeliveryDeferred {
11866            module_id: spec.module_id.clone(),
11867        });
11868    }
11869    let prepared_spec = spec.clone();
11870    let prepared_runtime = runtime.clone();
11871    let prepared = tokio::task::spawn_blocking(move || {
11872        let prepared = prepare_child_in_slot(
11873            &prepared_spec,
11874            prepared_runtime.connection_file_path.as_deref(),
11875            prepared_runtime.supervisor_handle.as_ref(),
11876            prepared_runtime.capture_logs_dir.as_deref(),
11877            &prepared_runtime.child_roster,
11878            prepared_runtime.spawn_delivery(),
11879            #[cfg(target_os = "linux")]
11880            prepared_runtime.cgroup_placement.as_ref(),
11881            role,
11882            alternate_slot,
11883            true,
11884        );
11885        prepared
11886    })
11887    .await
11888    .map_err(|_| SuperviseError::InvalidSpec {
11889        reason: "configuration launch preparation stopped".into(),
11890    })??;
11891    if let Some(registration) = &prepared.delivery_registration {
11892        if !registration.launch_current()? {
11893            return Err(spawn_plan_stale(spec));
11894        }
11895    }
11896    let _gate = match gate {
11897        Some(gate) => {
11898            Some(
11899                gate.try_lock_owned()
11900                    .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
11901                        module_id: spec.module_id.clone(),
11902                    })?,
11903            )
11904        }
11905        None => None,
11906    };
11907    if let (Some(delivery), Some(admission)) = (runtime.spawn_delivery(), &prepared.spawn_admission)
11908    {
11909        delivery.check(spec, admission)?;
11910    }
11911    if prepared
11912        .spawn_admission
11913        .as_ref()
11914        .is_none_or(|admission| admission.launch.is_none())
11915        && prepared
11916            .program_binding
11917            .as_ref()
11918            .is_some_and(|binding| !binding.current())
11919    {
11920        return Err(spawn_plan_stale(spec));
11921    }
11922    // No await may separate this last identity check from ownership publication.
11923    let checked_base = prepared
11924        .spawn_admission
11925        .as_ref()
11926        .and_then(|admission| admission.approved_base())
11927        .cloned();
11928    let mut result = launch_child_in_slot(
11929        spec,
11930        &runtime.stderr_ring,
11931        &runtime.child_roster,
11932        prepared,
11933        runtime.register_timeout,
11934    );
11935    drop(_gate);
11936    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
11937        (runtime.config_delivery.as_ref(), &result)
11938    {
11939        if let Some(base) = checked_base.filter(|_| code == "program_refused") {
11940            let module = spec.module_id.clone();
11941            let identity = subc_config::raw_digest(detail.as_bytes());
11942            let recorded = delivery
11943                .0
11944                .on_blocking(move |owner| owner.record_program_refusal(&module, &base, identity))
11945                .await;
11946            match recorded {
11947                Ok(true) => {}
11948                Ok(false) => result = Err(spawn_plan_stale(spec)),
11949                Err(error) => {
11950                    result = Err(config_delivery::gate_hold_error(
11951                        spec,
11952                        error,
11953                        Some(delivery),
11954                    ))
11955                }
11956            }
11957        }
11958    }
11959    result
11960}
11961
11962fn validate_spawn_program(
11963    spec: &ModuleSpec,
11964    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
11965    delivery: Option<config_delivery::SpawnDelivery<'_>>,
11966) -> Result<(), SuperviseError> {
11967    if let Some(admission) = admission {
11968        if let Some(program) = &admission.launch {
11969            if let Err(error) = program.validate_for_spawn() {
11970                // A captured unsigned image is a definite refusal. Uncertain
11971                // reads are deferred by validate_for_spawn, not attributed to
11972                // the operator as a changed or unapprovable program.
11973                if let (Some(context), Some(base)) = (delivery, admission.approved_base()) {
11974                    if error.code == "program_refused"
11975                        && !context.record_refusal(spec, base, &error.detail)?
11976                    {
11977                        return Err(spawn_plan_stale(spec));
11978                    }
11979                }
11980                return Err(config_delivery::gate_hold_error(
11981                    spec,
11982                    error,
11983                    delivery.map(|context| context.runtime()).as_ref(),
11984                ));
11985            }
11986        }
11987    }
11988    Ok(())
11989}
11990
11991#[allow(clippy::too_many_arguments)]
11992fn prepare_child_in_slot(
11993    spec: &ModuleSpec,
11994    connection_file_path: Option<&std::path::Path>,
11995    handle: Option<&SupervisorHandle>,
11996    capture_logs_dir: Option<&std::path::Path>,
11997    roster: &ChildRoster,
11998    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11999    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
12000    role: SpawnRole,
12001    alternate_slot: bool,
12002    asynchronous: bool,
12003) -> Result<PreparedChild, SuperviseError> {
12004    require_program_search_path(spec)?;
12005    let spawn_admission = config_delivery
12006        .map(|delivery| delivery.prepare(spec))
12007        .transpose()?;
12008    #[cfg(target_os = "macos")]
12009    let gated = spawn_admission
12010        .as_ref()
12011        .is_some_and(|admission| admission.approved_base().is_some());
12012    let mut launch_spec = spawn_admission
12013        .as_ref()
12014        .and_then(|admission| admission.launch.as_ref())
12015        .map(|launch| launch.spec.clone())
12016        .unwrap_or_else(|| spec.clone());
12017    if let Some(script) = &launch_spec.script {
12018        launch_spec.program =
12019            script::runner_path(script.runtime).map_err(|source| SuperviseError::Spawn {
12020                program: launch_spec.program.clone(),
12021                source,
12022                cgroup_path: None,
12023            })?;
12024    }
12025    let script_content = if let Some(entry) = &launch_spec.script {
12026        Some(
12027            spawn_admission
12028                .as_ref()
12029                .and_then(|admission| admission.launch.as_ref())
12030                .and_then(|launch| launch.script.clone())
12031                .map_or_else(|| script::ScriptBytes::read(&entry.path), Ok)
12032                .map_err(|error| config_delivery::gate_hold_error(&launch_spec, error, None))?,
12033        )
12034    } else {
12035        None
12036    };
12037    let spec = &launch_spec;
12038    if let Some(error) = recovery_block_error(spec, roster) {
12039        return Err(error);
12040    }
12041    if let Some((pid, reason)) = roster.previous_instance(&spec.module_id) {
12042        return Err(previous_instance_error(spec, pid, reason));
12043    }
12044    if roster.is_closed() {
12045        return Err(SuperviseError::Spawn {
12046            program: spec.program.clone(),
12047            source: io::Error::other("the daemon is shutting down; not starting a new process"),
12048            cgroup_path: None,
12049        });
12050    }
12051    let carried = containment::current(&roster.containment);
12052    let carrying = carries_containment(spec.carry_containment, carried.is_some());
12053    if role != SpawnRole::Plain && carrying {
12054        return Err(SuperviseError::InvalidSpec {
12055            reason: "a carried container cannot overlap a swap candidate".to_owned(),
12056        });
12057    }
12058    #[cfg(unix)]
12059    let launch_identity = if carrying && carried.is_none() {
12060        Some(
12061            containment::LaunchIdentity::capture().map_err(|source| SuperviseError::Spawn {
12062                program: spec.program.clone(),
12063                source,
12064                cgroup_path: None,
12065            })?,
12066        )
12067    } else {
12068        None
12069    };
12070    #[cfg(target_os = "linux")]
12071    let cgroup_placement = match &carried {
12072        Some(container) => container.cgroup().map(|(placement, _)| placement),
12073        None => cgroup_placement,
12074    };
12075    #[cfg(unix)]
12076    let group_target = if let Some(container) = carried
12077        .as_ref()
12078        .filter(|container| container.group().is_some())
12079    {
12080        containment::GroupTarget::Pinned(Arc::clone(container))
12081    } else {
12082        #[cfg(target_os = "linux")]
12083        let cgroup_container = carrying && cgroup_placement.is_some();
12084        #[cfg(not(target_os = "linux"))]
12085        let cgroup_container = false;
12086        if cgroup_container {
12087            containment::GroupTarget::NoGroup
12088        } else {
12089            containment::GroupTarget::OwnLeader
12090        }
12091    };
12092    #[cfg(target_os = "linux")]
12093    let cgroup_name = {
12094        // Slot names alone are not kill domains: a retired incumbent may still
12095        // be draining when a later enable/restart spawns into the same slot.
12096        // Decimal entropy keeps the suffix unambiguous; Placement performs
12097        // the module-id escaping and constructs the filesystem path.
12098        if let Some((_, name)) = carried.as_ref().and_then(|container| container.cgroup()) {
12099            name.to_owned()
12100        } else if cgroup_placement.is_none() {
12101            swap::cgroup_name(&spec.module_id, alternate_slot)
12102        } else {
12103            let nonce = generate_launch_nonce()?;
12104            let suffix = u128::from_str_radix(&nonce[..32], 16).expect("hex launch nonce");
12105            cgroup_label::generation_label(&spec.module_id, alternate_slot, suffix)
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(unix)]
12677    let plain_group = (!carrying
12678        && cgroup_path.is_none()
12679        && matches!(group_target, containment::GroupTarget::OwnLeader))
12680    .then(|| plain_group::PlainGroup::from_spawn(pid).map(Arc::new))
12681    .flatten();
12682    #[cfg(windows)]
12683    let nonce_delivery = start_windows_nonce_pipe(nonce_handoff, pid, spec);
12684    #[cfg(not(windows))]
12685    let process_start_time = admitted
12686        .as_ref()
12687        .map(|admitted| admitted.birth)
12688        .or_else(|| crate::provenance::process_start_time(pid));
12689    #[cfg(windows)]
12690    let process_start_time = Some(windows_image.start_time());
12691    let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
12692    #[cfg(all(test, target_os = "macos"))]
12693    privacy_exec_boundary_tests::before_image_sample(spec, pid);
12694    #[cfg(all(test, target_os = "linux"))]
12695    assert!(roster.admission_event_for_test(&spec.module_id, "before_image_binding", Some(pid)));
12696    // Record the committed kernel image, not the configured pathname: PATH
12697    // lookup and shebang interpretation can select a different executable.
12698    // Linux's posix_spawn can return before that image is installed, so the
12699    // observer also waits for the kernel's first-exec flag to clear.
12700    #[cfg(not(windows))]
12701    let recorded_image = observe_spawned_image(pid);
12702    #[cfg(all(test, target_os = "linux"))]
12703    let recorded_image = if roster.admission_event_for_test(
12704        &spec.module_id,
12705        "after_spawn_image_sample",
12706        Some(pid),
12707    ) {
12708        recorded_image
12709    } else {
12710        None
12711    };
12712    #[cfg(target_os = "linux")]
12713    // An exited child cannot receive HELLO service and has no readable /proc/exe.
12714    // Keep its real exit for the supervisor instead of turning a crash into a hold.
12715    let exited_before_binding = expected_image.is_some()
12716        && recorded_image.and_then(|image| image.executable) != expected_image
12717        && subc_os::child_exit::observe(pid).ok().flatten().is_some();
12718    #[cfg(target_os = "linux")]
12719    let unavailable_initial_image = expected_image.is_some()
12720        && recorded_image.and_then(|image| image.executable).is_none()
12721        && !exited_before_binding;
12722    #[cfg(not(target_os = "linux"))]
12723    let unavailable_initial_image = false;
12724    #[cfg(target_os = "linux")]
12725    if expected_image
12726        .is_some_and(|expected| recorded_image.and_then(|image| image.executable) != Some(expected))
12727        && !exited_before_binding
12728        && !unavailable_initial_image
12729    {
12730        kill_module_cgroup(cgroup_placement, &cgroup_name);
12731        kill_and_reap_rejected_child(&mut child, group_target.clone());
12732        return Err(SuperviseError::ConfigHeld {
12733            module_id: spec.module_id.clone(),
12734            code: "program_refused".into(),
12735            detail: format!(
12736                "spawned executable {:?} does not match hashed program {:?}",
12737                recorded_image.and_then(|image| image.executable),
12738                expected_image
12739            ),
12740        });
12741    }
12742    #[cfg(not(target_os = "linux"))]
12743    let _ = expected_image;
12744    #[cfg(target_os = "macos")]
12745    let binding_ready = privacy_exec.is_none();
12746    #[cfg(target_os = "linux")]
12747    let binding_ready = !exited_before_binding;
12748    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
12749    let binding_ready = cfg!(windows);
12750    // spawn() confirms only the first exec, into the trampoline. Never persist
12751    // the trampoline image; the asynchronous acknowledgement publishes the
12752    // module image once the trampoline has replaced itself with the module.
12753    #[cfg(target_os = "macos")]
12754    let recorded_image = if privacy_exec.is_some() {
12755        None
12756    } else {
12757        recorded_image
12758    };
12759    #[cfg(target_os = "linux")]
12760    let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
12761    #[cfg(not(target_os = "linux"))]
12762    let recorded_cgroup_name = None;
12763    #[cfg(unix)]
12764    let preadmitted = admitted
12765        .as_mut()
12766        .and_then(|admitted| admitted.leader.take());
12767    #[cfg(not(unix))]
12768    let preadmitted: Option<crate::child_roster::RosterGuard> = None;
12769    let roster_guard = if let Some(guard) = preadmitted {
12770        Ok(guard)
12771    } else {
12772        roster.admit(
12773            spec.module_id.clone(),
12774            pid,
12775            spec.protocol,
12776            process_start_time,
12777            crate::child_roster::RecordedIdentity {
12778                #[cfg(target_os = "linux")]
12779                container: cgroup_path
12780                    .clone()
12781                    .filter(|_| !carrying)
12782                    .map(ordinary_cgroup::recorded_identity),
12783                #[cfg(not(target_os = "linux"))]
12784                container: None,
12785                #[cfg(unix)]
12786                carried: None,
12787                #[cfg(unix)]
12788                plain_group: plain_group.as_ref().map(Arc::downgrade),
12789                #[cfg(not(windows))]
12790                start_time: recorded_image.map(|image| image.start_time),
12791                #[cfg(windows)]
12792                start_time: process_start_time,
12793                #[cfg(not(windows))]
12794                executable: recorded_image
12795                    .and_then(|image| image.executable)
12796                    .map(crate::live_children::ExecutableIdentity::from),
12797                #[cfg(windows)]
12798                executable: Some(crate::live_children::ExecutableIdentity::from(
12799                    windows_image.identity(),
12800                )),
12801                cgroup_name: recorded_cgroup_name,
12802                #[cfg(target_os = "linux")]
12803                cgroup_placement: cgroup_placement.cloned(),
12804            },
12805        )
12806    };
12807    let roster_guard = match roster_guard {
12808        Ok(guard) => guard,
12809        Err(failure) => {
12810            return failure.with_cleanup(|source| {
12811                #[cfg(windows)]
12812                if let Some(job) = &job {
12813                    let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
12814                }
12815                #[cfg(target_os = "linux")]
12816                kill_module_cgroup(cgroup_placement, &cgroup_name);
12817                #[cfg(unix)]
12818                let rejected_group = group_target.clone();
12819                kill_and_reap_rejected_child(
12820                    &mut child,
12821                    #[cfg(unix)]
12822                    rejected_group,
12823                );
12824                #[cfg(target_os = "linux")]
12825                if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12826                    remove_module_cgroup(placement, &cgroup_name);
12827                }
12828                Err(SuperviseError::Spawn {
12829                    program: spec.program.clone(),
12830                    source: io::Error::other(format!(
12831                        "could not durably record module child: {source}"
12832                    )),
12833                    cgroup_path,
12834                })
12835            });
12836        }
12837    };
12838    #[cfg(unix)]
12839    if admitted.is_some() {
12840        if let Some(image) = recorded_image {
12841            if let Err(source) = roster_guard.confirm_executable(image) {
12842                kill_and_reap_rejected_child(&mut child, group_target.clone());
12843                return Err(SuperviseError::Spawn {
12844                    program: spec.program.clone(),
12845                    source,
12846                    cgroup_path,
12847                });
12848            }
12849        }
12850    }
12851    // The pre-spawn check can pass just before shutdown begins. Ownership is
12852    // published at the start of admission, even while a record write is queued.
12853    // If shutdown already saw an empty roster before that publication, this
12854    // check sees the roster closed and ends the child before starting a module.
12855    if roster.is_closed() {
12856        if carrying {
12857            #[cfg(unix)]
12858            let rejected_group = admitted
12859                .as_ref()
12860                .map(|admitted| admitted.rejection_target())
12861                .unwrap_or_else(|| group_target.clone());
12862            #[cfg(windows)]
12863            if let Some(job) = &job {
12864                let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
12865            }
12866            kill_and_reap_rejected_child(
12867                &mut child,
12868                #[cfg(unix)]
12869                rejected_group,
12870            );
12871            #[cfg(all(test, unix))]
12872            let _ =
12873                roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
12874            drop(roster_guard);
12875            return Err(SuperviseError::Spawn {
12876                program: spec.program.clone(),
12877                source: io::Error::other(
12878                    "the daemon began shutting down during carried admission; ended the container",
12879                ),
12880                cgroup_path,
12881            });
12882        }
12883        // This child was never admitted, so there is no module protocol shutdown to wait for.
12884        #[cfg(target_os = "linux")]
12885        kill_module_cgroup(cgroup_placement, &cgroup_name);
12886        if let Err(error) = child.start_kill() {
12887            debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
12888        }
12889        #[cfg(target_os = "linux")]
12890        if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12891            // This spawn was never admitted, so shutdown has no roster entry
12892            // to await. Do not detach its cleanup: the runtime could exit
12893            // before that task reaps the rejected child and removes its group.
12894            while matches!(child.try_wait(), Ok(None)) {
12895                std::thread::yield_now();
12896            }
12897            if matches!(
12898                subc_cgroup::kill_module(Some(placement), &cgroup_name),
12899                subc_cgroup::KillOutcome::Killed
12900            ) {
12901                if let Ok(path) = placement.module_path(&cgroup_name) {
12902                    while std::fs::read_to_string(path.join("cgroup.events"))
12903                        .ok()
12904                        .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
12905                    {
12906                        std::thread::yield_now();
12907                    }
12908                }
12909            }
12910            remove_module_cgroup(placement, &cgroup_name);
12911        }
12912        drop(roster_guard);
12913        return Err(SuperviseError::Spawn {
12914            program: spec.program.clone(),
12915            source: io::Error::other(
12916                "the daemon began shutting down while this process was starting; ended it",
12917            ),
12918            cgroup_path,
12919        });
12920    }
12921
12922    let pumps = crate::child_output::start(
12923        &mut child,
12924        output_sink,
12925        ring,
12926        &spec.module_id,
12927        #[cfg(unix)]
12928        plain_group.is_some(),
12929    );
12930
12931    let exec = Arc::new(crate::activity::ExecOutcome::new());
12932    #[cfg(target_os = "macos")]
12933    let pending_exec = privacy_exec.is_some();
12934    #[cfg(not(target_os = "macos"))]
12935    let pending_exec = false;
12936    if !pending_exec {
12937        exec.finish(crate::activity::ExecState::CommittedExec);
12938    }
12939    #[cfg(windows)]
12940    let subtree_target = job
12941        .as_ref()
12942        .map(|job| crate::subtree_resources::Target::Job(Arc::downgrade(job)))
12943        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_job"));
12944    #[cfg(target_os = "linux")]
12945    let subtree_target = cgroup_path
12946        .map(crate::subtree_resources::Target::Cgroup)
12947        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_cgroup"));
12948    #[cfg(not(any(target_os = "linux", windows)))]
12949    let subtree_target = crate::subtree_resources::Target::Unavailable("unsupported_platform");
12950    let mut supervised = SupervisedChild {
12951        registration_spawn,
12952        #[cfg(any(unix, windows))]
12953        registration_channel,
12954        live_program_binding: None,
12955        registered_config_connection: None,
12956        admission_base,
12957        registration_declaration,
12958        _program_binding: binding_publication,
12959        subtree_target,
12960        child: containment::ProcessChild::plain(child, pid),
12961        exec: crate::activity::ExecOwner(exec),
12962        #[cfg(windows)]
12963        nonce_delivery,
12964        protocol: spec.protocol,
12965        #[cfg(target_os = "linux")]
12966        module_id: cgroup_name,
12967        #[cfg(target_os = "linux")]
12968        cgroup_placement: cgroup_placement.cloned(),
12969        #[cfg(target_os = "linux")]
12970        unresolved_cgroup: None,
12971        #[cfg(windows)]
12972        job,
12973        stdout_pump: pumps.stdout,
12974        stderr_pump: pumps.stderr,
12975        #[cfg(unix)]
12976        capture_stop: pumps.stop,
12977        #[cfg(unix)]
12978        late_output_lost: false,
12979        stderr_ring: Arc::clone(ring),
12980        spawned_at,
12981        config_delivery,
12982        registration_deadline: None,
12983        registration_watch: None,
12984        spawned_at_ms,
12985        spawned_from,
12986        launch_spec_digest: LaunchSpecDigest::from_spec(spec),
12987        spawned_file_identity,
12988        process_start_time,
12989        process_identity,
12990        pid,
12991        roster_guard: Some(roster_guard),
12992        #[cfg(target_os = "macos")]
12993        privacy_exec,
12994        #[cfg(target_os = "macos")]
12995        report_ready: Arc::new(OnceLock::new()),
12996        spawn_failure: None,
12997        admission_kill_sent: false,
12998    };
12999    #[cfg(unix)]
13000    {
13001        supervised.child.plain_group = plain_group;
13002    }
13003    if let Err(error) = containment::adopt(&mut supervised, spec, roster) {
13004        supervised.child.reject(
13005            #[cfg(unix)]
13006            group_target,
13007        );
13008        #[cfg(all(test, unix))]
13009        let _ = roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
13010        return Err(error);
13011    }
13012    if let (Some(launch), Some(owner), Some(base)) = (
13013        program_launch,
13014        config_owner,
13015        supervised.admission_base.clone(),
13016    ) {
13017        supervised.live_program_binding =
13018            content_binding::LiveProgramBinding::new(launch, &supervised, owner, base);
13019        if let (Some(publication), Some(live)) = (
13020            &supervised._program_binding,
13021            &supervised.live_program_binding,
13022        ) {
13023            publication.attach(live);
13024        }
13025    }
13026    #[cfg(unix)]
13027    if let Some(admitted) = admitted.take() {
13028        admitted.disarm();
13029    }
13030    #[cfg(windows)]
13031    if let Err(error) = resume_suspended_child(pid, spec) {
13032        containment::terminate_blocking(&roster.containment);
13033        let _ = supervised.child.start_kill();
13034        return Err(error);
13035    }
13036    if binding_ready {
13037        // An unreadable initial image is not a definite mismatch. Keep the
13038        // owned child and delivery registration until its reaped status decides
13039        // whether it crashed on its own or was stopped by admission's kill.
13040        let checked = if unavailable_initial_image {
13041            Err(crate::config_gate::GateError::new(
13042                "config_delivery_deferred",
13043                "initial process image is unavailable",
13044            ))
13045        } else {
13046            match (
13047                &supervised._program_binding,
13048                &supervised.live_program_binding,
13049            ) {
13050                (Some(binding), _) => binding.verify(),
13051                (None, Some(live)) => live.check(),
13052                _ if supervised.admission_base.is_some() => {
13053                    Err(crate::config_gate::GateError::new(
13054                        "config_delivery_deferred",
13055                        "live program witness is unavailable",
13056                    ))
13057                }
13058                _ => Ok(()),
13059            }
13060        };
13061        #[cfg(all(test, target_os = "linux"))]
13062        let checked = if roster.admission_event_for_test(
13063            &spec.module_id,
13064            "after_content_witness_check",
13065            Some(pid),
13066        ) {
13067            checked
13068        } else {
13069            Err(crate::config_gate::GateError::new(
13070                "config_delivery_deferred",
13071                "current process image is unavailable",
13072            ))
13073        };
13074        if let Err(error) = checked {
13075            if let Some(binding) = &mut supervised._program_binding {
13076                binding.reject();
13077            }
13078            // Reap through the normal child-reaping path, retaining the real exit record and
13079            // its roster ownership. A refusal must also end any helpers.
13080            if error.code == "program_refused" || supervised.try_wait().ok().flatten().is_none() {
13081                supervised.spawn_failure = Some(format!("{}: {}", error.code, error.detail));
13082                #[cfg(all(test, target_os = "linux"))]
13083                assert!(roster.admission_event_for_test(
13084                    &spec.module_id,
13085                    if unavailable_initial_image {
13086                        "before_initial_image_kill"
13087                    } else {
13088                        "before_content_witness_kill"
13089                    },
13090                    Some(pid),
13091                ));
13092                let _ = supervised.start_admission_kill();
13093                #[cfg(all(test, target_os = "linux"))]
13094                if supervised.admission_kill_sent {
13095                    assert!(roster.admission_event_for_test(
13096                        &spec.module_id,
13097                        "after_admission_kill_sent",
13098                        Some(pid),
13099                    ));
13100                }
13101            }
13102        }
13103    }
13104    if let Some(registration) = delivery_registration {
13105        registration.commit();
13106    }
13107    if let Some(spawn) = &supervised.registration_spawn {
13108        if let Some(identity) = supervised.process_identity {
13109            let _ = spawn.identity.set(identity);
13110        }
13111        if supervised.spawn_failure.is_some() {
13112            spawn.refuse();
13113        } else if binding_ready {
13114            spawn.ready();
13115        }
13116        #[cfg(any(unix, windows))]
13117        if let (Some(handle), Some(channel)) =
13118            (registration_handle, supervised.registration_channel.take())
13119        {
13120            handle.serve_registration(channel, spawn.clone(), pid, spawned_at + register_timeout);
13121        }
13122    }
13123    Ok(supervised)
13124}
13125
13126#[cfg(test)]
13127mod spawn_record_tests {
13128    use super::*;
13129
13130    thread_local! {
13131        static LAST_PID: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
13132    }
13133
13134    pub(super) fn after_create(child: &Child, _spec: &ModuleSpec) {
13135        LAST_PID.set(child.id());
13136        #[cfg(windows)]
13137        if let Some((_, address)) = _spec
13138            .env
13139            .iter()
13140            .find(|(key, _)| key == "SUBC_TEST_AFTER_CREATE")
13141        {
13142            use std::io::{Read, Write};
13143            let mut stream = std::net::TcpStream::connect(address).unwrap();
13144            stream
13145                .write_all(&child.id().unwrap().to_ne_bytes())
13146                .unwrap();
13147            let mut release = [0];
13148            stream.read_exact(&mut release).unwrap();
13149        }
13150    }
13151
13152    #[cfg(windows)]
13153    pub(super) fn assignment_failpoint(spec: &ModuleSpec) -> io::Result<()> {
13154        if spec
13155            .env
13156            .iter()
13157            .any(|(key, _)| key == "SUBC_TEST_ASSIGNMENT_FAILURE")
13158        {
13159            Err(io::Error::other("injected module job assignment failure"))
13160        } else {
13161            Ok(())
13162        }
13163    }
13164
13165    fn spec() -> ModuleSpec {
13166        ModuleSpec {
13167            script: None,
13168            module_id: "spawn-record-worker".into(),
13169            #[cfg(unix)]
13170            program: "/bin/sleep".into(),
13171            #[cfg(windows)]
13172            program: std::env::current_exe().unwrap(),
13173            #[cfg(unix)]
13174            args: vec!["60".into()],
13175            #[cfg(windows)]
13176            args: vec![
13177                "--exact".into(),
13178                "supervise::spawn_record_tests::windows_store_touch_fixture".into(),
13179                "--nocapture".into(),
13180            ],
13181            env: vec![],
13182            reserved: false,
13183            reserved_prefixes: vec![],
13184            protocol: ModuleProtocol::None,
13185            overlap: Default::default(),
13186            carry_containment: false,
13187        }
13188    }
13189
13190    #[tokio::test]
13191    async fn record_sync_failure_fails_spawn_and_reaps_child() {
13192        let home = cortexkit_test_support::ScratchDir::new("record-sync-failure");
13193        let supervisor =
13194            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
13195                .with_live_children_record(home.join("live-children.json"));
13196        crate::live_children::fail_next_file_sync();
13197        let result = supervisor.spawn(spec());
13198        let failed = result.is_err();
13199        if let Ok(module) = result {
13200            module.stop().await.unwrap();
13201        }
13202        assert!(failed, "record failure must fail spawn");
13203        let pid = LAST_PID.get().expect("the real OS child was created");
13204        assert!(
13205            subc_os::Process::open(pid).unwrap().is_none(),
13206            "child {pid} survived rejected admission or was not reaped"
13207        );
13208    }
13209
13210    #[cfg(target_os = "macos")]
13211    #[test]
13212    #[ignore = "manual on-device latency measurement"]
13213    fn durable_record_write_latency_50() {
13214        let home = cortexkit_test_support::ScratchDir::new("record-latency");
13215        let path = home.join("live-children.json");
13216        let children = vec![crate::live_children::LiveChild {
13217            module_id: "latency-worker".into(),
13218            pid: std::process::id(),
13219            protocol: ModuleProtocol::None,
13220            start_time: Some(1),
13221            executable: None,
13222            cgroup_name: None,
13223            container: None,
13224        }];
13225        let mut samples = Vec::new();
13226        for _ in 0..50 {
13227            let start = std::time::Instant::now();
13228            crate::live_children::write_record(&path, &children).unwrap();
13229            samples.push(start.elapsed());
13230        }
13231        samples.sort();
13232        eprintln!(
13233            "durable_record_write_latency_50: n=50 median={:?} p95={:?}",
13234            (samples[24] + samples[25]) / 2,
13235            samples[47]
13236        );
13237    }
13238
13239    #[cfg(windows)]
13240    #[test]
13241    fn windows_store_touch_fixture() {
13242        if let Some(path) = std::env::var_os("SUBC_TEST_STORE_TOUCH") {
13243            std::fs::write(path, b"module ran").unwrap();
13244        }
13245    }
13246
13247    #[cfg(windows)]
13248    #[tokio::test]
13249    async fn windows_daemon_fixture() {
13250        let Ok(address) = std::env::var("SUBC_TEST_DAEMON_BARRIER") else {
13251            return;
13252        };
13253        let mut spec = spec();
13254        spec.env.push(("SUBC_TEST_AFTER_CREATE".into(), address));
13255        let supervisor =
13256            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13257        let _module = supervisor.spawn(spec).unwrap();
13258    }
13259
13260    #[cfg(windows)]
13261    #[test]
13262    fn windows_daemon_death_before_module_job_assignment_leaves_no_child() {
13263        use std::io::Read;
13264        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
13265        // An outer job models a scheduler/service host. The daemon's root and
13266        // root job must nest without requiring breakaway from this job.
13267        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
13268        command
13269            .args([
13270                "--exact",
13271                "supervise::spawn_record_tests::windows_daemon_fixture",
13272                "--nocapture",
13273            ])
13274            .env(
13275                "SUBC_TEST_DAEMON_BARRIER",
13276                listener.local_addr().unwrap().to_string(),
13277            );
13278        let mut daemon = subc_jobobject::spawn_contained(&mut command).unwrap();
13279        listener.set_nonblocking(true).unwrap();
13280        let deadline = std::time::Instant::now() + Duration::from_secs(30);
13281        let mut stream = loop {
13282            if let Ok((stream, _)) = listener.accept() {
13283                break stream;
13284            }
13285            assert!(
13286                daemon.child.try_wait().unwrap().is_none(),
13287                "daemon failed before rendezvous"
13288            );
13289            assert!(
13290                std::time::Instant::now() < deadline,
13291                "daemon did not reach CreateProcess failpoint"
13292            );
13293            std::thread::yield_now();
13294        };
13295        stream
13296            .set_read_timeout(Some(Duration::from_secs(30)))
13297            .unwrap();
13298        let mut pid = [0; 4];
13299        stream.read_exact(&mut pid).unwrap();
13300        let pid = u32::from_ne_bytes(pid);
13301        assert!(subc_jobobject::process_exists(pid));
13302        // Terminate only the daemon, not its outer job: otherwise the host job
13303        // would also kill a child whose daemon never joined its root job.
13304        daemon.child.kill().unwrap();
13305        daemon.child.wait().unwrap();
13306        let exited = subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10));
13307        if !exited {
13308            daemon.job.terminate().unwrap();
13309        }
13310        assert!(exited, "suspended child {pid} outlived hard-killed daemon");
13311    }
13312
13313    #[cfg(windows)]
13314    #[tokio::test]
13315    async fn windows_containment_failure_never_resumes() {
13316        let home = cortexkit_test_support::ScratchDir::new("assignment-refusal");
13317        let sentinel = home.join("store-touched");
13318        let mut spec = spec();
13319        spec.env
13320            .push(("SUBC_TEST_ASSIGNMENT_FAILURE".into(), "1".into()));
13321        spec.env.push((
13322            "SUBC_TEST_STORE_TOUCH".into(),
13323            sentinel.display().to_string(),
13324        ));
13325        let supervisor =
13326            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13327        let result = supervisor.spawn(spec);
13328        // A version that resumes despite assignment failure must have time to
13329        // execute its sentinel before dropping the returned module kills it.
13330        if let Ok(module) = result {
13331            let _ = tokio::time::timeout(Duration::from_secs(10), async {
13332                while !sentinel.exists() && module.state().unwrap() == ModuleState::Running {
13333                    tokio::task::yield_now().await;
13334                }
13335            })
13336            .await;
13337            let _ = module.stop().await;
13338            panic!(
13339                "assignment failure resumed a module; store touched={}",
13340                sentinel.exists()
13341            );
13342        }
13343        assert!(
13344            !sentinel.exists(),
13345            "refused module executed store-touch sentinel"
13346        );
13347        assert!(!subc_jobobject::process_exists(LAST_PID.get().unwrap()));
13348    }
13349
13350    #[cfg(windows)]
13351    #[tokio::test]
13352    async fn windows_nested_daemon_fixture() {
13353        let Some(sentinel) = std::env::var_os("SUBC_TEST_NESTED_STORE") else {
13354            return;
13355        };
13356        let mut spec = spec();
13357        spec.env.push((
13358            "SUBC_TEST_STORE_TOUCH".into(),
13359            sentinel.to_str().unwrap().into(),
13360        ));
13361        let supervisor =
13362            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13363        let module = supervisor
13364            .spawn(spec)
13365            .expect("per-module job must nest below daemon and host jobs");
13366        tokio::time::timeout(Duration::from_secs(10), async {
13367            while !PathBuf::from(&sentinel).exists() {
13368                tokio::task::yield_now().await;
13369            }
13370        })
13371        .await
13372        .unwrap();
13373        module.stop().await.unwrap();
13374    }
13375
13376    #[cfg(windows)]
13377    #[test]
13378    fn windows_module_job_nests_under_host_job() {
13379        let home = cortexkit_test_support::ScratchDir::new("nested-jobs");
13380        let sentinel = home.join("nested-store-touched");
13381        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
13382        command
13383            .args([
13384                "--exact",
13385                "supervise::spawn_record_tests::windows_nested_daemon_fixture",
13386                "--nocapture",
13387            ])
13388            .env("SUBC_TEST_NESTED_STORE", &sentinel);
13389        let mut daemon = subc_jobobject::spawn_contained(&mut command).unwrap();
13390        assert!(daemon.child.wait().unwrap().success());
13391        assert!(sentinel.exists(), "nested protocol:none module never ran");
13392    }
13393}
13394
13395#[cfg(target_os = "linux")]
13396pub(crate) fn kill_module_cgroup(placement: Option<&subc_cgroup::Placement>, module_id: &str) {
13397    use subc_cgroup::KillOutcome;
13398    match subc_cgroup::kill_module(placement, module_id) {
13399        KillOutcome::Killed => {}
13400        KillOutcome::NotPlaced | KillOutcome::Unsupported => {
13401            debug!(
13402                module_id,
13403                "cgroup tree kill unavailable; using direct-child kill"
13404            );
13405        }
13406        KillOutcome::IoError { path, error } => {
13407            warn!(module_id, path = %path.display(), %error, "cgroup tree kill failed; using direct-child kill");
13408        }
13409    }
13410}
13411
13412/// Assign a freshly spawned Windows child without ever resuming on failure.
13413///
13414/// Steps 2 and 3 of the suspended-create contract: the job is created and the
13415/// child assigned **while it is still suspended** (step 1 is
13416/// `suspend_on_create_async` at the spawn site). The caller resumes only after
13417/// the child's roster admission is durable. Failed containment kills and reaps
13418/// the suspended child instead of running an unprotected module.
13419#[cfg(windows)]
13420fn contain_spawned_child(
13421    child: &mut Child,
13422    spec: &ModuleSpec,
13423    carried: Option<&Arc<containment::CarriedContainment>>,
13424) -> Result<Option<Arc<Mutex<subc_jobobject::JobObject>>>, SuperviseError> {
13425    let assignment = || {
13426        let job = match carried {
13427            Some(container) => container.job(),
13428            None => Arc::new(Mutex::new(subc_jobobject::JobObject::new()?)),
13429        };
13430        #[cfg(test)]
13431        spawn_record_tests::assignment_failpoint(spec)?;
13432        job.lock()
13433            .unwrap_or_else(|p| p.into_inner())
13434            .assign(child)?;
13435        Ok::<_, io::Error>(job)
13436    };
13437    match assignment() {
13438        Ok(job) => Ok(Some(job)),
13439        Err(source) => {
13440            kill_and_reap_rejected_child(child);
13441            Err(SuperviseError::Spawn {
13442                program: spec.program.clone(),
13443                source: io::Error::other(format!(
13444                    "Windows module job containment failed: {source}"
13445                )),
13446                cgroup_path: None,
13447            })
13448        }
13449    }
13450}
13451
13452/// Rejection is synchronous: do not return a spawn error while the child can
13453/// still run, or rely on kill-on-drop to reap it at some later runtime turn.
13454fn kill_and_reap_rejected_child(child: &mut Child, #[cfg(unix)] group: containment::GroupTarget) {
13455    #[cfg(unix)]
13456    group.signal_rejected(child);
13457    let _ = child.start_kill();
13458    while matches!(child.try_wait(), Ok(None)) {
13459        std::thread::yield_now();
13460    }
13461}
13462
13463/// Resume a suspended child, killing it if it cannot be started.
13464///
13465/// A suspended process holds a pid and does nothing, so there is no useful
13466/// state to return: the caller gets an error and the spawn fails.
13467#[cfg(windows)]
13468fn resume_suspended_child(pid: u32, spec: &ModuleSpec) -> Result<(), SuperviseError> {
13469    if let Err(source) = subc_jobobject::resume_main_thread(pid) {
13470        // Kill it here rather than leaving a suspended process for the caller
13471        // to notice; `kill_on_drop` would eventually do this, but the module
13472        // would have been reported as running in between.
13473        let _ = subc_os::child_spawn::status(
13474            std::process::Command::new("taskkill.exe")
13475                .args(["/PID", &pid.to_string(), "/T", "/F"])
13476                .stdin(Stdio::null())
13477                .stdout(Stdio::null())
13478                .stderr(Stdio::null()),
13479        );
13480        return Err(SuperviseError::Spawn {
13481            program: spec.program.clone(),
13482            source,
13483            cgroup_path: None,
13484        });
13485    }
13486    Ok(())
13487}
13488
13489#[cfg(target_os = "linux")]
13490fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
13491    match placement.remove_module(module_id) {
13492        Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
13493        Err(error) => warn!(
13494            module_id,
13495            error = %error,
13496            "could not remove module cgroup after process exit; continuing teardown"
13497        ),
13498    }
13499}
13500
13501#[cfg(target_os = "linux")]
13502fn apply_cgroup_placement(
13503    command: &mut Command,
13504    spec: &ModuleSpec,
13505    path: &std::path::Path,
13506) -> Result<(), SuperviseError> {
13507    subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
13508        module_id: spec.module_id.clone(),
13509        source,
13510    })
13511}
13512
13513fn capture_retention(spec: &ModuleSpec) -> Retention {
13514    let defaults = Retention::default();
13515    let value = |name: &str| {
13516        spec.env
13517            .iter()
13518            .rev()
13519            .find_map(|(key, value)| (key == name).then_some(value.as_str()))
13520    };
13521    Retention {
13522        max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
13523            .and_then(|value| value.parse().ok())
13524            .unwrap_or(defaults.max_file_mb),
13525        keep: value(CAPTURE_KEEP_ENV)
13526            .and_then(|value| value.parse().ok())
13527            .unwrap_or(defaults.keep),
13528        max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
13529            .and_then(|value| value.parse().ok())
13530            .unwrap_or(defaults.max_age_days),
13531    }
13532}
13533
13534/// A fresh 256-bit CSPRNG launch nonce, lowercase hex. Used to bind a reserved
13535/// module's registration to the exact process the supervisor spawned.
13536fn generate_launch_nonce() -> Result<String, SuperviseError> {
13537    let mut bytes = [0u8; 32];
13538    getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
13539        reason: source.to_string(),
13540    })?;
13541    let mut hex = String::with_capacity(64);
13542    for b in bytes {
13543        use std::fmt::Write;
13544        let _ = write!(hex, "{b:02x}");
13545    }
13546    Ok(hex)
13547}
13548
13549/// Constant-time byte comparison so a reserved-nonce mismatch leaks no timing
13550/// signal about how many leading bytes matched.
13551fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
13552    if a.len() != b.len() {
13553        return false;
13554    }
13555    let mut diff = 0u8;
13556    for (x, y) in a.iter().zip(b.iter()) {
13557        diff |= x ^ y;
13558    }
13559    diff == 0
13560}
13561
13562/// The kernel's image after an acknowledged exec, shared by ordinary launches
13563/// and privacy trampolines. PATH and shebang interpretation are kernel facts,
13564/// not identities inferred from a configured pathname.
13565#[cfg(not(windows))]
13566fn observe_spawned_image(pid: u32) -> Option<subc_os::Observation> {
13567    let process = subc_os::Process::open(pid).ok().flatten()?;
13568    #[cfg(target_os = "linux")]
13569    return sample_after_linux_exec(
13570        || {
13571            let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
13572            let committed = linux_exec_committed(&stat);
13573            #[cfg(test)]
13574            spawn_image_tests::report_exec_state(committed);
13575            committed
13576        },
13577        || process.observe(),
13578    );
13579    #[cfg(not(target_os = "linux"))]
13580    process.observe()
13581}
13582
13583/// glibc's posix_spawn parent can wake in exec_mmap before the child's new mm
13584/// is installed. PF_FORKNOEXEC is cleared later in begin_new_exec, after that
13585/// installation. Until it clears, /proc/pid/exe can still name the daemon.
13586#[cfg(target_os = "linux")]
13587fn linux_exec_committed(stat: &str) -> Option<bool> {
13588    const PF_FORKNOEXEC: u64 = 0x40;
13589    let flags = stat.rsplit_once(')')?.1.split_whitespace().nth(6)?;
13590    Some(flags.parse::<u64>().ok()? & PF_FORKNOEXEC == 0)
13591}
13592
13593#[cfg(target_os = "linux")]
13594fn sample_after_linux_exec(
13595    mut exec_committed: impl FnMut() -> Option<bool>,
13596    observe: impl FnOnce() -> Option<subc_os::Observation>,
13597) -> Option<subc_os::Observation> {
13598    let deadline = std::time::Instant::now() + Duration::from_secs(1);
13599    while !exec_committed()? {
13600        // A failed or indefinitely stalled exec must not publish the inherited
13601        // image as authority to signal a future orphan. Missing identity keeps
13602        // the existing conservative orphan-sweep behavior.
13603        if std::time::Instant::now() >= deadline {
13604            return None;
13605        }
13606        std::thread::sleep(Duration::from_micros(50));
13607    }
13608    observe()
13609}
13610
13611#[cfg(all(test, target_os = "linux"))]
13612mod spawn_image_tests {
13613    use super::*;
13614    use std::cell::{Cell, RefCell};
13615
13616    enum ExecEvent {
13617        Uncommitted,
13618        Image(Option<subc_os::Observation>),
13619    }
13620
13621    thread_local! {
13622        static EXEC_EVENTS: RefCell<Option<std::sync::mpsc::Sender<ExecEvent>>> = const { RefCell::new(None) };
13623    }
13624
13625    pub(super) fn report_exec_state(committed: Option<bool>) {
13626        if committed == Some(false) {
13627            EXEC_EVENTS.with(|events| {
13628                if let Some(events) = events.borrow_mut().take() {
13629                    let _ = events.send(ExecEvent::Uncommitted);
13630                }
13631            });
13632        }
13633    }
13634
13635    #[test]
13636    fn linux_spawn_observation_waits_for_a_paused_fork_to_exec() {
13637        use std::io::{Read, Write};
13638        use std::os::fd::AsRawFd;
13639
13640        let descriptor = std::fs::File::open("/dev/null").unwrap();
13641        let mut command = std::process::Command::new("/bin/sleep");
13642        command.arg("30");
13643        let (mut ready, mut release) =
13644            subc_os::fork_exec_test::pause_before_exec(&mut command, descriptor.as_raw_fd())
13645                .unwrap();
13646        let spawn = std::thread::spawn(move || command.spawn());
13647        let mut message = [0u8; 8];
13648        ready.read_exact(&mut message).unwrap();
13649        let pid = i32::from_ne_bytes(message[..4].try_into().unwrap()) as u32;
13650        let before = std::fs::read_to_string(format!("/proc/{pid}/stat"));
13651        let inherited = subc_os::Process::open(pid).unwrap().unwrap().observe();
13652        let (events, received) = std::sync::mpsc::channel();
13653        let observer = std::thread::spawn(move || {
13654            EXEC_EVENTS.with(|slot| *slot.borrow_mut() = Some(events.clone()));
13655            let image = observe_spawned_image(pid);
13656            let _ = events.send(ExecEvent::Image(image));
13657        });
13658        // Release only once the production observer has seen the uncommitted
13659        // exec, or has incorrectly returned the inherited image. Either way,
13660        // release and reap before asserting so a regression cannot leak a child.
13661        let first = received.recv_timeout(Duration::from_secs(5));
13662        release.write_all(&[1]).unwrap();
13663        let mut child = spawn.join().unwrap().unwrap();
13664        let after = match first {
13665            Ok(ExecEvent::Uncommitted) => match received.recv_timeout(Duration::from_secs(5)) {
13666                Ok(ExecEvent::Image(image)) => image,
13667                _ => None,
13668            },
13669            Ok(ExecEvent::Image(image)) => image,
13670            Err(_) => None,
13671        };
13672        observer.join().unwrap();
13673        child.kill().unwrap();
13674        child.wait().unwrap();
13675
13676        assert_eq!(linux_exec_committed(&before.unwrap()), Some(false));
13677        assert_eq!(
13678            inherited.unwrap().executable,
13679            subc_os::file_identity(&std::env::current_exe().unwrap())
13680        );
13681        assert_eq!(
13682            after.unwrap().executable,
13683            subc_os::file_identity(std::path::Path::new("/bin/sleep"))
13684        );
13685    }
13686
13687    #[test]
13688    fn spawned_image_is_not_sampled_until_linux_exec_commits() {
13689        let committed = Cell::new(false);
13690        let inherited = subc_os::Observation {
13691            start_time: 23,
13692            executable: Some(subc_os::FileIdentity {
13693                device: 29,
13694                inode: 31,
13695            }),
13696        };
13697        let module = subc_os::Observation {
13698            start_time: 23,
13699            executable: Some(subc_os::FileIdentity {
13700                device: 29,
13701                inode: 37,
13702            }),
13703        };
13704        let polls = Cell::new(0);
13705        let image = sample_after_linux_exec(
13706            || {
13707                polls.set(polls.get() + 1);
13708                // Hold the inherited image through the first poll, as in the
13709                // posix_spawn parent-wake window, then commit the module image.
13710                committed.set(polls.get() == 2);
13711                Some(committed.get())
13712            },
13713            || Some(if committed.get() { module } else { inherited }),
13714        );
13715        assert_eq!(image, Some(module));
13716        assert_eq!(polls.get(), 2);
13717    }
13718
13719    #[test]
13720    fn linux_exec_flag_is_read_from_flags_after_the_last_parenthesis() {
13721        assert_eq!(
13722            linux_exec_committed("17 (a ) b) R 1 2 3 4 5 4194368"),
13723            Some(false)
13724        );
13725        assert_eq!(
13726            linux_exec_committed("17 (a ) b) R 1 2 3 4 5 4194304"),
13727            Some(true)
13728        );
13729        assert_eq!(linux_exec_committed("17 (a) R 1 2 3 4 5 invalid"), None);
13730        assert_eq!(linux_exec_committed("17 (a) R"), None);
13731    }
13732
13733    #[test]
13734    fn unreadable_exec_state_never_samples_an_inherited_image() {
13735        assert_eq!(
13736            sample_after_linux_exec(
13737                || None,
13738                || panic!("must not sample before exec confirmation")
13739            ),
13740            None
13741        );
13742    }
13743
13744    #[test]
13745    fn uncommitted_exec_times_out_without_sampling_an_inherited_image() {
13746        assert_eq!(
13747            sample_after_linux_exec(
13748                || Some(false),
13749                || panic!("must not sample after an exec timeout")
13750            ),
13751            None
13752        );
13753    }
13754}
13755
13756/// Resolve once and spawn that exact path, so PATH lookup cannot choose a
13757/// different executable after the no-delete capture was taken.
13758#[cfg(windows)]
13759pub(crate) fn windows_spawn_capture(spec: &ModuleSpec) -> io::Result<subc_os::ExecutableCapture> {
13760    if let Err(error) = require_program_search_path(spec) {
13761        return Err(match error {
13762            SuperviseError::Spawn { source, .. } => source,
13763            error => io::Error::other(error),
13764        });
13765    }
13766    let mut program = spec.program.clone();
13767    if program.is_absolute() || program.components().count() > 1 {
13768        // An explicit path can name a PE image with no extension. Try that
13769        // exact file first, as Command does, before falling back to .exe.
13770        match subc_os::ExecutableCapture::open(&program) {
13771            Ok(capture) => return Ok(capture),
13772            Err(error)
13773                if error.kind() == io::ErrorKind::NotFound && program.extension().is_none() => {}
13774            Err(error) => return Err(error),
13775        }
13776        program.set_extension("exe");
13777        return subc_os::ExecutableCapture::open(&program);
13778    }
13779    if program.extension().is_none() {
13780        program.set_extension("exe");
13781    }
13782    let custom_path = spec
13783        .env
13784        .iter()
13785        .rev()
13786        .find(|(key, _)| key.eq_ignore_ascii_case("PATH"));
13787    let mut directories = Vec::new();
13788    // These are Windows' default executable search locations. A configured
13789    // PATH still overrides the inherited PATH, not the system directories.
13790    if let Some(parent) = std::env::current_exe()?.parent() {
13791        directories.push(parent.to_path_buf());
13792    }
13793    directories.push(std::env::current_dir()?);
13794    if let Some(windows) = std::env::var_os("SystemRoot") {
13795        let windows = PathBuf::from(windows);
13796        directories.push(windows.join("System32"));
13797        directories.push(windows.clone());
13798    }
13799    let path = custom_path
13800        .map(|(_, value)| std::ffi::OsString::from(value))
13801        .or_else(|| std::env::var_os("PATH"));
13802    if let Some(path) = path {
13803        directories.extend(std::env::split_paths(&path));
13804    }
13805    for directory in directories {
13806        match subc_os::ExecutableCapture::open(&directory.join(&program)) {
13807            Ok(capture) => return Ok(capture),
13808            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
13809            Err(error) => return Err(error),
13810        }
13811    }
13812    Err(io::Error::new(
13813        io::ErrorKind::NotFound,
13814        "resolved executable not found",
13815    ))
13816}
13817
13818#[cfg(test)]
13819fn spawn_and_mark_running(
13820    spec: &ModuleSpec,
13821    runtime: &SupervisorRuntimeConfig,
13822    snapshot: &SharedSnapshot,
13823) -> Result<SupervisedChild, SuperviseError> {
13824    let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
13825    let registration_watch = watch_registration(&runtime.registry, spec);
13826    #[cfg(unix)]
13827    let joining_group = containment::current(&runtime.child_roster.containment)
13828        .is_some_and(|container| container.group().is_some());
13829    let spawn = || {
13830        spawn_child(
13831            spec,
13832            runtime.connection_file_path.as_deref(),
13833            runtime.supervisor_handle.as_ref(),
13834            &runtime.stderr_ring,
13835            runtime.capture_logs_dir.as_deref(),
13836            &runtime.child_roster,
13837            runtime.spawn_delivery(),
13838            #[cfg(target_os = "linux")]
13839            runtime.cgroup_placement.as_ref(),
13840            runtime.register_timeout,
13841        )
13842    };
13843    let result = spawn();
13844    #[cfg(unix)]
13845    let result = match result {
13846        Err(error)
13847            if joining_group
13848                && !is_launch_deferral(&error)
13849                && !runtime.child_roster.is_closed()
13850                && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
13851                && runtime
13852                    .child_roster
13853                    .previous_instance(&spec.module_id)
13854                    .is_none() =>
13855        {
13856            // The failed join already destroyed and verified the old container.
13857            // Try one fresh group as part of this same restart, without spending
13858            // another crash-budget entry. Cgroups and Windows jobs do not retry.
13859            warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
13860            spawn()
13861        }
13862        other => other,
13863    };
13864    let child = result?;
13865    let mut child = child;
13866    arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
13867    if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
13868        containment::terminate_blocking(&runtime.child_roster.containment);
13869        return Err(error);
13870    }
13871    if let Some(spawn) = activity_spawn {
13872        spawn.complete(snapshot);
13873    }
13874    Ok(child)
13875}
13876
13877struct RegistrationWatch {
13878    changes: watch::Receiver<u64>,
13879    baseline: u64,
13880}
13881
13882// Capture before spawning: a fast child's accepted HELLO can disappear from the
13883// active registry before the monitor first runs. A pre-existing registration
13884// must not satisfy a new process's deadline either.
13885fn watch_registration(registry: &Registry, spec: &ModuleSpec) -> Option<RegistrationWatch> {
13886    if spec.protocol != ModuleProtocol::Subc {
13887        return None;
13888    }
13889    let changes = registry.subscribe_module_changes(&spec.module_id).ok()?;
13890    let baseline = *changes.borrow();
13891    Some(RegistrationWatch { changes, baseline })
13892}
13893
13894fn arm_registration_deadline(
13895    child: &mut SupervisedChild,
13896    budget: Duration,
13897    registration_watch: Option<RegistrationWatch>,
13898) {
13899    child.registration_watch = registration_watch;
13900    child.registration_deadline = (child.protocol == ModuleProtocol::Subc
13901        && child.awaiting_registration())
13902    .then_some(child.spawned_at + budget);
13903}
13904
13905enum RegistrationWaitOutcome {
13906    Registered,
13907    Exited(ExitReport),
13908    TimedOut,
13909}
13910
13911struct ReloadRegistrationFailure {
13912    cleanup_detail: Option<String>,
13913    exit_report: ExitReport,
13914    reason: String,
13915}
13916
13917#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13918enum BusyGaugeObservation {
13919    Quiescent,
13920    Busy,
13921    Omitted,
13922}
13923
13924/// What one health answer said about one declared busy gauge.
13925#[derive(Debug, Clone, PartialEq, Eq)]
13926enum GaugeVerdict {
13927    /// The gauge read 0: this gauge is not what holds the drain.
13928    Zero,
13929    /// The gauge read a positive count.
13930    NonZero(u64),
13931    /// The gauge was present but not a non-negative integer (`0.0`, a string,
13932    /// a negative number). It counts as busy, because the daemon cannot tell
13933    /// it is idle. Carries the value as JSON text, cut to a short prefix.
13934    NotACount(String),
13935    /// The health answer had no metrics object, or one without this gauge.
13936    Missing,
13937    /// The probe produced no health answer to read; carries the probe error's
13938    /// evidence label (`no-answer` for a probe that timed out).
13939    ProbeFailed(&'static str),
13940}
13941
13942impl GaugeVerdict {
13943    fn reads_quiet(&self) -> bool {
13944        matches!(self, Self::Zero)
13945    }
13946}
13947
13948impl fmt::Display for GaugeVerdict {
13949    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13950        match self {
13951            Self::Zero => f.write_str("zero"),
13952            Self::NonZero(value) => write!(f, "non_zero({value})"),
13953            Self::NotACount(value) => write!(f, "not_a_count({value})"),
13954            Self::Missing => f.write_str("missing_from_health_body"),
13955            Self::ProbeFailed(kind) => write!(f, "probe_failed({kind})"),
13956        }
13957    }
13958}
13959
13960/// The longest JSON text kept for a gauge value that is not a count, so a
13961/// module reporting a large object as a gauge cannot flood the drain log.
13962const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
13963
13964/// Read each declared gauge out of one health answer's metrics.
13965fn gauge_verdicts(metrics: Option<&Value>, gauges: &[String]) -> Vec<GaugeVerdict> {
13966    let metrics = metrics.and_then(Value::as_object);
13967    gauges
13968        .iter()
13969        .map(
13970            |gauge| match metrics.and_then(|metrics| metrics.get(gauge)) {
13971                None => GaugeVerdict::Missing,
13972                Some(value) => match value.as_u64() {
13973                    Some(0) => GaugeVerdict::Zero,
13974                    Some(count) => GaugeVerdict::NonZero(count),
13975                    None => {
13976                        let mut text = value.to_string();
13977                        if text.len() > GAUGE_VALUE_TEXT_LIMIT {
13978                            let mut end = GAUGE_VALUE_TEXT_LIMIT;
13979                            while !text.is_char_boundary(end) {
13980                                end -= 1;
13981                            }
13982                            text.truncate(end);
13983                            text.push_str("...");
13984                        }
13985                        GaugeVerdict::NotACount(text)
13986                    }
13987                },
13988            },
13989        )
13990        .collect()
13991}
13992
13993/// The drain's overall reading of one health answer: omitted when any
13994/// declared gauge is missing, quiescent only when every gauge reads 0.
13995fn busy_gauge_observation(verdicts: &[GaugeVerdict]) -> BusyGaugeObservation {
13996    if verdicts
13997        .iter()
13998        .any(|verdict| matches!(verdict, GaugeVerdict::Missing))
13999    {
14000        BusyGaugeObservation::Omitted
14001    } else if verdicts.iter().all(GaugeVerdict::reads_quiet) {
14002        BusyGaugeObservation::Quiescent
14003    } else {
14004        BusyGaugeObservation::Busy
14005    }
14006}
14007
14008/// One declared gauge's history over a drain: the latest verdict on it, and
14009/// the latest value actually read for it (which a later failed probe or
14010/// missing gauge does not erase). Times are offsets from the start of the
14011/// drain's wait.
14012#[derive(Debug, Clone, Default, PartialEq, Eq)]
14013struct GaugeTrace {
14014    latest: Option<(GaugeVerdict, Duration)>,
14015    last_value: Option<(GaugeVerdict, Duration)>,
14016}
14017
14018/// What a drain's busy-gauge probes saw, kept so that a drain which runs to
14019/// its ceiling can say in its timeout line which declared gauge held it and
14020/// why. Without it, a gauge that read busy, a gauge the module never
14021/// reported, and a probe that never got an answer all looked the same: a
14022/// drain that ended at its ceiling with nothing in flight.
14023#[derive(Debug, Clone, Default, PartialEq, Eq)]
14024struct DrainGaugeTrace {
14025    /// Health probes the drain sent.
14026    probes: u32,
14027    /// Each declared gauge, in declaration order.
14028    gauges: Vec<(String, GaugeTrace)>,
14029}
14030
14031impl DrainGaugeTrace {
14032    fn new(gauges: &[String]) -> Self {
14033        Self {
14034            probes: 0,
14035            gauges: gauges
14036                .iter()
14037                .map(|gauge| (gauge.clone(), GaugeTrace::default()))
14038                .collect(),
14039        }
14040    }
14041
14042    /// Record one probe's verdicts, one per declared gauge, `at` into the drain.
14043    fn record(&mut self, verdicts: &[GaugeVerdict], at: Duration) {
14044        self.probes = self.probes.saturating_add(1);
14045        for ((_, trace), verdict) in self.gauges.iter_mut().zip(verdicts) {
14046            trace.latest = Some((verdict.clone(), at));
14047            if matches!(
14048                verdict,
14049                GaugeVerdict::Zero | GaugeVerdict::NonZero(_) | GaugeVerdict::NotACount(_)
14050            ) {
14051                trace.last_value = Some((verdict.clone(), at));
14052            }
14053        }
14054    }
14055}
14056
14057/// Renders as `gauge: latest verdict @ offset; last value @ offset` for each
14058/// declared gauge, separated by ` | `. A value is shown as its verdict
14059/// (`zero`, `non_zero(n)`, `not_a_count(json)`), so it says both what was read
14060/// and whether that counted as busy.
14061impl fmt::Display for DrainGaugeTrace {
14062    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14063        if self.gauges.is_empty() {
14064            return f.write_str("none declared");
14065        }
14066        for (index, (name, trace)) in self.gauges.iter().enumerate() {
14067            if index > 0 {
14068                f.write_str(" | ")?;
14069            }
14070            write!(f, "{name}: ")?;
14071            match &trace.latest {
14072                Some((verdict, at)) => write!(f, "{verdict} @{}ms", at.as_millis())?,
14073                None => f.write_str("never probed")?,
14074            }
14075            match &trace.last_value {
14076                Some((value, at)) => write!(f, "; last value {value} @{}ms", at.as_millis())?,
14077                None => f.write_str("; no value ever read")?,
14078            }
14079        }
14080        Ok(())
14081    }
14082}
14083
14084pub(crate) fn declared_busy_gauges(
14085    registry: &Registry,
14086    module_id: &str,
14087) -> Result<Vec<String>, SuperviseError> {
14088    busy_gauges_of(
14089        registry
14090            .get_module(module_id)
14091            .map_err(SuperviseError::Registry)?,
14092    )
14093}
14094
14095/// [`declared_busy_gauges`] for the registration a connection holds, in any
14096/// slot: after cutover the incumbent is no longer the id's active
14097/// registration, and its own manifest is the one that names its gauges.
14098fn declared_busy_gauges_for_connection(
14099    registry: &Registry,
14100    connection_id: ConnectionId,
14101) -> Result<Vec<String>, SuperviseError> {
14102    busy_gauges_of(
14103        registry
14104            .get_module_by_connection(connection_id)
14105            .map_err(SuperviseError::Registry)?,
14106    )
14107}
14108
14109fn busy_gauges_of(
14110    registration: Option<crate::registry::ModuleRegistration>,
14111) -> Result<Vec<String>, SuperviseError> {
14112    let Some(registration) = registration else {
14113        return Ok(Vec::new());
14114    };
14115    let Some(self_signals) = registration.manifest.self_signals else {
14116        return Ok(Vec::new());
14117    };
14118
14119    let mut gauges = Vec::new();
14120    for declaration in self_signals {
14121        if declaration.kind != SelfSignalKind::Busy {
14122            continue;
14123        }
14124        match declaration.anchored_to {
14125            SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
14126                gauges.extend(declared)
14127            }
14128            _ => {
14129                // An invalid Busy anchor is fail-safe: the empty name cannot be
14130                // present in a conforming health report, so this drain stays busy.
14131                gauges.push(String::new());
14132            }
14133        }
14134    }
14135    Ok(gauges)
14136}
14137
14138/// Wait for `endpoint` to have nothing in flight and, when the module declares
14139/// busy gauges, for a health probe to report them quiet. The probe is addressed
14140/// by `scope`: a swap's superseded incumbent must be asked about its own
14141/// gauges, and by module id the probe would reach the promoted candidate.
14142/// While the gauges read busy, the probe repeats every
14143/// [`DRAIN_BUSY_REPROBE_INTERVAL`] until they read quiet or `deadline` passes.
14144/// Every probe's reading of each gauge is recorded in `trace`, for the caller's
14145/// timeout line.
14146#[allow(clippy::too_many_arguments)]
14147async fn wait_for_forwarding_quiescence(
14148    forwarding: &ForwardingTable,
14149    module_id: &str,
14150    runtime: &SupervisorRuntimeConfig,
14151    endpoint: crate::ModuleEndpointId,
14152    deadline: Instant,
14153    busy_gauges: &[String],
14154    scope: DrainScope,
14155    trace: &mut DrainGaugeTrace,
14156) -> Result<bool, SuperviseError> {
14157    let wait_started = Instant::now();
14158    let mut gauges_quiescent = busy_gauges.is_empty();
14159    let mut next_probe_at = wait_started;
14160    let mut omission_reported = false;
14161
14162    loop {
14163        let now = Instant::now();
14164        if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
14165            let report = match scope {
14166                DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
14167                DrainScope::Endpoint(endpoint) => {
14168                    probe_endpoint_health(endpoint, runtime, Some(deadline)).await
14169                }
14170            };
14171            let verdicts = match &report {
14172                Ok(report) => gauge_verdicts(report.metrics.as_ref(), busy_gauges),
14173                Err(err) => vec![GaugeVerdict::ProbeFailed(err.label()); busy_gauges.len()],
14174            };
14175            trace.record(&verdicts, wait_started.elapsed());
14176            gauges_quiescent = match report {
14177                Ok(_) => match busy_gauge_observation(&verdicts) {
14178                    BusyGaugeObservation::Quiescent => true,
14179                    BusyGaugeObservation::Busy => false,
14180                    BusyGaugeObservation::Omitted => {
14181                        // Once per drain: a module that never reports a gauge
14182                        // it declared would otherwise say so on every probe.
14183                        if !omission_reported {
14184                            forwarding
14185                                .counters()
14186                                .increment_drains_with_undeclared_gauge();
14187                            let missing = busy_gauges
14188                                .iter()
14189                                .zip(&verdicts)
14190                                .filter(|(_, verdict)| matches!(verdict, GaugeVerdict::Missing))
14191                                .map(|(gauge, _)| gauge.as_str())
14192                                .collect::<Vec<_>>()
14193                                .join(",");
14194                            warn!(
14195                                module_id,
14196                                missing_gauges = %missing,
14197                                "drain health.check answer lacks a declared busy gauge; the drain treats the module as busy until it reports it"
14198                            );
14199                            omission_reported = true;
14200                        }
14201                        false
14202                    }
14203                },
14204                Err(err) => {
14205                    warn!(
14206                        module_id,
14207                        error = %err,
14208                        "drain health.check did not produce declared busy gauges; treating module as busy"
14209                    );
14210                    false
14211                }
14212            };
14213            // Counted from the probe's completion: the probe above was awaited,
14214            // so no second probe can start while one is still outstanding.
14215            next_probe_at = Instant::now() + drain_busy_reprobe_interval();
14216        }
14217
14218        let in_flight = forwarding
14219            .endpoint_in_flight_count(endpoint)
14220            .map_err(SuperviseError::Forwarding)?;
14221        if in_flight == 0 && gauges_quiescent {
14222            return Ok(true);
14223        }
14224
14225        let now = Instant::now();
14226        if now >= deadline {
14227            return Ok(false);
14228        }
14229        let mut wait = deadline
14230            .saturating_duration_since(now)
14231            .min(REGISTRY_RELEASE_POLL);
14232        if !busy_gauges.is_empty() {
14233            wait = wait.min(next_probe_at.saturating_duration_since(now));
14234        }
14235        sleep(wait).await;
14236    }
14237}
14238
14239/// The wait between drain busy-gauge probes: the larger of
14240/// [`DRAIN_BUSY_REPROBE_INTERVAL`] and [`REGISTRY_RELEASE_POLL`], the
14241/// drain's own in-flight poll interval.
14242fn drain_busy_reprobe_interval() -> Duration {
14243    DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
14244}
14245
14246/// Logs why a drain gave up: the drain waited its full timeout without the
14247/// module going quiet, and teardown is being forced.
14248///
14249/// The line names two kinds of evidence, because a bare "timed out" hides
14250/// causes that need different fixes:
14251/// - `holdouts`: the requests and routes still open when the timeout hit,
14252///   and on which connections. One stuck call is a module bug; a held stream
14253///   on every session is a module that should end its streams when it
14254///   receives `module.draining`.
14255/// - `gauges`: for each busy gauge the module declares, its latest reading
14256///   and how many probes ran. This separates a module that kept reporting
14257///   itself busy, one whose health answer never contained the gauge, and one
14258///   that never answered the probes, which otherwise all look like a timeout
14259///   with nothing in flight.
14260fn warn_drain_timed_out(
14261    module_id: &str,
14262    drain_timeout: Duration,
14263    reason: RouteCloseReason,
14264    holdouts: &crate::forwarding::DrainHoldouts,
14265    gauges: &DrainGaugeTrace,
14266) {
14267    warn!(
14268        module_id = %module_id,
14269        waited = ?drain_timeout,
14270        ?reason,
14271        held_requests = holdouts.requests,
14272        held_routes = holdouts.routes,
14273        total_routes = holdouts.total_routes,
14274        top_connections = ?holdouts.top_connections,
14275        // `module_channel:corr`, so the module can find each held request
14276        // in its own log; capped, so `held_requests` is the full count.
14277        held = %holdouts
14278            .held
14279            .iter()
14280            .map(|(channel, corr)| format!("{channel}:{corr}"))
14281            .collect::<Vec<_>>()
14282            .join(","),
14283        gauge_probes = gauges.probes,
14284        busy_gauges = %gauges,
14285        "route drain timed out before request quiescence; forcing teardown"
14286    );
14287}
14288
14289/// The `route.closed` `drained` value implied by a quiescence-wait outcome.
14290///
14291/// `Ok` is always honest and passed straight through -- the wait actually measured
14292/// in-flight state. `Err` means the wait produced no measurement at all (the
14293/// forwarding table's lock was poisoned), so `false` is reported as the one honest
14294/// constant: the drain did not complete. Never recomputed from route state, never a
14295/// third "unknown" value -- the caller must still send a well-formed `route.closed`.
14296fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
14297    match wait_result {
14298        Ok(drained) => *drained,
14299        Err(_) => false,
14300    }
14301}
14302
14303fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
14304    for released in released_routes {
14305        let frame = match Frame::build_with_version(
14306            released.negotiated_ver,
14307            FrameType::Goodbye,
14308            control_flags(),
14309            released.channel,
14310            released.epoch,
14311            0,
14312            Vec::new(),
14313        ) {
14314            Ok(frame) => frame,
14315            Err(err) => {
14316                warn!(
14317                    route_channel = released.channel,
14318                    error = %err,
14319                    "failed to build supervisor drain route GOODBYE frame"
14320                );
14321                continue;
14322            }
14323        };
14324        if !released.close_on_delivery_failure() {
14325            crate::forwarding::send_module_route_goodbye(
14326                &forwarding.counters(),
14327                &released.sink,
14328                frame,
14329                released.module_id.as_deref(),
14330                "supervisor drain",
14331            );
14332            continue;
14333        }
14334        if let Err(err) = released.sink.try_send(frame) {
14335            warn!(
14336                target_connection_id = released.connection_id.get(),
14337                route_channel = released.channel,
14338                error = %err,
14339                "supervisor drain route GOODBYE was not delivered to client; closing target connection"
14340            );
14341            let _ = forwarding.escalate_client_delivery_failure(
14342                released.connection_id,
14343                released.channel,
14344                released.epoch,
14345                CloseReason::new(
14346                    "route_goodbye_delivery_failed",
14347                    format!(
14348                        "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
14349                        released.channel
14350                    ),
14351                ),
14352                crate::forwarding::UndeliveredFrame {
14353                    module_id: released.module_id.as_deref(),
14354                    sink: &released.sink,
14355                },
14356            );
14357        }
14358    }
14359}
14360
14361async fn send_module_draining(
14362    module_id: &str,
14363    reason: RouteCloseReason,
14364    deadline_ms: u64,
14365    target: &ModuleDrainTarget,
14366    _wait_for_flush: bool,
14367) -> bool {
14368    let body = match serde_json::to_vec(&ModuleControlCommand::Draining {
14369        reason,
14370        deadline_ms,
14371    }) {
14372        Ok(body) => body,
14373        Err(err) => {
14374            warn!(
14375                module_id,
14376                error = %err,
14377                "failed to encode module draining command"
14378            );
14379            return false;
14380        }
14381    };
14382    let frame = match Frame::build_with_version(
14383        target.negotiated_ver,
14384        FrameType::Push,
14385        control_flags(),
14386        0,
14387        0,
14388        0,
14389        body,
14390    ) {
14391        Ok(frame) => frame,
14392        Err(err) => {
14393            warn!(
14394                module_id,
14395                error = %err,
14396                "failed to build module draining command frame"
14397            );
14398            return false;
14399        }
14400    };
14401    #[cfg(unix)]
14402    if _wait_for_flush {
14403        return target.sink.send_flushed(frame).await.is_ok();
14404    }
14405    if let Err(err) = target.sink.try_send(frame) {
14406        warn!(
14407            module_id,
14408            target_connection_id = target.endpoint.connection_id.get(),
14409            error = %err,
14410            "module draining command was not delivered to peer"
14411        );
14412        return false;
14413    }
14414    true
14415}
14416
14417/// The channel-0 GOODBYE that tells a module its stop is planned.
14418fn module_goodbye_frame(module_id: &str, negotiated_ver: u8) -> Option<Frame> {
14419    match Frame::build_with_version(
14420        negotiated_ver,
14421        FrameType::Goodbye,
14422        control_flags(),
14423        0,
14424        0,
14425        0,
14426        Vec::new(),
14427    ) {
14428        Ok(frame) => Some(frame),
14429        Err(err) => {
14430            warn!(
14431                module_id,
14432                error = %err,
14433                "failed to build module GOODBYE frame"
14434            );
14435            None
14436        }
14437    }
14438}
14439
14440/// Send every registered module connection its module GOODBYE at daemon
14441/// shutdown, then request that connection's close.
14442///
14443/// A module tells a planned stop from a lost daemon by whether a GOODBYE came
14444/// before EOF, so the GOODBYE must reach the socket before the close. A close
14445/// request does not wait for the connection's queued frames: its writer gets a
14446/// bounded grace after the close, is aborted if it overruns it, and the daemon
14447/// process may exit before that grace ends. So with `wait_for_flush`, each
14448/// connection is closed only after its writer has acknowledged writing the
14449/// GOODBYE, or once a short shared budget runs out, so one module that is not
14450/// reading cannot hold up the others or the shutdown. Without it the GOODBYEs
14451/// are only queued, for a shutdown the operator has told to stop waiting.
14452/// A connection that is already gone is skipped.
14453#[cfg(unix)]
14454async fn send_module_goodbyes_for_daemon_shutdown(
14455    forwarding: &Arc<ForwardingTable>,
14456    reason: &CloseReason,
14457    wait_for_flush: bool,
14458) {
14459    const GOODBYE_BUDGET: Duration = Duration::from_millis(500);
14460    let targets = match forwarding.module_connections() {
14461        Ok(targets) => targets,
14462        Err(err) => {
14463            warn!(error = %err, "could not list module connections for shutdown GOODBYE");
14464            return;
14465        }
14466    };
14467    let deadline = Instant::now() + GOODBYE_BUDGET;
14468    let mut sends = tokio::task::JoinSet::new();
14469    for target in targets {
14470        let Some(frame) = module_goodbye_frame(&target.module_id, target.negotiated_ver) else {
14471            continue;
14472        };
14473        if !wait_for_flush {
14474            if let Err(err) = target.sink.try_send(frame) {
14475                debug!(
14476                    module_id = %target.module_id,
14477                    error = %err,
14478                    "shutdown module GOODBYE was not queued"
14479                );
14480            }
14481            continue;
14482        }
14483        let forwarding = Arc::clone(forwarding);
14484        let reason = reason.clone();
14485        sends.spawn(async move {
14486            match timeout_at(deadline, target.sink.send_flushed(frame)).await {
14487                Ok(Ok(())) => {}
14488                Ok(Err(err)) => debug!(
14489                    module_id = %target.module_id,
14490                    error = %err,
14491                    "module connection closed before its shutdown GOODBYE was written"
14492                ),
14493                Err(_) => warn!(
14494                    module_id = %target.module_id,
14495                    budget = ?GOODBYE_BUDGET,
14496                    "shutdown module GOODBYE was not written within its budget; closing anyway"
14497                ),
14498            }
14499            forwarding.request_connection_close(target.endpoint.connection_id, reason);
14500        });
14501    }
14502    // Every task ends by the shared deadline, so this wait is bounded too.
14503    while sends.join_next().await.is_some() {}
14504}
14505
14506async fn send_module_goodbye(
14507    module_id: &str,
14508    forwarding: &ForwardingTable,
14509    target: &ModuleDrainTarget,
14510    wait_for_flush: bool,
14511) {
14512    let Some(frame) = module_goodbye_frame(module_id, target.negotiated_ver) else {
14513        return;
14514    };
14515    // A channel is shut down synchronously after its drain. Its final frame
14516    // must reach the socket writer first; queue admission alone can lose it.
14517    let sent = if wait_for_flush {
14518        timeout(Duration::from_millis(500), target.sink.send_flushed(frame))
14519            .await
14520            .map_err(|_| "module GOODBYE flush exceeded 500ms".to_owned())
14521            .and_then(|result| result.map_err(|err| err.to_string()))
14522    } else {
14523        target.sink.try_send(frame).map_err(|err| err.to_string())
14524    };
14525    if let Err(err) = sent {
14526        warn!(
14527            module_id,
14528            target_connection_id = target.endpoint.connection_id.get(),
14529            error = %err,
14530            "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
14531        );
14532        forwarding.request_connection_close(
14533            target.endpoint.connection_id,
14534            CloseReason::new(
14535                "module_goodbye_delivery_failed",
14536                format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
14537            ),
14538        );
14539    }
14540}
14541
14542#[derive(Clone, Copy)]
14543struct ForwardingDrainContext<'a> {
14544    spec: &'a ModuleSpec,
14545    runtime: &'a SupervisorRuntimeConfig,
14546    registry: &'a Registry,
14547    scope: DrainScope,
14548}
14549
14550/// Which process a forwarding drain addresses.
14551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14552enum DrainScope {
14553    /// Whatever endpoint is active for the module id: every plain stop,
14554    /// restart and reload. Also moves the module's state to `Draining`.
14555    Active,
14556    /// One specific endpoint: a swap's incumbent after cutover. Draining it by
14557    /// module id would resolve to the promoted candidate and leave neither
14558    /// process routable. The module's state is left alone, since the promoted
14559    /// candidate is what it describes and that process is running.
14560    Endpoint(crate::ModuleEndpointId),
14561}
14562
14563/// Whether a child being drained has already been asked to stop by the time
14564/// its drain wait starts.
14565///
14566/// The drain wait is the same budget whatever this says. What it decides is
14567/// whether the supervisor must ask by signal before that wait begins: a child
14568/// that nobody asked will sit out the whole budget and then be SIGKILLed,
14569/// healthy or not.
14570#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14571enum StopNotice {
14572    /// The module was sent `module.draining` and a module GOODBYE over its own
14573    /// registered connection, and stops itself.
14574    SentOverConnection,
14575    /// The forwarding drain found no registered connection for the module: a
14576    /// subc child spawned moments ago that has not sent HELLO yet, or a
14577    /// `protocol: "none"` child, which never registers.
14578    NoConnection,
14579    /// This path sends nothing over the module's connection: the supervisor has
14580    /// no forwarding table, or the caller stops the child without a forwarding
14581    /// drain.
14582    NotSent,
14583}
14584
14585async fn begin_forwarding_drain(
14586    spec: &ModuleSpec,
14587    runtime: &SupervisorRuntimeConfig,
14588    registry: &Registry,
14589    snapshot: &SharedSnapshot,
14590    enabled: Option<bool>,
14591    reason: RouteCloseReason,
14592) -> Result<StopNotice, SuperviseError> {
14593    let Some(forwarding) = runtime.forwarding.as_ref() else {
14594        return Err(SuperviseError::ReloadUnavailable {
14595            module_id: spec.module_id.clone(),
14596            reason: "supervisor was not configured with a forwarding table".to_string(),
14597        });
14598    };
14599
14600    begin_forwarding_drain_with(
14601        forwarding,
14602        ForwardingDrainContext {
14603            spec,
14604            runtime,
14605            registry,
14606            scope: DrainScope::Active,
14607        },
14608        snapshot,
14609        enabled,
14610        reason,
14611        runtime.drain_timeout,
14612    )
14613    .await
14614}
14615
14616async fn begin_forwarding_drain_if_configured(
14617    spec: &ModuleSpec,
14618    runtime: &SupervisorRuntimeConfig,
14619    registry: &Registry,
14620    snapshot: &SharedSnapshot,
14621    enabled: Option<bool>,
14622    reason: RouteCloseReason,
14623) -> Result<StopNotice, SuperviseError> {
14624    begin_forwarding_drain_with_timeout(
14625        spec,
14626        runtime,
14627        registry,
14628        snapshot,
14629        enabled,
14630        reason,
14631        runtime.drain_timeout,
14632    )
14633    .await
14634}
14635
14636/// Like [`begin_forwarding_drain_if_configured`] but with an explicit drain
14637/// budget, for paths where the operator overrides the module's configured one
14638/// (`supervisor.restart{drain_timeout_ms}`).
14639async fn begin_forwarding_drain_with_timeout(
14640    spec: &ModuleSpec,
14641    runtime: &SupervisorRuntimeConfig,
14642    registry: &Registry,
14643    snapshot: &SharedSnapshot,
14644    enabled: Option<bool>,
14645    reason: RouteCloseReason,
14646    drain_timeout: Duration,
14647) -> Result<StopNotice, SuperviseError> {
14648    let Some(forwarding) = runtime.forwarding.as_ref() else {
14649        return Ok(StopNotice::NotSent);
14650    };
14651
14652    begin_forwarding_drain_with(
14653        forwarding,
14654        ForwardingDrainContext {
14655            spec,
14656            runtime,
14657            registry,
14658            scope: DrainScope::Active,
14659        },
14660        snapshot,
14661        enabled,
14662        reason,
14663        drain_timeout,
14664    )
14665    .await
14666}
14667
14668async fn begin_forwarding_drain_with(
14669    forwarding: &ForwardingTable,
14670    context: ForwardingDrainContext<'_>,
14671    snapshot: &SharedSnapshot,
14672    enabled: Option<bool>,
14673    reason: RouteCloseReason,
14674    drain_timeout: Duration,
14675) -> Result<StopNotice, SuperviseError> {
14676    let ForwardingDrainContext {
14677        spec,
14678        runtime,
14679        registry,
14680        scope,
14681    } = context;
14682    debug_assert_ne!(reason, RouteCloseReason::Crash);
14683    let terminal = matches!(reason, RouteCloseReason::Disable);
14684    let drain_started_at = Instant::now();
14685    let drain_deadline = drain_started_at + drain_timeout;
14686    let deadline_ms =
14687        unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
14688    let busy_gauges = match scope {
14689        DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
14690        DrainScope::Endpoint(endpoint) => {
14691            declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
14692        }
14693    };
14694
14695    // Admission gate first: route.open/commit and route REQUEST admission are closed
14696    // before the first quiescence check, so the outstanding count can only fall.
14697    let gate_started = Instant::now();
14698    let drain_target = match scope {
14699        DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
14700        DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
14701    }
14702    .map_err(SuperviseError::Forwarding)?;
14703    // The instant admission closed, and how long taking the forwarding write
14704    // lock to close it took. The timeout line reports only the quiescence
14705    // wait, so without this a drain that started late looked like one that
14706    // started on time.
14707    info!(
14708        module_id = %spec.module_id,
14709        ?reason,
14710        gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
14711        connected = drain_target.is_some(),
14712        "module drain began; route admission closed"
14713    );
14714    if scope == DrainScope::Active {
14715        update_snapshot(snapshot, Some(&spec.module_id), |state| {
14716            state.state = ModuleState::Draining;
14717            state.draining_to_replace =
14718                matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
14719            if let Some(enabled) = enabled {
14720                state.enabled = enabled;
14721            }
14722        })?;
14723    }
14724
14725    let Some(target) = drain_target.as_ref() else {
14726        // Nothing was sent: the module has no registered connection to carry
14727        // `module.draining` or a GOODBYE. The caller must not assume the child
14728        // was asked to stop.
14729        return Ok(StopNotice::NoConnection);
14730    };
14731    let flush_goodbye = runtime.supervisor_handle.as_ref().is_some_and(|handle| {
14732        handle
14733            .registration_spawn(target.endpoint.connection_id)
14734            .is_some()
14735    });
14736    {
14737        send_module_draining(&spec.module_id, reason, deadline_ms, target, false).await;
14738        #[cfg(feature = "test-support")]
14739        forwarding.wait_before_route_closing_for_test().await;
14740        let routes = forwarding
14741            .endpoint_routes(target.endpoint)
14742            .map_err(SuperviseError::Forwarding)?;
14743        let routes_notified = routes.len();
14744        crate::control::send_route_control_pushes(
14745            forwarding,
14746            routes.clone(),
14747            ClientControlPush::RouteClosing {
14748                module_id: spec.module_id.clone(),
14749                channels: Vec::new(),
14750                reason,
14751            },
14752        );
14753        send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
14754
14755        // `route.closing` was just sent above: from here on every return path,
14756        // including an early one, MUST send `route.closed` before propagating
14757        // anything else. A client holds `closing` as a promise that a verdict is
14758        // coming; leaving early without `closed` strands it waiting forever, since
14759        // `closing` carries no timeout of its own.
14760        let mut gauge_trace = DrainGaugeTrace::new(&busy_gauges);
14761        let wait_result = wait_for_forwarding_quiescence(
14762            forwarding,
14763            &spec.module_id,
14764            runtime,
14765            target.endpoint,
14766            drain_deadline,
14767            &busy_gauges,
14768            scope,
14769            &mut gauge_trace,
14770        )
14771        .await;
14772        let drained = drained_after_quiescence_wait(&wait_result);
14773        if let Err(err) = &wait_result {
14774            error!(
14775                module_id = %spec.module_id,
14776                ?reason,
14777                error = %err,
14778                "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
14779            );
14780        } else if !drained {
14781            // Read before teardown releases the routes.
14782            let holdouts = forwarding
14783                .endpoint_drain_holdouts(target.endpoint)
14784                .unwrap_or_default();
14785            warn_drain_timed_out(
14786                &spec.module_id,
14787                drain_timeout,
14788                reason,
14789                &holdouts,
14790                &gauge_trace,
14791            );
14792        }
14793        crate::control::send_route_control_pushes(
14794            forwarding,
14795            routes,
14796            ClientControlPush::RouteClosed {
14797                module_id: spec.module_id.clone(),
14798                channels: Vec::new(),
14799                reason,
14800                drained,
14801                abandoned: target.abandoned_bindings.len() as u32,
14802                excluded_subscriptions: target.excluded_subscriptions,
14803                terminal: Some(terminal),
14804            },
14805        );
14806        wait_result?;
14807
14808        // `route.closed` has now been sent unconditionally above. From here the
14809        // remaining steps are cleanup (route + module GOODBYE) rather than a
14810        // promise the client is waiting on, but a lock-poisoned
14811        // `release_module_endpoint_routes` would otherwise skip the module
14812        // GOODBYE silently too -- send it before propagating the error.
14813        let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
14814            Ok(routes) => routes,
14815            Err(err) => {
14816                warn!(
14817                    module_id = %spec.module_id,
14818                    ?reason,
14819                    error = %err,
14820                    "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
14821                );
14822                send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
14823                return Err(SuperviseError::Forwarding(err));
14824            }
14825        };
14826        let route_goodbye_count = released_routes.len();
14827        send_route_goodbyes(forwarding, released_routes);
14828        send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
14829
14830        // The drain's happy path was previously silent: every emission above is
14831        // best-effort with only its failure arm logged, so "were consumers told"
14832        // was unprovable from the daemon log (surfaced by a 30-minute consumer
14833        // hang where the open question was exactly whether teardown notice went
14834        // out). One summary line makes that class decidable in one grep.
14835        info!(
14836            module_id = %spec.module_id,
14837            ?reason,
14838            routes_notified,
14839            route_goodbyes = route_goodbye_count,
14840            abandoned_reservations = target.abandoned_bindings.len(),
14841            excluded_subscriptions = target.excluded_subscriptions,
14842            drained,
14843            "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
14844        );
14845    }
14846
14847    Ok(StopNotice::SentOverConnection)
14848}
14849
14850/// Wait for the freshly spawned child to take the ACTIVE slot for `module_id`,
14851/// the only slot a plain (non-swap) spawn can register into.
14852async fn wait_for_registration_after_reload(
14853    registry: &Registry,
14854    module_id: &str,
14855    snapshot: &SharedSnapshot,
14856    child: &mut SupervisedChild,
14857    wait: Duration,
14858) -> Result<RegistrationWaitOutcome, SuperviseError> {
14859    wait_for_slot_registration(
14860        registry,
14861        crate::registry::RegistrationSlot::Active(module_id),
14862        module_id,
14863        snapshot,
14864        child,
14865        wait,
14866    )
14867    .await
14868}
14869
14870/// Wait for `child` to register into `slot`, or to exit, or for `wait` to pass.
14871///
14872/// Keyed on the slot rather than the bare module id because during a swap the
14873/// id's active slot is already held by the incumbent: an id-keyed wait would
14874/// report the incumbent's registration as the candidate's and a candidate that
14875/// never registers would look registered. A swap candidate waits on
14876/// `crate::registry::RegistrationSlot::Candidate`.
14877async fn wait_for_slot_registration(
14878    registry: &Registry,
14879    slot: crate::registry::RegistrationSlot<'_>,
14880    module_id: &str,
14881    snapshot: &SharedSnapshot,
14882    child: &mut SupervisedChild,
14883    wait: Duration,
14884) -> Result<RegistrationWaitOutcome, SuperviseError> {
14885    let deadline = Instant::now() + wait;
14886    loop {
14887        if registry
14888            .registration(slot)
14889            .map_err(SuperviseError::Registry)?
14890            .is_some()
14891        {
14892            return Ok(RegistrationWaitOutcome::Registered);
14893        }
14894
14895        let now = Instant::now();
14896        if now >= deadline {
14897            return Ok(RegistrationWaitOutcome::TimedOut);
14898        }
14899        let remaining = deadline.saturating_duration_since(now);
14900        let poll = remaining.min(REGISTRY_RELEASE_POLL);
14901
14902        tokio::select! {
14903            wait_result = child.wait() => {
14904                let status = wait_result.map_err(|source| SuperviseError::Wait {
14905                    module_id: module_id.to_string(),
14906                    source,
14907                })?;
14908                return Ok(RegistrationWaitOutcome::Exited(classify_reaped_child_exit(
14909                    snapshot,
14910                    child,
14911                    &status,
14912                )));
14913            }
14914            _ = sleep(poll) => {}
14915        }
14916    }
14917}
14918
14919fn registration_failure_exit_report(mut exit_report: ExitReport) -> ExitReport {
14920    // A process stopped for missing its first HELLO did not provide service,
14921    // even if its TERM handler exits zero. Reload also uses this classification
14922    // when a replacement exits before registering.
14923    if exit_report.kind != ExitKind::DeliberateSeverance {
14924        exit_report.kind = ExitKind::Crash;
14925    }
14926    exit_report
14927}
14928
14929async fn handle_reload_child_registration_failure(
14930    spec: &ModuleSpec,
14931    runtime: &SupervisorRuntimeConfig,
14932    registry: &Registry,
14933    process_liveness: &SupervisorProcessLiveness,
14934    snapshot: &SharedSnapshot,
14935    _child: &mut Option<SupervisedChild>,
14936    failure: ReloadRegistrationFailure,
14937) -> Result<(), SuperviseError> {
14938    let ReloadRegistrationFailure {
14939        exit_report,
14940        reason,
14941        cleanup_detail,
14942    } = failure;
14943    match on_child_exit_with_detail(
14944        spec,
14945        runtime.restart_policy,
14946        registry,
14947        snapshot,
14948        &runtime.terminal_ring,
14949        &runtime.spawn_events,
14950        &runtime.child_roster,
14951        exit_report,
14952        runtime.recovery_is_daemon,
14953        cleanup_detail,
14954    )
14955    .await
14956    {
14957        NextAction::Stop {
14958            registration_released,
14959        } => {
14960            if registration_released {
14961                process_liveness.untrack_if_current(&spec.module_id, snapshot);
14962            }
14963        }
14964        NextAction::Restart { schedule } => {
14965            let delay = schedule.map_or(runtime.restart_policy.delay_for_restart(0), |schedule| {
14966                schedule.delay
14967            });
14968            if let Some(schedule) = schedule {
14969                log_crash_respawn(&spec.module_id, schedule);
14970            }
14971            schedule_respawn(
14972                runtime,
14973                snapshot,
14974                &spec.module_id,
14975                delay,
14976                RespawnKind::after_exit(schedule),
14977                true,
14978            )?;
14979        }
14980    }
14981    Err(SuperviseError::ReloadFailed {
14982        module_id: spec.module_id.clone(),
14983        reason,
14984    })
14985}
14986
14987async fn handle_reload_spawn_failure(
14988    spec: &ModuleSpec,
14989    runtime: &SupervisorRuntimeConfig,
14990    process_liveness: &SupervisorProcessLiveness,
14991    snapshot: &SharedSnapshot,
14992    _child: &mut Option<SupervisedChild>,
14993    reason: String,
14994) -> Result<(), SuperviseError> {
14995    let now = Instant::now();
14996    let mut schedule = None;
14997    update_snapshot(snapshot, Some(&spec.module_id), |state| {
14998        clear_current_process_facts(state);
14999        if state.enabled {
15000            schedule = state.next_crash_restart(&runtime.restart_policy, now);
15001            state.state = if schedule.is_some() {
15002                ModuleState::Restarting
15003            } else {
15004                if runtime
15005                    .failure_context(runtime.recovery_is_daemon)
15006                    .may_retry()
15007                {
15008                    state.failed_retry.schedule(&spec.module_id);
15009                }
15010                ModuleState::Failed
15011            };
15012        } else {
15013            state.state = ModuleState::Disabled;
15014        }
15015    })?;
15016    if let Some(schedule) = schedule {
15017        schedule_respawn(
15018            runtime,
15019            snapshot,
15020            &spec.module_id,
15021            schedule.delay,
15022            RespawnKind::CrashRestart,
15023            true,
15024        )?;
15025    } else {
15026        process_liveness.untrack_if_current(&spec.module_id, snapshot);
15027    }
15028    Err(SuperviseError::ReloadFailed {
15029        module_id: spec.module_id.clone(),
15030        reason,
15031    })
15032}
15033
15034fn control_flags() -> Flags {
15035    Flags::new(false, Priority::Passive, false)
15036}
15037
15038#[allow(clippy::too_many_arguments)]
15039async fn drain_optional_child(
15040    module_id: &str,
15041    protocol: ModuleProtocol,
15042    stop_notice: StopNotice,
15043    registry: &Registry,
15044    forwarding: Option<&ForwardingTable>,
15045    snapshot: &SharedSnapshot,
15046    terminal_ring: &Arc<Mutex<TerminalRing>>,
15047    spawn_events: &SpawnEventFeed,
15048    child: &mut Option<SupervisedChild>,
15049    drain_timeout: Duration,
15050    final_state: ModuleState,
15051    enabled: Option<bool>,
15052    failure: &FailureContext,
15053) -> Result<(), SuperviseError> {
15054    if let Some(child) = child.take() {
15055        drain_child_to_state(
15056            module_id,
15057            protocol,
15058            stop_notice,
15059            registry,
15060            forwarding,
15061            snapshot,
15062            terminal_ring,
15063            spawn_events,
15064            child,
15065            drain_timeout,
15066            final_state,
15067            enabled,
15068            failure,
15069        )
15070        .await
15071    } else {
15072        update_snapshot(snapshot, Some(module_id), |state| {
15073            state.state = final_state;
15074            if final_state == ModuleState::Failed {
15075                state.failed_retry.failed_at = Some(Instant::now());
15076            }
15077            if let Some(enabled) = enabled {
15078                state.enabled = enabled;
15079            }
15080            clear_current_process_facts(state);
15081        })?;
15082        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await
15083    }
15084}
15085
15086#[allow(clippy::too_many_arguments)]
15087async fn drain_child_to_state(
15088    module_id: &str,
15089    _protocol: ModuleProtocol,
15090    stop_notice: StopNotice,
15091    registry: &Registry,
15092    forwarding: Option<&ForwardingTable>,
15093    snapshot: &SharedSnapshot,
15094    terminal_ring: &Arc<Mutex<TerminalRing>>,
15095    spawn_events: &SpawnEventFeed,
15096    mut child: SupervisedChild,
15097    drain_timeout: Duration,
15098    final_state: ModuleState,
15099    enabled: Option<bool>,
15100    failure: &FailureContext,
15101) -> Result<(), SuperviseError> {
15102    let protocol = child.protocol;
15103    child.retire_registration();
15104    update_snapshot(snapshot, Some(module_id), |state| {
15105        state.state = ModuleState::Draining;
15106        state.draining_to_replace = final_state == ModuleState::Restarting;
15107        if let Some(enabled) = enabled {
15108            state.enabled = enabled;
15109        }
15110    })?;
15111
15112    // The wait below is the same budget in every case; what differs is
15113    // whether anything has ASKED the child to stop before it starts. Only a
15114    // forwarding drain that reached the module's registered connection has
15115    // (`module.draining`, then a module GOODBYE). Every other child was told
15116    // nothing: a `protocol: "none"` module, which never registers; a subc
15117    // module spawned moments ago that has not sent HELLO yet; or a stop that
15118    // runs no forwarding drain. Without a signal the budget is only a delay
15119    // in front of SIGKILL -- and the not-yet-registered child is the worst
15120    // case, because it registers into a module that is already draining,
15121    // is never told, and is killed while healthy.
15122    if stop_notice != StopNotice::SentOverConnection {
15123        if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
15124            info!(
15125                module_id,
15126                pid = child.pid,
15127                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
15128                "module has no connection yet; requesting stop by signal"
15129            );
15130        }
15131        request_graceful_stop(module_id, &child);
15132    }
15133
15134    let drain_timeout = child.group_drain_budget(drain_timeout, stop_notice);
15135    let exit_report = match timeout(drain_timeout, child.wait()).await {
15136        Ok(Ok(status)) => classify_reaped_child_exit(snapshot, &child, &status),
15137        Ok(Err(source)) => {
15138            fail_after_wait_error(
15139                module_id,
15140                snapshot,
15141                terminal_ring,
15142                spawn_events,
15143                format!("failed to wait during drain: {source}"),
15144                failure,
15145            );
15146            return Err(SuperviseError::Wait {
15147                module_id: module_id.to_string(),
15148                source,
15149            });
15150        }
15151        Err(_) => {
15152            // Mirror the sibling arm above: state is already `Draining`, and an
15153            // error propagated from here would strand it there -- a state
15154            // `set_enabled(true)` cannot heal (`revive_terminal` matches only
15155            // `Failed | Stopped`), leaving an operator Restart as the only exit.
15156            // `Failed` before `?` keeps the module operator-visible and
15157            // revivable. Trigger is an ESRCH race (process exits between the
15158            // drain timeout firing and the kill) or a post-kill wait failure
15159            // (issue #34).
15160            //
15161            // Logged because the kill is otherwise visible only as signal 9 in
15162            // the terminal ring, and the budget it follows can be long enough
15163            // that consumers see a stretch of refusals with no stated cause.
15164            warn!(
15165                module_id,
15166                pid = child.pid,
15167                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
15168                reason = ?final_state,
15169                ?stop_notice,
15170                "drain budget expired before the module exited; killing it"
15171            );
15172            let kill =
15173                if final_state == ModuleState::Restarting && child.child.container().is_some() {
15174                    child.kill_leader()
15175                } else {
15176                    child.start_kill()
15177                };
15178            kill.map_err(|source| {
15179                fail_after_wait_error(
15180                    module_id,
15181                    snapshot,
15182                    terminal_ring,
15183                    spawn_events,
15184                    format!("failed to kill during drain: {source}"),
15185                    failure,
15186                );
15187                SuperviseError::Kill {
15188                    module_id: module_id.to_string(),
15189                    source,
15190                }
15191            })?;
15192            let status = child.wait().await.map_err(|source| {
15193                fail_after_wait_error(
15194                    module_id,
15195                    snapshot,
15196                    terminal_ring,
15197                    spawn_events,
15198                    format!("failed to wait after drain kill: {source}"),
15199                    failure,
15200                );
15201                SuperviseError::Wait {
15202                    module_id: module_id.to_string(),
15203                    source,
15204                }
15205            })?;
15206            classify_reaped_child_exit(snapshot, &child, &status)
15207        }
15208    };
15209
15210    child.drain_stderr(module_id).await;
15211    let detail =
15212        child.exit_cleanup_detail(lock_snapshot(snapshot)?.drain_disposition_detail.take());
15213    publish_after_terminal_record(
15214        module_id,
15215        || {
15216            record_terminal_with_detail(
15217                module_id,
15218                terminal_ring,
15219                spawn_events,
15220                &exit_report,
15221                terminal_disposition(final_state),
15222                detail,
15223            )
15224        },
15225        || {
15226            update_snapshot(snapshot, Some(module_id), |state| {
15227                state.state = final_state;
15228                if final_state == ModuleState::Failed {
15229                    state.failed_retry.failed_at = Some(Instant::now());
15230                }
15231                if let Some(enabled) = enabled {
15232                    state.enabled = enabled;
15233                }
15234                clear_current_process_facts(state);
15235                state.last_exit = Some(exit_report.clone());
15236                if exit_report.kind == ExitKind::DeliberateSeverance {
15237                    state.lifetime_restarts += 1;
15238                }
15239            })
15240        },
15241    )?;
15242    let released =
15243        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
15244    child
15245        .finish_exit(
15246            released.is_ok()
15247                && final_state == ModuleState::Restarting
15248                && child.spawn_failure.is_none(),
15249        )
15250        .await
15251        .map_err(|source| SuperviseError::Wait {
15252            module_id: module_id.to_owned(),
15253            source,
15254        })?;
15255    released
15256}
15257
15258/// Ask a child that nothing else has asked to stop, by signal.
15259///
15260/// A registered subc module is asked over its own connection: the drain sends
15261/// `route.closing`/`route.closed` to its consumers, a GOODBYE per route, then a
15262/// module GOODBYE, and the module stops itself. A module that speaks no subc
15263/// wire receives none of that, and neither does a subc module that has not
15264/// registered yet, so for them the drain budget would be pure delay in front of
15265/// a SIGKILL -- and for a process with a store to flush (JetStream is the
15266/// reason `protocol: "none"` exists) a SIGKILL turns every ordinary teardown
15267/// into a recovery on the next start.
15268///
15269/// NEVER CALLED FOR A MODULE THAT WAS TOLD OVER ITS CONNECTION, and that is a
15270/// rule rather than an optimisation: that module's graceful stop is already
15271/// running by the time its child is drained, and a signal would race it.
15272///
15273/// Best-effort by construction. A child that has already exited is the ordinary
15274/// case rather than an error (the kill lands on a reaped or exiting pid), so a
15275/// failure is logged at debug and the wait-then-kill below still decides the
15276/// outcome.
15277#[cfg(unix)]
15278fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
15279    if let Some(group) = &child.child.plain_group {
15280        if let Err(error) = group.signal(rustix::process::Signal::TERM) {
15281            debug!(module_id, %error, "group TERM was not delivered; the drain wait and kill still apply");
15282        }
15283        return;
15284    }
15285    let Some(pid) = child
15286        .id()
15287        .and_then(|pid| i32::try_from(pid).ok())
15288        .filter(|pid| *pid > 1)
15289        .and_then(rustix::process::Pid::from_raw)
15290    else {
15291        debug!(
15292            module_id,
15293            "no pid to signal for teardown; falling through to the drain wait"
15294        );
15295        return;
15296    };
15297    match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
15298        Ok(()) => debug!(
15299            module_id,
15300            "sent SIGTERM to a module nothing else asked to stop"
15301        ),
15302        Err(err) => debug!(
15303            module_id,
15304            error = %err,
15305            "SIGTERM to module failed; the drain wait and kill still apply"
15306        ),
15307    }
15308}
15309
15310/// Windows has no SIGTERM and no portable stand-in for one. The graceful stops
15311/// Windows does offer need cooperation this supervisor cannot assume: a console
15312/// control event requires sharing a console with the child, and `WM_CLOSE`
15313/// requires the child to pump a message loop. A supervised server process does
15314/// neither, so there is nothing to send and teardown is the wait followed by the
15315/// kill. Emulating a signal here would mean inventing a stop protocol, which is
15316/// the thing `protocol: "none"` exists to avoid.
15317#[cfg(not(unix))]
15318fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
15319    debug!(
15320        module_id,
15321        "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
15322    );
15323}
15324
15325fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
15326    match final_state {
15327        ModuleState::Stopped => TerminalDisposition::Stopped,
15328        ModuleState::Disabled => TerminalDisposition::Disabled,
15329        ModuleState::Restarting => TerminalDisposition::Restarting,
15330        ModuleState::Failed => TerminalDisposition::Failed,
15331        ModuleState::Starting
15332        | ModuleState::Running
15333        | ModuleState::Unresponsive
15334        | ModuleState::Draining => {
15335            unreachable!("terminal exits only finish in terminal or restarting states")
15336        }
15337    }
15338}
15339
15340/// Release a reaped child's registration before allowing another spawn.
15341///
15342/// EOF is not a process-lifetime signal: an inherited socket can stay open
15343/// indefinitely, and serial frame dispatch can be waiting on egress instead of
15344/// reading EOF. After the normal release grace, request connection close (which
15345/// cancels both reads and dispatch), then allow one more release grace for the
15346/// connection guard's forwarding cleanup. Never evict a different connection.
15347async fn release_dead_registration(
15348    registry: &Registry,
15349    forwarding: Option<&ForwardingTable>,
15350    snapshot: &SharedSnapshot,
15351    module_id: &str,
15352    failure: &FailureContext,
15353) -> Result<(), SuperviseError> {
15354    let result = async {
15355        let registration = registry
15356            .get_module(module_id)
15357            .map_err(SuperviseError::Registry)?;
15358        match wait_for_registration_release(registry, module_id, REGISTRY_RELEASE_TIMEOUT).await {
15359            Ok(()) => return Ok(()),
15360            Err(SuperviseError::RegistrationStillActive { .. }) => {}
15361            Err(err) => return Err(err),
15362        }
15363        let pid = lock_snapshot(snapshot)?.reaped_pid;
15364        if let (Some(registration), Some(forwarding), Some(pid)) = (registration, forwarding, pid) {
15365            warn!(
15366                module_id,
15367                pid,
15368                connection_id = registration.connection_id.get(),
15369                "reaped module registration outlived release grace; closing dead connection"
15370            );
15371            forwarding.request_connection_close(
15372                registration.connection_id,
15373                CloseReason::new(
15374                    "supervised_process_reaped",
15375                    format!("module '{module_id}' pid {pid} exited"),
15376                ),
15377            );
15378            wait_for_slot_registration_release(
15379                registry,
15380                crate::registry::RegistrationSlot::Connection(registration.connection_id),
15381                REGISTRY_RELEASE_TIMEOUT,
15382            )
15383            .await?;
15384        }
15385        wait_for_registration_release(registry, module_id, Duration::ZERO).await
15386    }
15387    .await;
15388    if let Err(err) = &result {
15389        fail_snapshot(snapshot, Some(module_id), None, failure);
15390        error!(module_id, error = %err, "registration release failed after child exit; module is failed and start can retry");
15391    }
15392    result
15393}
15394
15395/// Wait for the ACTIVE registration of `module_id` to go away, which is what a
15396/// plain stop or restart waits for before it spawns a replacement.
15397async fn wait_for_registration_release(
15398    registry: &Registry,
15399    module_id: &str,
15400    wait: Duration,
15401) -> Result<(), SuperviseError> {
15402    wait_for_slot_registration_release(
15403        registry,
15404        crate::registry::RegistrationSlot::Active(module_id),
15405        wait,
15406    )
15407    .await
15408}
15409
15410/// Wait for the registration in `slot` to go away.
15411///
15412/// Keyed on the slot rather than the bare module id because a successful swap
15413/// never empties the id's active slot (the promoted candidate is in it), so an
15414/// id-keyed wait for the incumbent's release would always time out. Draining a
15415/// swap's incumbent waits on `crate::registry::RegistrationSlot::Connection` with the
15416/// incumbent's connection instead.
15417async fn wait_for_slot_registration_release(
15418    registry: &Registry,
15419    slot: crate::registry::RegistrationSlot<'_>,
15420    wait: Duration,
15421) -> Result<(), SuperviseError> {
15422    let deadline = Instant::now() + wait;
15423    let mut release_events = registration_release_events().subscribe();
15424    let still_active = |registration: &crate::registry::ModuleRegistration| {
15425        SuperviseError::RegistrationStillActive {
15426            module_id: registration.manifest.module_id.clone(),
15427            waited: wait,
15428        }
15429    };
15430    loop {
15431        let _observed_generation = *release_events.borrow_and_update();
15432        let Some(registration) = registry
15433            .registration(slot)
15434            .map_err(SuperviseError::Registry)?
15435        else {
15436            return Ok(());
15437        };
15438
15439        let now = Instant::now();
15440        if now >= deadline {
15441            return Err(still_active(&registration));
15442        }
15443
15444        let remaining = deadline.saturating_duration_since(now);
15445        match timeout(remaining, release_events.changed()).await {
15446            Ok(Ok(())) | Ok(Err(_)) => {}
15447            Err(_) => return Err(still_active(&registration)),
15448        }
15449    }
15450}
15451
15452#[cfg(test)]
15453mod slot_registration_wait_tests {
15454    use super::*;
15455    use crate::registry::{ConnectionId, RegistrationSlot};
15456    use subc_protocol::manifest::ModuleManifest;
15457
15458    #[tokio::test]
15459    async fn enable_release_failure_is_failed_and_a_second_enable_retries() {
15460        let registry = Arc::new(Registry::default());
15461        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default());
15462        let runtime = supervisor.runtime_config();
15463        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::disabled()));
15464        let spec = ModuleSpec {
15465            script: None,
15466            module_id: "enable-stale-registration".to_string(),
15467            program: PathBuf::from("/missing/enable-retry-test"),
15468            args: Vec::new(),
15469            env: Vec::new(),
15470            reserved: false,
15471            reserved_prefixes: Vec::new(),
15472            protocol: ModuleProtocol::Subc,
15473            overlap: Default::default(),
15474            carry_containment: false,
15475        };
15476        let connection = ConnectionId::new(90);
15477        registry
15478            .register_with_control_ops(
15479                ModuleManifest::builder(&spec.module_id, "0.1.0").build(),
15480                1,
15481                connection,
15482                Vec::new(),
15483            )
15484            .unwrap();
15485        let mut child = None;
15486        let err = set_child_enabled(
15487            &spec,
15488            &runtime,
15489            &registry,
15490            &supervisor.process_liveness,
15491            &snapshot,
15492            &mut child,
15493            true,
15494            &runtime.failure_context(false),
15495        )
15496        .await
15497        .unwrap_err();
15498        assert!(matches!(
15499            err,
15500            SuperviseError::RegistrationStillActive { .. }
15501        ));
15502        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
15503        assert!(child.is_none());
15504        registry.deregister_connection(connection).unwrap();
15505        let err = set_child_enabled(
15506            &spec,
15507            &runtime,
15508            &registry,
15509            &supervisor.process_liveness,
15510            &snapshot,
15511            &mut child,
15512            true,
15513            &runtime.failure_context(false),
15514        )
15515        .await
15516        .unwrap_err();
15517        assert!(
15518            matches!(err, SuperviseError::Spawn { .. }),
15519            "second enable must attempt a spawn: {err}"
15520        );
15521        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
15522    }
15523
15524    const INCUMBENT: u64 = 1;
15525    const CANDIDATE: u64 = 2;
15526
15527    fn swapped_registry() -> Arc<Registry> {
15528        let registry = Arc::new(Registry::default());
15529        let manifest = ModuleManifest::builder("m", "0.1.0").build();
15530        registry
15531            .register_with_control_ops(
15532                manifest.clone(),
15533                1,
15534                ConnectionId::new(INCUMBENT),
15535                Vec::new(),
15536            )
15537            .unwrap();
15538        registry
15539            .register_candidate_with_control_ops(
15540                manifest,
15541                1,
15542                ConnectionId::new(CANDIDATE),
15543                Vec::new(),
15544            )
15545            .unwrap();
15546        registry
15547    }
15548
15549    /// After a promotion the id's active slot is held by the new process, so an
15550    /// id-keyed wait for the incumbent's release can never succeed; the
15551    /// connection-keyed wait completes as soon as the incumbent deregisters.
15552    #[tokio::test]
15553    async fn incumbent_release_is_awaited_by_connection_not_by_module_id() {
15554        let registry = swapped_registry();
15555        registry.promote_candidate("m").unwrap().unwrap();
15556
15557        assert!(matches!(
15558            wait_for_registration_release(&registry, "m", Duration::from_millis(50)).await,
15559            Err(SuperviseError::RegistrationStillActive { .. })
15560        ));
15561
15562        // Still held while the incumbent's connection has not deregistered.
15563        assert!(matches!(
15564            wait_for_slot_registration_release(
15565                &registry,
15566                RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
15567                Duration::from_millis(50),
15568            )
15569            .await,
15570            Err(SuperviseError::RegistrationStillActive { .. })
15571        ));
15572
15573        let releaser = Arc::clone(&registry);
15574        let release = tokio::spawn(async move {
15575            sleep(Duration::from_millis(20)).await;
15576            releaser
15577                .deregister_connection(ConnectionId::new(INCUMBENT))
15578                .unwrap();
15579            notify_registration_release();
15580        });
15581        wait_for_slot_registration_release(
15582            &registry,
15583            RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
15584            Duration::from_secs(5),
15585        )
15586        .await
15587        .expect("the incumbent's own registration is released");
15588        release.await.unwrap();
15589        assert!(registry.get_module("m").unwrap().is_some());
15590    }
15591
15592    /// The candidate slot is waited on separately from the active slot: the
15593    /// incumbent's registration neither holds up nor stands in for it.
15594    #[tokio::test]
15595    async fn candidate_slot_wait_ignores_the_incumbents_registration() {
15596        let registry = swapped_registry();
15597        assert!(matches!(
15598            wait_for_slot_registration_release(
15599                &registry,
15600                RegistrationSlot::Candidate("m"),
15601                Duration::from_millis(50),
15602            )
15603            .await,
15604            Err(SuperviseError::RegistrationStillActive { .. })
15605        ));
15606        registry
15607            .deregister_connection(ConnectionId::new(CANDIDATE))
15608            .unwrap();
15609        wait_for_slot_registration_release(
15610            &registry,
15611            RegistrationSlot::Candidate("m"),
15612            Duration::from_millis(50),
15613        )
15614        .await
15615        .expect("a candidate slot with no candidate is released");
15616        assert!(registry
15617            .registration(RegistrationSlot::Active("m"))
15618            .unwrap()
15619            .is_some());
15620    }
15621}
15622
15623fn classify_exit(status: &ExitStatus) -> ExitReport {
15624    ExitReport {
15625        kind: if status.success() {
15626            ExitKind::Clean
15627        } else {
15628            ExitKind::Crash
15629        },
15630        code: status.code(),
15631        signal: exit_signal(status),
15632        at_ms: unix_ms_now(),
15633    }
15634}
15635
15636/// The terminal record for a module whose `wait()` call itself errored (e.g. the
15637/// child was already reaped out-of-band). There is no `ExitStatus` to read a code
15638/// or signal from -- `None`/`None` is the honest shape, not a guess -- but the
15639/// disposition still must be `Failed` so the terminal ring is not silently missing
15640/// an entry, matching what `fail_snapshot` records for this same arm.
15641fn wait_error_exit_report() -> ExitReport {
15642    ExitReport {
15643        kind: ExitKind::Crash,
15644        code: None,
15645        signal: None,
15646        at_ms: unix_ms_now(),
15647    }
15648}
15649
15650#[cfg(unix)]
15651fn exit_signal(status: &ExitStatus) -> Option<i32> {
15652    use std::os::unix::process::ExitStatusExt;
15653
15654    status.signal()
15655}
15656
15657#[cfg(not(unix))]
15658fn exit_signal(_status: &ExitStatus) -> Option<i32> {
15659    None
15660}
15661
15662/// Give an operator-touched module its full crash budget back.
15663///
15664/// Named for the counter it used to zero; it now empties the in-window ring,
15665/// which is the same act. `lifetime_restarts` is untouched on purpose -- the
15666/// ledger of what happened survives every operator action.
15667fn reset_restart_count(snapshot: &SharedSnapshot, module_id: &str) -> Result<(), SuperviseError> {
15668    update_snapshot(snapshot, Some(module_id), |state| {
15669        state.clear_crash_restarts();
15670    })
15671}
15672
15673fn set_running(
15674    snapshot: &SharedSnapshot,
15675    child: &SupervisedChild,
15676    module_id: &str,
15677    spawn_events: &SpawnEventFeed,
15678) -> Result<(), SuperviseError> {
15679    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
15680        module_id: Some(module_id.to_string()),
15681    })?;
15682    state.spawn_generation = spawn_events.emit_spawned(
15683        module_id,
15684        child
15685            .registration_spawn
15686            .as_ref()
15687            .map(|spawn| spawn.authority.spawn_number()),
15688        child.pid,
15689        child.spawned_at_ms,
15690    );
15691    if std::mem::take(&mut state.coalesced_restart_pending) {
15692        let generation = state.spawn_generation;
15693        info!(module_id, "restart already satisfied by generation {generation}; coalesced pending request completed");
15694    }
15695    state.drain_disposition_detail = None;
15696    state.spawn_failure = None;
15697    state.admission_refused = None;
15698    state.config_hold_parked = false;
15699    state.config_hold_daemon_initiated = false;
15700    state.config_hold_approval = None;
15701    state.legacy_registration_spawn =
15702        child.registration_spawn.is_some() && child.admission_base.is_none();
15703    state.registration_declaration = child.registration_declaration.clone();
15704    state.stop_reason = None;
15705    state.config_exit_failed_approval = None;
15706    state.waiting_for_previous_pid = None;
15707    state.waiting_for_previous_detail = None;
15708    // Every caller of this is a plain spawn, which always uses the primary key;
15709    // a promoted swap candidate sets the flag itself after this returns.
15710    state.in_alternate_slot = false;
15711    state.configuration_updated_since_spawn = false;
15712    state.spawned_protocol = Some(child.protocol);
15713    state.state = ModuleState::Running;
15714    state.approved_start_failure = None;
15715    state.enabled = true;
15716    state.process_alive = true;
15717    state.pid = child.id();
15718    state.subtree_target = child.subtree_target.clone();
15719    // Probe samples belong to one process. Keep module-level escalation and
15720    // late-answer history, but never charge a new child for its predecessor's misses.
15721    state.health.status = SupervisorHealthStatus::Unknown;
15722    state.last_probe_evidence = None;
15723    state.health.consecutive_failures = 0;
15724    state.health.detail = None;
15725    state.health.metrics = None;
15726    state.health.last_probe_ms = None;
15727    state.failed_retry.healthy_since = None;
15728    state.failed_retry.failed_at = None;
15729    state.failed_retry.running_since = Some(child.spawned_at);
15730    #[cfg(windows)]
15731    {
15732        state.pipe_consumed = child
15733            .nonce_delivery
15734            .as_ref()
15735            .map(|delivery| delivery.consumed());
15736    }
15737    #[cfg(target_os = "macos")]
15738    {
15739        state.report_ready = Some(Arc::clone(&child.report_ready));
15740    }
15741    state.spawned_at_ms = Some(child.spawned_at_ms);
15742    state.exec_outcome = Some(Arc::clone(&child.exec.0));
15743    state.spawned_from = Some(child.spawned_from.clone());
15744    state.launch_spec_digest = Some(child.launch_spec_digest.clone());
15745    state.spawned_file_identity = child.spawned_file_identity.clone();
15746    state.process_start_time = child.process_start_time;
15747    Ok(())
15748}
15749
15750fn clear_current_process_facts(state: &mut SupervisorSnapshot) {
15751    state.legacy_registration_spawn = false;
15752    state.registration_declaration = None;
15753    state.subtree_target = crate::subtree_resources::Target::Unavailable("not_running");
15754    state.failed_retry.healthy_since = None;
15755    state.failed_retry.running_since = None;
15756    state.waiting_for_previous_pid = None;
15757    state.waiting_for_previous_detail = None;
15758    state.process_alive = false;
15759    state.spawned_protocol = None;
15760    state.pid = None;
15761    #[cfg(windows)]
15762    {
15763        state.pipe_consumed = None;
15764    }
15765    #[cfg(target_os = "macos")]
15766    {
15767        state.report_ready = None;
15768    }
15769    state.spawned_at_ms = None;
15770    state.exec_outcome = None;
15771    state.spawned_from = None;
15772    state.launch_spec_digest = None;
15773    state.spawned_file_identity = None;
15774    state.process_start_time = None;
15775    state.deliberate_severance = None;
15776}
15777
15778#[cfg(test)]
15779fn record_deliberate_severance(
15780    snapshot: &SharedSnapshot,
15781    identity: ProcessIdentity,
15782) -> Result<(), SuperviseError> {
15783    update_snapshot(snapshot, None, |state| {
15784        state.deliberate_severance = Some(identity);
15785    })
15786}
15787
15788fn apply_deliberate_severance_marker(
15789    snapshot: &SharedSnapshot,
15790    exited_identity: Option<ProcessIdentity>,
15791    mut exit_report: ExitReport,
15792) -> ExitReport {
15793    let marker = lock_snapshot(snapshot)
15794        .ok()
15795        .and_then(|mut state| state.deliberate_severance.take());
15796    if marker.is_some() && marker == exited_identity {
15797        exit_report.kind = ExitKind::DeliberateSeverance;
15798    }
15799    exit_report
15800}
15801
15802fn classify_reaped_child_exit(
15803    snapshot: &SharedSnapshot,
15804    child: &SupervisedChild,
15805    status: &ExitStatus,
15806) -> ExitReport {
15807    let _ = update_snapshot(snapshot, None, |state| {
15808        state.reaped_pid = Some(child.pid);
15809        state.spawn_failure = child.spawn_failure.clone();
15810    });
15811    if matches!(
15812        child.spawn_failure.as_deref(),
15813        Some("registration_timeout" | "registration_channel_closed")
15814    ) {
15815        registration_failure_exit_report(classify_exit(status))
15816    } else {
15817        apply_deliberate_severance_marker(snapshot, child.process_identity(), classify_exit(status))
15818    }
15819}
15820
15821fn fail_snapshot(
15822    snapshot: &SharedSnapshot,
15823    module_id: Option<&str>,
15824    last_exit: Option<ExitReport>,
15825    failure: &FailureContext,
15826) {
15827    if let Err(err) = update_snapshot(snapshot, module_id, |state| {
15828        state.state = ModuleState::Failed;
15829        state.config_hold_parked = false;
15830        state.config_hold_daemon_initiated = false;
15831        state.config_hold_approval = None;
15832        clear_current_process_facts(state);
15833        if failure.may_retry() && state.enabled {
15834            state.failed_retry.schedule(module_id.unwrap_or("unknown"));
15835        } else if failure.shutdown.is_set() {
15836            state.failed_retry.cancel();
15837        }
15838        if let Some(last_exit) = last_exit {
15839            state.last_exit = Some(last_exit);
15840        }
15841    }) {
15842        error!(error = %err, "failed to mark supervisor state failed");
15843    }
15844}
15845
15846fn update_snapshot(
15847    snapshot: &SharedSnapshot,
15848    module_id: Option<&str>,
15849    update: impl FnOnce(&mut SupervisorSnapshot),
15850) -> Result<(), SuperviseError> {
15851    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
15852        module_id: module_id.map(ToOwned::to_owned),
15853    })?;
15854    update(&mut state);
15855    Ok(())
15856}
15857
15858const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
15859
15860fn lock_snapshot_for_control<'a>(
15861    snapshot: &'a SharedSnapshot,
15862    module_id: &str,
15863    caller: &'static str,
15864) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
15865    let started_at = Instant::now();
15866    let guard = lock_snapshot(snapshot)?;
15867    let waited = started_at.elapsed();
15868    if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
15869        warn!(
15870            module_id = %module_id,
15871            waited_ms = waited.as_millis() as u64,
15872            caller = %caller,
15873            "slow snapshot lock"
15874        );
15875    }
15876    Ok(guard)
15877}
15878
15879fn lock_snapshot(
15880    snapshot: &SharedSnapshot,
15881) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
15882    snapshot
15883        .lock()
15884        .map_err(|_| SuperviseError::StatePoisoned { module_id: None })
15885}
15886
15887#[cfg(test)]
15888mod terminal_history_tests {
15889    include!("supervise_route_open_recovery_tests.rs");
15890    use std::{
15891        path::PathBuf,
15892        sync::Arc,
15893        time::{Duration, Instant},
15894    };
15895
15896    use tokio::{sync::mpsc, time::sleep};
15897
15898    use super::{
15899        apply_deliberate_severance_marker, daemon_will_restart, drain_child_to_state,
15900        drained_after_quiescence_wait, handle_reload_spawn_failure, health_restart_child,
15901        lock_snapshot, on_child_exit, record_deliberate_severance, record_wait_error_terminal,
15902        reset_restart_count, spawn_and_mark_running, update_snapshot, wait_error_exit_report,
15903        ExitKind, ExitReport, ModuleProtocol, ModuleSpec, ModuleState, NextAction, ProcessIdentity,
15904        RestartPolicy, SpawnEventKind, StopNotice, SuperviseError, SupervisedConfiguration,
15905        SupervisedModule, SupervisedModuleInner, Supervisor, SupervisorHandle,
15906        SupervisorHealthStatus, SupervisorSnapshot,
15907    };
15908    // The supervisor's clock, distinct from the `std::time::Instant` these tests
15909    // use for their own wall-clock deadlines: crash-restart instants must be on
15910    // the same clock the production code stamps them with, which is tokio's (and
15911    // is what `start_paused` tests can move).
15912    use super::Instant as ClockInstant;
15913    use crate::{
15914        registry::Registry,
15915        terminal_ring::{TerminalRing, TerminalRingConfig},
15916    };
15917    use std::sync::Mutex;
15918    use subc_control::TerminalDisposition;
15919
15920    /// See the twin in `control.rs` for why this derives the path from
15921    /// `current_exe()` and why the existence check is here: `--lib` alone does
15922    /// not build `[[bin]]` targets, and a bare spawn then fails with a raw
15923    /// `NotFound` that reads as a broken test rather than an unbuilt dependency.
15924    pub(super) fn fake_aft_stub_path() -> PathBuf {
15925        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
15926        assert!(
15927            path.exists(),
15928            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
15929             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
15930            path.display()
15931        );
15932        path
15933    }
15934
15935    #[test]
15936    fn reserved_never_spawned_refuses_every_hello() {
15937        // The canary hole: a reserved id whose module has never spawned had NO
15938        // gate entry and admitted anyone -- the reservation protected the nonce
15939        // holder, not the NAME. Now the entry is present with no legitimate
15940        // holder and refuses all comers.
15941        let supervisor = SupervisorHandle::default();
15942        supervisor.apply_identity_configuration(&ModuleSpec {
15943            script: None,
15944            module_id: "never-spawned".to_string(),
15945            program: PathBuf::from("/usr/bin/false"),
15946            args: Vec::new(),
15947            env: Vec::new(),
15948            reserved: true,
15949            reserved_prefixes: Vec::new(),
15950            protocol: ModuleProtocol::Subc,
15951            overlap: Default::default(),
15952            carry_containment: false,
15953        });
15954        assert!(
15955            supervisor
15956                .reserved_hello_verification("never-spawned", Some("any-forged-nonce"))
15957                .is_err(),
15958            "forged nonce must refuse on a reserved never-spawned id"
15959        );
15960        assert!(
15961            supervisor
15962                .reserved_hello_verification("never-spawned", None)
15963                .is_err(),
15964            "absent nonce must refuse on a reserved never-spawned id"
15965        );
15966        // And a real spawn nonce minted later admits exactly that nonce.
15967        supervisor.set_spawn_nonce("never-spawned", "minted".to_string());
15968        supervisor.apply_identity_configuration(&ModuleSpec {
15969            script: None,
15970            module_id: "never-spawned".to_string(),
15971            program: PathBuf::from("/usr/bin/false"),
15972            args: Vec::new(),
15973            env: Vec::new(),
15974            reserved: true,
15975            reserved_prefixes: Vec::new(),
15976            protocol: ModuleProtocol::Subc,
15977            overlap: Default::default(),
15978            carry_containment: false,
15979        });
15980        assert!(supervisor
15981            .reserved_hello_verification("never-spawned", Some("minted"))
15982            .is_ok());
15983        assert!(supervisor
15984            .reserved_hello_verification("never-spawned", Some("forged"))
15985            .is_err());
15986    }
15987
15988    /// Put `count` crash restarts on a snapshot's ring as if they had all just
15989    /// happened, which is what "spent budget" looks like to every reader.
15990    fn seed_crash_restarts(state: &mut SupervisorSnapshot, count: u32) {
15991        let now = ClockInstant::now();
15992        for _ in 0..count {
15993            state.crash_restarts.push_back(now);
15994        }
15995    }
15996
15997    /// Age the oldest recorded restart out of `window`, standing in for the hours
15998    /// that would otherwise have to pass. Injecting the instant is the point: a
15999    /// test that slept a real window would take ten minutes and still prove less.
16000    fn age_oldest_crash_restart_out_of_window(state: &mut SupervisorSnapshot, window: Duration) {
16001        let aged = state
16002            .crash_restarts
16003            .front()
16004            .expect("a crash restart must be recorded before it can be aged")
16005            .checked_sub(window + Duration::from_secs(1))
16006            .expect("the test clock is far enough from its origin to age an instant");
16007        state.crash_restarts[0] = aged;
16008    }
16009
16010    fn snapshot_with_restarts(enabled: bool, count: u32) -> SupervisorSnapshot {
16011        let mut state = SupervisorSnapshot::new(ModuleState::Running, enabled);
16012        seed_crash_restarts(&mut state, count);
16013        state
16014    }
16015
16016    #[test]
16017    fn daemon_owned_recovery_predicate_uses_the_pre_increment_budget() {
16018        let policy = RestartPolicy::new(3, Duration::ZERO);
16019        let now = ClockInstant::now();
16020        assert!(daemon_will_restart(
16021            &mut snapshot_with_restarts(true, 2),
16022            &policy,
16023            now
16024        ));
16025        assert!(!daemon_will_restart(
16026            &mut snapshot_with_restarts(true, 3),
16027            &policy,
16028            now
16029        ));
16030        assert!(!daemon_will_restart(
16031            &mut snapshot_with_restarts(false, 0),
16032            &policy,
16033            now
16034        ));
16035    }
16036
16037    #[test]
16038    fn crash_restart_backoff_escalates_with_in_window_count() {
16039        let policy = RestartPolicy::new(4, Duration::from_millis(100))
16040            .with_max_backoff(Duration::from_secs(30));
16041        let now = ClockInstant::now();
16042        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16043        let schedules = (0..4)
16044            .map(|_| {
16045                let schedule = state
16046                    .next_crash_restart(&policy, now)
16047                    .expect("the test policy allows four crash restarts");
16048                state.record_crash_restart(&policy, now);
16049                schedule
16050            })
16051            .collect::<Vec<_>>();
16052
16053        assert_eq!(
16054            schedules
16055                .iter()
16056                .map(|schedule| schedule.restart_in_window)
16057                .collect::<Vec<_>>(),
16058            vec![0, 1, 2, 3]
16059        );
16060        assert_eq!(
16061            schedules
16062                .iter()
16063                .map(|schedule| schedule.delay)
16064                .collect::<Vec<_>>(),
16065            vec![
16066                Duration::from_millis(100),
16067                Duration::from_secs(1),
16068                Duration::from_secs(10),
16069                Duration::from_secs(30),
16070            ]
16071        );
16072    }
16073
16074    #[test]
16075    fn crash_restart_backoff_resets_after_ring_clear() {
16076        let policy = RestartPolicy::new(3, Duration::from_millis(100));
16077        let now = ClockInstant::now();
16078        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16079        assert_eq!(
16080            state.next_crash_restart(&policy, now).unwrap().delay,
16081            Duration::from_millis(100)
16082        );
16083        state.record_crash_restart(&policy, now);
16084        assert_eq!(
16085            state.next_crash_restart(&policy, now).unwrap().delay,
16086            Duration::from_secs(1)
16087        );
16088
16089        state.clear_crash_restarts();
16090        let schedule = state
16091            .next_crash_restart(&policy, now)
16092            .expect("a cleared ring must allow another restart");
16093        assert_eq!(schedule.restart_in_window, 0);
16094        assert_eq!(schedule.delay, Duration::from_millis(100));
16095    }
16096
16097    #[test]
16098    fn crash_restart_backoff_ignores_aged_restarts() {
16099        let policy = RestartPolicy::new(3, Duration::from_millis(100));
16100        let now = ClockInstant::now();
16101        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16102        state
16103            .next_crash_restart(&policy, now)
16104            .expect("the first restart is allowed");
16105        state.record_crash_restart(&policy, now);
16106        state
16107            .next_crash_restart(&policy, now)
16108            .expect("the second restart is allowed");
16109        state.record_crash_restart(&policy, now);
16110        state.crash_restarts[0] = now
16111            .checked_sub(policy.window + Duration::from_secs(1))
16112            .expect("the fake clock can age a restart past the window");
16113
16114        let schedule = state
16115            .next_crash_restart(&policy, now)
16116            .expect("an aged restart must release its slot");
16117        assert_eq!(schedule.restart_in_window, 1);
16118        assert_eq!(schedule.delay, Duration::from_secs(1));
16119        state.record_crash_restart(&policy, now);
16120        assert_eq!(state.crash_restarts.len(), 2);
16121    }
16122
16123    /// The budget is a rate: the same three spent restarts refuse a respawn
16124    /// while they are recent and allow one once they have aged past the window.
16125    /// Nothing about the module changed in between, which is the whole point.
16126    #[test]
16127    fn a_budget_spent_before_the_window_no_longer_refuses() {
16128        let policy = RestartPolicy::new(3, Duration::ZERO);
16129        let mut state = snapshot_with_restarts(true, 3);
16130        let now = ClockInstant::now();
16131        assert!(!daemon_will_restart(&mut state, &policy, now));
16132
16133        assert!(daemon_will_restart(
16134            &mut state,
16135            &policy,
16136            now + policy.window + Duration::from_secs(1)
16137        ));
16138        assert!(
16139            state.crash_restarts.is_empty(),
16140            "reading the budget must drop the instants that left the window"
16141        );
16142    }
16143
16144    fn module_with_recovery_snapshot(
16145        state: ModuleState,
16146        enabled: bool,
16147        restart_count: u32,
16148    ) -> SupervisedModule {
16149        let registry = Arc::new(Registry::default());
16150        let supervisor =
16151            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(3, Duration::ZERO));
16152        let runtime = supervisor.runtime_config();
16153        let spec = ModuleSpec {
16154            script: None,
16155            module_id: "recovery-snapshot".to_string(),
16156            program: fake_aft_stub_path(),
16157            args: Vec::new(),
16158            env: Vec::new(),
16159            reserved: false,
16160            reserved_prefixes: Vec::new(),
16161            protocol: ModuleProtocol::Subc,
16162            overlap: Default::default(),
16163            carry_containment: false,
16164        };
16165        let mut snapshot = SupervisorSnapshot::new(state, enabled);
16166        seed_crash_restarts(&mut snapshot, restart_count);
16167        // These tests read synthetic snapshots. A real child and monitor would
16168        // race those reads by replacing the requested state during startup.
16169        let (commands, _rx) = mpsc::channel(4);
16170        let configured_enabled = snapshot.enabled;
16171        SupervisedModule {
16172            inner: Arc::new(SupervisedModuleInner {
16173                module_id: spec.module_id.clone(),
16174                registry,
16175                snapshot: Arc::new(Mutex::new(snapshot)),
16176                configuration: Arc::new(Mutex::new(SupervisedConfiguration {
16177                    spec,
16178                    enabled: configured_enabled,
16179                    health: runtime.health,
16180                    register_timeout: runtime.register_timeout,
16181                    restart_policy: runtime.restart_policy,
16182                })),
16183                stderr_ring: runtime.stderr_ring,
16184                terminal_ring: runtime.terminal_ring,
16185                commands,
16186                monitor: Mutex::new(None),
16187                effective_drain_timeout: runtime.effective_drain_timeout,
16188                provenance_probe: supervisor.provenance_probe.clone(),
16189                retained: runtime.child_roster.retained_view(),
16190            }),
16191        }
16192    }
16193
16194    #[cfg(target_os = "linux")]
16195    #[tokio::test]
16196    async fn no_cgroup_placement_does_not_block_fake_aft_stub_spawn() {
16197        let supervisor =
16198            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
16199                .with_cgroup_placement(None);
16200        let result = supervisor.spawn(ModuleSpec {
16201            script: None,
16202            module_id: "no-cgroup-placement".to_string(),
16203            program: fake_aft_stub_path(),
16204            args: Vec::new(),
16205            env: Vec::new(),
16206            reserved: false,
16207            reserved_prefixes: Vec::new(),
16208            protocol: ModuleProtocol::Subc,
16209            overlap: Default::default(),
16210            carry_containment: false,
16211        });
16212
16213        assert!(
16214            result.is_ok(),
16215            "no delegation must not turn an otherwise valid spawn into a failure: {result:?}"
16216        );
16217    }
16218
16219    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16220    async fn undecided_snapshot_uses_shared_restart_predicate() {
16221        assert!(module_with_recovery_snapshot(ModuleState::Running, true, 2)
16222            .will_recover_after_connection_loss()
16223            .unwrap());
16224        assert!(
16225            !module_with_recovery_snapshot(ModuleState::Running, true, 3)
16226                .will_recover_after_connection_loss()
16227                .unwrap()
16228        );
16229    }
16230
16231    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16232    async fn restarting_snapshot_at_exhausted_budget_is_non_terminal() {
16233        assert!(
16234            module_with_recovery_snapshot(ModuleState::Restarting, true, 3)
16235                .will_recover_after_connection_loss()
16236                .unwrap()
16237        );
16238    }
16239
16240    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16241    async fn terminal_phase_snapshots_are_terminal_before_budget_exhaustion() {
16242        assert!(!module_with_recovery_snapshot(ModuleState::Failed, true, 0)
16243            .will_recover_after_connection_loss()
16244            .unwrap());
16245        assert!(
16246            !module_with_recovery_snapshot(ModuleState::Disabled, true, 0)
16247                .will_recover_after_connection_loss()
16248                .unwrap()
16249        );
16250    }
16251
16252    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16253    async fn warming_snapshot_is_limited_to_startup_phases() {
16254        for state in [
16255            ModuleState::Starting,
16256            ModuleState::Running,
16257            ModuleState::Restarting,
16258        ] {
16259            assert!(
16260                module_with_recovery_snapshot(state, true, 0)
16261                    .is_warming()
16262                    .unwrap(),
16263                "{state:?} should be warming"
16264            );
16265        }
16266        for state in [
16267            ModuleState::Unresponsive,
16268            ModuleState::Draining,
16269            ModuleState::Stopped,
16270            ModuleState::Failed,
16271            ModuleState::Disabled,
16272        ] {
16273            assert!(
16274                !module_with_recovery_snapshot(state, true, 0)
16275                    .is_warming()
16276                    .unwrap(),
16277                "{state:?} should not be warming"
16278            );
16279        }
16280    }
16281
16282    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16283    async fn terminal_history_survives_respawn_and_keeps_both_crashes_in_order() {
16284        let registry = Arc::new(Registry::default());
16285        let supervisor =
16286            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO));
16287        let module = supervisor
16288            .spawn(ModuleSpec {
16289                script: None,
16290                module_id: "terminal-history".to_string(),
16291                program: fake_aft_stub_path(),
16292                args: Vec::new(),
16293                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
16294                reserved: false,
16295                reserved_prefixes: Vec::new(),
16296                protocol: ModuleProtocol::Subc,
16297                overlap: Default::default(),
16298                carry_containment: false,
16299            })
16300            .unwrap();
16301
16302        let deadline = Instant::now() + Duration::from_secs(5);
16303        loop {
16304            let history = module.terminal_history();
16305            if history.entries.len() == 2 {
16306                assert_eq!(module.status().unwrap().state, ModuleState::Failed);
16307                assert_eq!(history.dropped, 0);
16308                assert_eq!(
16309                    history
16310                        .entries
16311                        .iter()
16312                        .map(|entry| entry.exit_code)
16313                        .collect::<Vec<_>>(),
16314                    vec![Some(23), Some(23)]
16315                );
16316                assert!(history.entries[0].at_ms <= history.entries[1].at_ms);
16317                return;
16318            }
16319            assert!(
16320                Instant::now() < deadline,
16321                "module did not retain two terminal exits: {history:?}"
16322            );
16323            sleep(Duration::from_millis(10)).await;
16324        }
16325    }
16326
16327    /// A disable issued while a crash respawn is still backing off must preempt
16328    /// that respawn: the operator's stop wins, the disable must not queue behind
16329    /// the backoff, and the module must never come back up afterwards.
16330    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16331    async fn disable_during_crash_backoff_cancels_pending_respawn() {
16332        let backoff = Duration::from_secs(2);
16333        let supervisor = Supervisor::new_for_test(
16334            Arc::new(Registry::default()),
16335            RestartPolicy::new(10, backoff),
16336        );
16337        let module = supervisor
16338            .spawn(ModuleSpec {
16339                script: None,
16340                module_id: "disable-during-backoff".to_string(),
16341                program: fake_aft_stub_path(),
16342                args: Vec::new(),
16343                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
16344                reserved: false,
16345                reserved_prefixes: Vec::new(),
16346                protocol: ModuleProtocol::Subc,
16347                overlap: Default::default(),
16348                carry_containment: false,
16349            })
16350            .unwrap();
16351
16352        // Wait for the first crash to put the module into its backoff window.
16353        let deadline = Instant::now() + Duration::from_secs(5);
16354        loop {
16355            if module.status().unwrap().state == ModuleState::Restarting {
16356                break;
16357            }
16358            assert!(
16359                Instant::now() < deadline,
16360                "module never entered the crash backoff"
16361            );
16362            sleep(Duration::from_millis(10)).await;
16363        }
16364
16365        let started = Instant::now();
16366        module.set_enabled(false).await.unwrap();
16367        let waited = started.elapsed();
16368
16369        assert!(
16370            waited < backoff / 2,
16371            "disable waited {waited:?} behind the {backoff:?} crash backoff; the operator command must preempt the pending respawn"
16372        );
16373        assert_eq!(module.status().unwrap().state, ModuleState::Disabled);
16374
16375        // Outlast the backoff: the respawn it was counting down to must never run.
16376        sleep(backoff + Duration::from_millis(500)).await;
16377        let status = module.status().unwrap();
16378        assert_eq!(status.state, ModuleState::Disabled);
16379        assert_eq!(
16380            status.spawn_generation, 1,
16381            "module respawned after the operator disabled it"
16382        );
16383        assert_eq!((status.restart_count, status.lifetime_restarts), (0, 0));
16384    }
16385
16386    /// A `protocol: "none"` child that stays parked and exits 0 on SIGTERM:
16387    /// the shape of nats-server, the program this rule exists for.
16388    #[cfg(unix)]
16389    fn protocol_none_sigterm_exits_clean_spec(
16390        module_id: &str,
16391        dir: &std::path::Path,
16392    ) -> (ModuleSpec, PathBuf, PathBuf) {
16393        let ready = dir.join("ready");
16394        let marker = dir.join("sigterm");
16395        let spec = ModuleSpec {
16396            script: None,
16397            module_id: module_id.to_string(),
16398            program: fake_aft_stub_path(),
16399            args: Vec::new(),
16400            env: vec![
16401                ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
16402                (
16403                    "FAKE_AFT_SIGTERM_MARKER_PATH".to_string(),
16404                    marker.display().to_string(),
16405                ),
16406                (
16407                    "FAKE_AFT_NEVER_CONNECT_READY_PATH".to_string(),
16408                    ready.display().to_string(),
16409                ),
16410            ],
16411            reserved: false,
16412            reserved_prefixes: Vec::new(),
16413            protocol: ModuleProtocol::None,
16414            overlap: Default::default(),
16415            carry_containment: false,
16416        };
16417        (spec, ready, marker)
16418    }
16419
16420    /// Wait for a file the child writes, so a signal is never sent before the
16421    /// child's SIGTERM handler is installed (the default disposition would
16422    /// kill it by signal and the exit would not be clean).
16423    #[cfg(unix)]
16424    async fn wait_for_file(path: &std::path::Path) {
16425        let deadline = Instant::now() + Duration::from_secs(10);
16426        while !path.exists() {
16427            assert!(
16428                Instant::now() < deadline,
16429                "{} never appeared",
16430                path.display()
16431            );
16432            sleep(Duration::from_millis(10)).await;
16433        }
16434    }
16435
16436    /// A protocol-none module that exits 0 because something OUTSIDE the
16437    /// supervisor sent it SIGTERM is respawned, and the terminal record carries
16438    /// the crash-path disposition rather than `stopped`.
16439    #[cfg(unix)]
16440    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16441    async fn protocol_none_unrequested_clean_exit_restarts_as_a_crash() {
16442        let dir = cortexkit_test_support::ScratchDir::new("none-unrequested-clean-exit");
16443        let (spec, ready, marker) =
16444            protocol_none_sigterm_exits_clean_spec("none-unrequested-clean-exit", dir.path());
16445        let supervisor = Supervisor::new_for_test(
16446            Arc::new(Registry::default()),
16447            RestartPolicy::new(3, Duration::ZERO),
16448        );
16449        let module = supervisor.spawn(spec).unwrap();
16450        wait_for_file(&ready).await;
16451        // The ready file proves the child installed its SIGTERM handler, not
16452        // that the supervisor has processed the privacy trampoline's exec
16453        // acknowledgement. On macOS status withholds the pid until then.
16454        let deadline = Instant::now() + Duration::from_secs(10);
16455        let first_pid = loop {
16456            let status = module.status().unwrap();
16457            if status.state == ModuleState::Running {
16458                if let Some(pid) = status.pid {
16459                    break pid;
16460                }
16461            }
16462            assert!(
16463                Instant::now() < deadline,
16464                "a running module must report its pid after exec confirmation: {status:?}"
16465            );
16466            sleep(Duration::from_millis(10)).await;
16467        };
16468
16469        rustix::process::kill_process(
16470            rustix::process::Pid::from_raw(i32::try_from(first_pid).unwrap()).unwrap(),
16471            rustix::process::Signal::TERM,
16472        )
16473        .unwrap();
16474
16475        let deadline = Instant::now() + Duration::from_secs(10);
16476        let respawned = loop {
16477            let status = module.status().unwrap();
16478            if status.state == ModuleState::Running
16479                && status.pid.is_some_and(|pid| pid != first_pid)
16480            {
16481                break status;
16482            }
16483            assert!(
16484                Instant::now() < deadline,
16485                "protocol-none module was not respawned after an unrequested clean exit: {status:?}"
16486            );
16487            sleep(Duration::from_millis(10)).await;
16488        };
16489        assert_eq!(respawned.spawn_generation, 2);
16490        assert!(
16491            marker.exists(),
16492            "the child must have exited through its SIGTERM handler (exit 0), or this proves nothing about clean exits"
16493        );
16494
16495        let history = module.terminal_history();
16496        assert_eq!(history.entries.len(), 1, "{history:?}");
16497        let entry = &history.entries[0];
16498        assert_eq!(entry.exit_code, Some(0));
16499        assert_eq!(entry.exit_kind, subc_control::TerminalExitKind::Clean);
16500        assert_eq!(entry.disposition, TerminalDisposition::Restarting);
16501
16502        module.stop().await.unwrap();
16503    }
16504
16505    /// Repeated unrequested clean exits of a protocol-none module spend the
16506    /// restart budget exactly as crashes do, and the module ends `failed` with
16507    /// the budget named.
16508    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16509    async fn protocol_none_repeated_clean_exits_exhaust_the_restart_budget() {
16510        let supervisor = Supervisor::new_for_test(
16511            Arc::new(Registry::default()),
16512            RestartPolicy::new(1, Duration::ZERO),
16513        );
16514        let module = supervisor
16515            .spawn(ModuleSpec {
16516                script: None,
16517                module_id: "none-clean-exit-budget".to_string(),
16518                program: fake_aft_stub_path(),
16519                args: Vec::new(),
16520                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "0".to_string())],
16521                reserved: false,
16522                reserved_prefixes: Vec::new(),
16523                protocol: ModuleProtocol::None,
16524                overlap: Default::default(),
16525                carry_containment: false,
16526            })
16527            .unwrap();
16528
16529        // Failed follows the terminal write; this deadline only bounds a hang,
16530        // not an assumed duration for the two launches or their exit recording.
16531        let deadline = Instant::now() + Duration::from_secs(10);
16532        loop {
16533            let status = module.status().unwrap();
16534            if status.state == ModuleState::Failed {
16535                break;
16536            }
16537            assert!(
16538                Instant::now() < deadline,
16539                "module never exhausted its budget: {status:?} {:?}",
16540                module.terminal_history()
16541            );
16542            sleep(Duration::from_millis(10)).await;
16543        }
16544        let history = module.terminal_history();
16545        assert_eq!(
16546            history
16547                .entries
16548                .iter()
16549                .map(|entry| (entry.exit_code, entry.disposition.clone()))
16550                .collect::<Vec<_>>(),
16551            vec![
16552                (Some(0), TerminalDisposition::Restarting),
16553                (Some(0), TerminalDisposition::Failed),
16554            ]
16555        );
16556        let detail = history.entries[1]
16557            .disposition_detail
16558            .as_deref()
16559            .expect("a budget failure names the budget");
16560        assert!(detail.contains("max_restarts=1"), "{detail}");
16561        assert_eq!(module.status().unwrap().spawn_generation, 2);
16562    }
16563
16564    #[test]
16565    fn restart_budget_failure_is_published_after_its_terminal_record() {
16566        use std::io::{Read, Write};
16567        let supervisor = Supervisor::new_for_test(
16568            Arc::new(Registry::default()),
16569            RestartPolicy::new(0, Duration::ZERO),
16570        );
16571        let runtime = supervisor.runtime_config();
16572        let spec = ModuleSpec {
16573            script: None,
16574            protocol: ModuleProtocol::None,
16575            ..windowed_crash_spec("budget-publication-order")
16576        };
16577        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
16578            ModuleState::Running,
16579            true,
16580        )));
16581        lock_snapshot(&snapshot).unwrap().process_alive = true;
16582        let reaped_snapshot = snapshot.clone();
16583        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16584        let history = runtime.terminal_ring.clone();
16585        let reap = std::thread::spawn(move || {
16586            tokio::runtime::Builder::new_current_thread()
16587                .enable_all()
16588                .build()
16589                .unwrap()
16590                .block_on(on_child_exit(
16591                    &spec,
16592                    runtime.restart_policy,
16593                    &supervisor.registry,
16594                    &reaped_snapshot,
16595                    &runtime.terminal_ring,
16596                    &runtime.spawn_events,
16597                    &runtime.child_roster,
16598                    ExitReport {
16599                        kind: ExitKind::Clean,
16600                        code: Some(0),
16601                        signal: None,
16602                        at_ms: 1,
16603                    },
16604                    true,
16605                ))
16606        });
16607        let mut reached = [0];
16608        barrier.read_exact(&mut reached).unwrap();
16609        assert_eq!(&reached, b"R");
16610        let (before_state, before_alive) = {
16611            let state = lock_snapshot(&snapshot).unwrap();
16612            (state.state, state.process_alive)
16613        };
16614        let before_history = history.lock().unwrap().snapshot();
16615        barrier.write_all(b"X").unwrap();
16616        assert!(matches!(reap.join().unwrap(), NextAction::Stop { .. }));
16617        assert!(before_history.entries.is_empty());
16618        assert_ne!(
16619            before_state,
16620            ModuleState::Failed,
16621            "Failed was visible before its terminal record could be written"
16622        );
16623        assert!(before_alive);
16624        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
16625        let history = history.lock().unwrap().snapshot();
16626        assert_eq!(history.entries.len(), 1);
16627        assert_eq!(history.entries[0].exit_code, Some(0));
16628        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16629    }
16630
16631    #[test]
16632    fn crash_restart_at_budget_limit_remains_recoverable_while_recording() {
16633        use std::io::{Read, Write};
16634
16635        let supervisor = Supervisor::new_for_test(
16636            Arc::new(Registry::default()),
16637            RestartPolicy::new(3, Duration::ZERO),
16638        );
16639        let mut runtime = supervisor.runtime_config();
16640        let module = module_with_recovery_snapshot(ModuleState::Running, true, 2);
16641        let snapshot = module.inner.snapshot.clone();
16642        lock_snapshot(&snapshot).unwrap().process_alive = true;
16643        runtime.terminal_ring = module.inner.terminal_ring.clone();
16644        let spec = windowed_crash_spec(module.module_id());
16645        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16646        let reaped_snapshot = snapshot.clone();
16647        let reap = std::thread::spawn(move || {
16648            tokio::runtime::Builder::new_current_thread()
16649                .enable_all()
16650                .build()
16651                .unwrap()
16652                .block_on(on_child_exit(
16653                    &spec,
16654                    runtime.restart_policy,
16655                    &supervisor.registry,
16656                    &reaped_snapshot,
16657                    &runtime.terminal_ring,
16658                    &runtime.spawn_events,
16659                    &runtime.child_roster,
16660                    ExitReport {
16661                        kind: ExitKind::Crash,
16662                        code: Some(2),
16663                        signal: None,
16664                        at_ms: 1,
16665                    },
16666                    true,
16667                ))
16668        });
16669
16670        // Hold the crash handler between its budget decision and publication.
16671        // Connection cleanup must still see the recovery that this crash chose,
16672        // even when that recovery consumes the last available restart slot.
16673        let mut reached = [0];
16674        barrier.read_exact(&mut reached).unwrap();
16675        assert_eq!(&reached, b"R");
16676        let before_status = module.status().unwrap();
16677        let before_history = module.terminal_history();
16678        let before_recovers = module.will_recover_after_connection_loss().unwrap();
16679        barrier.write_all(b"X").unwrap();
16680        assert!(matches!(reap.join().unwrap(), NextAction::Restart { .. }));
16681
16682        assert_eq!(before_status.state, ModuleState::Running);
16683        assert!(before_status.process_alive);
16684        assert_eq!(before_status.restart_count, 2);
16685        assert!(before_history.entries.is_empty());
16686        assert!(
16687            before_recovers,
16688            "connection cleanup would report a terminal close for a scheduled crash restart"
16689        );
16690        let restarting = module.status().unwrap();
16691        assert_eq!(restarting.state, ModuleState::Restarting);
16692        assert_eq!(restarting.restart_count, 2);
16693        assert!(module.will_recover_after_connection_loss().unwrap());
16694        let history = module.terminal_history();
16695        assert_eq!(history.entries.len(), 1);
16696        assert_eq!(
16697            history.entries[0].disposition,
16698            TerminalDisposition::Restarting
16699        );
16700
16701        // Once the replacement is running, its next crash must be judged
16702        // against the exhausted budget rather than the previous recovery.
16703        update_snapshot(&snapshot, Some(module.module_id()), |state| {
16704            state.record_crash_restart(&RestartPolicy::new(3, Duration::ZERO), ClockInstant::now());
16705            state.state = ModuleState::Running;
16706            state.respawn_pending = false;
16707        })
16708        .unwrap();
16709        assert!(!module.will_recover_after_connection_loss().unwrap());
16710        update_snapshot(&snapshot, Some(module.module_id()), |state| {
16711            state.enabled = false;
16712            state.respawn_pending = true;
16713        })
16714        .unwrap();
16715        assert!(!module.will_recover_after_connection_loss().unwrap());
16716    }
16717
16718    fn terminal_record_barrier(events: &super::SpawnEventFeed) -> std::net::TcpStream {
16719        use std::net::{TcpListener, TcpStream};
16720        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
16721        let writer = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
16722        let (barrier, _) = listener.accept().unwrap();
16723        for stream in [&writer, &barrier] {
16724            stream
16725                .set_read_timeout(Some(Duration::from_secs(10)))
16726                .unwrap();
16727            stream
16728                .set_write_timeout(Some(Duration::from_secs(10)))
16729                .unwrap();
16730        }
16731        *events.1.lock().unwrap() = Some(writer);
16732        barrier
16733    }
16734
16735    pub(super) fn before_terminal_record(events: &super::SpawnEventFeed) {
16736        use std::io::{Read, Write};
16737        let barrier = events.1.lock().unwrap().take();
16738        if let Some(mut barrier) = barrier {
16739            barrier.write_all(b"R").unwrap();
16740            let mut release = [0];
16741            barrier.read_exact(&mut release).unwrap();
16742            assert_eq!(&release, b"X");
16743        }
16744    }
16745
16746    #[test]
16747    fn health_restart_budget_failure_is_published_after_its_terminal_record() {
16748        use std::io::{Read, Write};
16749
16750        let supervisor = Supervisor::new_for_test(
16751            Arc::new(Registry::default()),
16752            RestartPolicy::new(0, Duration::ZERO),
16753        );
16754        let mut runtime = supervisor.runtime_config();
16755        let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
16756        let snapshot = module.inner.snapshot.clone();
16757        runtime.terminal_ring = module.inner.terminal_ring.clone();
16758        let spec = ModuleSpec {
16759            script: None,
16760            module_id: module.module_id().into(),
16761            program: fake_aft_stub_path(),
16762            protocol: ModuleProtocol::None,
16763            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
16764            ..windowed_crash_spec(module.module_id())
16765        };
16766        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16767        let reap = std::thread::spawn(move || {
16768            tokio::runtime::Builder::new_current_thread()
16769                .enable_all()
16770                .build()
16771                .unwrap()
16772                .block_on(async {
16773                    let mut child =
16774                        Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
16775                    health_restart_child(
16776                        &spec,
16777                        &runtime,
16778                        &supervisor.registry,
16779                        &supervisor.process_liveness,
16780                        &snapshot,
16781                        &mut child,
16782                        SupervisorHealthStatus::Failing,
16783                        Some("health probe did not answer"),
16784                        1,
16785                    )
16786                    .await
16787                    .unwrap();
16788                    assert!(child.is_none());
16789                });
16790        });
16791        // The loopback barrier acknowledges entry into terminal recording by
16792        // health_restart_child's drain, then waits for the test's release byte.
16793        // Status and history are observed while that writer is held, not after
16794        // an elapsed-time guess about when the health action has completed.
16795        let mut reached = [0];
16796        barrier.read_exact(&mut reached).unwrap();
16797        assert_eq!(&reached, b"R");
16798        let before_status = module.status().unwrap();
16799        let before_history = module.terminal_history();
16800        barrier.write_all(b"X").unwrap();
16801        reap.join().unwrap();
16802        assert!(before_history.entries.is_empty());
16803        assert_ne!(
16804            before_status.state,
16805            ModuleState::Failed,
16806            "Failed was visible before its terminal record could be written"
16807        );
16808        assert!(
16809            before_status.process_alive,
16810            "process death was visible before its terminal record could be written"
16811        );
16812        let failed = module.status().unwrap();
16813        assert_eq!(failed.state, ModuleState::Failed);
16814        assert!(!failed.process_alive);
16815        let history = module.terminal_history();
16816        assert_eq!(history.entries.len(), 1);
16817        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16818        assert_eq!(
16819            history.entries[0].disposition_detail.as_deref(),
16820            Some("crash budget exhausted: max_restarts=0 within window_secs=600")
16821        );
16822    }
16823
16824    #[test]
16825    fn observed_exits_publish_process_death_after_terminal_history() {
16826        use std::io::{Read, Write};
16827        for (kind, enabled, shutdown, wait_error, expected_state) in [
16828            (ExitKind::Clean, true, false, false, ModuleState::Stopped),
16829            (ExitKind::Crash, true, false, false, ModuleState::Restarting),
16830            (ExitKind::Crash, false, false, false, ModuleState::Disabled),
16831            (
16832                ExitKind::DeliberateSeverance,
16833                true,
16834                false,
16835                false,
16836                ModuleState::Restarting,
16837            ),
16838            #[cfg(unix)]
16839            (ExitKind::Crash, true, true, false, ModuleState::Stopped),
16840            (ExitKind::Crash, true, false, true, ModuleState::Failed),
16841        ] {
16842            let supervisor = Supervisor::new_for_test(
16843                Arc::new(Registry::default()),
16844                RestartPolicy::new(1, Duration::ZERO),
16845            );
16846            let runtime = supervisor.runtime_config();
16847            #[cfg(unix)]
16848            if shutdown {
16849                runtime.child_roster.close();
16850            }
16851            #[cfg(not(unix))]
16852            let _ = shutdown;
16853            let spec = windowed_crash_spec("exit-publication-order");
16854            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
16855                ModuleState::Running,
16856                enabled,
16857            )));
16858            lock_snapshot(&snapshot).unwrap().process_alive = true;
16859            let reaped_snapshot = snapshot.clone();
16860            let history = runtime.terminal_ring.clone();
16861            let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16862            let reap = std::thread::spawn(move || {
16863                if wait_error {
16864                    super::fail_after_wait_error(
16865                        &spec.module_id,
16866                        &reaped_snapshot,
16867                        &runtime.terminal_ring,
16868                        &runtime.spawn_events,
16869                        "wait failed".into(),
16870                        &runtime.failure_context(true),
16871                    );
16872                } else {
16873                    tokio::runtime::Builder::new_current_thread()
16874                        .enable_all()
16875                        .build()
16876                        .unwrap()
16877                        .block_on(on_child_exit(
16878                            &spec,
16879                            runtime.restart_policy,
16880                            &supervisor.registry,
16881                            &reaped_snapshot,
16882                            &runtime.terminal_ring,
16883                            &runtime.spawn_events,
16884                            &runtime.child_roster,
16885                            ExitReport {
16886                                kind,
16887                                code: Some(0),
16888                                signal: None,
16889                                at_ms: 1,
16890                            },
16891                            true,
16892                        ));
16893                }
16894            });
16895            let mut reached = [0];
16896            barrier.read_exact(&mut reached).unwrap();
16897            assert_eq!(&reached, b"R");
16898            let before_alive = lock_snapshot(&snapshot).unwrap().process_alive;
16899            let before_history = history.lock().unwrap().snapshot();
16900            barrier.write_all(b"X").unwrap();
16901            reap.join().unwrap();
16902            assert!(
16903                before_alive,
16904                "{kind:?}: death was published before recording"
16905            );
16906            assert!(before_history.entries.is_empty());
16907            assert_eq!(lock_snapshot(&snapshot).unwrap().state, expected_state);
16908            assert!(!lock_snapshot(&snapshot).unwrap().process_alive);
16909            assert_eq!(history.lock().unwrap().snapshot().entries.len(), 1);
16910        }
16911    }
16912
16913    #[tokio::test]
16914    async fn health_restart_budget_failure_remains_failed_when_journal_append_fails() {
16915        let dir = cortexkit_test_support::ScratchDir::new("health-budget-journal-failure");
16916        let path = dir.join("terminals.jsonl");
16917        std::fs::create_dir(&path).unwrap();
16918        let supervisor = Supervisor::new_for_test(
16919            Arc::new(Registry::default()),
16920            RestartPolicy::new(0, Duration::ZERO),
16921        )
16922        .with_terminal_journal(path, "health-budget-journal-failure".into());
16923        let runtime = supervisor.runtime_config();
16924        let spec = ModuleSpec {
16925            script: None,
16926            program: fake_aft_stub_path(),
16927            protocol: ModuleProtocol::None,
16928            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
16929            ..windowed_crash_spec("health-budget-journal-failure")
16930        };
16931        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
16932        let mut child = Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
16933        health_restart_child(
16934            &spec,
16935            &runtime,
16936            &supervisor.registry,
16937            &supervisor.process_liveness,
16938            &snapshot,
16939            &mut child,
16940            SupervisorHealthStatus::Failing,
16941            None,
16942            1,
16943        )
16944        .await
16945        .unwrap();
16946        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
16947        assert!(!lock_snapshot(&snapshot).unwrap().process_alive);
16948        let history = runtime
16949            .terminal_ring
16950            .lock()
16951            .unwrap()
16952            .durable_history(&spec.module_id);
16953        assert!(history.journal_write_failures > 0);
16954        assert_eq!(history.entries.len(), 1);
16955        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16956    }
16957
16958    #[test]
16959    fn health_restart_budget_failure_remains_failed_when_exit_recording_panics() {
16960        let supervisor = Supervisor::new_for_test(
16961            Arc::new(Registry::default()),
16962            RestartPolicy::new(0, Duration::ZERO),
16963        );
16964        let runtime = supervisor.runtime_config();
16965        let spec = ModuleSpec {
16966            script: None,
16967            program: fake_aft_stub_path(),
16968            protocol: ModuleProtocol::None,
16969            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
16970            ..windowed_crash_spec("health-budget-recording-panic")
16971        };
16972        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
16973        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
16974            tokio::runtime::Builder::new_current_thread()
16975                .enable_all()
16976                .build()
16977                .unwrap()
16978                .block_on(async {
16979                    let mut child =
16980                        Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
16981                    runtime.spawn_events.0.lock().unwrap().seq = u64::MAX;
16982                    health_restart_child(
16983                        &spec,
16984                        &runtime,
16985                        &supervisor.registry,
16986                        &supervisor.process_liveness,
16987                        &snapshot,
16988                        &mut child,
16989                        SupervisorHealthStatus::Failing,
16990                        None,
16991                        1,
16992                    )
16993                    .await
16994                    .unwrap();
16995                });
16996        }));
16997        let panic = result.expect_err("recording must still unwind");
16998        assert_eq!(
16999            panic.downcast_ref::<String>().map(String::as_str),
17000            Some("spawn event sequence exhausted")
17001        );
17002        let state = lock_snapshot(&snapshot).unwrap();
17003        assert_eq!(state.state, ModuleState::Failed);
17004        assert!(!state.process_alive);
17005        assert!(state.last_exit.is_some());
17006    }
17007
17008    #[tokio::test]
17009    async fn restart_budget_failure_remains_failed_when_journal_append_fails() {
17010        let dir = cortexkit_test_support::ScratchDir::new("budget-journal-failure");
17011        let path = dir.join("terminals.jsonl");
17012        std::fs::create_dir(&path).unwrap();
17013        let supervisor = Supervisor::new_for_test(
17014            Arc::new(Registry::default()),
17015            RestartPolicy::new(0, Duration::ZERO),
17016        )
17017        .with_terminal_journal(path, "budget-journal-failure".into());
17018        let runtime = supervisor.runtime_config();
17019        let spec = windowed_crash_spec("budget-journal-failure");
17020        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17021        assert!(matches!(
17022            on_child_exit(
17023                &spec,
17024                runtime.restart_policy,
17025                &supervisor.registry,
17026                &snapshot,
17027                &runtime.terminal_ring,
17028                &runtime.spawn_events,
17029                &runtime.child_roster,
17030                crash_exit_report(1),
17031                true,
17032            )
17033            .await,
17034            NextAction::Stop { .. }
17035        ));
17036        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17037        let history = runtime
17038            .terminal_ring
17039            .lock()
17040            .unwrap()
17041            .durable_history(&spec.module_id);
17042        assert!(history.journal_write_failures > 0);
17043        assert_eq!(history.entries.len(), 1);
17044        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
17045    }
17046
17047    #[test]
17048    fn restart_budget_failure_remains_failed_when_exit_recording_panics() {
17049        let supervisor = Supervisor::new_for_test(
17050            Arc::new(Registry::default()),
17051            RestartPolicy::new(0, Duration::ZERO),
17052        );
17053        let runtime = supervisor.runtime_config();
17054        let spec = windowed_crash_spec("budget-recording-panic");
17055        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17056        runtime
17057            .spawn_events
17058            .emit_spawned(&spec.module_id, None, 1, 1);
17059        // Exhausting the event sequence makes emit_exited panic before the
17060        // terminal write, exercising publication on the recording unwind.
17061        runtime.spawn_events.0.lock().unwrap().seq = u64::MAX;
17062        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
17063            tokio::runtime::Builder::new_current_thread()
17064                .enable_all()
17065                .build()
17066                .unwrap()
17067                .block_on(on_child_exit(
17068                    &spec,
17069                    runtime.restart_policy,
17070                    &supervisor.registry,
17071                    &snapshot,
17072                    &runtime.terminal_ring,
17073                    &runtime.spawn_events,
17074                    &runtime.child_roster,
17075                    crash_exit_report(1),
17076                    true,
17077                ))
17078        }));
17079        let panic = result.err().expect("recording must still unwind");
17080        assert_eq!(
17081            panic.downcast_ref::<String>().map(String::as_str),
17082            Some("spawn event sequence exhausted")
17083        );
17084        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17085    }
17086
17087    /// A stop the supervisor itself requests still stops a protocol-none
17088    /// module, even though the child answers the SIGTERM with exit 0.
17089    #[cfg(unix)]
17090    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17091    async fn protocol_none_requested_stop_and_disable_do_not_respawn() {
17092        for disable in [false, true] {
17093            let label = if disable {
17094                "none-requested-disable"
17095            } else {
17096                "none-requested-stop"
17097            };
17098            let dir = cortexkit_test_support::ScratchDir::new(label);
17099            let (spec, ready, marker) = protocol_none_sigterm_exits_clean_spec(label, dir.path());
17100            let supervisor = Supervisor::new_for_test(
17101                Arc::new(Registry::default()),
17102                RestartPolicy::new(3, Duration::ZERO),
17103            );
17104            let module = supervisor.spawn(spec).unwrap();
17105            wait_for_file(&ready).await;
17106
17107            if disable {
17108                module.set_enabled(false).await.unwrap();
17109            } else {
17110                module.stop().await.unwrap();
17111            }
17112            assert!(
17113                marker.exists(),
17114                "{label}: the child must have left through its SIGTERM handler with exit 0"
17115            );
17116
17117            // Long enough for a zero-backoff respawn to have happened if the
17118            // exit had been treated as a crash.
17119            sleep(Duration::from_millis(500)).await;
17120            let status = module.status().unwrap();
17121            let expected = if disable {
17122                ModuleState::Disabled
17123            } else {
17124                ModuleState::Stopped
17125            };
17126            assert_eq!(status.state, expected, "{label}");
17127            assert_eq!(
17128                status.spawn_generation, 1,
17129                "{label}: respawned after a requested stop"
17130            );
17131            let history = module.terminal_history();
17132            assert_eq!(history.entries.len(), 1, "{label}: {history:?}");
17133            assert_eq!(history.entries[0].exit_code, Some(0), "{label}");
17134            assert_ne!(
17135                history.entries[0].disposition,
17136                TerminalDisposition::Restarting,
17137                "{label}"
17138            );
17139        }
17140    }
17141
17142    /// A subc-wire module that exits 0 on its own is still a stop: the
17143    /// protocol-none rule must not reach it.
17144    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17145    async fn subc_wire_clean_exit_is_still_a_stop() {
17146        let supervisor = Supervisor::new_for_test(
17147            Arc::new(Registry::default()),
17148            RestartPolicy::new(3, Duration::ZERO),
17149        );
17150        let module = supervisor
17151            .spawn(ModuleSpec {
17152                script: None,
17153                module_id: "wire-clean-exit".to_string(),
17154                program: fake_aft_stub_path(),
17155                args: Vec::new(),
17156                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "0".to_string())],
17157                reserved: false,
17158                reserved_prefixes: Vec::new(),
17159                protocol: ModuleProtocol::Subc,
17160                overlap: Default::default(),
17161                carry_containment: false,
17162            })
17163            .unwrap();
17164
17165        let deadline = Instant::now() + Duration::from_secs(10);
17166        while module.terminal_history().entries.is_empty() {
17167            assert!(Instant::now() < deadline, "module never exited");
17168            sleep(Duration::from_millis(10)).await;
17169        }
17170        // Long enough for a zero-backoff respawn to have happened.
17171        sleep(Duration::from_millis(500)).await;
17172        let status = module.status().unwrap();
17173        assert_eq!(status.state, ModuleState::Stopped);
17174        assert_eq!(status.spawn_generation, 1);
17175        let history = module.terminal_history();
17176        assert_eq!(history.entries.len(), 1, "{history:?}");
17177        assert_eq!(history.entries[0].exit_code, Some(0));
17178        assert_eq!(history.entries[0].disposition, TerminalDisposition::Stopped);
17179    }
17180
17181    #[cfg(unix)]
17182    #[tokio::test]
17183    async fn reload_exit_keeps_roster_until_terminal_is_recorded_during_shutdown() {
17184        let dir = cortexkit_test_support::ScratchDir::new("reload-roster-terminal-order");
17185        let record = dir.join("live-children.json");
17186        let supervisor = Supervisor::new_for_test(
17187            Arc::new(Registry::default()),
17188            RestartPolicy::new(0, Duration::ZERO),
17189        );
17190        let mut runtime = supervisor.runtime_config();
17191        runtime.child_roster.record_to(record.clone());
17192        let gate = Arc::new(super::ReloadExitRecordGate::default());
17193        runtime.test_reload_exit_record_gate = Some(Arc::clone(&gate));
17194        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17195        let spec = ModuleSpec {
17196            script: None,
17197            module_id: "reload-exit-roster".into(),
17198            program: fake_aft_stub_path(),
17199            args: Vec::new(),
17200            env: vec![("FAKE_AFT_EXIT_CODE".into(), "23".into())],
17201            reserved: false,
17202            reserved_prefixes: Vec::new(),
17203            protocol: ModuleProtocol::Subc,
17204            overlap: Default::default(),
17205            carry_containment: false,
17206        };
17207        let mut child = None;
17208        let reload = super::finish_reload_child(
17209            &spec,
17210            &runtime,
17211            &supervisor.registry,
17212            &supervisor.process_liveness,
17213            &snapshot,
17214            &mut child,
17215        );
17216        tokio::pin!(reload);
17217        tokio::select! {
17218            result = &mut reload => panic!("reload missed the before-record gate: {result:?}"),
17219            _ = gate.reached.notified() => {}
17220        }
17221        assert!(runtime
17222            .terminal_ring
17223            .lock()
17224            .unwrap()
17225            .snapshot()
17226            .entries
17227            .is_empty());
17228        assert_eq!(
17229            crate::live_children::read_record(&record).unwrap().len(),
17230            1,
17231            "shutdown must still wait for the reaped child until its terminal record exists"
17232        );
17233        runtime.child_roster.close();
17234        gate.resume.notify_one();
17235        assert!(reload.await.is_err());
17236        assert!(crate::live_children::read_record(&record)
17237            .unwrap()
17238            .is_empty());
17239        let history = runtime.terminal_ring.lock().unwrap().snapshot();
17240        assert_eq!(history.entries.len(), 1);
17241        assert_eq!(
17242            history.entries[0].disposition,
17243            TerminalDisposition::DaemonShutdown
17244        );
17245    }
17246
17247    /// Each budgeted recovery can be blocked or cancelled before the new child
17248    /// starts, so none of their disposition decisions should count a spawn.
17249    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17250    async fn no_budgeted_recovery_is_counted_before_spawn() {
17251        let supervisor = Supervisor::new_for_test(
17252            Arc::new(Registry::default()),
17253            RestartPolicy::new(1, Duration::ZERO),
17254        );
17255        let runtime = supervisor.runtime_config();
17256        let spec = ModuleSpec {
17257            script: None,
17258            module_id: "lifetime-increment-path".to_string(),
17259            program: PathBuf::from("/unused/lifetime-increment-path"),
17260            args: Vec::new(),
17261            env: Vec::new(),
17262            reserved: false,
17263            reserved_prefixes: Vec::new(),
17264            protocol: ModuleProtocol::Subc,
17265            overlap: Default::default(),
17266            carry_containment: false,
17267        };
17268
17269        let crash_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17270        assert!(matches!(
17271            on_child_exit(
17272                &spec,
17273                runtime.restart_policy,
17274                &supervisor.registry,
17275                &crash_snapshot,
17276                &runtime.terminal_ring,
17277                &runtime.spawn_events,
17278                &runtime.child_roster,
17279                ExitReport {
17280                    kind: ExitKind::Crash,
17281                    code: Some(1),
17282                    signal: None,
17283                    at_ms: 1,
17284                },
17285                true,
17286            )
17287            .await,
17288            NextAction::Restart { schedule: _ }
17289        ));
17290        let (crash_restarts, crash_lifetime) = {
17291            let state = lock_snapshot(&crash_snapshot).unwrap();
17292            (state.crash_restarts.len(), state.lifetime_restarts)
17293        };
17294        assert_eq!((crash_restarts, crash_lifetime), (0, 0));
17295
17296        let health_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17297        let mut health_child = None;
17298        assert!(matches!(
17299            health_restart_child(
17300                &spec,
17301                &runtime,
17302                &supervisor.registry,
17303                &supervisor.process_liveness,
17304                &health_snapshot,
17305                &mut health_child,
17306                SupervisorHealthStatus::Failing,
17307                None,
17308                2,
17309            )
17310            .await,
17311            Ok(())
17312        ));
17313        assert!(health_child.is_none());
17314        assert!(lock_snapshot(&health_snapshot).unwrap().respawn_pending);
17315        assert!(runtime.scheduled_respawn.lock().unwrap().take().is_some());
17316        let (health_restarts, health_lifetime) = {
17317            let state = lock_snapshot(&health_snapshot).unwrap();
17318            (state.crash_restarts.len(), state.lifetime_restarts)
17319        };
17320        assert_eq!((health_restarts, health_lifetime), (0, 0));
17321
17322        let reload_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17323        let mut reload_child = None;
17324        assert!(matches!(
17325            handle_reload_spawn_failure(
17326                &spec,
17327                &runtime,
17328                &supervisor.process_liveness,
17329                &reload_snapshot,
17330                &mut reload_child,
17331                "forced reload spawn failure".to_string(),
17332            )
17333            .await,
17334            Err(SuperviseError::ReloadFailed { .. })
17335        ));
17336        let (reload_restarts, reload_lifetime) = {
17337            let state = lock_snapshot(&reload_snapshot).unwrap();
17338            (state.crash_restarts.len(), state.lifetime_restarts)
17339        };
17340        assert_eq!((reload_restarts, reload_lifetime), (0, 0));
17341    }
17342
17343    #[tokio::test]
17344    async fn deliberately_severed_live_child_records_lifetime_without_spending_restart_budget() {
17345        let supervisor = Supervisor::new_for_test(
17346            Arc::new(Registry::default()),
17347            RestartPolicy::new(3, Duration::ZERO),
17348        );
17349        let runtime = supervisor.runtime_config();
17350        let spec = ModuleSpec {
17351            script: None,
17352            module_id: "deliberately-severed".to_string(),
17353            program: PathBuf::from("/unused/deliberately-severed"),
17354            args: Vec::new(),
17355            env: Vec::new(),
17356            reserved: false,
17357            reserved_prefixes: Vec::new(),
17358            protocol: ModuleProtocol::Subc,
17359            overlap: Default::default(),
17360            carry_containment: false,
17361        };
17362        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17363        let process = ProcessIdentity {
17364            pid: 41,
17365            start_time: 101,
17366        };
17367        record_deliberate_severance(&snapshot, process).unwrap();
17368        let exit_report = apply_deliberate_severance_marker(
17369            &snapshot,
17370            Some(process),
17371            ExitReport {
17372                kind: ExitKind::Crash,
17373                code: Some(1),
17374                signal: None,
17375                at_ms: 1,
17376            },
17377        );
17378        assert_eq!(exit_report.kind, ExitKind::DeliberateSeverance);
17379
17380        assert!(matches!(
17381            on_child_exit(
17382                &spec,
17383                runtime.restart_policy,
17384                &supervisor.registry,
17385                &snapshot,
17386                &runtime.terminal_ring,
17387                &runtime.spawn_events,
17388                &runtime.child_roster,
17389                exit_report,
17390                true,
17391            )
17392            .await,
17393            NextAction::Restart { schedule: _ }
17394        ));
17395        let state = lock_snapshot(&snapshot).unwrap();
17396        assert_eq!(state.lifetime_restarts, 1);
17397        assert_eq!(state.crash_restarts.len(), 0);
17398    }
17399
17400    #[tokio::test]
17401    async fn genuine_crash_spends_restart_budget_and_records_lifetime() {
17402        let supervisor = Supervisor::new_for_test(
17403            Arc::new(Registry::default()),
17404            RestartPolicy::new(3, Duration::ZERO),
17405        );
17406        let runtime = supervisor.runtime_config();
17407        let spec = ModuleSpec {
17408            script: None,
17409            module_id: "genuine-crash".to_string(),
17410            program: PathBuf::from("/unused/genuine-crash"),
17411            args: Vec::new(),
17412            env: Vec::new(),
17413            reserved: false,
17414            reserved_prefixes: Vec::new(),
17415            protocol: ModuleProtocol::Subc,
17416            overlap: Default::default(),
17417            carry_containment: false,
17418        };
17419        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17420
17421        assert!(matches!(
17422            on_child_exit(
17423                &spec,
17424                runtime.restart_policy,
17425                &supervisor.registry,
17426                &snapshot,
17427                &runtime.terminal_ring,
17428                &runtime.spawn_events,
17429                &runtime.child_roster,
17430                ExitReport {
17431                    kind: ExitKind::Crash,
17432                    code: Some(1),
17433                    signal: None,
17434                    at_ms: 1,
17435                },
17436                true,
17437            )
17438            .await,
17439            NextAction::Restart { schedule: Some(_) }
17440        ));
17441        let mut state = lock_snapshot(&snapshot).unwrap();
17442        assert!(state.respawn_pending);
17443        assert_eq!(state.lifetime_restarts, 0);
17444        state.record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17445        assert_eq!(state.lifetime_restarts, 1);
17446        assert_eq!(state.crash_restarts.len(), 1);
17447    }
17448
17449    fn crash_exit_report(at_ms: u64) -> ExitReport {
17450        ExitReport {
17451            kind: ExitKind::Crash,
17452            code: Some(1),
17453            signal: None,
17454            at_ms,
17455        }
17456    }
17457
17458    fn windowed_crash_spec(module_id: &str) -> ModuleSpec {
17459        ModuleSpec {
17460            script: None,
17461            module_id: module_id.to_string(),
17462            program: PathBuf::from("/unused").join(module_id),
17463            args: Vec::new(),
17464            env: Vec::new(),
17465            reserved: false,
17466            reserved_prefixes: Vec::new(),
17467            protocol: ModuleProtocol::Subc,
17468            overlap: Default::default(),
17469            carry_containment: false,
17470        }
17471    }
17472
17473    /// A real crash loop still stops. Three crashes with nothing aging out spend
17474    /// a budget of two and the third respawn is refused, and both surfaces an
17475    /// operator has -- the log line and the retained terminal record -- name the
17476    /// window rather than only the cap, because `max_restarts=2` alone is what
17477    /// this budget used to mean.
17478    #[tokio::test]
17479    async fn three_crashes_inside_the_window_stop_the_module_and_name_the_window() {
17480        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::ERROR);
17481        let supervisor = Supervisor::new_for_test(
17482            Arc::new(Registry::default()),
17483            RestartPolicy::new(2, Duration::ZERO),
17484        );
17485        let runtime = supervisor.runtime_config();
17486        let spec = windowed_crash_spec("crash-loop-in-window");
17487        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17488
17489        for attempt in 1..=2 {
17490            assert!(
17491                matches!(
17492                    on_child_exit(
17493                        &spec,
17494                        runtime.restart_policy,
17495                        &supervisor.registry,
17496                        &snapshot,
17497                        &runtime.terminal_ring,
17498                        &runtime.spawn_events,
17499                        &runtime.child_roster,
17500                        crash_exit_report(attempt),
17501                        true,
17502                    )
17503                    .await,
17504                    NextAction::Restart { schedule: _ }
17505                ),
17506                "crash {attempt} is inside the budget and must respawn"
17507            );
17508            lock_snapshot(&snapshot)
17509                .unwrap()
17510                .record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17511        }
17512
17513        assert!(matches!(
17514            on_child_exit(
17515                &spec,
17516                runtime.restart_policy,
17517                &supervisor.registry,
17518                &snapshot,
17519                &runtime.terminal_ring,
17520                &runtime.spawn_events,
17521                &runtime.child_roster,
17522                crash_exit_report(3),
17523                true,
17524            )
17525            .await,
17526            NextAction::Stop { .. }
17527        ));
17528
17529        {
17530            let state = lock_snapshot(&snapshot).unwrap();
17531            assert_eq!(state.state, ModuleState::Failed);
17532            assert_eq!(state.crash_restarts.len(), 2);
17533            assert_eq!(state.lifetime_restarts, 2);
17534        }
17535
17536        let history = runtime
17537            .terminal_ring
17538            .lock()
17539            .expect("terminal ring is not poisoned")
17540            .snapshot();
17541        let last = history
17542            .entries
17543            .last()
17544            .expect("the refused crash is retained");
17545        assert_eq!(last.disposition, TerminalDisposition::Failed);
17546        assert_eq!(
17547            last.disposition_detail.as_deref(),
17548            Some("crash budget exhausted: max_restarts=2 within window_secs=600")
17549        );
17550
17551        let captured = crate::router::test_log::captured_logs(&logs);
17552        assert!(
17553            captured.contains("crash budget exhausted: max_restarts=2 within window_secs=600"),
17554            "the stop must be logged with its window: {captured}"
17555        );
17556    }
17557
17558    /// The rate, stated as a test: three crashes where the first has aged past
17559    /// the window are two crashes as far as the budget is concerned, so the
17560    /// third respawn is allowed and the ring holds only the two recent ones.
17561    ///
17562    /// This is the case a lifetime counter got wrong -- and the case the daemon
17563    /// now hits routinely, since a module exits non-zero every time its
17564    /// connection to the daemon drops.
17565    #[tokio::test]
17566    async fn a_crash_older_than_the_window_frees_its_slot_for_a_later_crash() {
17567        let supervisor = Supervisor::new_for_test(
17568            Arc::new(Registry::default()),
17569            RestartPolicy::new(2, Duration::ZERO),
17570        );
17571        let runtime = supervisor.runtime_config();
17572        let spec = windowed_crash_spec("crash-across-windows");
17573        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17574
17575        for attempt in 1..=2 {
17576            assert!(matches!(
17577                on_child_exit(
17578                    &spec,
17579                    runtime.restart_policy,
17580                    &supervisor.registry,
17581                    &snapshot,
17582                    &runtime.terminal_ring,
17583                    &runtime.spawn_events,
17584                    &runtime.child_roster,
17585                    crash_exit_report(attempt),
17586                    true,
17587                )
17588                .await,
17589                NextAction::Restart { schedule: _ }
17590            ));
17591            lock_snapshot(&snapshot)
17592                .unwrap()
17593                .record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17594        }
17595
17596        // The oldest crash moves out of the window; nothing else about the
17597        // module changes.
17598        update_snapshot(&snapshot, Some(&spec.module_id), |state| {
17599            age_oldest_crash_restart_out_of_window(state, runtime.restart_policy.window);
17600        })
17601        .unwrap();
17602
17603        assert!(
17604            matches!(
17605                on_child_exit(
17606                    &spec,
17607                    runtime.restart_policy,
17608                    &supervisor.registry,
17609                    &snapshot,
17610                    &runtime.terminal_ring,
17611                    &runtime.spawn_events,
17612                    &runtime.child_roster,
17613                    crash_exit_report(3),
17614                    true,
17615                )
17616                .await,
17617                NextAction::Restart { schedule: _ }
17618            ),
17619            "a crash older than the window must not hold a budget slot"
17620        );
17621
17622        let mut state = lock_snapshot(&snapshot).unwrap();
17623        state.record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17624        assert_eq!(state.state, ModuleState::Restarting);
17625        assert_eq!(
17626            state.crash_restarts.len(),
17627            2,
17628            "the aged instant is dropped and the new one takes its place"
17629        );
17630        assert_eq!(
17631            state.lifetime_restarts, 3,
17632            "the ledger counts every restart, including the ones the window forgot"
17633        );
17634    }
17635
17636    /// An operator restart hands the budget back whole, and the ledger keeps
17637    /// counting. Those are different questions -- "how close is this module to
17638    /// being stopped" and "how many times has it been replaced" -- and the
17639    /// operator action answers only the first.
17640    #[tokio::test]
17641    async fn an_operator_restart_clears_the_ring_and_leaves_the_ledger_alone() {
17642        let supervisor = Supervisor::new_for_test(
17643            Arc::new(Registry::default()),
17644            RestartPolicy::new(2, Duration::ZERO),
17645        );
17646        let runtime = supervisor.runtime_config();
17647        let spec = windowed_crash_spec("operator-cleared-budget");
17648        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17649
17650        for attempt in 1..=2 {
17651            assert!(matches!(
17652                on_child_exit(
17653                    &spec,
17654                    runtime.restart_policy,
17655                    &supervisor.registry,
17656                    &snapshot,
17657                    &runtime.terminal_ring,
17658                    &runtime.spawn_events,
17659                    &runtime.child_roster,
17660                    crash_exit_report(attempt),
17661                    true,
17662                )
17663                .await,
17664                NextAction::Restart { schedule: _ }
17665            ));
17666            lock_snapshot(&snapshot)
17667                .unwrap()
17668                .record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17669        }
17670
17671        reset_restart_count(&snapshot, &spec.module_id).unwrap();
17672        {
17673            let state = lock_snapshot(&snapshot).unwrap();
17674            assert!(
17675                state.crash_restarts.is_empty(),
17676                "an operator restart returns the full budget"
17677            );
17678            assert_eq!(
17679                state.lifetime_restarts, 2,
17680                "clearing the budget must not unmake the crashes"
17681            );
17682        }
17683
17684        assert!(
17685            matches!(
17686                on_child_exit(
17687                    &spec,
17688                    runtime.restart_policy,
17689                    &supervisor.registry,
17690                    &snapshot,
17691                    &runtime.terminal_ring,
17692                    &runtime.spawn_events,
17693                    &runtime.child_roster,
17694                    crash_exit_report(3),
17695                    true,
17696                )
17697                .await,
17698                NextAction::Restart { schedule: _ }
17699            ),
17700            "the cleared budget must be spendable again"
17701        );
17702        let mut state = lock_snapshot(&snapshot).unwrap();
17703        state.record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17704        assert_eq!(state.crash_restarts.len(), 1);
17705        assert_eq!(state.lifetime_restarts, 3);
17706    }
17707
17708    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17709    async fn severance_marker_for_a_dead_child_does_not_label_its_successor() {
17710        let severed = ProcessIdentity {
17711            pid: 41,
17712            start_time: 101,
17713        };
17714        let successor = ProcessIdentity {
17715            pid: 41,
17716            start_time: 202,
17717        };
17718        let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
17719        update_snapshot(&module.inner.snapshot, Some("recovery-snapshot"), |state| {
17720            state.pid = Some(successor.pid);
17721            state.process_start_time = Some(successor.start_time);
17722        })
17723        .unwrap();
17724        assert!(!module.record_deliberate_severance(severed).unwrap());
17725
17726        let exit_report = apply_deliberate_severance_marker(
17727            &module.inner.snapshot,
17728            Some(successor),
17729            ExitReport {
17730                kind: ExitKind::Crash,
17731                code: Some(1),
17732                signal: None,
17733                at_ms: 1,
17734            },
17735        );
17736
17737        assert_eq!(exit_report.kind, ExitKind::Crash);
17738    }
17739
17740    #[tokio::test]
17741    async fn drain_reap_marks_deliberate_severance_and_records_lifetime_without_budget() {
17742        let registry = Registry::default();
17743        let supervisor = Supervisor::new_for_test(
17744            Arc::new(Registry::default()),
17745            RestartPolicy::new(3, Duration::ZERO),
17746        );
17747        let runtime = supervisor.runtime_config();
17748        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17749        let spec = ModuleSpec {
17750            script: None,
17751            module_id: "drain-deliberate-severance".to_string(),
17752            program: fake_aft_stub_path(),
17753            args: Vec::new(),
17754            env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
17755            reserved: false,
17756            reserved_prefixes: Vec::new(),
17757            protocol: ModuleProtocol::Subc,
17758            overlap: Default::default(),
17759            carry_containment: false,
17760        };
17761        let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
17762        let process = ProcessIdentity {
17763            pid: 41,
17764            start_time: 101,
17765        };
17766        child.process_identity = Some(process);
17767        update_snapshot(&snapshot, Some(&spec.module_id), |state| {
17768            state.pid = Some(process.pid);
17769            state.process_start_time = Some(process.start_time);
17770        })
17771        .unwrap();
17772        record_deliberate_severance(&snapshot, process).unwrap();
17773
17774        drain_child_to_state(
17775            &spec.module_id,
17776            spec.protocol,
17777            // The child exits on its own; no signal may change the exit this
17778            // test classifies.
17779            StopNotice::SentOverConnection,
17780            &registry,
17781            None,
17782            &snapshot,
17783            &runtime.terminal_ring,
17784            &runtime.spawn_events,
17785            child,
17786            Duration::from_secs(1),
17787            ModuleState::Stopped,
17788            Some(false),
17789            &super::FailureContext::operator(),
17790        )
17791        .await
17792        .unwrap();
17793
17794        let state = lock_snapshot(&snapshot).unwrap();
17795        assert_eq!(
17796            state.last_exit.as_ref().map(|exit| exit.kind),
17797            Some(ExitKind::DeliberateSeverance)
17798        );
17799        assert_eq!(state.lifetime_restarts, 1);
17800        assert_eq!(state.crash_restarts.len(), 0);
17801        drop(state);
17802        let history = runtime.terminal_ring.lock().unwrap().snapshot();
17803        assert_eq!(
17804            history.entries[0].exit_kind,
17805            subc_control::TerminalExitKind::DeliberateSeverance
17806        );
17807    }
17808
17809    #[tokio::test]
17810    async fn ordinary_drain_reap_does_not_record_a_lifetime_restart() {
17811        let registry = Registry::default();
17812        let supervisor = Supervisor::new_for_test(
17813            Arc::new(Registry::default()),
17814            RestartPolicy::new(3, Duration::ZERO),
17815        );
17816        let runtime = supervisor.runtime_config();
17817        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17818        let spec = ModuleSpec {
17819            script: None,
17820            module_id: "ordinary-drain".to_string(),
17821            program: fake_aft_stub_path(),
17822            args: Vec::new(),
17823            env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
17824            reserved: false,
17825            reserved_prefixes: Vec::new(),
17826            protocol: ModuleProtocol::Subc,
17827            overlap: Default::default(),
17828            carry_containment: false,
17829        };
17830        let child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
17831
17832        drain_child_to_state(
17833            &spec.module_id,
17834            spec.protocol,
17835            // The child exits on its own; no signal may change the exit this
17836            // test classifies.
17837            StopNotice::SentOverConnection,
17838            &registry,
17839            None,
17840            &snapshot,
17841            &runtime.terminal_ring,
17842            &runtime.spawn_events,
17843            child,
17844            Duration::from_secs(1),
17845            ModuleState::Stopped,
17846            Some(false),
17847            &super::FailureContext::operator(),
17848        )
17849        .await
17850        .unwrap();
17851
17852        let state = lock_snapshot(&snapshot).unwrap();
17853        assert_eq!(
17854            state.last_exit.as_ref().map(|exit| exit.kind),
17855            Some(ExitKind::Crash)
17856        );
17857        assert_eq!(state.lifetime_restarts, 0);
17858        assert_eq!(state.crash_restarts.len(), 0);
17859    }
17860
17861    #[test]
17862    fn fatal_connection_teardown_cannot_arm_a_marker_for_a_surviving_process() {
17863        // The server's generic fatal-routing branch only knows that the
17864        // connection failed; it does not know that the daemon deliberately
17865        // initiated a process-killing severance. Keep this seam explicit so a
17866        // future connection error path cannot silently reintroduce the stale
17867        // exemption that mislabels a later genuine crash.
17868        assert!(!include_str!("server.rs")
17869            .contains("router.record_deliberate_connection_severance(ctx.connection_id)"));
17870    }
17871
17872    /// The `route.closed` `drained` value must be the quiescence wait's own
17873    /// measurement (`Ok`), never invented -- except on `Err`, where there is no
17874    /// measurement at all and `false` is the one honest constant. This is the exact
17875    /// logic `begin_forwarding_drain_with` now applies before sending `route.closed`
17876    /// on every return path, including the one that used to return early via `?`
17877    /// with `route.closing` already sent and no `route.closed` ever following.
17878    #[test]
17879    fn drained_after_quiescence_wait_passes_ok_through_and_forces_false_on_err() {
17880        assert!(drained_after_quiescence_wait(&Ok(true)));
17881        assert!(!drained_after_quiescence_wait(&Ok(false)));
17882        assert!(!drained_after_quiescence_wait(&Err(
17883            SuperviseError::StatePoisoned { module_id: None }
17884        )));
17885    }
17886
17887    /// `supervise_loop`'s `wait()`-error arm now calls `record_terminal` like every
17888    /// other exit path does, so a module whose child `wait()` itself errored (e.g.
17889    /// already reaped out-of-band) still leaves a terminal record rather than none
17890    /// at all. Triggering the real `wait()` I/O error from an integration test would
17891    /// need a genuine already-reaped-child race, which is OS-specific and not
17892    /// something this suite attempts elsewhere; this test instead verifies the
17893    /// record produced for that arm end-to-end through the real `TerminalRing`, and
17894    /// the call site itself is verified by inspection to sit in that exact arm.
17895    #[test]
17896    fn wait_error_exit_report_records_a_failed_terminal_with_no_code_or_signal() {
17897        let ring = Arc::new(Mutex::new(TerminalRing::new(
17898            TerminalRingConfig::default(),
17899            0,
17900        )));
17901        record_wait_error_terminal("wait-error", &ring, &super::SpawnEventFeed::default());
17902
17903        let snapshot = ring.lock().unwrap().snapshot();
17904        assert_eq!(snapshot.entries.len(), 1);
17905        let entry = &snapshot.entries[0];
17906        assert_eq!(entry.exit_code, None);
17907        assert_eq!(entry.exit_signal, None);
17908        assert_eq!(entry.disposition, TerminalDisposition::Failed);
17909    }
17910
17911    /// A launch is numbered before it starts. One that never runs keeps its
17912    /// number, and the next launch of the module is numbered after it.
17913    #[test]
17914    fn spawn_generation_of_a_failed_launch_is_never_reused() {
17915        let feed = super::SpawnEventFeed::default();
17916        feed.configure_incarnation("launch-numbering".to_string());
17917        let (incarnation, failed) = feed.allocate_generation("relaunched");
17918        assert_eq!(incarnation, "launch-numbering");
17919        let (_, next) = feed.allocate_generation("relaunched");
17920        assert!(next > failed);
17921        assert_eq!(feed.emit_spawned("relaunched", Some(next), 7, 1), next);
17922        // A process with no pre-allocated number is numbered after both.
17923        assert!(feed.emit_spawned("relaunched", None, 8, 2) > next);
17924        assert_eq!(
17925            feed.allocate_generation("other").1,
17926            1,
17927            "numbering is per module"
17928        );
17929    }
17930
17931    #[test]
17932    fn wait_error_exit_path_preserves_spawn_event_density() {
17933        let feed = super::SpawnEventFeed::default();
17934        feed.configure_incarnation("wait-error-density".to_string());
17935        feed.emit_spawned("wait-error", None, 41, 1);
17936        let ring = Arc::new(Mutex::new(TerminalRing::new(
17937            TerminalRingConfig::default(),
17938            0,
17939        )));
17940
17941        record_wait_error_terminal("wait-error", &ring, &feed);
17942        feed.emit_spawned("after-wait-error", None, 42, 2);
17943
17944        let state = feed.0.lock().unwrap();
17945        let sequences = state
17946            .events
17947            .iter()
17948            .map(|event| event.cursor.seq)
17949            .collect::<Vec<_>>();
17950        assert_eq!(sequences, vec![1, 2, 3]);
17951        assert_eq!(state.events[1].kind, SpawnEventKind::Exited);
17952        assert_eq!(state.events[1].exit_code, None);
17953        assert_eq!(state.events[1].exit_signal, None);
17954    }
17955
17956    /// Pins the report's `kind` too: the wait-error arm treats an unwaitable child
17957    /// as a crash (matching `fail_snapshot`'s `Failed` disposition for this arm),
17958    /// not a clean exit it never actually observed.
17959    #[test]
17960    fn wait_error_exit_report_is_classified_as_a_crash() {
17961        assert_eq!(wait_error_exit_report().kind, ExitKind::Crash);
17962    }
17963}
17964
17965#[cfg(all(test, unix))]
17966mod restart_ordering_tests {
17967    use super::*;
17968    use std::io::Write;
17969    use tokio::io::AsyncReadExt;
17970
17971    #[test]
17972    #[ignore = "child process fixture"]
17973    fn serving_child() {
17974        let Ok(address_file) = std::env::var("RESTART_TEST_ADDRESS_FILE") else {
17975            return;
17976        };
17977        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
17978        std::fs::write(address_file, listener.local_addr().unwrap().to_string()).unwrap();
17979        for stream in listener.incoming() {
17980            writeln!(stream.unwrap(), "{}", std::process::id()).unwrap();
17981        }
17982    }
17983
17984    async fn restart_before_publication(requests: usize) {
17985        let home = cortexkit_test_support::ScratchDir::new("restart-before-publication");
17986        let address_file = home.path().join("address");
17987        let spec = ModuleSpec {
17988            script: None,
17989            module_id: "restart-serving-child".into(),
17990            program: std::env::current_exe().unwrap(),
17991            args: vec![
17992                "--exact".into(),
17993                "supervise::restart_ordering_tests::serving_child".into(),
17994                "--ignored".into(),
17995                "--nocapture".into(),
17996            ],
17997            env: vec![(
17998                "RESTART_TEST_ADDRESS_FILE".into(),
17999                address_file.display().to_string(),
18000            )],
18001            reserved: false,
18002            reserved_prefixes: vec![],
18003            protocol: ModuleProtocol::None,
18004            overlap: Default::default(),
18005            carry_containment: false,
18006        };
18007        let mut supervisor =
18008            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
18009        let (spawned_tx, spawned_rx) = oneshot::channel();
18010        let spawned_tx = Mutex::new(Some(spawned_tx));
18011        let (release_tx, release_rx) = std::sync::mpsc::channel();
18012        let release_rx = Mutex::new(release_rx);
18013        // Hold publication, not the child: it must answer a real request before
18014        // the restart enters the queue, even though status still has generation 0.
18015        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |_| {
18016            spawned_tx.lock().unwrap().take().unwrap().send(()).unwrap();
18017            release_rx
18018                .lock()
18019                .unwrap()
18020                .recv_timeout(Duration::from_secs(20))
18021                .unwrap();
18022        })));
18023        let registered = supervisor
18024            .register_configured_with_health(
18025                spec.clone(),
18026                true,
18027                HealthConfig::default(),
18028                None,
18029                RestartPolicy::new(3, Duration::ZERO),
18030                DEFAULT_REGISTER_TIMEOUT,
18031            )
18032            .unwrap();
18033        let module = registered.module.clone();
18034        let startup = tokio::task::spawn_blocking(move || {
18035            supervisor.start_registered_configured(registered, None, true)
18036        });
18037        spawned_rx.await.unwrap();
18038        let old_pid = tokio::time::timeout(Duration::from_secs(10), async {
18039            let address = loop {
18040                if let Ok(address) = std::fs::read_to_string(&address_file) {
18041                    if !address.is_empty() {
18042                        break address;
18043                    }
18044                }
18045                tokio::time::sleep(Duration::from_millis(1)).await;
18046            };
18047            let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();
18048            let mut reply = String::new();
18049            stream.read_to_string(&mut reply).await.unwrap();
18050            reply.trim().parse::<u32>().unwrap()
18051        })
18052        .await
18053        .expect("child must serve before generation publication");
18054        assert_eq!(
18055            lock_snapshot(&module.inner.snapshot)
18056                .unwrap()
18057                .spawn_generation,
18058            0
18059        );
18060        let mut replies = Vec::new();
18061        for _ in 0..requests {
18062            let mut restart = Box::pin(module.restart(Some(0)));
18063            // Poll the public API through queue admission, leaving only its ACK
18064            // pending. The monitor cannot consume the command until released.
18065            std::future::poll_fn(|cx| {
18066                assert!(std::future::Future::poll(restart.as_mut(), cx).is_pending());
18067                std::task::Poll::Ready(())
18068            })
18069            .await;
18070            replies.push(restart);
18071        }
18072        release_tx.send(()).unwrap();
18073        startup.await.unwrap().unwrap();
18074        for reply in replies {
18075            reply.await.unwrap();
18076        }
18077        // Restart schedules its replacement after completing the handler. Wait
18078        // for that separate actor turn before placing the command barrier.
18079        let replacement = tokio::time::timeout(Duration::from_secs(10), async {
18080            loop {
18081                if lock_snapshot(&module.inner.snapshot)
18082                    .unwrap()
18083                    .spawn_generation
18084                    > 1
18085                {
18086                    break;
18087                }
18088                tokio::time::sleep(Duration::from_millis(1)).await;
18089            }
18090        })
18091        .await;
18092        // Commands are handled serially. The update-spec reply proves every
18093        // restart handler has finished before we inspect the snapshot; restart's
18094        // own ACK only acknowledges initiation, not replacement completion.
18095        module.update_spec_for_test(spec).await.unwrap();
18096        let (generation, pid) = {
18097            let state = lock_snapshot(&module.inner.snapshot).unwrap();
18098            (state.spawn_generation, state.pid)
18099        };
18100        module.stop().await.unwrap();
18101        replacement.expect("restart must publish a replacement for the already-serving child");
18102        assert_ne!(
18103            pid,
18104            Some(old_pid),
18105            "a serving child predating the restart must be replaced"
18106        );
18107        assert_eq!(generation, 2, "queued restarts must share one replacement");
18108    }
18109
18110    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
18111    async fn restart_received_after_serving_before_generation_publication_replaces_child() {
18112        restart_before_publication(1).await;
18113    }
18114
18115    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
18116    async fn restart_queued_behind_restart_does_not_kill_its_replacement() {
18117        restart_before_publication(2).await;
18118    }
18119
18120    #[tokio::test]
18121    async fn restart_queued_before_replacement_spawn_keeps_the_new_child() {
18122        let supervisor =
18123            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
18124        let registered = supervisor
18125            .register_configured_with_health(
18126                ModuleSpec {
18127                    script: None,
18128                    module_id: "queued-before-replacement".into(),
18129                    // `/bin/sleep` itself, not `/bin/sh -c "exec sleep"`: on
18130                    // macOS a module whose running image is not the configured
18131                    // program is refused once its exec is confirmed (see
18132                    // `record_write_stall_tests::sleeping_spec`).
18133                    program: "/bin/sleep".into(),
18134                    args: vec!["600".into()],
18135                    env: vec![],
18136                    reserved: false,
18137                    reserved_prefixes: vec![],
18138                    protocol: ModuleProtocol::None,
18139                    overlap: Default::default(),
18140                    carry_containment: false,
18141                },
18142                true,
18143                HealthConfig::default(),
18144                None,
18145                RestartPolicy::default(),
18146                DEFAULT_REGISTER_TIMEOUT,
18147            )
18148            .unwrap();
18149        let RegisteredConfiguredModule {
18150            mut spec,
18151            mut runtime,
18152            module,
18153            mut commands,
18154        } = registered;
18155        let snapshot = &module.inner.snapshot;
18156        let mut restart = Box::pin(module.restart(Some(0)));
18157        std::future::poll_fn(|cx| {
18158            assert!(std::future::Future::poll(restart.as_mut(), cx).is_pending());
18159            std::task::Poll::Ready(())
18160        })
18161        .await;
18162        // Drive the actor explicitly so a replacement is definitely spawned
18163        // after receipt, but before this queued command is dequeued.
18164        let mut child = Some(spawn_and_mark_running(&spec, &runtime, snapshot).unwrap());
18165        let replacement_pid = child.as_ref().unwrap().id();
18166        let command = commands.recv().await.unwrap();
18167        assert!(
18168            handle_supervisor_command(
18169                command,
18170                &mut spec,
18171                &mut runtime,
18172                &supervisor.registry,
18173                &supervisor.process_liveness,
18174                snapshot,
18175                &mut child,
18176                &mut commands,
18177                &mut VecDeque::new(),
18178            )
18179            .await
18180        );
18181        restart.await.unwrap();
18182        let kept_pid = child.as_ref().and_then(SupervisedChild::id);
18183        let pending = lock_snapshot(snapshot).unwrap().respawn_pending;
18184        if let Some(mut child) = child {
18185            child.start_kill().unwrap();
18186            child.wait().await.unwrap();
18187        }
18188        assert_eq!(
18189            kept_pid, replacement_pid,
18190            "a newer replacement must survive"
18191        );
18192        assert!(
18193            !pending,
18194            "a satisfied restart must not schedule another spawn"
18195        );
18196    }
18197}
18198
18199#[cfg(all(test, unix))]
18200mod health_event_tests {
18201    use super::*;
18202    use cortexkit_test_support::ScratchDir;
18203    use subc_protocol::{manifest::Concurrency, session::ModuleControlResponse};
18204
18205    struct Actor {
18206        module: SupervisedModule,
18207        registry: Arc<Registry>,
18208        forwarding: Arc<ForwardingTable>,
18209        spec: ModuleSpec,
18210        health: HealthConfig,
18211        rx: mpsc::Receiver<crate::router::OutboundFrame>,
18212        roster: ChildRoster,
18213        _home: ScratchDir,
18214    }
18215
18216    async fn wait_for<T>(reason: &str, mut observe: impl FnMut() -> Option<T>) -> T {
18217        // OS exec and socket readiness are real I/O. Stay runnable while waiting
18218        // for an observed condition, rather than letting paused time auto-advance
18219        // deadlines or assuming a fixed number of yields finishes the work.
18220        let deadline = std::time::Instant::now() + Duration::from_secs(10);
18221        let tick = Instant::now();
18222        loop {
18223            if let Some(value) = observe() {
18224                assert_eq!(Instant::now(), tick, "{reason} must not wait for a timer");
18225                return value;
18226            }
18227            assert!(
18228                std::time::Instant::now() < deadline,
18229                "timed out waiting for {reason}"
18230            );
18231            tokio::task::yield_now().await;
18232        }
18233    }
18234
18235    impl Actor {
18236        async fn start(protocol: ModuleProtocol, cadence: Duration) -> Self {
18237            Self::start_with_policy(
18238                protocol,
18239                cadence,
18240                DEFAULT_REGISTER_TIMEOUT,
18241                RestartPolicy::new(3, Duration::ZERO),
18242            )
18243            .await
18244        }
18245
18246        async fn start_with_policy(
18247            protocol: ModuleProtocol,
18248            cadence: Duration,
18249            register_timeout: Duration,
18250            policy: RestartPolicy,
18251        ) -> Self {
18252            let home = ScratchDir::new("health-events");
18253            let registry = Arc::new(Registry::default());
18254            let forwarding = Arc::new(ForwardingTable::default());
18255            let health = HealthConfig {
18256                cadence,
18257                deadline: Duration::from_secs(3600),
18258                ..HealthConfig::default()
18259            };
18260            let supervisor = Supervisor::new_for_test(registry.clone(), policy)
18261                .with_forwarding(forwarding.clone())
18262                .with_health_config(health.clone());
18263            let spec = ModuleSpec {
18264                script: None,
18265                module_id: "event-health-child".into(),
18266                // `/bin/sleep` itself, not `/bin/sh -c "exec sleep"`: on macOS
18267                // the privacy trampoline refuses a module whose running image
18268                // is not the configured program, and `start` below waits for
18269                // the process to be confirmed (`reported_pid`). The shell form
18270                // passed only while the image check ran before the shell had
18271                // replaced itself with `sleep` (see
18272                // `record_write_stall_tests::sleeping_spec`).
18273                program: PathBuf::from("/bin/sleep"),
18274                // The process stays alive but has no real bus peer. Registrations
18275                // below exercise the same registry writes as accepted HELLOs.
18276                args: vec!["600".into()],
18277                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
18278                    .into_iter()
18279                    .map(|key| (key.into(), home.path().display().to_string()))
18280                    .collect(),
18281                reserved: false,
18282                reserved_prefixes: vec![],
18283                protocol,
18284                overlap: Default::default(),
18285                carry_containment: false,
18286            };
18287            let module = supervisor
18288                .supervise_configured_requested(
18289                    spec.clone(),
18290                    true,
18291                    health.clone(),
18292                    Some(0),
18293                    policy,
18294                    register_timeout,
18295                    None,
18296                )
18297                .unwrap();
18298            let (_, rx) = mpsc::channel(8);
18299            let actor = Self {
18300                module,
18301                registry,
18302                forwarding,
18303                spec,
18304                health,
18305                rx,
18306                roster: supervisor.child_roster.clone(),
18307                _home: home,
18308            };
18309            actor
18310                .wait_for_select(|checkpoint| checkpoint.generation > 0)
18311                .await;
18312            actor
18313        }
18314
18315        async fn expire_registration_wait(&self, remaining: Duration) {
18316            tokio::time::advance(remaining).await;
18317            wait_for("registration timeout TERM grace", || {
18318                lock_snapshot(&self.module.inner.snapshot)
18319                    .unwrap()
18320                    .actor_select
18321                    .is_none()
18322                    .then_some(())
18323            })
18324            .await;
18325            tokio::time::advance(crate::child_roster::TERM_TO_KILL).await;
18326        }
18327
18328        fn turns(&self) -> u64 {
18329            lock_snapshot(&self.module.inner.snapshot)
18330                .unwrap()
18331                .actor_turns
18332        }
18333
18334        async fn wait_for_select(
18335            &self,
18336            expected: impl Fn(&ActorSelectCheckpoint) -> bool,
18337        ) -> ActorSelectCheckpoint {
18338            wait_for("actor select checkpoint", || {
18339                let state = lock_snapshot(&self.module.inner.snapshot).unwrap();
18340                state.actor_select.filter(|checkpoint| {
18341                    checkpoint.generation == state.spawn_generation
18342                        && state.state == ModuleState::Running
18343                        && state.process_alive
18344                        && state.reported_pid().is_some()
18345                        && expected(checkpoint)
18346                })
18347            })
18348            .await
18349        }
18350
18351        fn hello(&mut self, connection: u64, health: bool) {
18352            let manifest =
18353                subc_protocol::manifest::ModuleManifest::builder(&self.spec.module_id, "1.0.0")
18354                    .protocol_ver(subc_protocol::PROTOCOL_VERSION)
18355                    .build();
18356            let connection = ConnectionId::new(connection);
18357            let (tx, rx) = mpsc::channel(8);
18358            self.rx = rx;
18359            self.forwarding
18360                .register_module_connection(
18361                    connection,
18362                    self.spec.module_id.clone(),
18363                    subc_protocol::PROTOCOL_VERSION,
18364                    Concurrency::ModuleManaged,
18365                    FrameSink::new(tx),
18366                )
18367                .unwrap();
18368            self.registry
18369                .register_with_control_ops(
18370                    manifest,
18371                    subc_protocol::PROTOCOL_VERSION,
18372                    connection,
18373                    if health {
18374                        vec![MODULE_CONTROL_OP_HEALTH_CHECK.into()]
18375                    } else {
18376                        vec![]
18377                    },
18378                )
18379                .unwrap();
18380        }
18381
18382        async fn probe(&mut self) -> crate::router::OutboundFrame {
18383            let frame = wait_for("outbound health probe", || match self.rx.try_recv() {
18384                Ok(frame) => Some(frame),
18385                Err(mpsc::error::TryRecvError::Empty) => None,
18386                Err(mpsc::error::TryRecvError::Disconnected) => panic!("health peer disconnected"),
18387            })
18388            .await;
18389            let body: Value = serde_json::from_slice(&frame.body).unwrap();
18390            assert_eq!(body["op"], MODULE_CONTROL_OP_HEALTH_CHECK);
18391            frame
18392        }
18393
18394        fn no_probe(&mut self) {
18395            assert!(matches!(
18396                self.rx.try_recv(),
18397                Err(mpsc::error::TryRecvError::Empty)
18398            ));
18399        }
18400
18401        fn answer(&self, connection: u64, frame: crate::router::OutboundFrame) {
18402            self.forwarding
18403                .complete_module_control_rpc(
18404                    ConnectionId::new(connection),
18405                    frame.header.corr,
18406                    Some(MODULE_CONTROL_OP_HEALTH_CHECK),
18407                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
18408                        status: HealthStatus::Ok,
18409                        detail: None,
18410                        metrics: None,
18411                    }),
18412                )
18413                .unwrap();
18414        }
18415    }
18416
18417    #[tokio::test(start_paused = true)]
18418    async fn registration_timeout_kills_at_120_seconds_and_respawns() {
18419        let actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18420        let initial = actor.module.status().unwrap();
18421        tokio::time::advance(Duration::from_secs(119)).await;
18422        tokio::task::yield_now().await;
18423        assert_eq!(actor.module.status().unwrap().pid, initial.pid);
18424        assert!(actor.module.terminal_history().entries.is_empty());
18425        actor.expire_registration_wait(Duration::from_secs(1)).await;
18426        actor
18427            .wait_for_select(|at| at.generation > initial.spawn_generation)
18428            .await;
18429        let status = actor.module.status().unwrap();
18430        assert_ne!(status.pid, initial.pid);
18431        assert!(!cortexkit_test_support::process_alive(
18432            initial.pid.unwrap() as i32
18433        ));
18434        assert_eq!(status.restart_count, 1);
18435        assert_eq!(status.last_exit.unwrap().kind, ExitKind::Crash);
18436        let entries = actor.module.terminal_history().entries;
18437        assert_eq!(entries.len(), 1);
18438        assert_eq!(
18439            entries[0].disposition_detail.as_deref(),
18440            Some("registration_timeout")
18441        );
18442        actor.module.stop().await.unwrap();
18443    }
18444
18445    #[tokio::test(start_paused = true)]
18446    async fn registration_timeout_is_cancelled_by_hello_at_119_seconds() {
18447        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18448        let pid = actor.module.status().unwrap().pid;
18449        tokio::time::advance(Duration::from_secs(119)).await;
18450        actor.hello(1, false);
18451        let registered = actor
18452            .wait_for_select(|at| at.registered_connection.is_some())
18453            .await;
18454        assert_eq!(
18455            registered.wake_after, None,
18456            "HELLO must cancel the deadline"
18457        );
18458        tokio::time::advance(Duration::from_secs(300)).await;
18459        tokio::task::yield_now().await;
18460        assert_eq!(actor.module.status().unwrap().pid, pid);
18461        assert!(actor.module.terminal_history().entries.is_empty());
18462        // A disconnect after the first HELLO must not re-arm a startup timer.
18463        actor
18464            .registry
18465            .deregister_connection(ConnectionId::new(1))
18466            .unwrap();
18467        actor
18468            .wait_for_select(|at| at.registered_connection.is_none())
18469            .await;
18470        tokio::time::advance(Duration::from_secs(300)).await;
18471        tokio::task::yield_now().await;
18472        assert_eq!(actor.module.status().unwrap().pid, pid);
18473        assert!(actor.module.terminal_history().entries.is_empty());
18474        actor.module.stop().await.unwrap();
18475
18476        let mut transient = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18477        let pid = transient.module.status().unwrap().pid;
18478        tokio::time::advance(Duration::from_secs(119)).await;
18479        let turns = transient.turns();
18480        // Both writes happen before the supervisor can refresh the registry.
18481        // An accepted HELLO must remain evidence after its connection is gone.
18482        transient.hello(1, false);
18483        transient
18484            .registry
18485            .deregister_connection(ConnectionId::new(1))
18486            .unwrap();
18487        let parked = transient.wait_for_select(|at| at.turn > turns).await;
18488        assert_eq!(
18489            parked.wake_after, None,
18490            "transient HELLO must cancel the deadline"
18491        );
18492        tokio::time::advance(Duration::from_secs(300)).await;
18493        tokio::task::yield_now().await;
18494        assert_eq!(transient.module.status().unwrap().pid, pid);
18495        assert!(transient.module.terminal_history().entries.is_empty());
18496        transient.module.stop().await.unwrap();
18497    }
18498
18499    #[tokio::test(start_paused = true)]
18500    async fn registration_timeouts_exhaust_budget_and_schedule_slow_retry() {
18501        let actor = Actor::start_with_policy(
18502            ModuleProtocol::Subc,
18503            Duration::from_secs(30),
18504            Duration::from_secs(10),
18505            RestartPolicy::new(1, Duration::ZERO),
18506        )
18507        .await;
18508        let generation = actor.module.status().unwrap().spawn_generation;
18509        actor
18510            .expire_registration_wait(Duration::from_secs(10))
18511            .await;
18512        actor.wait_for_select(|at| at.generation > generation).await;
18513        actor
18514            .expire_registration_wait(Duration::from_secs(10))
18515            .await;
18516        let retry = wait_for("failed retry schedule", || {
18517            let state = lock_snapshot(&actor.module.inner.snapshot).unwrap();
18518            (state.state == ModuleState::Failed)
18519                .then_some(state.failed_retry.pending)
18520                .flatten()
18521        })
18522        .await;
18523        assert_eq!(retry.delay, Duration::from_secs(600));
18524        assert_eq!(retry.attempt, 1);
18525        let entries = actor.module.terminal_history().entries;
18526        assert_eq!(entries.len(), 2);
18527        assert_eq!(entries[1].disposition, TerminalDisposition::Failed);
18528        assert!(entries[1]
18529            .disposition_detail
18530            .as_deref()
18531            .unwrap()
18532            .contains("registration_timeout"));
18533        tokio::time::advance(Duration::from_secs(599)).await;
18534        tokio::task::yield_now().await;
18535        assert_eq!(actor.module.state().unwrap(), ModuleState::Failed);
18536        tokio::time::advance(Duration::from_secs(1)).await;
18537        actor
18538            .wait_for_select(|at| at.generation > generation + 1)
18539            .await;
18540        // The slow retry is another ordinary spawn, with its own HELLO budget.
18541        actor
18542            .expire_registration_wait(Duration::from_secs(10))
18543            .await;
18544        wait_for("slow retry registration timeout", || {
18545            (actor.module.terminal_history().entries.len() == 3).then_some(())
18546        })
18547        .await;
18548        actor.module.stop().await.unwrap();
18549    }
18550
18551    #[tokio::test(start_paused = true)]
18552    async fn registration_timeout_honours_ten_second_override() {
18553        let actor = Actor::start_with_policy(
18554            ModuleProtocol::Subc,
18555            Duration::from_secs(30),
18556            Duration::from_secs(10),
18557            RestartPolicy::new(3, Duration::ZERO),
18558        )
18559        .await;
18560        let generation = actor.module.status().unwrap().spawn_generation;
18561        tokio::time::advance(Duration::from_secs(9)).await;
18562        tokio::task::yield_now().await;
18563        assert!(actor.module.terminal_history().entries.is_empty());
18564        actor.expire_registration_wait(Duration::from_secs(1)).await;
18565        actor.wait_for_select(|at| at.generation > generation).await;
18566        assert_eq!(actor.module.terminal_history().entries.len(), 1);
18567        actor.module.stop().await.unwrap();
18568    }
18569
18570    #[tokio::test]
18571    async fn registration_timeout_kills_term_ignoring_helper_before_reaping_leader() {
18572        use std::os::unix::process::{CommandExt, ExitStatusExt};
18573
18574        struct Helper(std::process::Child);
18575        impl Drop for Helper {
18576            fn drop(&mut self) {
18577                // This handle still owns the helper until wait returns. Never
18578                // clean up its old process group after the leader is reaped.
18579                if matches!(self.0.try_wait(), Ok(None)) {
18580                    let _ = self.0.kill();
18581                    let _ = self.0.wait();
18582                }
18583            }
18584        }
18585
18586        let home = ScratchDir::new("registration-timeout-helper");
18587        let supervisor = Supervisor::new_for_test(
18588            Arc::new(Registry::default()),
18589            RestartPolicy::new(0, Duration::ZERO),
18590        );
18591        let spec = ModuleSpec {
18592            script: None,
18593            module_id: "registration-timeout-group".into(),
18594            program: "/bin/sleep".into(),
18595            args: vec!["120".into()],
18596            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
18597                .into_iter()
18598                .map(|key| (key.into(), home.path().display().to_string()))
18599                .collect(),
18600            reserved: false,
18601            reserved_prefixes: vec![],
18602            protocol: ModuleProtocol::Subc,
18603            overlap: Default::default(),
18604            carry_containment: false,
18605        };
18606        let module = supervisor
18607            .supervise_configured_requested(
18608                spec,
18609                true,
18610                HealthConfig::default(),
18611                None,
18612                RestartPolicy::new(0, Duration::ZERO),
18613                Duration::from_secs(10),
18614                None,
18615            )
18616            .unwrap();
18617        let leader = timeout(Duration::from_secs(5), async {
18618            loop {
18619                if let Some(pid) = module.status().unwrap().pid {
18620                    break pid;
18621                }
18622                sleep(Duration::from_millis(5)).await;
18623            }
18624        })
18625        .await
18626        .expect("supervised group leader must be reported before the deadline");
18627        assert!(leader > 1);
18628        let ready = home.join("helper.ready");
18629        // Own the helper separately so even a broken group kill can be cleaned
18630        // up by its own unreaped child handle, without signalling a stale pgid.
18631        let mut helper = Helper(
18632            std::process::Command::new("/bin/sh")
18633                .args([
18634                    "-c",
18635                    "trap '' TERM; : > \"$1\"; exec /bin/sleep 120",
18636                    "helper",
18637                ])
18638                .arg(&ready)
18639                .process_group(i32::try_from(leader).unwrap())
18640                .stdout(std::process::Stdio::null())
18641                .stderr(std::process::Stdio::null())
18642                .spawn()
18643                .unwrap(),
18644        );
18645        timeout(Duration::from_secs(5), async {
18646            while !ready.exists() {
18647                assert!(helper.0.try_wait().unwrap().is_none());
18648                sleep(Duration::from_millis(5)).await;
18649            }
18650        })
18651        .await
18652        .expect("helper must install TERM ignore before the registration deadline");
18653        let helper_pid =
18654            rustix::process::Pid::from_raw(i32::try_from(helper.0.id()).unwrap()).unwrap();
18655        rustix::process::kill_process(helper_pid, rustix::process::Signal::TERM).unwrap();
18656        sleep(Duration::from_millis(20)).await;
18657        assert!(
18658            helper.0.try_wait().unwrap().is_none(),
18659            "helper must ignore TERM"
18660        );
18661
18662        timeout(Duration::from_secs(20), async {
18663            while module.state().unwrap() != ModuleState::Failed {
18664                sleep(Duration::from_millis(5)).await;
18665            }
18666        })
18667        .await
18668        .expect("registration timeout must stop and reap the group leader");
18669        let helper_exit = timeout(Duration::from_secs(3), async {
18670            loop {
18671                if let Some(status) = helper.0.try_wait().unwrap() {
18672                    break status;
18673                }
18674                sleep(Duration::from_millis(5)).await;
18675            }
18676        })
18677        .await
18678        .expect("TERM-ignoring helper survived the registration timeout's group KILL");
18679        assert_eq!(helper_exit.signal(), Some(9));
18680        assert!(!cortexkit_test_support::process_alive(
18681            i32::try_from(leader).unwrap()
18682        ));
18683        assert_eq!(
18684            module.status().unwrap().last_exit.unwrap().kind,
18685            ExitKind::Crash
18686        );
18687        assert!(module.terminal_history().entries[0]
18688            .disposition_detail
18689            .as_deref()
18690            .unwrap()
18691            .contains("registration_timeout"));
18692        module.stop().await.unwrap();
18693    }
18694
18695    #[tokio::test(start_paused = true)]
18696    async fn registration_timeout_does_not_count_an_earlier_exit() {
18697        let actor = Actor::start_with_policy(
18698            ModuleProtocol::Subc,
18699            Duration::from_secs(30),
18700            DEFAULT_REGISTER_TIMEOUT,
18701            RestartPolicy::new(0, Duration::ZERO),
18702        )
18703        .await;
18704        let pid = actor.module.status().unwrap().pid.unwrap();
18705        rustix::process::kill_process(
18706            rustix::process::Pid::from_raw(pid as i32).unwrap(),
18707            rustix::process::Signal::TERM,
18708        )
18709        .unwrap();
18710        wait_for("early exit", || {
18711            (actor.module.state().unwrap() == ModuleState::Failed).then_some(())
18712        })
18713        .await;
18714        tokio::time::advance(Duration::from_secs(121)).await;
18715        tokio::task::yield_now().await;
18716        let entries = actor.module.terminal_history().entries;
18717        assert_eq!(entries.len(), 1);
18718        assert!(!entries[0]
18719            .disposition_detail
18720            .as_deref()
18721            .unwrap()
18722            .contains("registration_timeout"));
18723        assert_eq!(actor.module.status().unwrap().lifetime_restarts, 0);
18724        actor.module.stop().await.unwrap();
18725    }
18726
18727    #[tokio::test(start_paused = true)]
18728    async fn registration_timeout_is_cancelled_by_daemon_shutdown() {
18729        let actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18730        let pid = actor.module.status().unwrap().pid;
18731        tokio::time::advance(Duration::from_secs(119)).await;
18732        actor.roster.close();
18733        let turns = actor.turns();
18734        tokio::time::advance(Duration::from_secs(300)).await;
18735        let parked = actor.wait_for_select(|at| at.turn > turns).await;
18736        assert_eq!(parked.wake_after, None);
18737        assert_eq!(actor.module.status().unwrap().pid, pid);
18738        assert!(actor.module.terminal_history().entries.is_empty());
18739        actor.module.stop().await.unwrap();
18740        let status = actor.module.status().unwrap();
18741        assert_eq!(status.restart_count, 0);
18742        assert_eq!(
18743            actor.module.terminal_history().entries[0].disposition,
18744            TerminalDisposition::DaemonShutdown
18745        );
18746    }
18747
18748    #[tokio::test(start_paused = true)]
18749    async fn no_health_children_park_for_sixty_seconds() {
18750        let none = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
18751        let unregistered = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18752        let mut unadvertised = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18753        unadvertised.hello(1, false);
18754        // Include any one-off registration wake in the budget; receiving a
18755        // no-health HELLO must not turn a parked child into a polling child.
18756        // Advance in 10 ms steps so the old poll really executes ~6,000 turns;
18757        // a single 60 s jump would only observe one expired timer.
18758        for _ in 0..6000 {
18759            tokio::time::advance(Duration::from_millis(10)).await;
18760            tokio::task::yield_now().await;
18761        }
18762        for actor in [&none, &unregistered, &unadvertised] {
18763            assert!(
18764                actor.turns() <= 5,
18765                "no-health actor woke {} times",
18766                actor.turns()
18767            );
18768            assert_eq!(actor.module.state().unwrap(), ModuleState::Running);
18769        }
18770    }
18771
18772    #[tokio::test(start_paused = true)]
18773    async fn late_hello_starts_a_due_probe_in_the_notification_tick() {
18774        // With a zero cadence the first probe is due at once, so this measures
18775        // only how fast the registration notification starts health probing,
18776        // not the normal 30-33 s wait before a first probe (checked below).
18777        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::ZERO).await;
18778        let tick = Instant::now();
18779        actor.hello(1, true);
18780        actor.probe().await;
18781        assert_eq!(Instant::now(), tick, "HELLO must not wait for a poll");
18782    }
18783
18784    #[tokio::test(start_paused = true)]
18785    async fn hello_keeps_the_jittered_cadence_and_catalog_updates_do_not_reset_it() {
18786        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18787        let hello_tick = Instant::now();
18788        actor.hello(1, true);
18789        let armed = actor
18790            .wait_for_select(|checkpoint| {
18791                checkpoint.registered_connection == Some(ConnectionId::new(1))
18792                    && checkpoint.next_probe_at.is_some()
18793            })
18794            .await;
18795        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18796        assert!((Duration::from_secs(30)..Duration::from_secs(33)).contains(&delay));
18797        let first_deadline = hello_tick + delay;
18798        assert_eq!(armed.next_probe_at, Some(first_deadline));
18799        tokio::time::advance(Duration::from_secs(29)).await;
18800        let turns = actor.turns();
18801        actor
18802            .registry
18803            .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
18804            .unwrap();
18805        let updated = actor
18806            .wait_for_select(|checkpoint| checkpoint.turn > turns)
18807            .await;
18808        assert_eq!(
18809            updated.next_probe_at,
18810            Some(first_deadline),
18811            "catalog update must not reset cadence"
18812        );
18813        actor.no_probe();
18814        tokio::time::advance(first_deadline - Instant::now()).await;
18815        let frame = actor.probe().await;
18816        actor.answer(1, frame);
18817        let next = jittered_health_delay(&actor.spec.module_id, 1, actor.health.cadence);
18818        let next_deadline = Instant::now() + next;
18819        let rearmed = actor
18820            .wait_for_select(|checkpoint| {
18821                checkpoint
18822                    .next_probe_at
18823                    .is_some_and(|deadline| deadline > first_deadline)
18824            })
18825            .await;
18826        assert_eq!(rearmed.next_probe_at, Some(next_deadline));
18827        tokio::time::advance(next - Duration::from_nanos(1)).await;
18828        actor.no_probe();
18829        tokio::time::advance(Duration::from_nanos(1)).await;
18830        actor.probe().await;
18831    }
18832
18833    #[tokio::test(start_paused = true)]
18834    async fn disconnect_disarms_and_reconnect_rearms_health() {
18835        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18836        actor.hello(1, true);
18837        actor
18838            .wait_for_select(|checkpoint| {
18839                checkpoint.registered_connection == Some(ConnectionId::new(1))
18840                    && checkpoint.next_probe_at.is_some()
18841            })
18842            .await;
18843        let turns = actor.turns();
18844        let tick = Instant::now();
18845        actor
18846            .registry
18847            .deregister_connection(ConnectionId::new(1))
18848            .unwrap();
18849        let disarmed = actor
18850            .wait_for_select(|checkpoint| {
18851                checkpoint.turn > turns && checkpoint.registered_connection.is_none()
18852            })
18853            .await;
18854        assert_eq!(disarmed.next_probe_at, None);
18855        assert_eq!(disarmed.wake_after, None);
18856        assert_eq!(
18857            Instant::now(),
18858            tick,
18859            "disconnect must disarm in the notification tick"
18860        );
18861        tokio::time::advance(Duration::from_secs(60)).await;
18862        actor.no_probe();
18863        let reconnect_tick = Instant::now();
18864        actor.hello(2, true);
18865        let rearmed = actor
18866            .wait_for_select(|checkpoint| {
18867                checkpoint.registered_connection == Some(ConnectionId::new(2))
18868                    && checkpoint.next_probe_at.is_some()
18869            })
18870            .await;
18871        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18872        assert_eq!(rearmed.next_probe_at, Some(reconnect_tick + delay));
18873        tokio::time::advance(delay).await;
18874        actor.probe().await;
18875    }
18876
18877    #[tokio::test(start_paused = true)]
18878    async fn reregistration_without_health_disarms_the_old_schedule() {
18879        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18880        actor.hello(1, true);
18881        actor
18882            .wait_for_select(|checkpoint| {
18883                checkpoint.registered_connection == Some(ConnectionId::new(1))
18884                    && checkpoint.next_probe_at.is_some()
18885            })
18886            .await;
18887        actor
18888            .registry
18889            .deregister_connection(ConnectionId::new(1))
18890            .unwrap();
18891        actor.hello(2, false);
18892        let disarmed = actor
18893            .wait_for_select(|checkpoint| {
18894                checkpoint.registered_connection == Some(ConnectionId::new(2))
18895            })
18896            .await;
18897        assert_eq!(disarmed.next_probe_at, None);
18898        assert_eq!(disarmed.wake_after, None);
18899        tokio::time::advance(Duration::from_secs(60)).await;
18900        actor.no_probe();
18901    }
18902
18903    #[tokio::test(start_paused = true)]
18904    async fn restart_waits_for_its_own_hello_before_rearming_health() {
18905        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18906        actor.hello(1, true);
18907        let armed = actor
18908            .wait_for_select(|checkpoint| {
18909                checkpoint.registered_connection == Some(ConnectionId::new(1))
18910                    && checkpoint.next_probe_at.is_some()
18911            })
18912            .await;
18913        // Simulate the old process's connection closing before the restart
18914        // tears the process down. The replacement process has started but has
18915        // not sent its HELLO, so it is not registered.
18916        actor
18917            .registry
18918            .deregister_connection(ConnectionId::new(1))
18919            .unwrap();
18920        actor.module.restart(Some(0)).await.unwrap();
18921        let parked = actor
18922            .wait_for_select(|checkpoint| {
18923                checkpoint.generation > armed.generation
18924                    && checkpoint.registered_connection.is_none()
18925                    && checkpoint.next_probe_at.is_none()
18926            })
18927            .await;
18928        assert_eq!(parked.wake_after, Some(DEFAULT_REGISTER_TIMEOUT));
18929        actor.rx.close();
18930        // Drain the stop notice the restart queued for the old process's connection,
18931        // so it isn't mistaken for traffic to the replacement.
18932        while actor.rx.try_recv().is_ok() {}
18933        let turns = actor.turns();
18934        tokio::time::advance(Duration::from_secs(60)).await;
18935        let after = actor.turns();
18936        eprintln!(
18937            "restart park turns: before={turns} after={after} delta={}",
18938            after - turns
18939        );
18940        assert_eq!(after, turns, "replacement must park before HELLO");
18941        let hello_tick = Instant::now();
18942        actor.hello(2, true);
18943        let rearmed = actor
18944            .wait_for_select(|checkpoint| {
18945                checkpoint.registered_connection == Some(ConnectionId::new(2))
18946                    && checkpoint.next_probe_at.is_some()
18947            })
18948            .await;
18949        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18950        assert_eq!(rearmed.next_probe_at, Some(hello_tick + delay));
18951        tokio::time::advance(delay).await;
18952        actor.probe().await;
18953    }
18954
18955    #[tokio::test(start_paused = true)]
18956    async fn http_probe_waits_a_full_cadence_for_each_spawn() {
18957        use tokio::{
18958            io::{AsyncReadExt, AsyncWriteExt},
18959            net::TcpListener,
18960        };
18961        let mut actor = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
18962        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
18963        actor.health.http = Some(format!("http://{}/healthz", listener.local_addr().unwrap()));
18964        let (started_tx, mut started_rx) = mpsc::channel(8);
18965        let peer = tokio::spawn(async move {
18966            loop {
18967                let (mut socket, _) = listener.accept().await.unwrap();
18968                let mut request = [0; 1024];
18969                assert!(socket.read(&mut request).await.unwrap() > 0);
18970                started_tx.send(Instant::now()).await.unwrap();
18971                socket
18972                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
18973                    .await
18974                    .unwrap();
18975            }
18976        });
18977        actor
18978            .module
18979            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
18980            .await
18981            .unwrap();
18982        let first_tick = Instant::now();
18983        let first = actor
18984            .wait_for_select(|checkpoint| checkpoint.next_probe_at.is_some())
18985            .await;
18986        assert!(first.next_probe_at.unwrap() >= first_tick + actor.health.cadence);
18987        assert!(started_rx.try_recv().is_err());
18988
18989        // Restart just before the old deadline: reusing it would give the new
18990        // process only one second to start, rather than a full cadence.
18991        tokio::time::advance(
18992            first.next_probe_at.unwrap() - Instant::now() - Duration::from_secs(1),
18993        )
18994        .await;
18995        actor.module.restart(Some(0)).await.unwrap();
18996        let spawn_tick = Instant::now();
18997        let replacement = actor
18998            .wait_for_select(|checkpoint| checkpoint.generation > first.generation)
18999            .await;
19000        let deadline = replacement.next_probe_at.unwrap();
19001        assert!(
19002            deadline >= spawn_tick + actor.health.cadence,
19003            "a replacement must not inherit its predecessor's probe deadline"
19004        );
19005        tokio::time::advance(actor.health.cadence - Duration::from_nanos(1)).await;
19006        assert!(
19007            started_rx.try_recv().is_err(),
19008            "no HTTP probe during startup grace"
19009        );
19010        tokio::time::advance(deadline - Instant::now()).await;
19011        let landed = wait_for("first replacement HTTP probe", || {
19012            started_rx.try_recv().ok()
19013        })
19014        .await;
19015        assert!(landed >= spawn_tick + actor.health.cadence);
19016        wait_for("healthy replacement", || {
19017            (actor.module.status().unwrap().health.status == SupervisorHealthStatus::Ok)
19018                .then_some(())
19019        })
19020        .await;
19021        peer.abort();
19022    }
19023
19024    #[tokio::test(start_paused = true)]
19025    async fn rescan_adds_and_removes_http_health_without_polling() {
19026        use tokio::{
19027            io::{AsyncReadExt, AsyncWriteExt},
19028            net::TcpListener,
19029        };
19030        let mut actor = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
19031        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
19032        actor.health.http = Some(format!("http://{}/health", listener.local_addr().unwrap()));
19033        // One millisecond separates successive probes without a polling delay.
19034        actor.health.cadence = Duration::from_millis(1);
19035        let (started_tx, mut started_rx) = mpsc::channel(8);
19036        let peer = tokio::spawn(async move {
19037            loop {
19038                let (mut socket, _) = listener.accept().await.unwrap();
19039                let mut request = [0; 1024];
19040                assert!(socket.read(&mut request).await.unwrap() > 0);
19041                started_tx.send(()).await.unwrap();
19042                socket
19043                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
19044                    .await
19045                    .unwrap();
19046            }
19047        });
19048        let tick = Instant::now();
19049        let turns = actor.turns();
19050        actor
19051            .module
19052            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
19053            .await
19054            .unwrap();
19055        let armed = actor
19056            .wait_for_select(|checkpoint| {
19057                checkpoint.turn > turns && checkpoint.next_probe_at.is_some()
19058            })
19059            .await;
19060        assert_eq!(armed.next_probe_at, Some(tick + Duration::from_millis(1)));
19061        assert_eq!(Instant::now(), tick);
19062        tokio::time::advance(Duration::from_millis(1)).await;
19063        let mut started = false;
19064        wait_for("successful HTTP probe", || {
19065            started |= started_rx.try_recv().is_ok();
19066            (started && actor.module.status().unwrap().health.status == SupervisorHealthStatus::Ok)
19067                .then_some(())
19068        })
19069        .await;
19070        assert!(started, "added HTTP check must start at its first deadline");
19071        assert_eq!(
19072            actor.module.status().unwrap().health.status,
19073            SupervisorHealthStatus::Ok
19074        );
19075        assert_eq!(Instant::now(), tick + Duration::from_millis(1));
19076        actor.health.http = None;
19077        let turns = actor.turns();
19078        actor
19079            .module
19080            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
19081            .await
19082            .unwrap();
19083        let parked = actor
19084            .wait_for_select(|checkpoint| {
19085                checkpoint.turn > turns && checkpoint.next_probe_at.is_none()
19086            })
19087            .await;
19088        assert_eq!(parked.wake_after, None);
19089        let turns = actor.turns();
19090        tokio::time::advance(Duration::from_secs(60)).await;
19091        assert_eq!(
19092            actor.turns(),
19093            turns,
19094            "removed HTTP check must park the actor"
19095        );
19096        assert!(
19097            started_rx.try_recv().is_err(),
19098            "removed HTTP check must stay disarmed"
19099        );
19100        assert_eq!(
19101            actor.module.status().unwrap().health,
19102            ModuleHealthStatus::default()
19103        );
19104        peer.abort();
19105    }
19106}
19107
19108#[cfg(test)]
19109mod drain_busy_reprobe_tests {
19110    //! The drain's busy-gauge wait, driven against an in-process module
19111    //! connection whose health answers the test scripts. Time is paused, so
19112    //! every elapsed duration below is exact virtual time.
19113    use super::*;
19114    use std::collections::BTreeMap;
19115    use std::sync::Mutex as StdMutex;
19116    use subc_protocol::{manifest::Concurrency, session::ModuleControlResponse};
19117
19118    const MODULE_ID: &str = "drain-reprobe-module";
19119    const CONNECTION: u64 = 7;
19120    const GAUGE: &str = "runs_in_flight";
19121    /// The production default for both the health cadence and the drain
19122    /// ceiling, which is the pairing that used to cost a full ceiling.
19123    const CADENCE: Duration = Duration::from_secs(30);
19124    const CEILING: Duration = Duration::from_secs(30);
19125
19126    /// How the scripted module answers each `health.check`.
19127    #[derive(Clone, Copy)]
19128    enum Answer {
19129        /// Report the gauge busy until this instant, quiet from then on, after
19130        /// taking `latency` to answer.
19131        BusyUntil { until: Instant, latency: Duration },
19132        /// Answer at once, with metrics that leave the declared gauge out.
19133        OmitsGauge,
19134        /// Never answer.
19135        Silent,
19136    }
19137
19138    struct Drain {
19139        forwarding: Arc<ForwardingTable>,
19140        runtime: SupervisorRuntimeConfig,
19141        endpoint: crate::ModuleEndpointId,
19142        /// When each probe reached the module.
19143        probes: Arc<StdMutex<Vec<Instant>>>,
19144        responder: tokio::task::JoinHandle<()>,
19145    }
19146
19147    impl Drain {
19148        fn start(answer: Answer) -> Self {
19149            let registry = Arc::new(Registry::default());
19150            let forwarding = Arc::new(ForwardingTable::default());
19151            let health = HealthConfig {
19152                cadence: CADENCE,
19153                ..HealthConfig::default()
19154            };
19155            let runtime = Supervisor::new_for_test(registry, RestartPolicy::new(3, Duration::ZERO))
19156                .with_forwarding(forwarding.clone())
19157                .with_health_config(health)
19158                .runtime_config();
19159            let (tx, mut rx) = mpsc::channel::<crate::router::OutboundFrame>(8);
19160            let endpoint = forwarding
19161                .register_module_connection(
19162                    ConnectionId::new(CONNECTION),
19163                    MODULE_ID.to_string(),
19164                    subc_protocol::PROTOCOL_VERSION,
19165                    Concurrency::ModuleManaged,
19166                    FrameSink::new(tx),
19167                )
19168                .unwrap();
19169            let probes = Arc::new(StdMutex::new(Vec::new()));
19170            let responder = tokio::spawn({
19171                let forwarding = forwarding.clone();
19172                let probes = probes.clone();
19173                async move {
19174                    while let Some(frame) = rx.recv().await {
19175                        let body: Value = serde_json::from_slice(&frame.body).unwrap();
19176                        assert_eq!(body["op"], MODULE_CONTROL_OP_HEALTH_CHECK);
19177                        probes.lock().unwrap().push(Instant::now());
19178                        let metrics = match answer {
19179                            Answer::BusyUntil { until, latency } => {
19180                                sleep(latency).await;
19181                                let busy = u64::from(Instant::now() < until);
19182                                serde_json::json!({ GAUGE: busy })
19183                            }
19184                            Answer::OmitsGauge => serde_json::json!({ "queue_depth": 0 }),
19185                            Answer::Silent => continue,
19186                        };
19187                        // A probe abandoned at its deadline has no RPC left to
19188                        // complete, so a late answer may be refused.
19189                        let _ = forwarding.complete_module_control_rpc(
19190                            ConnectionId::new(CONNECTION),
19191                            frame.header.corr,
19192                            Some(MODULE_CONTROL_OP_HEALTH_CHECK),
19193                            ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19194                                status: HealthStatus::Ok,
19195                                detail: None,
19196                                metrics: Some(metrics),
19197                            }),
19198                        );
19199                    }
19200                }
19201            });
19202            Self {
19203                forwarding,
19204                runtime,
19205                endpoint,
19206                probes,
19207                responder,
19208            }
19209        }
19210
19211        /// Run one by-id drain wait with `ceiling`, returning its verdict and
19212        /// how long it took.
19213        async fn run(&self, ceiling: Duration) -> (bool, Duration) {
19214            let (drained, elapsed, _) = self.run_traced(ceiling).await;
19215            (drained, elapsed)
19216        }
19217
19218        /// [`Self::run`], also returning what the drain's probes read.
19219        async fn run_traced(&self, ceiling: Duration) -> (bool, Duration, DrainGaugeTrace) {
19220            let started = Instant::now();
19221            let mut trace = DrainGaugeTrace::new(&[GAUGE.to_string()]);
19222            let drained = wait_for_forwarding_quiescence(
19223                &self.forwarding,
19224                MODULE_ID,
19225                &self.runtime,
19226                self.endpoint,
19227                started + ceiling,
19228                &[GAUGE.to_string()],
19229                DrainScope::Active,
19230                &mut trace,
19231            )
19232            .await
19233            .unwrap();
19234            (drained, started.elapsed(), trace)
19235        }
19236
19237        fn probes(&self) -> Vec<Instant> {
19238            self.probes.lock().unwrap().clone()
19239        }
19240    }
19241
19242    impl Drop for Drain {
19243        fn drop(&mut self) {
19244            self.responder.abort();
19245        }
19246    }
19247
19248    #[tokio::test(start_paused = true)]
19249    async fn busy_at_first_probe_then_quiet_drains_long_before_the_ceiling() {
19250        let drain = Drain::start(Answer::BusyUntil {
19251            until: Instant::now() + Duration::from_secs(1),
19252            latency: Duration::ZERO,
19253        });
19254        let (drained, elapsed) = drain.run(CEILING).await;
19255        assert!(
19256            drained,
19257            "gauges that read zero during the drain must let it finish drained, \
19258             not wait out the {CADENCE:?} health cadence (elapsed {elapsed:?})"
19259        );
19260        assert!(
19261            elapsed < Duration::from_secs(3),
19262            "drain took {elapsed:?} after the gauges went quiet at 1s"
19263        );
19264        let probes = drain.probes();
19265        assert!(
19266            probes.len() >= 2,
19267            "the module was busy at the first probe, so a quiet verdict needs a second: {probes:?}"
19268        );
19269    }
19270
19271    /// The same shape in real time on a multi-threaded runtime: the first
19272    /// probe is answered busy at once, within a millisecond of the drain
19273    /// starting, and later probes read idle. The drain must keep probing
19274    /// after that first instant answer and end soon after the gauge falls.
19275    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
19276    async fn an_instant_busy_first_answer_does_not_stop_later_probes_in_real_time() {
19277        let drain = Drain::start(Answer::BusyUntil {
19278            until: Instant::now() + Duration::from_millis(600),
19279            latency: Duration::ZERO,
19280        });
19281        let (drained, elapsed, trace) = drain.run_traced(CEILING).await;
19282        assert!(drained, "the gauge fell at 600ms: {trace}");
19283        assert!(
19284            elapsed < Duration::from_secs(3),
19285            "drain took {elapsed:?} after the gauge fell at 600ms: {trace}"
19286        );
19287        let probes = drain.probes();
19288        assert!(
19289            probes.len() >= 2 && trace.probes as usize == probes.len(),
19290            "the drain must re-probe after the first busy answer: {probes:?}, {trace}"
19291        );
19292    }
19293
19294    #[tokio::test(start_paused = true)]
19295    async fn busy_throughout_ends_undrained_at_the_ceiling_with_bounded_probes() {
19296        let started = Instant::now();
19297        let drain = Drain::start(Answer::BusyUntil {
19298            until: started + Duration::from_secs(3600),
19299            latency: Duration::ZERO,
19300        });
19301        let (drained, elapsed) = drain.run(CEILING).await;
19302        assert!(!drained, "a module busy throughout must not drain");
19303        assert!(
19304            elapsed >= CEILING && elapsed < CEILING + drain_busy_reprobe_interval(),
19305            "a busy module is held until the ceiling and no longer: {elapsed:?}"
19306        );
19307        // Re-probing is paced by the interval, not a busy loop: at most one
19308        // probe per interval across the ceiling, plus the first at time zero.
19309        let probes = drain.probes();
19310        let max_probes = (CEILING.as_millis() / drain_busy_reprobe_interval().as_millis()) + 1;
19311        assert!(
19312            probes.len() as u128 <= max_probes,
19313            "{} probes in a {CEILING:?} drain exceeds the {max_probes} the interval allows",
19314            probes.len()
19315        );
19316        for pair in probes.windows(2) {
19317            assert!(
19318                pair[1] - pair[0] >= drain_busy_reprobe_interval(),
19319                "consecutive probes {:?} apart",
19320                pair[1] - pair[0]
19321            );
19322        }
19323    }
19324
19325    #[tokio::test(start_paused = true)]
19326    async fn a_slow_probe_is_never_overlapped_by_the_next() {
19327        // Each answer takes longer than the re-probe interval; the next probe
19328        // must wait for the previous answer and then the interval.
19329        let latency = Duration::from_secs(1);
19330        let drain = Drain::start(Answer::BusyUntil {
19331            until: Instant::now() + Duration::from_secs(3600),
19332            latency,
19333        });
19334        let (drained, _) = drain.run(Duration::from_secs(5)).await;
19335        assert!(!drained);
19336        let probes = drain.probes();
19337        assert!(probes.len() >= 2, "the drain must re-probe: {probes:?}");
19338        for pair in probes.windows(2) {
19339            assert!(
19340                pair[1] - pair[0] >= latency + drain_busy_reprobe_interval(),
19341                "a probe started {:?} after the previous one, before it could finish",
19342                pair[1] - pair[0]
19343            );
19344        }
19345    }
19346
19347    #[tokio::test(start_paused = true)]
19348    async fn an_unanswered_probe_cannot_hold_the_drain_past_its_ceiling() {
19349        let drain = Drain::start(Answer::Silent);
19350        let ceiling = Duration::from_secs(2);
19351        let (drained, elapsed) = drain.run(ceiling).await;
19352        assert!(!drained, "an unanswered probe counts as busy");
19353        assert!(
19354            elapsed >= ceiling && elapsed < ceiling + drain_busy_reprobe_interval(),
19355            "the probe deadline is capped at the drain ceiling: {elapsed:?}"
19356        );
19357        assert_eq!(
19358            drain.probes().len(),
19359            1,
19360            "the unanswered probe holds the only slot until the ceiling"
19361        );
19362    }
19363
19364    /// Every event logged while it is installed, as `message` plus fields.
19365    #[derive(Clone, Default)]
19366    struct LogCapture {
19367        events: Arc<StdMutex<Vec<BTreeMap<String, String>>>>,
19368    }
19369
19370    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for LogCapture {
19371        fn on_event(
19372            &self,
19373            event: &tracing::Event<'_>,
19374            _context: tracing_subscriber::layer::Context<'_, S>,
19375        ) {
19376            struct Fields(BTreeMap<String, String>);
19377            impl tracing::field::Visit for Fields {
19378                fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
19379                    self.0
19380                        .insert(field.name().to_string(), format!("{value:?}"));
19381                }
19382            }
19383            let mut fields = Fields(BTreeMap::new());
19384            event.record(&mut fields);
19385            self.events.lock().unwrap().push(fields.0);
19386        }
19387    }
19388
19389    impl LogCapture {
19390        fn install(&self) -> tracing::subscriber::DefaultGuard {
19391            use tracing_subscriber::layer::SubscriberExt;
19392            tracing::subscriber::set_default(tracing_subscriber::registry().with(self.clone()))
19393        }
19394
19395        fn with_message(&self, needle: &str) -> Vec<BTreeMap<String, String>> {
19396            self.events
19397                .lock()
19398                .unwrap()
19399                .iter()
19400                .filter(|fields| fields.get("message").is_some_and(|m| m.contains(needle)))
19401                .cloned()
19402                .collect()
19403        }
19404    }
19405
19406    /// A module that declares a busy gauge but leaves it out of its health
19407    /// answers holds a drain to its ceiling. The timeout line must say so by
19408    /// name, and the drain must warn about the missing gauge once, not on
19409    /// every probe.
19410    #[tokio::test(start_paused = true)]
19411    async fn a_missing_declared_gauge_is_named_on_the_drain_timeout_line() {
19412        let capture = LogCapture::default();
19413        let _guard = capture.install();
19414        let drain = Drain::start(Answer::OmitsGauge);
19415        let (drained, _, trace) = drain.run_traced(Duration::from_secs(2)).await;
19416        assert!(!drained, "a gauge never reported cannot read quiet");
19417        assert!(trace.probes >= 2, "the drain must re-probe: {trace:?}");
19418
19419        let missing = capture.with_message("lacks a declared busy gauge");
19420        assert_eq!(missing.len(), 1, "one warning per drain: {missing:?}");
19421        assert_eq!(
19422            missing[0].get("missing_gauges").map(String::as_str),
19423            Some(GAUGE)
19424        );
19425
19426        warn_drain_timed_out(
19427            MODULE_ID,
19428            Duration::from_secs(2),
19429            RouteCloseReason::Restart,
19430            &Default::default(),
19431            &trace,
19432        );
19433        let timeouts = capture.with_message("route drain timed out");
19434        assert_eq!(timeouts.len(), 1, "{timeouts:?}");
19435        let gauges = &timeouts[0]["busy_gauges"];
19436        assert!(
19437            gauges.starts_with(&format!("{GAUGE}: missing_from_health_body @")),
19438            "the timeout line must name the gauge and why it read busy: {gauges}"
19439        );
19440        assert!(
19441            gauges.ends_with("; no value ever read"),
19442            "no value was ever read for the gauge: {gauges}"
19443        );
19444        assert_eq!(timeouts[0]["gauge_probes"], trace.probes.to_string());
19445    }
19446
19447    /// The trace names a busy value and when it was read. For a probe that
19448    /// never got an answer, it names the probe's error kind and says that no
19449    /// value was ever read.
19450    #[tokio::test(start_paused = true)]
19451    async fn the_drain_trace_names_a_busy_value_and_an_unanswered_probe() {
19452        let busy = Drain::start(Answer::BusyUntil {
19453            until: Instant::now() + Duration::from_secs(3600),
19454            latency: Duration::ZERO,
19455        });
19456        let (_, _, trace) = busy.run_traced(Duration::from_secs(1)).await;
19457        let rendered = trace.to_string();
19458        assert!(
19459            rendered.starts_with(&format!("{GAUGE}: non_zero(1) @"))
19460                && rendered.contains("; last value non_zero(1) @"),
19461            "{rendered}"
19462        );
19463
19464        let silent = Drain::start(Answer::Silent);
19465        let (_, _, trace) = silent.run_traced(Duration::from_secs(1)).await;
19466        // The probe is capped at the 1 s ceiling, and its reading is stamped
19467        // when it gave up.
19468        assert_eq!(
19469            trace.to_string(),
19470            format!("{GAUGE}: probe_failed(no-answer) @1000ms; no value ever read")
19471        );
19472        assert_eq!(trace.probes, 1);
19473    }
19474
19475    /// A gauge value that is not a count reads busy and is shown as sent.
19476    #[test]
19477    fn a_gauge_that_is_not_a_count_is_busy_and_shown_as_sent() {
19478        let gauges = [GAUGE.to_string()];
19479        let verdicts = gauge_verdicts(Some(&serde_json::json!({ GAUGE: 0.0 })), &gauges);
19480        assert_eq!(verdicts, vec![GaugeVerdict::NotACount("0.0".to_string())]);
19481        assert_eq!(
19482            busy_gauge_observation(&verdicts),
19483            BusyGaugeObservation::Busy
19484        );
19485        let zero = gauge_verdicts(Some(&serde_json::json!({ GAUGE: 0 })), &gauges);
19486        assert_eq!(
19487            busy_gauge_observation(&zero),
19488            BusyGaugeObservation::Quiescent
19489        );
19490        let none = gauge_verdicts(None, &gauges);
19491        assert_eq!(busy_gauge_observation(&none), BusyGaugeObservation::Omitted);
19492    }
19493}
19494
19495#[cfg(test)]
19496mod health_evidence_tests {
19497    use super::{HealthProbeError, HealthProbeEvidence};
19498    use std::collections::HashSet;
19499
19500    /// The evidential asymmetry, asserted rather than described.
19501    ///
19502    /// Exactly ONE observation is proof a module cannot serve, and the one that
19503    /// fires under CPU starvation is not it. Before the split, all fifteen
19504    /// construction sites collapsed into a single String, so a timeout carried the
19505    /// same weight as a dead lane -- which is how a healthy module was restarted
19506    /// three times in one day.
19507    #[test]
19508    fn only_a_dead_lane_is_proof_of_death() {
19509        assert!(HealthProbeError::lane_dead("gone").is_proof_of_death());
19510        // Three non-proof classes, each for a different reason: silence is
19511        // consistent with health, a bad answer proves the module ALIVE, and a
19512        // daemon-side fault never reached the module at all.
19513        assert!(!HealthProbeError::no_answer("timed out").is_proof_of_death());
19514        assert!(!HealthProbeError::bad_answer("garbage").is_proof_of_death());
19515        assert!(!HealthProbeError::misconfigured("no table").is_proof_of_death());
19516    }
19517
19518    /// Labels must be distinct, or the operator-facing distinction is cosmetic.
19519    ///
19520    /// A shared label renders two different observations identically in the line an
19521    /// operator reads after an unexplained restart -- the exact confusion this
19522    /// change removes.
19523    #[test]
19524    fn every_evidence_class_has_a_distinct_label() {
19525        let labels = [
19526            HealthProbeError::lane_dead("").label(),
19527            HealthProbeError::no_answer("").label(),
19528            HealthProbeError::bad_answer("").label(),
19529            HealthProbeError::misconfigured("").label(),
19530        ];
19531        let unique: HashSet<_> = labels.iter().collect();
19532        assert_eq!(unique.len(), labels.len(), "labels collided: {labels:?}");
19533    }
19534
19535    /// The class is additional information, not a replacement.
19536    ///
19537    /// An operator needs both "this was silence" and the specific text saying how
19538    /// long we waited; a classification that swallowed the message would trade one
19539    /// missing distinction for another.
19540    #[test]
19541    fn classification_preserves_the_original_message() {
19542        let err = HealthProbeError::no_answer("module did not answer within 5s");
19543        assert_eq!(err.to_string(), "module did not answer within 5s");
19544        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19545    }
19546}
19547
19548#[cfg(test)]
19549mod health_tombstone_tests {
19550    use std::{path::PathBuf, sync::Arc, time::Duration};
19551
19552    use subc_protocol::{
19553        manifest::Concurrency,
19554        session::{HealthStatus, ModuleControlResponse},
19555    };
19556    use tokio::sync::mpsc;
19557
19558    use super::{
19559        probe_module_health, HealthAction, HealthConfig, HealthProbeEvidence, ModuleProtocol,
19560        ModuleSpec, RestartPolicy, Supervisor, SupervisorRuntimeConfig,
19561    };
19562    use crate::{
19563        control::ControlHandler,
19564        forwarding::{ForwardingTable, ModuleControlRpcCompletion, ModuleControlRpcOutcome},
19565        registry::{ConnectionId, Registry},
19566        router::FrameSink,
19567    };
19568
19569    struct ProbeHarness {
19570        spec: ModuleSpec,
19571        runtime: SupervisorRuntimeConfig,
19572        forwarding: Arc<ForwardingTable>,
19573        module_connection: ConnectionId,
19574        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19575        handler: ControlHandler,
19576        module: super::SupervisedModule,
19577    }
19578
19579    fn probe_harness() -> ProbeHarness {
19580        let registry = Arc::new(Registry::default());
19581        let forwarding = Arc::new(ForwardingTable::default());
19582        let supervisor_handle = super::SupervisorHandle::new();
19583        let health = HealthConfig {
19584            http: None,
19585            cadence: Duration::from_secs(30),
19586            deadline: Duration::from_secs(5),
19587            failure_threshold: 3,
19588            on_degraded: HealthAction::Report,
19589            on_failing: HealthAction::Report,
19590            critical: false,
19591        };
19592        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
19593            .with_forwarding(Arc::clone(&forwarding))
19594            .with_handle(supervisor_handle.clone())
19595            .with_health_config(health);
19596        let spec = ModuleSpec {
19597            script: None,
19598            module_id: "late-health-module".to_string(),
19599            program: PathBuf::from("disabled-module"),
19600            args: Vec::new(),
19601            env: Vec::new(),
19602            reserved: false,
19603            reserved_prefixes: Vec::new(),
19604            protocol: ModuleProtocol::Subc,
19605            overlap: Default::default(),
19606            carry_containment: false,
19607        };
19608        let module = supervisor
19609            .supervise_configured(spec.clone(), false)
19610            .unwrap();
19611        let runtime = supervisor.runtime_config();
19612        let handler = ControlHandler::with_forwarding(registry, Arc::clone(&forwarding))
19613            .with_supervisor(supervisor_handle);
19614        let module_connection = ConnectionId::new(700);
19615        let (module_tx, module_rx) = mpsc::channel(8);
19616        forwarding
19617            .register_module_connection(
19618                module_connection,
19619                spec.module_id.clone(),
19620                subc_protocol::PROTOCOL_VERSION,
19621                Concurrency::ModuleManaged,
19622                FrameSink::new(module_tx),
19623            )
19624            .unwrap();
19625
19626        ProbeHarness {
19627            spec,
19628            runtime,
19629            forwarding,
19630            module_connection,
19631            module_rx,
19632            handler,
19633            module,
19634        }
19635    }
19636
19637    async fn finish_after(
19638        harness: &mut ProbeHarness,
19639        stall: Duration,
19640    ) -> ModuleControlRpcCompletion {
19641        assert!(stall > harness.runtime.health.deadline);
19642        let deadline = harness.runtime.health.deadline;
19643        let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
19644        let answer = async {
19645            let frame = harness.module_rx.recv().await.expect("health.check frame");
19646            tokio::time::advance(deadline).await;
19647            tokio::task::yield_now().await;
19648            tokio::time::advance(stall - deadline).await;
19649            harness
19650                .forwarding
19651                .complete_module_control_rpc(
19652                    harness.module_connection,
19653                    frame.header.corr,
19654                    Some("health.check"),
19655                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19656                        status: HealthStatus::Ok,
19657                        detail: None,
19658                        metrics: None,
19659                    }),
19660                )
19661                .unwrap()
19662        };
19663        let (probe_result, completion) = tokio::join!(probe, answer);
19664        let err = probe_result.expect_err("probe must miss its deadline");
19665        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19666        completion
19667    }
19668
19669    async fn time_out_without_answer(harness: &mut ProbeHarness) {
19670        let deadline = harness.runtime.health.deadline;
19671        let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
19672        let exhaust_deadline = async {
19673            let _frame = harness.module_rx.recv().await.expect("health.check frame");
19674            tokio::time::advance(deadline).await;
19675            tokio::task::yield_now().await;
19676        };
19677        let (probe_result, ()) = tokio::join!(probe, exhaust_deadline);
19678        let err = probe_result.expect_err("probe must miss its deadline");
19679        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19680    }
19681
19682    async fn run_probe_cycle(harness: &mut ProbeHarness, answer: bool) {
19683        let registry = Arc::clone(&harness.module.inner.registry);
19684        let snapshot = Arc::clone(&harness.module.inner.snapshot);
19685        let process_liveness = super::SupervisorProcessLiveness::default();
19686        let mut child = None;
19687        let cycle = super::run_health_probe_cycle(
19688            &harness.spec,
19689            &harness.runtime,
19690            &registry,
19691            &process_liveness,
19692            &snapshot,
19693            &mut child,
19694        );
19695        let peer = async {
19696            let frame = harness.module_rx.recv().await.expect("health.check frame");
19697            if answer {
19698                harness
19699                    .forwarding
19700                    .complete_module_control_rpc(
19701                        harness.module_connection,
19702                        frame.header.corr,
19703                        Some("health.check"),
19704                        ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19705                            status: HealthStatus::Ok,
19706                            detail: None,
19707                            metrics: Some(serde_json::json!({"ready": true})),
19708                        }),
19709                    )
19710                    .unwrap();
19711            } else {
19712                tokio::time::advance(harness.runtime.health.deadline).await;
19713                tokio::task::yield_now().await;
19714            }
19715        };
19716        tokio::join!(cycle, peer);
19717    }
19718
19719    #[tokio::test(start_paused = true)]
19720    async fn unanswered_probe_is_unknown_until_threshold_and_ok_report_recovers() {
19721        let mut harness = probe_harness();
19722        // Drive the probe cycle directly with an in-memory wire peer. Stop the
19723        // disabled module's monitor so only this test owns lifecycle transitions;
19724        // no OS process is launched, and a restart is observed at scheduling.
19725        let monitor = harness.module.inner.monitor.lock().unwrap().take().unwrap();
19726        monitor.abort();
19727        let _ = monitor.await;
19728        super::update_snapshot(&harness.module.inner.snapshot, None, |state| {
19729            state.enabled = true;
19730            state.state = super::ModuleState::Running;
19731            state.process_alive = true;
19732        })
19733        .unwrap();
19734
19735        run_probe_cycle(&mut harness, true).await;
19736        assert_eq!(
19737            harness.module.status().unwrap().health.status,
19738            super::SupervisorHealthStatus::Ok
19739        );
19740
19741        for failures in 1..harness.runtime.health.failure_threshold {
19742            run_probe_cycle(&mut harness, false).await;
19743            let status = harness.module.status().unwrap();
19744            assert_eq!(status.health.status, super::SupervisorHealthStatus::Unknown);
19745            assert_eq!(status.health.consecutive_failures, failures);
19746            assert!(status.health.last_probe_ms.is_some());
19747            assert!(status.health.detail.unwrap().starts_with("[no-answer]"));
19748            assert!(status.health.metrics.is_none());
19749            assert_eq!(status.state, super::ModuleState::Running);
19750            assert!(status.process_alive);
19751            assert_eq!(status.restart_count, 0);
19752            assert_eq!(status.lifetime_restarts, 0);
19753            assert!(status.health.last_action.is_none());
19754            assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_none());
19755        }
19756
19757        run_probe_cycle(&mut harness, true).await;
19758        let recovered = harness.module.status().unwrap();
19759        assert_eq!(recovered.health.status, super::SupervisorHealthStatus::Ok);
19760        assert_eq!(recovered.health.consecutive_failures, 0);
19761        assert!(recovered.health.detail.is_none());
19762        assert_eq!(
19763            recovered.health.metrics,
19764            Some(serde_json::json!({"ready": true}))
19765        );
19766        assert_eq!(recovered.lifetime_restarts, 0);
19767
19768        for failures in 1..=harness.runtime.health.failure_threshold {
19769            run_probe_cycle(&mut harness, false).await;
19770            let status = harness.module.status().unwrap();
19771            assert_eq!(status.health.consecutive_failures, failures);
19772            if failures < harness.runtime.health.failure_threshold {
19773                assert_eq!(status.health.status, super::SupervisorHealthStatus::Unknown);
19774                assert_eq!(status.state, super::ModuleState::Running);
19775                assert_eq!(status.lifetime_restarts, 0);
19776                assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_none());
19777            } else {
19778                assert_eq!(
19779                    status.health.status,
19780                    super::SupervisorHealthStatus::Unresponsive
19781                );
19782                assert_eq!(status.state, super::ModuleState::Restarting);
19783                // Count the replacement at spawn admission; this harness only schedules it.
19784                assert_eq!((status.restart_count, status.lifetime_restarts), (0, 0));
19785                assert_eq!(status.health.last_action.as_deref(), Some("restart"));
19786                assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_some());
19787            }
19788        }
19789    }
19790
19791    #[tokio::test(start_paused = true)]
19792    async fn late_health_answers_record_start_anchored_latency_for_two_stalls() {
19793        let mut harness = probe_harness();
19794
19795        let first = finish_after(&mut harness, Duration::from_secs(8)).await;
19796        let first_latency = match &first {
19797            ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
19798            other => panic!("late answer was not retained: {other:?}"),
19799        };
19800        assert!(harness.handler.observe_module_control_completion(first));
19801
19802        let second = finish_after(&mut harness, Duration::from_secs(11)).await;
19803        let second_latency = match &second {
19804            ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
19805            other => panic!("late answer was not retained: {other:?}"),
19806        };
19807        assert!(harness.handler.observe_module_control_completion(second));
19808
19809        assert_eq!(first_latency, Duration::from_secs(8));
19810        assert_eq!(
19811            second_latency - first_latency,
19812            Duration::from_secs(3),
19813            "latency must grow linearly with the additional stall"
19814        );
19815        let health = harness.module.status().unwrap().health;
19816        assert_eq!(health.late_answer_count, 2);
19817        assert_eq!(health.last_late_answer_latency_ms, Some(11_000));
19818    }
19819
19820    /// A module that answers every probe late must never march to the kill
19821    /// threshold: the late answer proves it is alive, so it must clear the miss
19822    /// streak the timeout recorded. Without the reset, a CPU-starved module
19823    /// that serves every probe seconds past the deadline accumulates
19824    /// `consecutive_failures` to the threshold and is killed — the exact
19825    /// sequence from the 2026-08-14 aft disable, where the daemon logged
19826    /// "proves the module is alive" five times while counting five misses.
19827    #[tokio::test(start_paused = true)]
19828    async fn late_answer_clears_the_consecutive_failure_streak() {
19829        let mut harness = probe_harness();
19830
19831        // Timeout recorded first: the probe path saw no answer in time.
19832        time_out_without_answer(&mut harness).await;
19833        harness
19834            .module
19835            .record_health_probe_failure_for_test("[no-answer] test miss")
19836            .unwrap();
19837        assert_eq!(
19838            harness.module.status().unwrap().health.consecutive_failures,
19839            1,
19840            "precondition: the miss must be on the streak before the late answer"
19841        );
19842
19843        // The stalled reply then lands: proof of life.
19844        let late = finish_after(&mut harness, Duration::from_secs(9)).await;
19845        assert!(matches!(
19846            late,
19847            ModuleControlRpcCompletion::LateHealthAnswer { .. }
19848        ));
19849        assert!(harness.handler.observe_module_control_completion(late));
19850
19851        let health = harness.module.status().unwrap().health;
19852        assert_eq!(
19853            health.consecutive_failures, 0,
19854            "a late answer is an answer: the streak must reset"
19855        );
19856        assert_eq!(health.late_answer_count, 1);
19857    }
19858
19859    #[tokio::test(start_paused = true)]
19860    async fn repeated_serial_probe_cycles_keep_one_tombstone_per_endpoint() {
19861        let mut harness = probe_harness();
19862
19863        for _ in 0..20 {
19864            time_out_without_answer(&mut harness).await;
19865            assert_eq!(
19866                harness.forwarding.health_probe_tombstone_count().unwrap(),
19867                1
19868            );
19869        }
19870    }
19871}
19872
19873#[cfg(test)]
19874mod child_env_tests {
19875    #[cfg(windows)]
19876    use super::{
19877        clear_current_process_facts, observed_launch_nonce_source, ModuleState, SupervisorSnapshot,
19878    };
19879    #[cfg(windows)]
19880    use std::sync::{Arc, OnceLock};
19881    #[cfg(windows)]
19882    #[test]
19883    fn windows_wire_spawn_prepares_pipe_and_keeps_phase_one_env() {
19884        let spec = spec(Vec::new());
19885        let mut command = Command::new("unused");
19886        let handoff = apply_wire_spawn_args(&mut command, &spec, None, None)
19887            .unwrap()
19888            .unwrap();
19889        let name = command
19890            .as_std()
19891            .get_envs()
19892            .find(|(key, _)| *key == OsStr::new(subc_os::launch_nonce::LAUNCH_NONCE_PIPE_ENV))
19893            .and_then(|(_, value)| value)
19894            .unwrap();
19895        assert_eq!(name, OsStr::new(handoff.name()));
19896        assert!(handoff.name().starts_with(r"\\.\pipe\subc-launch-"));
19897        assert!(command.as_std().get_envs().any(|(key, value)| key
19898            == OsStr::new(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV)
19899            && value == Some(OsStr::new("env"))));
19900        assert!(command
19901            .as_std()
19902            .get_envs()
19903            .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()));
19904    }
19905
19906    #[cfg(windows)]
19907    #[test]
19908    fn windows_source_reporting_tracks_consumption_and_resets_per_spawn() {
19909        let mut snapshot = SupervisorSnapshot::new(ModuleState::Running, true);
19910        snapshot.process_alive = true;
19911        snapshot.spawned_protocol = Some(ModuleProtocol::Subc);
19912        assert_eq!(
19913            observed_launch_nonce_source(&snapshot).as_deref(),
19914            Some("env")
19915        );
19916        let consumed = Arc::new(OnceLock::new());
19917        snapshot.pipe_consumed = Some(consumed.clone());
19918        assert_eq!(
19919            observed_launch_nonce_source(&snapshot).as_deref(),
19920            Some("env")
19921        );
19922        consumed.set(()).unwrap();
19923        assert_eq!(
19924            observed_launch_nonce_source(&snapshot).as_deref(),
19925            Some("pipe")
19926        );
19927        snapshot.pipe_consumed = Some(Arc::new(OnceLock::new()));
19928        assert_eq!(
19929            observed_launch_nonce_source(&snapshot).as_deref(),
19930            Some("env")
19931        );
19932        clear_current_process_facts(&mut snapshot);
19933        assert_eq!(observed_launch_nonce_source(&snapshot), None);
19934    }
19935    use super::{
19936        apply_child_env, apply_spawn_role, apply_wire_spawn_args, LaunchSpecDigest, ModuleProtocol,
19937        ModuleSpec, SpawnRole, SupervisorHandle, SPAWN_ROLE_SWAP_CANDIDATE, SUBC_ARG,
19938        SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV, SUBC_SPAWN_ROLE_ENV,
19939    };
19940    use std::{ffi::OsStr, path::PathBuf};
19941    use tokio::process::Command;
19942
19943    fn spec(env: Vec<(String, String)>) -> ModuleSpec {
19944        ModuleSpec {
19945            script: None,
19946            module_id: "env-plan".to_string(),
19947            program: PathBuf::from("/nonexistent"),
19948            args: Vec::new(),
19949            env,
19950            reserved: false,
19951            reserved_prefixes: Vec::new(),
19952            protocol: ModuleProtocol::Subc,
19953            overlap: Default::default(),
19954            carry_containment: false,
19955        }
19956    }
19957
19958    #[test]
19959    fn configured_launch_spec_digest_is_canonical_and_excludes_injected_inputs() {
19960        let base = spec(vec![("A".into(), "B=C".into()), ("Z".into(), "v".into())]);
19961        let digest = LaunchSpecDigest::from_spec(&base);
19962        let mut reordered = base.clone();
19963        reordered.env.reverse();
19964        reordered.module_id = "different-id".into();
19965        reordered.reserved = true;
19966        reordered.overlap = Default::default();
19967        assert_eq!(digest, LaunchSpecDigest::from_spec(&reordered));
19968        let mut delimiter_collision = base.clone();
19969        delimiter_collision.env[0] = ("A=B".into(), "C".into());
19970        assert_ne!(digest, LaunchSpecDigest::from_spec(&delimiter_collision));
19971        let mut changed = base.clone();
19972        changed.protocol = ModuleProtocol::None;
19973        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
19974        changed = base.clone();
19975        changed.args.push("--flag".into());
19976        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
19977        changed = base.clone();
19978        changed.program = PathBuf::from("/other");
19979        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
19980        changed = base.clone();
19981        changed.env[1].1 = "other".into();
19982        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
19983        assert!(!format!("{digest:?}").contains("B=C"));
19984        assert!(!format!("{digest:?}").contains("[u8"));
19985    }
19986
19987    #[cfg(unix)]
19988    #[test]
19989    fn native_program_bytes_do_not_collapse_through_lossy_utf8() {
19990        use std::os::unix::ffi::OsStringExt;
19991        let mut left = spec(Vec::new());
19992        left.program = std::ffi::OsString::from_vec(vec![b'/', 0xff]).into();
19993        let mut right = left.clone();
19994        right.program = std::ffi::OsString::from_vec(vec![b'/', 0xfe]).into();
19995        assert_eq!(
19996            left.program.to_string_lossy(),
19997            right.program.to_string_lossy()
19998        );
19999        assert_ne!(
20000            LaunchSpecDigest::from_spec(&left),
20001            LaunchSpecDigest::from_spec(&right)
20002        );
20003    }
20004
20005    /// Ambient `CK_LOG` is REMOVED for an unconfigured module, and a configured
20006    /// one still gets its own.
20007    ///
20008    /// This is the narrow goal `env_clear()` was reached for, and the reason the
20009    /// fix is `env_remove` rather than deleting the line: an operator's ambient
20010    /// filter silently becoming an unconfigured module's log level is a real
20011    /// defect, just a much smaller one than clearing the environment.
20012    ///
20013    /// Asserted on the command plan rather than a spawned child because proving
20014    /// the ABSENCE of an inherited variable needs the parent's environment
20015    /// mutated, and `forbid(unsafe_code)` refuses that. `get_envs()` reports a
20016    /// removal as `(key, None)`, which is exactly the distinction wanted: not
20017    /// "absent because nobody set it" but "explicitly unset for the child".
20018    #[test]
20019    fn ambient_ck_log_is_removed_and_a_configured_one_survives() {
20020        let mut command = Command::new("/nonexistent");
20021        apply_child_env(&mut command, &spec(Vec::new()));
20022        let removed = command
20023            .as_std()
20024            .get_envs()
20025            .any(|(key, value)| key == OsStr::new("CK_LOG") && value.is_none());
20026        assert!(
20027            removed,
20028            "ambient CK_LOG must be explicitly removed for an unconfigured module"
20029        );
20030
20031        let mut configured = Command::new("/nonexistent");
20032        apply_child_env(
20033            &mut configured,
20034            &spec(vec![("CK_LOG".to_string(), "debug".to_string())]),
20035        );
20036        let effective = configured
20037            .as_std()
20038            .get_envs()
20039            .filter(|(key, _)| *key == OsStr::new("CK_LOG"))
20040            .last()
20041            .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
20042        assert_eq!(
20043            effective,
20044            Some(Some("debug".to_string())),
20045            "a module's configured CK_LOG must survive the ambient removal"
20046        );
20047    }
20048
20049    /// A `protocol: "none"` spawn carries NO `--subc` argument and NO launch
20050    /// nonce; a subc-wire spawn carries both. Asserted on the command plan for
20051    /// the same reason as the CK_LOG test above.
20052    ///
20053    /// The argument is the load-bearing half: a stock binary exits on an
20054    /// unknown flag before it listens, so with `--subc` appended the mode
20055    /// could not supervise the one process it exists for. Found by the first
20056    /// conformance run (nats-server: `flag provided but not defined: -subc`).
20057    #[test]
20058    fn protocol_none_spawn_carries_no_subc_argument_and_no_nonce() {
20059        let connection_file = std::path::Path::new("/run/subc-connection.json");
20060        let handle = SupervisorHandle::new();
20061
20062        let mut none_spec = spec(Vec::new());
20063        none_spec.protocol = ModuleProtocol::None;
20064        let mut none = Command::new("/nonexistent");
20065        let none_handoff =
20066            apply_wire_spawn_args(&mut none, &none_spec, Some(connection_file), Some(&handle))
20067                .expect("protocol-none spawn args apply");
20068        assert!(
20069            none_handoff.is_none(),
20070            "protocol:none spawn must not receive a nonce descriptor"
20071        );
20072        #[cfg(windows)]
20073        assert!(!none.as_std().get_envs().any(|(key, value)| key
20074            == OsStr::new(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV)
20075            && value.is_some()));
20076        assert!(
20077            !none.as_std().get_envs().any(|(key, value)| key
20078                == OsStr::new(subc_os::LAUNCH_NONCE_FD_ENV)
20079                && value.is_some()),
20080            "protocol:none spawn must not name a nonce descriptor"
20081        );
20082        let none_args: Vec<String> = none
20083            .as_std()
20084            .get_args()
20085            .map(|a| a.to_string_lossy().into_owned())
20086            .collect();
20087        assert!(
20088            !none_args.iter().any(|a| a == SUBC_ARG),
20089            "protocol:none argv must not carry --subc; got {none_args:?}"
20090        );
20091        let none_has_nonce = none
20092            .as_std()
20093            .get_envs()
20094            .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some());
20095        assert!(
20096            !none_has_nonce,
20097            "protocol:none spawn must not receive a launch nonce"
20098        );
20099        let none_has_module_id = none
20100            .as_std()
20101            .get_envs()
20102            .any(|(key, value)| key == OsStr::new(SUBC_MODULE_ID_ENV) && value.is_some());
20103        assert!(
20104            none_has_module_id,
20105            "SUBC_MODULE_ID is inert and stays on every path"
20106        );
20107        assert!(
20108            handle.spawn_nonce(&none_spec.module_id).is_none(),
20109            "no nonce record for a process that will never present one"
20110        );
20111
20112        // Control: the subc-wire path is unchanged by the branch above.
20113        let wire_spec = spec(Vec::new());
20114        let mut wire = Command::new("/nonexistent");
20115        let wire_handoff =
20116            apply_wire_spawn_args(&mut wire, &wire_spec, Some(connection_file), Some(&handle))
20117                .expect("subc-wire spawn args apply");
20118        let wire_fd_env = wire
20119            .as_std()
20120            .get_envs()
20121            .find(|(key, _)| *key == OsStr::new(subc_os::LAUNCH_NONCE_FD_ENV))
20122            .and_then(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
20123        #[cfg(unix)]
20124        assert_eq!(
20125            wire_fd_env,
20126            Some(wire_handoff.expect("a descriptor handoff").fd_env_value()),
20127            "a subc-wire spawn names the pipe it will receive at descriptor 3"
20128        );
20129        #[cfg(windows)]
20130        assert!(wire_handoff.is_some() && wire_fd_env.is_none());
20131        #[cfg(not(any(unix, windows)))]
20132        assert!(wire_handoff.is_none() && wire_fd_env.is_none());
20133        let wire_args: Vec<String> = wire
20134            .as_std()
20135            .get_args()
20136            .map(|a| a.to_string_lossy().into_owned())
20137            .collect();
20138        assert_eq!(
20139            wire_args,
20140            vec![
20141                SUBC_ARG.to_string(),
20142                connection_file.to_string_lossy().into_owned()
20143            ],
20144            "a subc-wire spawn still carries --subc <path>"
20145        );
20146        assert_eq!(
20147            wire.as_std()
20148                .get_envs()
20149                .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()),
20150            !cfg!(unix),
20151            "only Windows supplies the environment nonce"
20152        );
20153        assert!(handle.spawn_nonce(&wire_spec.module_id).is_some());
20154    }
20155
20156    /// A plain spawn EXPLICITLY REMOVES the spawn role, even when the module's
20157    /// spec tries to set it; only a swap candidate carries it.
20158    ///
20159    /// "Set it only on candidates" is not enough, because spawn applies the
20160    /// spec's env verbatim and the daemon's own environment is inherited: either
20161    /// could hand a plain restart the swap role, and a module reading it would
20162    /// warm on its long swap budget while callers wait. Asserted as an explicit
20163    /// removal (`(key, None)`), not mere absence, for the reason the `CK_LOG`
20164    /// test above gives.
20165    #[test]
20166    fn plain_spawn_removes_the_spawn_role_even_when_the_spec_sets_it() {
20167        let role = |command: &Command| {
20168            command
20169                .as_std()
20170                .get_envs()
20171                .filter(|(key, _)| *key == OsStr::new(SUBC_SPAWN_ROLE_ENV))
20172                .last()
20173                .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()))
20174        };
20175        let forged = spec(vec![(
20176            SUBC_SPAWN_ROLE_ENV.to_string(),
20177            SPAWN_ROLE_SWAP_CANDIDATE.to_string(),
20178        )]);
20179
20180        let mut plain = Command::new("/nonexistent");
20181        apply_child_env(&mut plain, &forged);
20182        apply_spawn_role(&mut plain, SpawnRole::Plain);
20183        assert_eq!(
20184            role(&plain),
20185            Some(None),
20186            "a plain spawn must remove SUBC_SPAWN_ROLE, whatever the spec says"
20187        );
20188
20189        let mut candidate = Command::new("/nonexistent");
20190        apply_child_env(&mut candidate, &spec(Vec::new()));
20191        apply_spawn_role(&mut candidate, SpawnRole::SwapCandidate);
20192        assert_eq!(
20193            role(&candidate),
20194            Some(Some(SPAWN_ROLE_SWAP_CANDIDATE.to_string()))
20195        );
20196    }
20197
20198    /// Daemon-private capture retention keys never reach the child.
20199    ///
20200    /// cortexkit-log exposes retention as a Rust struct with no environment
20201    /// names, so these entries are supervisor metadata. Passing them through
20202    /// would invent a public child-process contract by accident.
20203    #[test]
20204    fn daemon_private_capture_keys_are_not_passed_to_the_child() {
20205        let mut command = Command::new("/nonexistent");
20206        apply_child_env(
20207            &mut command,
20208            &spec(vec![
20209                (super::CAPTURE_KEEP_ENV.to_string(), "5".to_string()),
20210                ("KEPT".to_string(), "yes".to_string()),
20211            ]),
20212        );
20213        let keys: Vec<String> = command
20214            .as_std()
20215            .get_envs()
20216            .filter(|(_, value)| value.is_some())
20217            .map(|(key, _)| key.to_string_lossy().into_owned())
20218            .collect();
20219        assert!(keys.contains(&"KEPT".to_string()), "got {keys:?}");
20220        assert!(
20221            !keys.contains(&super::CAPTURE_KEEP_ENV.to_string()),
20222            "daemon-private capture key leaked to the child: {keys:?}"
20223        );
20224    }
20225}
20226
20227#[cfg(test)]
20228mod jitter_tests {
20229    use super::jittered_health_delay;
20230    use std::{collections::HashSet, time::Duration};
20231
20232    /// Module ids drawn from a real fleet, so the dispersal claim is about names
20233    /// that actually occur rather than invented ones.
20234    ///
20235    /// This is a SAMPLE, not a registry: the property under test is that distinct
20236    /// ids disperse, which holds for any set of distinct strings. Several entries
20237    /// are already historical (modules get renamed), and that costs nothing here --
20238    /// but it means a reader must not mistake this for the live module set, and a
20239    /// rename sweep will match it without there being anything to change.
20240    const FLEET: [&str; 14] = [
20241        "aft",
20242        "alfonso-core",
20243        "magic-context",
20244        "broca",
20245        "thalamus",
20246        "quota",
20247        "engram",
20248        "plexus",
20249        "cerebellum",
20250        "astrocyte",
20251        "synapse",
20252        "subc-mcp",
20253        "cortexkit-credentials",
20254        "subc-federation",
20255    ];
20256
20257    /// Probes must not converge after a fleet-wide restart.
20258    ///
20259    /// This is the property the jitter exists for: every module reconnects at
20260    /// once, and without dispersal all fourteen would then probe on the same
20261    /// tick forever. Nothing failed visibly when this went untested -- a
20262    /// convergent fleet still probes correctly, just in a burst, so the symptom
20263    /// is a periodic load spike that looks like whatever else is running.
20264    #[test]
20265    fn probe_delays_disperse_across_the_fleet() {
20266        let cadence = Duration::from_secs(30);
20267        let delays: HashSet<Duration> = FLEET
20268            .iter()
20269            .map(|id| jittered_health_delay(id, 0, cadence))
20270            .collect();
20271        assert_eq!(
20272            delays.len(),
20273            FLEET.len(),
20274            "every supervised module must land on its own probe offset"
20275        );
20276    }
20277
20278    /// The offset may only ever DELAY a probe, never bring it forward.
20279    ///
20280    /// A delay below the cadence would probe a module more often than
20281    /// configured, which is the opposite of what an operator asked for and
20282    /// would tighten the failure budget without anyone changing it.
20283    #[test]
20284    fn jitter_only_delays_and_stays_within_one_tenth_of_cadence() {
20285        let cadence = Duration::from_secs(30);
20286        let span = cadence / 10;
20287        for id in FLEET {
20288            for probe_index in 0..8 {
20289                let delay = jittered_health_delay(id, probe_index, cadence);
20290                assert!(
20291                    delay >= cadence,
20292                    "{id}#{probe_index}: jitter must not shorten the cadence"
20293                );
20294                assert!(
20295                    delay < cadence + span,
20296                    "{id}#{probe_index}: jitter must stay inside one tenth of the cadence"
20297                );
20298            }
20299        }
20300    }
20301
20302    /// A module keeps its offset across daemon restarts.
20303    ///
20304    /// The delay is derived rather than randomised precisely so a restart does
20305    /// not re-roll every module into a fresh chance of collision. A random
20306    /// source would satisfy the dispersal test above and quietly lose this.
20307    #[test]
20308    fn a_module_offset_is_stable_across_restarts() {
20309        let cadence = Duration::from_secs(30);
20310        for id in FLEET {
20311            assert_eq!(
20312                jittered_health_delay(id, 0, cadence),
20313                jittered_health_delay(id, 0, cadence),
20314                "{id}: the same module and probe index must produce the same offset"
20315            );
20316        }
20317    }
20318
20319    /// A zero cadence disables probing rather than producing a busy loop.
20320    #[test]
20321    fn zero_cadence_yields_zero_delay() {
20322        assert_eq!(
20323            jittered_health_delay("aft", 0, Duration::ZERO),
20324            Duration::ZERO
20325        );
20326    }
20327}
20328
20329#[cfg(all(test, target_os = "linux"))]
20330mod cgroup_placement_tests {
20331    use super::{
20332        apply_cgroup_placement, remove_module_cgroup, LaunchSpecDigest, ModuleProtocol, ModuleSpec,
20333        SuperviseError, SupervisedChild,
20334    };
20335    use crate::stderr_tail::{StderrRing, StderrTailConfig};
20336    use cortexkit_test_support::ScratchDir;
20337    use std::{
20338        fs, io,
20339        path::{Path, PathBuf},
20340        sync::{Arc, Mutex},
20341    };
20342    use tokio::process::Command;
20343
20344    #[tokio::test]
20345    async fn unique_spawn_cgroups_clean_up_across_restarts_and_shutdown() {
20346        use super::*;
20347        let dir = ScratchDir::new("unique-spawn-cgroups");
20348        let root = PathBuf::from(format!(
20349            "/sys/fs/cgroup/subc-unique-test-{}-{}",
20350            std::process::id(),
20351            unix_ms_now()
20352        ));
20353        if let Err(error) = fs::create_dir(&root) {
20354            assert!(
20355                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
20356                "required cgroup test cannot execute: {error}"
20357            );
20358            eprintln!("SKIP unique_spawn_cgroups_clean_up_across_restarts_and_shutdown: {error}");
20359            return;
20360        }
20361        let placement = subc_cgroup::prepare_at(&root).unwrap().unwrap();
20362        let group_count = || {
20363            fs::read_dir(root.join("subc-modules"))
20364                .unwrap()
20365                .map(|entry| entry.unwrap().file_type().unwrap())
20366                .filter(|kind| kind.is_dir())
20367                .count()
20368        };
20369        let supervisor =
20370            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
20371                .with_cgroup_placement(Some(placement.clone()));
20372        let runtime = supervisor.runtime_config();
20373        let mut spec = ModuleSpec {
20374            script: None,
20375            module_id: "unique-spawn".into(),
20376            program: PathBuf::from("/bin/sleep"),
20377            args: vec!["60".into()],
20378            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
20379                .into_iter()
20380                .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
20381                .collect(),
20382            reserved: false,
20383            reserved_prefixes: vec![],
20384            protocol: ModuleProtocol::None,
20385            overlap: Default::default(),
20386            carry_containment: false,
20387        };
20388        let spawn = |spec: &ModuleSpec| {
20389            spawn_child(
20390                spec,
20391                None,
20392                None,
20393                &runtime.stderr_ring,
20394                None,
20395                &runtime.child_roster,
20396                runtime.spawn_delivery(),
20397                Some(&placement),
20398                runtime.register_timeout,
20399            )
20400            .unwrap()
20401        };
20402        let mut live = spawn(&spec);
20403        for _ in 0..3 {
20404            // A new process can enter the old slot while retirement is pending.
20405            let next = spawn(&spec);
20406            assert_ne!(live.module_id, next.module_id);
20407            live.start_kill().unwrap();
20408            live.wait().await.unwrap();
20409            live.finish_exit(false).await.unwrap();
20410            live = next;
20411            assert!(
20412                live.child.try_wait().unwrap().is_none(),
20413                "retiring the old slot must not kill the replacement"
20414            );
20415            assert_eq!(
20416                group_count(),
20417                1,
20418                "only the live spawn's cgroup should remain"
20419            );
20420        }
20421        supervisor.begin_daemon_shutdown();
20422        let reap = tokio::spawn(async move {
20423            live.wait().await.unwrap();
20424            live.finish_exit(false).await.unwrap();
20425        });
20426        supervisor
20427            .end_children_for_daemon_shutdown(false, std::future::pending())
20428            .await;
20429        reap.await.unwrap();
20430        assert_eq!(group_count(), 0);
20431        // A normal exit uses the same tree-cleanup path as a killed spawn.
20432        spec.program = PathBuf::from("/bin/true");
20433        spec.args.clear();
20434        let fresh_roster = ChildRoster::default();
20435        let mut short = spawn_child(
20436            &spec,
20437            None,
20438            None,
20439            &runtime.stderr_ring,
20440            None,
20441            &fresh_roster,
20442            None,
20443            Some(&placement),
20444            runtime.register_timeout,
20445        )
20446        .unwrap();
20447        short.wait().await.unwrap();
20448        short.finish_exit(false).await.unwrap();
20449        assert_eq!(group_count(), 0);
20450        spec.module_id = "_".repeat(255);
20451        let mut long_id = spawn_child(
20452            &spec,
20453            None,
20454            None,
20455            &runtime.stderr_ring,
20456            None,
20457            &fresh_roster,
20458            None,
20459            Some(&placement),
20460            runtime.register_timeout,
20461        )
20462        .unwrap();
20463        long_id.wait().await.unwrap();
20464        long_id.finish_exit(false).await.unwrap();
20465        assert_eq!(
20466            group_count(),
20467            0,
20468            "valid long module IDs must not exceed cgroup NAME_MAX"
20469        );
20470        fs::remove_dir(root.join("subc-modules")).unwrap();
20471        fs::remove_dir(root).unwrap();
20472        eprintln!("EXECUTED unique_spawn_cgroups_clean_up_across_restarts_and_shutdown");
20473    }
20474
20475    #[test]
20476    fn failed_parent_cgroup_open_is_a_cgroup_supervision_error() {
20477        let path = Path::new("/definitely-missing-subc-cgroup");
20478        let mut command = Command::new("true");
20479        let error = apply_cgroup_placement(
20480            &mut command,
20481            &ModuleSpec {
20482                script: None,
20483                module_id: "broken-cgroup".to_string(),
20484                program: PathBuf::from("true"),
20485                args: Vec::new(),
20486                env: Vec::new(),
20487                reserved: false,
20488                reserved_prefixes: Vec::new(),
20489                protocol: ModuleProtocol::Subc,
20490                overlap: Default::default(),
20491                carry_containment: false,
20492            },
20493            path,
20494        )
20495        .expect_err("a parent cgroup open failure must reject the supervised spawn");
20496        let reason = error.to_string();
20497
20498        assert!(
20499            matches!(error, SuperviseError::Cgroup { .. }),
20500            "parent cgroup open must be reported as a cgroup supervision error: {reason}"
20501        );
20502        assert!(
20503            reason.contains("/definitely-missing-subc-cgroup/cgroup.procs"),
20504            "parent cgroup open failure must name cgroup.procs: {reason}"
20505        );
20506    }
20507
20508    #[tokio::test]
20509    async fn reaping_a_child_does_not_treat_missing_cgroup_events_as_empty() {
20510        let root = ScratchDir::new("supervisor-reap-cgroup");
20511        fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
20512        let placement = subc_cgroup::prepare_at(&root)
20513            .expect("prepare scratch cgroup root")
20514            .expect("scratch root has a cgroup.procs marker");
20515        let module_id = "reaped-module";
20516        let module = placement
20517            .module_path(module_id)
20518            .expect("create scratch module cgroup");
20519        let child = Command::new("true")
20520            .env("XDG_DATA_HOME", root.path())
20521            .env("XDG_RUNTIME_DIR", root.path())
20522            .env("XDG_CONFIG_HOME", root.path())
20523            .spawn()
20524            .expect("spawn short-lived child");
20525        let pid = child.id().expect("spawned child has pid");
20526        let mut child = SupervisedChild {
20527            registration_channel: None,
20528            registration_spawn: None,
20529            live_program_binding: None,
20530            registered_config_connection: None,
20531            admission_base: None,
20532            registration_declaration: None,
20533            _program_binding: None,
20534            subtree_target: crate::subtree_resources::Target::Cgroup(module.clone()),
20535            child: crate::supervise::containment::ProcessChild::plain(child, pid),
20536            exec: crate::activity::ExecOwner(Arc::new(crate::activity::ExecOutcome::new())),
20537            protocol: ModuleProtocol::Subc,
20538            module_id: module_id.to_string(),
20539            cgroup_placement: Some(placement),
20540            unresolved_cgroup: None,
20541            stdout_pump: None,
20542            stderr_pump: None,
20543            capture_stop: None,
20544            late_output_lost: false,
20545            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
20546            spawned_at: tokio::time::Instant::now(),
20547            config_delivery: None,
20548            registration_deadline: None,
20549            registration_watch: None,
20550            spawned_at_ms: 0,
20551            spawned_from: PathBuf::from("true"),
20552            launch_spec_digest: LaunchSpecDigest([0; 32]),
20553            spawned_file_identity: None,
20554            process_start_time: None,
20555            process_identity: None,
20556            pid,
20557            roster_guard: None,
20558            #[cfg(target_os = "macos")]
20559            privacy_exec: None,
20560            spawn_failure: None,
20561            admission_kill_sent: false,
20562        };
20563
20564        child.wait().await.expect("reap short-lived child");
20565
20566        child.cleanup_ordinary_cgroup().await;
20567        assert!(module.is_dir());
20568        assert!(child
20569            .exit_cleanup_detail(None)
20570            .unwrap()
20571            .contains(&module.display().to_string()));
20572        child.finish_exit(false).await.unwrap();
20573    }
20574
20575    #[test]
20576    fn non_empty_cgroup_removal_is_reported_without_blocking_teardown() {
20577        let root = ScratchDir::new("supervisor-non-empty-cgroup");
20578        fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
20579        let placement = subc_cgroup::prepare_at(&root)
20580            .expect("prepare scratch cgroup root")
20581            .expect("scratch root has a cgroup.procs marker");
20582        let module = placement
20583            .module_path("surviving-module")
20584            .expect("create scratch module cgroup");
20585        fs::write(module.join("surviving-process"), b"still present")
20586            .expect("make scratch cgroup non-empty");
20587        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
20588
20589        remove_module_cgroup(&placement, "surviving-module");
20590
20591        let logs = crate::router::test_log::captured_logs(&logs);
20592        assert!(
20593            module.exists(),
20594            "failed removal must leave the cgroup intact"
20595        );
20596        assert!(
20597            logs.contains("could not remove module cgroup after process exit; continuing teardown")
20598                && logs.contains("surviving-module"),
20599            "best-effort removal must report the failure without returning it: {logs}"
20600        );
20601    }
20602
20603    #[test]
20604    fn cgroup_pre_exec_spawn_failure_names_the_cgroup_path() {
20605        let cgroup_path = PathBuf::from("/sys/fs/cgroup/subc-modules/broken-module");
20606        let reason = SuperviseError::Spawn {
20607            program: PathBuf::from("/bin/true"),
20608            source: io::Error::from_raw_os_error(13),
20609            cgroup_path: Some(cgroup_path.clone()),
20610        }
20611        .to_string();
20612
20613        assert!(
20614            reason.contains(&cgroup_path.display().to_string()),
20615            "a pre_exec spawn failure must name the cgroup path: {reason}"
20616        );
20617    }
20618}
20619
20620#[cfg(test)]
20621mod spawn_subscriber_lag_tests {
20622    use super::*;
20623
20624    /// A subscriber whose connection stops draining is dropped once its frame
20625    /// channel fills. The client must learn that from a terminal Error frame
20626    /// after the frames already queued for it, not from a stream that simply
20627    /// goes quiet.
20628    #[tokio::test]
20629    async fn lagged_spawn_subscriber_receives_a_terminal_lagged_error_after_its_queued_frames() {
20630        let feed = SpawnEventFeed::default();
20631        feed.configure_incarnation("lag-incarnation".to_string());
20632        // A one-slot connection queue that nobody reads until the emits are
20633        // done: the forwarder parks on it and the subscriber channel fills.
20634        let (tx, mut rx) = mpsc::channel(1);
20635        feed.subscribe(ConnectionId::new(1), 7, 1, None, FrameSink::new(tx))
20636            .expect("subscribe");
20637        let emitted = SPAWN_SUBSCRIBER_BUFFER + 16;
20638        for index in 0..emitted {
20639            feed.emit_spawned(&format!("lag-module-{index}"), None, 1000, 0);
20640            // Let the forwarder take what it can so the fill point is the
20641            // subscriber channel, not a scheduling accident.
20642            tokio::task::yield_now().await;
20643        }
20644        assert_eq!(
20645            feed.subscriber_count(),
20646            0,
20647            "the lagged subscriber must be removed"
20648        );
20649
20650        let mut data = Vec::new();
20651        let mut last = None;
20652        loop {
20653            let next = tokio::time::timeout(Duration::from_secs(5), rx.recv())
20654                .await
20655                .expect("the forwarder must finish once the subscriber is dropped");
20656            let Some(outbound) = next else { break };
20657            let frame = outbound.frame;
20658            if frame.header.ty == FrameType::StreamData {
20659                assert!(last.is_none(), "no data may follow the terminal frame");
20660                let event: SpawnEvent = serde_json::from_slice(&frame.body).unwrap();
20661                data.push(event.cursor.seq);
20662            } else {
20663                assert!(last.is_none(), "exactly one terminal frame");
20664                last = Some(frame);
20665            }
20666        }
20667        assert!(!data.is_empty(), "queued frames drain before the terminal");
20668        for pair in data.windows(2) {
20669            assert_eq!(
20670                pair[1],
20671                pair[0] + 1,
20672                "queued frames arrive dense and in order"
20673            );
20674        }
20675        let terminal = last.expect("a lagged subscriber must receive a terminal frame");
20676        assert_eq!(terminal.header.ty, FrameType::Error);
20677        assert_eq!(terminal.header.corr, 7);
20678        let body: subc_protocol::ErrorBody = serde_json::from_slice(&terminal.body).unwrap();
20679        assert_eq!(body.code, SPAWN_SUBSCRIBER_LAGGED_CODE);
20680        let detail = body.detail.expect("lagged error carries detail");
20681        assert_eq!(
20682            detail["first_undelivered_cursor"]["seq"],
20683            data.last().unwrap() + 1,
20684            "the named cursor is the first event the subscriber did not receive"
20685        );
20686        assert_eq!(
20687            detail["first_undelivered_cursor"]["daemon_incarnation"],
20688            "lag-incarnation"
20689        );
20690    }
20691}
20692
20693#[cfg(test)]
20694mod terminal_history_read_concurrency_tests {
20695    use super::*;
20696    use crate::terminal_journal::read_pause;
20697    use cortexkit_test_support::ScratchDir;
20698    use std::sync::mpsc as std_mpsc;
20699
20700    fn journaled_ring(
20701        journal: &Arc<crate::terminal_journal::TerminalJournal>,
20702    ) -> Arc<Mutex<TerminalRing>> {
20703        Arc::new(Mutex::new(
20704            TerminalRing::new(TerminalRingConfig::default(), 1)
20705                .with_journal(Some(Arc::clone(journal))),
20706        ))
20707    }
20708
20709    fn crash(at_ms: u64) -> ExitReport {
20710        ExitReport {
20711            kind: ExitKind::Crash,
20712            code: Some(1),
20713            signal: None,
20714            at_ms,
20715        }
20716    }
20717
20718    /// Record an exit on another thread and report whether it finished within
20719    /// `bound`. The recorder thread is left running if it did not.
20720    fn record_within(
20721        module_id: &'static str,
20722        ring: &Arc<Mutex<TerminalRing>>,
20723        at_ms: u64,
20724        bound: Duration,
20725    ) -> bool {
20726        let ring = Arc::clone(ring);
20727        let (done, done_rx) = std_mpsc::channel();
20728        std::thread::spawn(move || {
20729            record_terminal(
20730                module_id,
20731                &ring,
20732                &SpawnEventFeed::default(),
20733                &crash(at_ms),
20734                TerminalDisposition::Restarting,
20735            );
20736            let _ = done.send(());
20737        });
20738        done_rx.recv_timeout(bound).is_ok()
20739    }
20740
20741    /// A history read in progress must not hold the journal writer (which every
20742    /// module's exit recording needs) or the module's own ring. Exits recorded
20743    /// while the read is paused complete promptly; the paused read answers as of
20744    /// the moment it started, and the next read has each exit exactly once.
20745    #[test]
20746    fn exits_recorded_during_a_paused_history_read_are_not_blocked_or_half_merged() {
20747        let dir = ScratchDir::new("terminal-history-concurrent-read");
20748        let path = dir.join("terminals.jsonl");
20749        let journal = Arc::new(crate::terminal_journal::TerminalJournal::open(
20750            path.clone(),
20751            "daemon".into(),
20752        ));
20753        let reader_ring = journaled_ring(&journal);
20754        let other_ring = journaled_ring(&journal);
20755        assert!(record_within(
20756            "reader-module",
20757            &reader_ring,
20758            10,
20759            Duration::from_secs(5)
20760        ));
20761
20762        let (started, release) = read_pause::install(&path);
20763        let reading = {
20764            let ring = Arc::clone(&reader_ring);
20765            std::thread::spawn(move || durable_terminal_history_of(&ring, "reader-module"))
20766        };
20767        started
20768            .recv_timeout(Duration::from_secs(5))
20769            .expect("the history read reached its pause");
20770
20771        let bound = Duration::from_secs(1);
20772        assert!(
20773            record_within("other-module", &other_ring, 20, bound),
20774            "another module's exit waited on a history read (journal writer held)"
20775        );
20776        assert!(
20777            record_within("reader-module", &reader_ring, 30, bound),
20778            "the read module's own exit waited on its history read (ring held)"
20779        );
20780
20781        drop(release);
20782        let paused = reading.join().unwrap();
20783        assert_eq!(
20784            paused.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
20785            vec![10],
20786            "an exit recorded after the read began lands in neither half of it"
20787        );
20788        assert_eq!(paused.journal_skipped_lines, 0);
20789        assert_eq!(paused.journal_read_errors, 0);
20790
20791        let after = durable_terminal_history_of(&reader_ring, "reader-module");
20792        assert_eq!(
20793            after.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
20794            vec![10, 30],
20795            "the next read merges ring and journal with no duplicate"
20796        );
20797        assert_eq!(after.journal_skipped_lines, 0);
20798    }
20799}
20800
20801/// What a restart does with the exited process's output readers. These drive
20802/// the same settle functions the supervisor calls, with a reader the test
20803/// holds, so a reader that has not been scheduled by the bound is a controlled
20804/// input rather than something only a loaded machine produces.
20805#[cfg(test)]
20806mod stderr_settle_tests {
20807    use std::{
20808        future::Future,
20809        io,
20810        pin::Pin,
20811        sync::{Arc, Mutex},
20812        task::{Context, Poll},
20813        time::Duration,
20814    };
20815
20816    use tokio::{
20817        io::{AsyncRead, ReadBuf},
20818        sync::oneshot,
20819        time::Instant,
20820    };
20821
20822    use super::{settle_stderr_pump, settle_stdout_pump, StderrPump};
20823    use crate::stderr_tail::{
20824        pump_stderr_to, pump_stdout_to, split_capture_stamp, untimed, CaptureState,
20825        ChildOutputSink, OutputSink, StderrRing, StderrTailConfig, TailEntry,
20826    };
20827
20828    const BOUND: Duration = Duration::from_millis(250);
20829
20830    /// Yields `before`, then stays pending until the gate is released, then
20831    /// yields `after` and reaches EOF. The bytes after the gate were written
20832    /// by a process that has already exited; only the reader is behind.
20833    struct HeldReader {
20834        before: Option<Vec<u8>>,
20835        gate: Option<oneshot::Receiver<()>>,
20836        after: io::Cursor<Vec<u8>>,
20837    }
20838
20839    impl AsyncRead for HeldReader {
20840        fn poll_read(
20841            mut self: Pin<&mut Self>,
20842            cx: &mut Context<'_>,
20843            buf: &mut ReadBuf<'_>,
20844        ) -> Poll<io::Result<()>> {
20845            if let Some(bytes) = self.before.take() {
20846                buf.put_slice(&bytes);
20847                return Poll::Ready(Ok(()));
20848            }
20849            if let Some(gate) = self.gate.as_mut() {
20850                match Pin::new(gate).poll(cx) {
20851                    Poll::Pending => return Poll::Pending,
20852                    Poll::Ready(_) => self.gate = None,
20853                }
20854            }
20855            Pin::new(&mut self.after).poll_read(cx, buf)
20856        }
20857    }
20858
20859    struct DiscardSink;
20860
20861    impl OutputSink for DiscardSink {
20862        fn write_line(&mut self, _line: &[u8]) {}
20863    }
20864
20865    fn line(text: &str) -> TailEntry {
20866        TailEntry::Line {
20867            text: text.to_string(),
20868            truncated: false,
20869            at_ms: None,
20870        }
20871    }
20872
20873    fn lock(ring: &Arc<Mutex<StderrRing>>) -> std::sync::MutexGuard<'_, StderrRing> {
20874        ring.lock().unwrap()
20875    }
20876
20877    /// Start a reader for a new process generation that delivers `before`
20878    /// immediately and `after` only once the returned sender fires (or is
20879    /// dropped).
20880    fn held_pump(
20881        ring: &Arc<Mutex<StderrRing>>,
20882        before: &str,
20883        after: &str,
20884    ) -> (StderrPump<tokio::task::JoinHandle<()>>, oneshot::Sender<()>) {
20885        let generation = lock(ring).begin_process();
20886        let (release, gate) = oneshot::channel();
20887        let reader = HeldReader {
20888            before: Some(before.as_bytes().to_vec()),
20889            gate: Some(gate),
20890            after: io::Cursor::new(after.as_bytes().to_vec()),
20891        };
20892        let task = tokio::spawn(pump_stderr_to(
20893            reader,
20894            Arc::clone(ring),
20895            generation,
20896            DiscardSink,
20897        ));
20898        (StderrPump { task, generation }, release)
20899    }
20900
20901    async fn wait_until(ring: &Arc<Mutex<StderrRing>>, done: impl Fn(&StderrRing) -> bool) {
20902        for _ in 0..1000 {
20903            if done(&lock(ring)) {
20904                return;
20905            }
20906            tokio::time::sleep(Duration::from_millis(1)).await;
20907        }
20908        panic!(
20909            "ring never reached the expected state: {:?}",
20910            lock(ring).snapshot(None, None)
20911        );
20912    }
20913
20914    #[tokio::test(start_paused = true)]
20915    async fn a_crash_line_the_reader_had_not_reached_by_the_bound_is_kept_before_the_restart() {
20916        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
20917        let (pump, release) = held_pump(&ring, "booting\n", "config error: missing storage\n");
20918
20919        settle_stderr_pump("crasher", &ring, pump, BOUND).await;
20920        let before_release = lock(&ring).snapshot(None, None);
20921        assert!(
20922            matches!(before_release.capture, CaptureState::Incomplete { .. }),
20923            "a reader that has not reached EOF cannot claim a whole tail: {before_release:?}"
20924        );
20925
20926        // The restart: the next process starts and writes before the old
20927        // reader catches up.
20928        let next = lock(&ring).begin_process();
20929        lock(&ring).push_line_from(next, "next process booting");
20930        release.send(()).unwrap();
20931        wait_until(&ring, |ring| {
20932            ring.snapshot(None, None).capture == CaptureState::Captured
20933        })
20934        .await;
20935
20936        assert_eq!(
20937            untimed(lock(&ring).snapshot(None, None).entries),
20938            vec![
20939                line("booting"),
20940                line("config error: missing storage"),
20941                TailEntry::ProcessStart,
20942                line("next process booting"),
20943            ],
20944            "the crash's last line must survive a slow reader and stay in the crashed process's section"
20945        );
20946    }
20947
20948    #[tokio::test(start_paused = true)]
20949    async fn a_pipe_held_open_by_a_descendant_reads_incomplete_without_delaying_the_restart_past_the_bound(
20950    ) {
20951        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
20952        // `_held` is never fired: a descendant keeps the pipe open for the
20953        // whole test.
20954        let (pump, _held) = held_pump(&ring, "parent exiting\n", "");
20955
20956        let started = Instant::now();
20957        settle_stderr_pump("orphaning", &ring, pump, BOUND).await;
20958        assert_eq!(
20959            started.elapsed(),
20960            BOUND,
20961            "the restart must wait exactly the bound for a pipe that stays open, no longer"
20962        );
20963
20964        let next = lock(&ring).begin_process();
20965        lock(&ring).push_line_from(next, "next process booting");
20966        tokio::time::sleep(Duration::from_secs(60)).await;
20967
20968        let snapshot = lock(&ring).snapshot(None, None);
20969        match &snapshot.capture {
20970            CaptureState::Incomplete { reason } => assert!(
20971                reason.contains("had not reached EOF") && reason.contains("250ms"),
20972                "the reason must say what is missing and after how long: {reason}"
20973            ),
20974            other => panic!("expected Incomplete while the pipe is held open, got {other:?}"),
20975        }
20976        assert_eq!(
20977            untimed(snapshot.entries),
20978            vec![
20979                line("parent exiting"),
20980                TailEntry::ProcessStart,
20981                line("next process booting"),
20982            ]
20983        );
20984    }
20985
20986    #[tokio::test(start_paused = true)]
20987    async fn a_reader_that_reaches_eof_within_the_bound_leaves_the_tail_captured() {
20988        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
20989        let (pump, release) = held_pump(&ring, "one\n", "two\n");
20990        release.send(()).unwrap();
20991
20992        settle_stderr_pump("clean", &ring, pump, BOUND).await;
20993
20994        let snapshot = lock(&ring).snapshot(None, None);
20995        assert_eq!(snapshot.capture, CaptureState::Captured);
20996        assert_eq!(untimed(snapshot.entries), vec![line("one"), line("two")]);
20997    }
20998
20999    #[tokio::test(start_paused = true)]
21000    async fn stdout_buffered_past_the_exit_drain_bound_reaches_the_capture_file() {
21001        const BURST: usize = 150;
21002        let capture = cortexkit_test_support::ScratchDir::new("stdout-exit-drain");
21003        let path = capture.join("two-pipe.stderr.log");
21004        let sink = ChildOutputSink::open(&path, cortexkit_log::Retention::default()).unwrap();
21005        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21006        let generation = lock(&ring).begin_process();
21007        let stdout = (0..BURST)
21008            .map(|i| format!("out-{i:04}-{}\n", "o".repeat(64)))
21009            .collect::<String>();
21010        let stderr = (0..BURST)
21011            .map(|i| format!("err-{i:04}-{}\n", "e".repeat(64)))
21012            .collect::<String>();
21013        // Model a child that has written both bursts and exited. Hold the stdout
21014        // reader after one line and a partial prefix, as if pipe readiness or
21015        // capture-file writes had delayed it. The final line also needs EOF to
21016        // flush: neither complete nor partial buffered output may be discarded.
21017        let first_chunk = stdout.find('\n').unwrap() + 1 + "out-0001-".len();
21018        let (release, gate) = oneshot::channel();
21019        let reader = HeldReader {
21020            before: Some(stdout.as_bytes()[..first_chunk].to_vec()),
21021            gate: Some(gate),
21022            after: io::Cursor::new(stdout.as_bytes()[first_chunk..stdout.len() - 1].to_vec()),
21023        };
21024        let (finished, completion) = oneshot::channel();
21025        let stdout_sink = sink.clone();
21026        let pump = tokio::spawn(async move {
21027            pump_stdout_to(reader, stdout_sink).await;
21028            finished.send(()).unwrap();
21029        });
21030        pump_stderr_to(io::Cursor::new(stderr.into_bytes()), ring, generation, sink).await;
21031
21032        let started = Instant::now();
21033        settle_stdout_pump("two-pipe", pump, BOUND).await;
21034        assert_eq!(
21035            started.elapsed(),
21036            BOUND,
21037            "a late reader must not hold up restart"
21038        );
21039        assert_eq!(
21040            std::fs::read_to_string(&path).unwrap().lines().count(),
21041            BURST + 1
21042        );
21043
21044        release
21045            .send(())
21046            .expect("stdout reader must survive the exit drain bound");
21047        tokio::time::timeout(Duration::from_secs(1), completion)
21048            .await
21049            .expect("released stdout reader must reach EOF")
21050            .expect("stdout capture must finish at EOF, not be cancelled");
21051        let contents = std::fs::read_to_string(&path).unwrap();
21052        let mut lines = contents
21053            .lines()
21054            .map(|line| split_capture_stamp(line).expect("capture stamp").1)
21055            .collect::<Vec<_>>();
21056        let mut expected = (0..BURST)
21057            .flat_map(|i| {
21058                [
21059                    format!("out-{i:04}-{}", "o".repeat(64)),
21060                    format!("err-{i:04}-{}", "e".repeat(64)),
21061                ]
21062            })
21063            .collect::<Vec<_>>();
21064        lines.sort_unstable();
21065        expected.sort_unstable();
21066        assert_eq!(
21067            lines, expected,
21068            "both pipes must retain every complete line exactly once"
21069        );
21070    }
21071}
21072
21073/// Containment of a module's process tree (issue #109).
21074///
21075/// The behaviour these defend against is a module helper surviving its module:
21076/// on a real machine the Synapse embedding module's CUDA worker holds ~2.2 GB of
21077/// VRAM, so a leaked grandchild is a leaked GPU allocation, and a day of restarts
21078/// compounds it.
21079///
21080/// They run against the SUPERVISOR rather than the job-object crate because the
21081/// claim is about teardown: a crate-level test proves a job can reap a tree, not
21082/// that the daemon's drain path reaches it.
21083///
21084/// Windows-only, like the mechanism. On Unix this arm compiles out; the cgroup
21085/// lane there is a separate containment path with its own tests.
21086#[cfg(all(test, windows))]
21087mod job_containment_tests {
21088    use super::*;
21089    use cortexkit_test_support::ScratchDir;
21090    use std::{
21091        path::{Path, PathBuf},
21092        sync::{Arc, Mutex},
21093        time::{Duration, Instant},
21094    };
21095
21096    /// The stub, expected beside this test executable.
21097    ///
21098    /// The existence check is here for the reason its twin at `fake_aft_stub_path`
21099    /// documents: `--lib` does not build `[[bin]]` targets, and a bare spawn
21100    /// failure then reads as a broken test rather than an unbuilt dependency.
21101    fn stub_path() -> PathBuf {
21102        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
21103        assert!(
21104            path.exists(),
21105            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
21106             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
21107            path.display()
21108        );
21109        path
21110    }
21111
21112    /// Poll for the grandchild pid the stub records, and parse it.
21113    fn read_grandchild_pid(path: &Path) -> u32 {
21114        let deadline = Instant::now() + Duration::from_secs(10);
21115        loop {
21116            if let Ok(contents) = std::fs::read_to_string(path) {
21117                if let Ok(pid) = contents.trim().parse() {
21118                    return pid;
21119                }
21120            }
21121            assert!(
21122                Instant::now() < deadline,
21123                "the stub never recorded a grandchild pid at {}",
21124                path.display()
21125            );
21126            std::thread::sleep(Duration::from_millis(10));
21127        }
21128    }
21129
21130    /// Everything one fixture run needs, so the two tests below differ in exactly
21131    /// one place: whether the child is contained.
21132    struct Fixture {
21133        _dir: ScratchDir,
21134        _roster: ChildRoster,
21135        module_id: String,
21136        grandchild: u32,
21137        child: Option<SupervisedChild>,
21138        registry: Arc<Registry>,
21139        snapshot: Arc<Mutex<SupervisorSnapshot>>,
21140        terminal_ring: Arc<Mutex<TerminalRing>>,
21141        spawn_events: SpawnEventFeed,
21142    }
21143
21144    fn fixture(label: &str, module_id: &str) -> Fixture {
21145        fixture_with_carry(label, module_id, false)
21146    }
21147
21148    fn fixture_with_carry(label: &str, module_id: &str, carry_containment: bool) -> Fixture {
21149        let dir = ScratchDir::new(label);
21150        let pid_file = dir.join("grandchild.pid");
21151        let supervisor = Supervisor::new_for_test(
21152            Arc::new(Registry::default()),
21153            RestartPolicy::new(3, Duration::ZERO),
21154        );
21155        let runtime = supervisor.runtime_config();
21156        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21157        let spec = ModuleSpec {
21158            script: None,
21159            module_id: module_id.to_string(),
21160            program: stub_path(),
21161            // Zero args deliberately: a `--subc` argument would make the stub dial
21162            // a daemon that is not there, and the failure would land in the same
21163            // stderr ring this fixture exists to keep quiet.
21164            args: Vec::new(),
21165            env: vec![
21166                ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
21167                (
21168                    "FAKE_AFT_GRANDCHILD_PID_FILE".to_string(),
21169                    pid_file.display().to_string(),
21170                ),
21171            ],
21172            reserved: false,
21173            reserved_prefixes: Vec::new(),
21174            protocol: ModuleProtocol::Subc,
21175            overlap: Default::default(),
21176            carry_containment,
21177        };
21178        let child = spawn_and_mark_running(&spec, &runtime, &snapshot)
21179            .expect("spawn the supervised fixture");
21180        let grandchild = read_grandchild_pid(&pid_file);
21181        Fixture {
21182            _dir: dir,
21183            _roster: runtime.child_roster.clone(),
21184            module_id: module_id.to_string(),
21185            grandchild,
21186            child: Some(child),
21187            registry: Arc::new(Registry::default()),
21188            snapshot,
21189            terminal_ring: Arc::clone(&runtime.terminal_ring),
21190            spawn_events: SpawnEventFeed::default(),
21191        }
21192    }
21193
21194    async fn assert_admission_kill_reaps_grandchild(carry: bool) {
21195        let label = if carry {
21196            "admission-kill-carried-tree"
21197        } else {
21198            "admission-kill-plain-tree"
21199        };
21200        let mut fixture = fixture_with_carry(label, label, carry);
21201        let descendant = subc_os::Process::open(fixture.grandchild)
21202            .unwrap()
21203            .expect("the stub descendant must be alive before admission kill");
21204        assert!(descendant.observe().is_some());
21205        let child = fixture.child.as_mut().unwrap();
21206        assert_eq!(child.child.container().is_some(), carry);
21207        assert_eq!(child.job.is_some(), !carry);
21208
21209        child.start_admission_kill().unwrap();
21210        assert!(child.admission_kill_sent);
21211        let status = timeout(Duration::from_secs(10), child.wait())
21212            .await
21213            .unwrap()
21214            .unwrap();
21215        assert_eq!(
21216            status.code(),
21217            Some(admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE),
21218            "containment teardown must preserve the leader's distinctive status"
21219        );
21220        // Keep the child and its job/container alive: later exit finalization or
21221        // handle drop must not be what makes the descendant-death claim pass.
21222        assert!(
21223            descendant.wait_for_exit(Duration::from_secs(10)).unwrap(),
21224            "admission kill left a descendant running before exit finalization"
21225        );
21226        assert_eq!(child.child.container().is_some(), carry);
21227        assert_eq!(child.job.is_some(), !carry);
21228        child.finish_exit(false).await.unwrap();
21229    }
21230
21231    #[tokio::test]
21232    async fn admission_kill_reaps_grandchild_with_plain_job() {
21233        assert_admission_kill_reaps_grandchild(false).await;
21234    }
21235
21236    #[tokio::test]
21237    async fn admission_kill_reaps_grandchild_with_carried_job() {
21238        assert_admission_kill_reaps_grandchild(true).await;
21239    }
21240
21241    #[tokio::test]
21242    async fn admission_kill_retires_registration_before_wait() {
21243        let mut fixture = fixture("admission-registration", "admission-registration");
21244        let handle = SupervisorHandle::new();
21245        let spawn =
21246            RegistrationSpawn::new(&handle, "admission-registration", SpawnRole::Plain, None);
21247        spawn.ready();
21248        let child = fixture.child.as_mut().unwrap();
21249        child.registration_spawn = Some(spawn.clone());
21250        child.start_admission_kill().unwrap();
21251        assert!(
21252            !spawn.launch_ready(),
21253            "admission kill must retire before its caller can await the child"
21254        );
21255        timeout(Duration::from_secs(10), child.wait())
21256            .await
21257            .unwrap()
21258            .unwrap();
21259        child.finish_exit(false).await.unwrap();
21260    }
21261
21262    impl Fixture {
21263        /// Drain through the supervisor's own teardown path.
21264        async fn drain(&mut self) {
21265            let child = self
21266                .child
21267                .take()
21268                .expect("the fixture child is still present");
21269            drain_child_to_state(
21270                &self.module_id,
21271                ModuleProtocol::Subc,
21272                // No forwarding table in this fixture, so nothing reaches the
21273                // child over a connection.
21274                StopNotice::NotSent,
21275                &self.registry,
21276                None,
21277                &self.snapshot,
21278                &self.terminal_ring,
21279                &self.spawn_events,
21280                child,
21281                Duration::from_millis(500),
21282                ModuleState::Stopped,
21283                Some(false),
21284                &FailureContext::operator(),
21285            )
21286            .await
21287            .expect("drain the supervised fixture");
21288        }
21289    }
21290
21291    /// Teardown reaps the grandchild, not merely the direct child.
21292    ///
21293    /// This is the assertion the change exists for. Before containment the
21294    /// grandchild survived: it is a separate process, and `start_kill` is
21295    /// `TerminateProcess` scoped to one pid.
21296    #[tokio::test]
21297    async fn teardown_reaps_the_grandchild() {
21298        let mut fixture = fixture("teardown-grandchild", "tree-teardown");
21299        let grandchild = fixture.grandchild;
21300
21301        assert!(
21302            subc_jobobject::process_exists(grandchild),
21303            "grandchild {grandchild} must be alive before teardown, or this proves nothing"
21304        );
21305
21306        fixture.drain().await;
21307
21308        assert!(
21309            subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
21310            "grandchild {grandchild} outlived module teardown: the tree was not contained"
21311        );
21312    }
21313
21314    /// The mutation control: with containment withheld, the grandchild survives
21315    /// the same kill.
21316    ///
21317    /// This is the defect reproduction from #109 — a direct-child kill reaches
21318    /// one pid, and the grandchild is a different process. It spawns OUTSIDE the
21319    /// supervisor because `spawn_and_mark_running` now always contains on
21320    /// Windows, which is the point: there is no longer a path that spawns
21321    /// uncontained, so the control has to construct one.
21322    ///
21323    /// Its job is to keep `teardown_reaps_the_grandchild` honest. If the
21324    /// grandchild ever dies here, that test is passing for a reason unrelated to
21325    /// the job object and the containment claim is unproven.
21326    #[test]
21327    fn an_uncontained_grandchild_survives_a_direct_child_kill() {
21328        let dir = ScratchDir::new("teardown-uncontained");
21329        let pid_file = dir.join("grandchild.pid");
21330        let mut child = std::process::Command::new(stub_path())
21331            .env("FAKE_AFT_NEVER_CONNECT", "1")
21332            .env(
21333                "FAKE_AFT_GRANDCHILD_PID_FILE",
21334                pid_file.display().to_string(),
21335            )
21336            .stdin(std::process::Stdio::null())
21337            .stdout(std::process::Stdio::null())
21338            .stderr(std::process::Stdio::null())
21339            .spawn()
21340            .expect("spawn the uncontained fixture");
21341        let grandchild = read_grandchild_pid(&pid_file);
21342
21343        // Exactly what the pre-fix teardown did: kill the direct child.
21344        child.kill().expect("kill the direct child");
21345        let _ = child.wait();
21346
21347        assert!(
21348            subc_jobobject::process_exists(grandchild),
21349            "grandchild {grandchild} died with the direct child, so this control no longer \
21350             distinguishes contained from uncontained teardown and the regression test is \
21351             passing vacuously"
21352        );
21353
21354        // The orphan this control demonstrates is the leak the fix prevents, so
21355        // the control must not leave one behind.
21356        kill_tree(grandchild);
21357    }
21358
21359    /// Crash durability: closing the containment handle reaps the tree with no
21360    /// teardown code running at all.
21361    ///
21362    /// This is the case `taskkill /T` cannot cover — a daemon that dies cannot
21363    /// call anything — and it is why containment is a kernel property of the
21364    /// handle rather than a step in the drain. Discovered by getting the
21365    /// mutation control wrong: clearing `job` to "disable" containment instead
21366    /// killed the tree, which is the guarantee, not a mistake.
21367    #[tokio::test]
21368    async fn dropping_containment_reaps_the_grandchild() {
21369        let mut fixture = fixture("drop-containment", "tree-drop");
21370        let grandchild = fixture.grandchild;
21371
21372        assert!(subc_jobobject::process_exists(grandchild));
21373
21374        // No `drain` call, no kill: dropping the handle is the entire mechanism.
21375        fixture.child.as_mut().expect("child present").job = None;
21376
21377        assert!(
21378            subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
21379            "grandchild {grandchild} survived the containment handle closing, so a daemon \
21380             crash would leave the tree behind"
21381        );
21382    }
21383
21384    /// Kill a pid and its tree, then confirm it is gone.
21385    fn kill_tree(pid: u32) {
21386        let _ = std::process::Command::new("taskkill.exe")
21387            .args(["/PID", &pid.to_string(), "/T", "/F"])
21388            .stdin(std::process::Stdio::null())
21389            .stdout(std::process::Stdio::null())
21390            .stderr(std::process::Stdio::null())
21391            .status();
21392        assert!(
21393            subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10)),
21394            "could not clean up grandchild {pid}"
21395        );
21396    }
21397}
21398
21399#[cfg(test)]
21400mod privacy_trampoline_configuration_tests {
21401    #[tokio::test]
21402    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21403    async fn macos_spawn_without_a_configured_trampoline_refuses_by_name() {
21404        #[cfg(target_os = "macos")]
21405        {
21406            let supervisor = super::Supervisor::new(
21407                std::sync::Arc::new(crate::Registry::default()),
21408                super::RestartPolicy::default(),
21409            );
21410            let error = supervisor.spawn(spec()).unwrap_err();
21411            assert!(
21412                error
21413                    .to_string()
21414                    .contains("no privacy trampoline configured"),
21415                "{error}"
21416            );
21417        }
21418    }
21419
21420    #[tokio::test]
21421    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21422    async fn macos_wrong_trampoline_is_rejected_by_the_startup_probe() {
21423        #[cfg(target_os = "macos")]
21424        {
21425            let supervisor = super::Supervisor::new(
21426                std::sync::Arc::new(crate::Registry::default()),
21427                super::RestartPolicy::default(),
21428            )
21429            .with_privacy_trampoline(std::env::current_exe().unwrap());
21430            let error = supervisor.spawn(spec()).unwrap_err();
21431            assert!(
21432                error
21433                    .to_string()
21434                    .contains("binary does not implement the privacy trampoline protocol"),
21435                "{error}"
21436            );
21437        }
21438    }
21439
21440    #[cfg(target_os = "macos")]
21441    fn spec() -> super::ModuleSpec {
21442        super::ModuleSpec {
21443            module_id: "privacy-configuration".into(),
21444            program: "/bin/sleep".into(),
21445            args: vec!["30".into()],
21446            env: vec![],
21447            reserved: false,
21448            reserved_prefixes: vec![],
21449            protocol: subc_control::ModuleProtocol::None,
21450            overlap: super::ModuleOverlap::Exclusive,
21451            carry_containment: false,
21452            script: None,
21453        }
21454    }
21455}
21456
21457#[cfg(test)]
21458mod privacy_exec_boundary_tests {
21459    #[cfg(target_os = "macos")]
21460    use super::*;
21461    #[cfg(target_os = "macos")]
21462    use std::{
21463        io::{Read, Write},
21464        net::{TcpListener, TcpStream},
21465    };
21466
21467    /// Unit-test-only pause at the actual early image read, not at a later
21468    /// status read. Production supervisors never inspect this environment key.
21469    #[cfg(target_os = "macos")]
21470    pub(super) fn before_image_sample(spec: &ModuleSpec, pid: u32) {
21471        if let Some((_, path)) = spec
21472            .env
21473            .iter()
21474            .find(|(key, _)| key == "SUBC_TEST_PRIVACY_SAMPLE_BARRIER")
21475        {
21476            let mut barrier = TcpStream::connect(path).unwrap();
21477            barrier
21478                .set_read_timeout(Some(Duration::from_secs(30)))
21479                .unwrap();
21480            barrier.write_all(&pid.to_ne_bytes()).unwrap();
21481            let mut release = [0];
21482            barrier.read_exact(&mut release).unwrap();
21483            assert_eq!(&release, b"X");
21484        }
21485    }
21486
21487    #[cfg(target_os = "macos")]
21488    fn spec(program: &str, args: &[&str]) -> ModuleSpec {
21489        ModuleSpec {
21490            script: None,
21491            module_id: "privacy-boundary".into(),
21492            program: program.into(),
21493            args: args.iter().map(|arg| (*arg).into()).collect(),
21494            env: vec![],
21495            reserved: false,
21496            reserved_prefixes: vec![],
21497            protocol: ModuleProtocol::None,
21498            overlap: ModuleOverlap::Exclusive,
21499            carry_containment: false,
21500        }
21501    }
21502
21503    #[cfg(target_os = "macos")]
21504    async fn accept(listener: TcpListener) -> TcpStream {
21505        // Socket readiness, not elapsed time, establishes both pause points.
21506        let listener = tokio::net::TcpListener::from_std({
21507            listener.set_nonblocking(true).unwrap();
21508            listener
21509        })
21510        .unwrap();
21511        let (stream, _) = tokio::time::timeout(Duration::from_secs(30), listener.accept())
21512            .await
21513            .unwrap()
21514            .unwrap();
21515        let stream = stream.into_std().unwrap();
21516        stream.set_nonblocking(false).unwrap();
21517        stream
21518            .set_read_timeout(Some(Duration::from_secs(30)))
21519            .unwrap();
21520        stream
21521    }
21522
21523    #[tokio::test]
21524    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21525    async fn macos_roster_withholds_a_nonnull_trampoline_image_until_exec_confirmation() {
21526        #[cfg(target_os = "macos")]
21527        {
21528            let root = cortexkit_test_support::ScratchDir::new("privacy-roster-barrier");
21529            // Loopback sockets also work when the replay adapter's TMPDIR is
21530            // longer than Darwin's Unix-domain socket path limit.
21531            let exec_listener = TcpListener::bind("127.0.0.1:0").unwrap();
21532            let sample_listener = TcpListener::bind("127.0.0.1:0").unwrap();
21533            let record = root.join("live-children.json");
21534            let supervisor =
21535                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21536                    .with_live_children_record(&record);
21537            let runtime = supervisor.runtime_config();
21538            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21539            let mut spec = spec("/bin/sleep", &["30"]);
21540            spec.env = vec![
21541                (
21542                    "SUBC_TEST_PRIVACY_EXEC_BARRIER".into(),
21543                    exec_listener.local_addr().unwrap().to_string(),
21544                ),
21545                (
21546                    "SUBC_TEST_PRIVACY_SAMPLE_BARRIER".into(),
21547                    sample_listener.local_addr().unwrap().to_string(),
21548                ),
21549            ];
21550            let spawn = tokio::task::spawn_blocking(move || {
21551                spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap()
21552            });
21553            let mut sample = accept(sample_listener).await;
21554            let mut pid = [0; 4];
21555            sample.read_exact(&mut pid).unwrap();
21556            let pid = u32::from_ne_bytes(pid);
21557            let mut exec = accept(exec_listener).await;
21558            let mut ready = [0];
21559            exec.read_exact(&mut ready).unwrap();
21560            assert_eq!(&ready, b"R");
21561            // The early read is guaranteed to see a real, non-null trampoline
21562            // image: the fixture has reached its barrier and cannot exec yet.
21563            let trampoline = subc_os::file_identity(&test_privacy_trampoline()).unwrap();
21564            assert_eq!(
21565                observe_spawned_image(pid).unwrap().executable,
21566                Some(trampoline)
21567            );
21568            sample.write_all(b"X").unwrap();
21569            let mut child = spawn.await.unwrap();
21570            let early = crate::live_children::read_record(&record).unwrap();
21571            assert_eq!(early.len(), 1);
21572            assert_eq!(early[0].pid, pid);
21573            assert_eq!(
21574                early[0].executable, None,
21575                "unconfirmed trampoline image entered the roster"
21576            );
21577            assert!(child.report_ready.get().is_none());
21578            // The barrier's duration is unrelated to the production five-second
21579            // exec budget. Start the test's confirmation budget upon release.
21580            child.privacy_exec.as_mut().unwrap().deadline =
21581                tokio::time::Instant::now() + Duration::from_secs(30);
21582            exec.write_all(b"X").unwrap();
21583            child.confirm_privacy_exec().await;
21584            assert_eq!(child.spawn_failure, None);
21585            assert!(child.report_ready.get().is_some());
21586            let confirmed = crate::live_children::read_record(&record).unwrap();
21587            let module = subc_os::file_identity(std::path::Path::new("/bin/sleep")).unwrap();
21588            assert_ne!(module, trampoline);
21589            assert_eq!(confirmed[0].executable, Some(module.into()));
21590            child.start_kill().unwrap();
21591            child.wait().await.unwrap();
21592            child.release_roster();
21593        }
21594    }
21595
21596    #[tokio::test]
21597    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21598    async fn macos_unstamped_reexec_records_the_observed_native_image() {
21599        #[cfg(target_os = "macos")]
21600        {
21601            let root = cortexkit_test_support::ScratchDir::new("privacy-reexec");
21602            let record = root.join("live-children.json");
21603            let supervisor =
21604                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21605                    .with_live_children_record(&record);
21606            let runtime = supervisor.runtime_config();
21607            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21608            let fixture = crate::config_gate::program::native_fixture_for_test();
21609            let mut spec = spec(
21610                "/bin/sh",
21611                &["-c", "exec \"$1\" 600", "reexec", fixture.to_str().unwrap()],
21612            );
21613            spec.env
21614                .push(("SUBC_TEST_PRIVACY_IMAGE_DELAY_MS".into(), "5".into()));
21615            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21616            let native_image = subc_os::file_identity(&fixture).unwrap();
21617            // Native image installation, not shell startup speed, establishes
21618            // that this launch has crossed the re-exec boundary before sampling.
21619            let reexec = tokio::time::timeout(Duration::from_secs(5), async {
21620                while observe_spawned_image(child.pid).and_then(|image| image.executable)
21621                    != Some(native_image)
21622                {
21623                    tokio::time::sleep(Duration::from_millis(1)).await;
21624                }
21625            })
21626            .await;
21627            child.confirm_privacy_exec().await;
21628            let failure = child.spawn_failure.clone();
21629            let ready = child.report_ready.get().is_some();
21630            let confirmed = crate::live_children::read_record(&record).unwrap();
21631            child.start_kill().unwrap();
21632            tokio::time::timeout(Duration::from_secs(5), child.wait())
21633                .await
21634                .unwrap()
21635                .unwrap();
21636            child.release_roster();
21637
21638            reexec.expect("the shell must re-exec the native fixture");
21639            assert_eq!(
21640                failure, None,
21641                "an unstamped program may re-exec before observation"
21642            );
21643            assert!(ready);
21644            assert_eq!(confirmed.len(), 1);
21645            assert_eq!(confirmed[0].executable, Some(native_image.into()));
21646        }
21647    }
21648
21649    #[tokio::test]
21650    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21651    async fn macos_unstamped_ack_without_exec_still_refuses_the_trampoline() {
21652        #[cfg(target_os = "macos")]
21653        {
21654            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
21655            let supervisor =
21656                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
21657            let runtime = supervisor.runtime_config();
21658            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21659            let fixture = crate::config_gate::program::native_fixture_for_test();
21660            let mut spec = spec(fixture.to_str().unwrap(), &["600"]);
21661            spec.env.push((
21662                "SUBC_TEST_PRIVACY_EXEC_BARRIER".into(),
21663                listener.local_addr().unwrap().to_string(),
21664            ));
21665            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21666            let mut exec = accept(listener).await;
21667            let mut ready = [0];
21668            exec.read_exact(&mut ready).unwrap();
21669            assert_eq!(&ready, b"R");
21670            assert_eq!(
21671                observe_spawned_image(child.pid).unwrap().executable,
21672                subc_os::file_identity(&test_privacy_trampoline())
21673            );
21674            // Simulate a broken trampoline that acknowledges exec but keeps
21675            // running its own image, held at the fixture's pre-exec barrier.
21676            let (reader, writer) = std::io::pipe().unwrap();
21677            drop(writer);
21678            child.privacy_exec.as_mut().unwrap().reader =
21679                tokio::io::unix::AsyncFd::new(reader).unwrap();
21680            child.confirm_privacy_exec().await;
21681            let failure = child.spawn_failure.clone();
21682            let ready = child.report_ready.get().is_some();
21683            child.start_kill().unwrap();
21684            tokio::time::timeout(Duration::from_secs(5), child.wait())
21685                .await
21686                .unwrap()
21687                .unwrap();
21688            child.release_roster();
21689            assert_eq!(
21690                failure.as_deref(),
21691                Some("privacy identity trampoline did not exec the module")
21692            );
21693            assert!(!ready);
21694        }
21695    }
21696
21697    #[tokio::test]
21698    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21699    async fn macos_resumed_121_is_a_module_exit_not_a_trampoline_refusal() {
21700        #[cfg(target_os = "macos")]
21701        {
21702            let registry = Arc::new(Registry::default());
21703            let policy = RestartPolicy::new(0, Duration::ZERO);
21704            let fixture = crate::config_gate::program::native_fixture_for_test();
21705            let spec = spec(fixture.to_str().unwrap(), &["exit121"]);
21706            let scratch = cortexkit_test_support::ScratchDir::new("resumed-exit");
21707            let supervisor = Supervisor::new_for_test(Arc::clone(&registry), policy)
21708                .with_config_runtime(suspended_spawn_tests::gated_owner(&scratch, &spec, true));
21709            let runtime = supervisor.runtime_config();
21710            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21711            // A module cannot exit before suspended admission. After resume,
21712            // retain the real exit status even when it resembles a refusal.
21713            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21714            child.confirm_privacy_exec().await;
21715            assert_eq!(child.spawn_failure, None);
21716            assert!(child.report_ready.get().is_some());
21717            let pid = child.pid;
21718            tokio::task::spawn_blocking(move || {
21719                subc_os::fork_exec_test::wait_for_child_exit_without_reaping(pid)
21720            })
21721            .await
21722            .unwrap()
21723            .unwrap();
21724            let status = child.wait().await.unwrap();
21725            assert_eq!(status.code(), Some(121));
21726            assert!(child.privacy_exec.is_none());
21727            let report = classify_reaped_child_exit(&snapshot, &child, &status);
21728            on_child_exit(
21729                &spec,
21730                policy,
21731                &registry,
21732                &snapshot,
21733                &runtime.terminal_ring,
21734                &runtime.spawn_events,
21735                &runtime.child_roster,
21736                report,
21737                true,
21738            )
21739            .await;
21740            let state = lock_snapshot(&snapshot).unwrap();
21741            assert_eq!(state.state, ModuleState::Failed);
21742            assert_eq!(state.last_exit.as_ref().unwrap().code, Some(121));
21743            assert_eq!(state.reported_pid(), None);
21744            drop(state);
21745            let history = runtime.terminal_ring.lock().unwrap().snapshot();
21746            assert_eq!(history.entries.len(), 1);
21747            let terminal = &history.entries[0];
21748            assert_eq!(terminal.exit_code, Some(121));
21749            assert_eq!(terminal.exit_kind, subc_control::TerminalExitKind::Crash);
21750            assert_eq!(terminal.disposition, TerminalDisposition::Failed);
21751            assert_eq!(
21752                terminal.disposition_detail.as_deref(),
21753                Some(policy.budget_exhausted_detail().as_str()),
21754                "module exit 121 was classified as a trampoline refusal: {terminal:?}"
21755            );
21756            assert_eq!(child.spawn_failure, None);
21757            child.release_roster();
21758        }
21759    }
21760}
21761
21762#[cfg(all(test, target_os = "macos"))]
21763#[path = "supervise/suspended_spawn_tests.rs"]
21764mod suspended_spawn_tests;
21765
21766/// The daemon's real spawn path hands a subc-wire child its launch nonce on
21767/// descriptor 3, without an environment copy. The shell records the nonce
21768/// and its environment after exec so these tests observe the real handover.
21769#[cfg(all(test, unix))]
21770mod launch_nonce_descriptor_tests {
21771    use super::{ChildRoster, ModuleProtocol, ModuleSpec, SupervisorHandle};
21772    use crate::stderr_tail::{StderrRing, StderrTailConfig};
21773    use cortexkit_test_support::ScratchDir;
21774    use std::{
21775        path::PathBuf,
21776        sync::{Arc, Mutex},
21777        time::{Duration, Instant},
21778    };
21779
21780    async fn probe(role: super::SpawnRole) {
21781        let scratch = ScratchDir::new("launch-nonce-descriptor");
21782        let fd_copy = scratch.join("from-descriptor");
21783        let env_copy = scratch.join("environment");
21784        let script = format!(
21785            "env > '{env}.tmp' && mv '{env}.tmp' '{env}'; cat <&3 > '{fd}.tmp' && mv '{fd}.tmp' '{fd}'; sleep 30",
21786            fd = fd_copy.display(), env = env_copy.display(),
21787        );
21788        let xdg = |name: &str| (name.to_string(), scratch.join(name).display().to_string());
21789        let spec = ModuleSpec {
21790            script: None,
21791            module_id: "nonce-descriptor-probe".to_string(),
21792            program: PathBuf::from("/bin/sh"),
21793            args: vec!["-c".to_string(), script],
21794            env: vec![
21795                xdg("XDG_DATA_HOME"),
21796                xdg("XDG_RUNTIME_DIR"),
21797                xdg("XDG_CONFIG_HOME"),
21798                ("SUBC_LAUNCH_NONCE".to_string(), "must-not-leak".to_string()),
21799            ],
21800            reserved: true,
21801            reserved_prefixes: Vec::new(),
21802            protocol: ModuleProtocol::Subc,
21803            overlap: Default::default(),
21804            carry_containment: false,
21805        };
21806        let handle = SupervisorHandle::new();
21807        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21808        let roster = ChildRoster::default();
21809        #[cfg(target_os = "macos")]
21810        {
21811            let path = super::test_privacy_trampoline();
21812            roster.set_privacy_trampoline(super::probe_privacy_trampoline(&path).map(|()| path));
21813        }
21814        let child = super::spawn_child_in_slot(
21815            &spec,
21816            None,
21817            Some(&handle),
21818            &ring,
21819            None,
21820            &roster,
21821            None,
21822            #[cfg(target_os = "linux")]
21823            None,
21824            role,
21825            matches!(role, super::SpawnRole::SwapCandidate),
21826            super::DEFAULT_REGISTER_TIMEOUT,
21827        )
21828        .expect("spawn probe");
21829        let deadline = Instant::now() + Duration::from_secs(10);
21830        while !(fd_copy.exists() && env_copy.exists()) {
21831            assert!(Instant::now() < deadline, "probe never wrote its copies");
21832            tokio::time::sleep(Duration::from_millis(20)).await;
21833        }
21834        let nonce = std::fs::read_to_string(fd_copy).unwrap();
21835        assert!(!nonce.is_empty());
21836        let environment = std::fs::read_to_string(env_copy).unwrap();
21837        assert!(environment
21838            .lines()
21839            .any(|line| line.starts_with("SUBC_LAUNCH_NONCE_FD=3:")));
21840        let copy = environment
21841            .lines()
21842            .find_map(|line| line.strip_prefix("SUBC_LAUNCH_NONCE="));
21843        assert_eq!(
21844            copy, None,
21845            "Unix children must never receive the environment nonce"
21846        );
21847        if matches!(role, super::SpawnRole::Plain) {
21848            assert_eq!(
21849                handle.spawn_nonce(&spec.module_id).as_deref(),
21850                Some(nonce.as_str())
21851            );
21852        }
21853        drop(child);
21854    }
21855
21856    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
21857    async fn a_spawned_module_receives_its_nonce_only_on_descriptor_3() {
21858        probe(super::SpawnRole::Plain).await;
21859    }
21860
21861    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
21862    async fn swap_candidate_receives_its_nonce_only_on_descriptor_3() {
21863        probe(super::SpawnRole::SwapCandidate).await;
21864    }
21865}
21866
21867#[cfg(all(test, target_os = "linux"))]
21868#[path = "supervise/cgroup_reap_tests.rs"]
21869mod cgroup_reap_tests;
21870
21871#[cfg(all(test, target_os = "linux"))]
21872mod cgroup_containment_tests {
21873    use super::*;
21874    use cortexkit_test_support::ScratchDir;
21875
21876    #[tokio::test]
21877    async fn linux_subtree_memory_covers_module_children() {
21878        let dir = ScratchDir::new("subtree-memory");
21879        let root = PathBuf::from(format!(
21880            "/sys/fs/cgroup/subc-memory-test-{}-{}",
21881            std::process::id(),
21882            unix_ms_now()
21883        ));
21884        if let Err(error) = std::fs::create_dir(&root) {
21885            assert!(
21886                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
21887                "required cgroup test cannot execute: {error}"
21888            );
21889            eprintln!("SKIP linux_subtree_memory_covers_module_children: {error}");
21890            return;
21891        }
21892        let placement = subc_cgroup::prepare_at(&root)
21893            .unwrap()
21894            .expect("delegated cgroup");
21895        let supervisor = Supervisor::new_for_test(
21896            Arc::new(Registry::default()),
21897            RestartPolicy::new(3, Duration::ZERO),
21898        )
21899        .with_cgroup_placement(Some(placement));
21900        let ready = dir.join("ready");
21901        let module = supervisor
21902            .spawn(ModuleSpec {
21903                script: None,
21904                module_id: "memory-tree".into(),
21905                program: PathBuf::from("/bin/sh"),
21906                args: vec![
21907                    "-c".into(),
21908                    "sleep 600 & sleep 600 & sleep 600 & echo ready > \"$1\"; wait".into(),
21909                    "fixture".into(),
21910                    ready.display().to_string(),
21911                ],
21912                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
21913                    .into_iter()
21914                    .map(|key| (key.into(), dir.display().to_string()))
21915                    .collect(),
21916                reserved: false,
21917                reserved_prefixes: Vec::new(),
21918                protocol: ModuleProtocol::None,
21919                overlap: Default::default(),
21920                carry_containment: false,
21921            })
21922            .unwrap();
21923        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
21924        while !ready.exists() {
21925            assert!(
21926                tokio::time::Instant::now() < deadline,
21927                "children never started"
21928            );
21929            tokio::time::sleep(Duration::from_millis(10)).await;
21930        }
21931        let readings = crate::subtree_resources::read(vec![module.subtree_target()]).await;
21932        let reading = &readings[0];
21933        assert!(
21934            reading.process_count.is_some_and(|count| count >= 4),
21935            "{reading:?}"
21936        );
21937        assert!(
21938            reading.memory_bytes.is_some_and(|bytes| bytes > 0),
21939            "{reading:?}"
21940        );
21941        module.stop().await.unwrap();
21942        drop(module);
21943        std::fs::remove_dir(root.join("subc-modules")).unwrap();
21944        std::fs::remove_dir(&root).unwrap();
21945        eprintln!("EXECUTED linux_subtree_memory_covers_module_children: {reading:?}");
21946    }
21947
21948    fn running(pid: u32) -> bool {
21949        // An orphan can remain a zombie until the container init reaps it.
21950        std::fs::read_to_string(format!("/proc/{pid}/stat"))
21951            .ok()
21952            .and_then(|stat| {
21953                stat.rsplit_once(") ")
21954                    .map(|(_, rest)| rest.starts_with('Z'))
21955            })
21956            .is_some_and(|zombie| !zombie)
21957    }
21958
21959    #[tokio::test]
21960    async fn linux_teardown_reaps_the_grandchild() {
21961        teardown_tree("linux_teardown_reaps_the_grandchild", false).await;
21962    }
21963
21964    #[tokio::test]
21965    async fn linux_shutdown_straggler_reaps_the_grandchild() {
21966        teardown_tree("linux_shutdown_straggler_reaps_the_grandchild", true).await;
21967    }
21968
21969    async fn teardown_tree(test_name: &str, shutdown: bool) {
21970        let dir = ScratchDir::new(test_name);
21971        let root = PathBuf::from(format!(
21972            "/sys/fs/cgroup/subc-tree-test-{test_name}-{}-{}",
21973            std::process::id(),
21974            unix_ms_now()
21975        ));
21976        if let Err(error) = std::fs::create_dir(&root) {
21977            assert!(
21978                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
21979                "required cgroup test cannot execute: {error}"
21980            );
21981            eprintln!(
21982                "SKIP {test_name}: no writable delegated cgroup at {}: {error}",
21983                root.display()
21984            );
21985            return;
21986        }
21987        let placement = subc_cgroup::prepare_at(&root)
21988            .expect("prepare isolated kernel cgroup")
21989            .expect("isolated cgroup is delegated");
21990        let module_id = "tree-teardown";
21991        let module = placement
21992            .module_path(module_id)
21993            .expect("create isolated module cgroup");
21994        if !module.join("cgroup.kill").exists() {
21995            std::fs::remove_dir(&module).unwrap();
21996            std::fs::remove_dir(root.join("subc-modules")).unwrap();
21997            std::fs::remove_dir(&root).unwrap();
21998            assert!(
21999                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
22000                "required cgroup.kill interface unavailable"
22001            );
22002            eprintln!("SKIP {test_name}: cgroup.kill unavailable (kernel < 5.14)");
22003            return;
22004        }
22005        let supervisor = Supervisor::new_for_test(
22006            Arc::new(Registry::default()),
22007            RestartPolicy::new(3, Duration::ZERO),
22008        )
22009        .with_cgroup_placement(Some(placement));
22010        let mut runtime = supervisor.runtime_config();
22011        runtime.child_roster = runtime
22012            .child_roster
22013            .for_module(Arc::new(Mutex::new(Duration::from_millis(100))));
22014        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
22015        let pid_file = dir.join("grandchild.pid");
22016        let spec = ModuleSpec {
22017            script: None,
22018            module_id: module_id.to_string(),
22019            program: PathBuf::from("/bin/sh"),
22020            args: vec![
22021                "-c".into(),
22022                "trap '' TERM; sleep 600 & echo $! > \"$1\"; wait".into(),
22023                "fixture".into(),
22024                pid_file.display().to_string(),
22025            ],
22026            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
22027                .into_iter()
22028                .map(|key| (key.to_string(), dir.display().to_string()))
22029                .collect(),
22030            reserved: false,
22031            reserved_prefixes: Vec::new(),
22032            protocol: ModuleProtocol::None,
22033            overlap: Default::default(),
22034            carry_containment: false,
22035        };
22036        let child =
22037            spawn_and_mark_running(&spec, &runtime, &snapshot).expect("spawn supervised tree");
22038        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
22039        let grandchild: u32 = loop {
22040            if let Ok(contents) = std::fs::read_to_string(&pid_file) {
22041                if let Ok(pid) = contents.trim().parse() {
22042                    break pid;
22043                }
22044            }
22045            assert!(
22046                tokio::time::Instant::now() < deadline,
22047                "grandchild pid was not recorded"
22048            );
22049            tokio::time::sleep(Duration::from_millis(10)).await;
22050        };
22051        assert!(
22052            running(grandchild),
22053            "grandchild must be alive before teardown"
22054        );
22055        if shutdown {
22056            let mut child = child;
22057            crate::child_roster::end_children_for_daemon_shutdown(
22058                &runtime.child_roster,
22059                false,
22060                std::future::pending(),
22061            )
22062            .await;
22063            child.wait().await.expect("reap shutdown straggler");
22064            child
22065                .finish_exit(false)
22066                .await
22067                .expect("finalize shutdown straggler's cgroup");
22068        } else {
22069            drain_child_to_state(
22070                module_id,
22071                ModuleProtocol::None,
22072                StopNotice::NotSent,
22073                &Registry::default(),
22074                None,
22075                &snapshot,
22076                &runtime.terminal_ring,
22077                &SpawnEventFeed::default(),
22078                child,
22079                Duration::from_millis(100),
22080                ModuleState::Stopped,
22081                Some(false),
22082                &FailureContext::operator(),
22083            )
22084            .await
22085            .expect("real supervisor teardown");
22086        }
22087        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
22088        while running(grandchild) && tokio::time::Instant::now() < deadline {
22089            tokio::time::sleep(Duration::from_millis(10)).await;
22090        }
22091        let survived = running(grandchild);
22092        // Kill a surviving grandchild so a failed test does not leave it behind.
22093        if survived {
22094            let pid = rustix::process::Pid::from_raw(grandchild as i32).unwrap();
22095            let _ = rustix::process::kill_process(pid, rustix::process::Signal::KILL);
22096            tokio::time::sleep(Duration::from_millis(100)).await;
22097        }
22098        if module.exists() {
22099            std::fs::remove_dir(&module).expect("remove empty module cgroup");
22100        }
22101        std::fs::remove_dir(root.join("subc-modules")).unwrap();
22102        std::fs::remove_dir(&root).unwrap();
22103        assert!(
22104            !survived,
22105            "grandchild {grandchild} outlived module teardown"
22106        );
22107        eprintln!("EXECUTED {test_name}: grandchild {grandchild} killed in isolated cgroup");
22108    }
22109}
22110
22111/// A slow live-children record write on the restart path must not stop the
22112/// daemon from answering the replacement module's authentication handshake.
22113#[cfg(all(test, unix))]
22114mod record_write_stall_tests {
22115    use super::*;
22116    use std::sync::atomic::{AtomicBool, Ordering};
22117    use subc_transport::{authenticate_client, ConnectionInfo, Endpoint, SCHEMA_VERSION};
22118
22119    /// `subc-client-rs` gives the whole handshake this long before the module
22120    /// exits with `Timeout { stage: ServerProof }`.
22121    const MODULE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
22122    /// How long the replacement's admission write is held: longer than the
22123    /// module's deadline, standing in for the delay a busy disk can add
22124    /// across the two syncs in that write.
22125    const HELD_RECORD_WRITE: Duration = Duration::from_secs(3);
22126
22127    /// A module that runs `/bin/sleep` directly, not through `/bin/sh -c`.
22128    /// On macOS every module is launched through the privacy trampoline, and
22129    /// a module that is not a `#!` script is admitted only if its running
22130    /// image is the configured program. With `/bin/sh -c "exec sleep 600"`
22131    /// the shell soon replaces itself with `/bin/sleep`, which does not match
22132    /// the configured `/bin/sh`. The image is read only after the spawn's
22133    /// live-children record write, and here that write lasted long enough for
22134    /// the shell to have exec'd every time, so each process was refused and
22135    /// killed right after spawn, and the supervisor crash-looped it with
22136    /// backoff until its restart budget ran out. The restart this test
22137    /// measures would then never produce a module at all.
22138    fn sleeping_spec() -> ModuleSpec {
22139        ModuleSpec {
22140            script: None,
22141            module_id: "record-write-stall".into(),
22142            program: "/bin/sleep".into(),
22143            args: vec!["600".into()],
22144            env: vec![],
22145            reserved: false,
22146            reserved_prefixes: vec![],
22147            protocol: ModuleProtocol::None,
22148            overlap: Default::default(),
22149            carry_containment: false,
22150        }
22151    }
22152
22153    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
22154    async fn module_auth_completes_while_the_restart_waits_on_the_record_write() {
22155        let home = cortexkit_test_support::ScratchDir::new("record-write-stall");
22156        let supervisor =
22157            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
22158                .with_live_children_record(home.join("live-children.json"));
22159        let module = supervisor.spawn(sleeping_spec()).unwrap();
22160        // `reported_pid` names a process only once it is confirmed as the
22161        // module (on macOS, once the trampoline's image check has passed), so
22162        // a process the daemon is about to refuse and kill never counts as
22163        // the running module, here or in the final wait below.
22164        let old_pid = tokio::time::timeout(Duration::from_secs(10), async {
22165            loop {
22166                if let Some(pid) = lock_snapshot(&module.inner.snapshot)
22167                    .unwrap()
22168                    .reported_pid()
22169                {
22170                    return pid;
22171                }
22172                tokio::time::sleep(Duration::from_millis(10)).await;
22173            }
22174        })
22175        .await
22176        .expect("the first process was admitted as the module");
22177
22178        // The daemon's listener, served by this runtime's workers like the
22179        // supervisor's own tasks.
22180        let key = vec![0x42; 32];
22181        let daemon_id = [0x24; 16];
22182        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
22183        let port = listener.local_addr().unwrap().port();
22184        let server = tokio::spawn(crate::server::serve_listener(
22185            listener,
22186            Arc::new(crate::router::Router::with_default_self_handler()),
22187            crate::server::ServerAuth::with_limits(
22188                key.clone(),
22189                daemon_id,
22190                "test",
22191                crate::server::DEFAULT_AUTH_DEADLINE,
22192                4,
22193            ),
22194        ));
22195
22196        // Hold the write that admits the replacement, once, and say when it
22197        // has started.
22198        let (held_tx, held_rx) = std::sync::mpsc::channel();
22199        let armed = AtomicBool::new(true);
22200        supervisor
22201            .child_roster
22202            .set_record_write_hook_for_test(move |live| {
22203                let admitting_replacement = live.values().any(|entry| entry.pid != old_pid);
22204                if admitting_replacement && armed.swap(false, Ordering::SeqCst) {
22205                    let _ = held_tx.send(());
22206                    std::thread::sleep(HELD_RECORD_WRITE);
22207                }
22208            });
22209
22210        // The replacement module, as a separate process would be: its own
22211        // thread and runtime, so only the daemon's runtime can be stalled.
22212        let module_process = std::thread::spawn(move || {
22213            held_rx
22214                .recv_timeout(Duration::from_secs(30))
22215                .expect("the restart reached the replacement's record write");
22216            let conn = ConnectionInfo {
22217                schema: SCHEMA_VERSION,
22218                wire_version: None,
22219                endpoints: vec![Endpoint {
22220                    host: "127.0.0.1".to_owned(),
22221                    port,
22222                }],
22223                key,
22224                daemon_id,
22225                pid: std::process::id(),
22226                daemon_ver: "test".to_owned(),
22227            };
22228            tokio::runtime::Builder::new_current_thread()
22229                .enable_all()
22230                .build()
22231                .unwrap()
22232                .block_on(async {
22233                    let started = Instant::now();
22234                    let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
22235                        .await
22236                        .unwrap();
22237                    let result =
22238                        authenticate_client(&mut stream, &conn, MODULE_AUTH_DEADLINE).await;
22239                    (result, started.elapsed())
22240                })
22241        });
22242
22243        module.restart(Some(0)).await.unwrap();
22244        let (auth, elapsed) = tokio::task::spawn_blocking(move || module_process.join().unwrap())
22245            .await
22246            .unwrap();
22247        assert!(
22248            auth.is_ok(),
22249            "the daemon must answer a module's handshake while a restart waits on the \
22250             live-children record write; got {auth:?} after {elapsed:?}"
22251        );
22252
22253        tokio::time::timeout(Duration::from_secs(20), async {
22254            while lock_snapshot(&module.inner.snapshot)
22255                .unwrap()
22256                .reported_pid()
22257                .is_none_or(|pid| pid == old_pid)
22258            {
22259                tokio::time::sleep(Duration::from_millis(10)).await;
22260            }
22261        })
22262        .await
22263        .expect("the restart published its replacement");
22264        module.stop().await.unwrap();
22265        server.abort();
22266    }
22267}
22268
22269#[cfg(all(test, unix))]
22270mod retained_status_tests {
22271    use super::*;
22272
22273    #[tokio::test]
22274    async fn cached_container_block_is_visible_in_status_and_health_without_rechecking() {
22275        use crate::live_children::{ContainerIdentity, RetainedReason};
22276        for (reason, carried, expected) in [
22277            (
22278                RetainedReason::ContainerSurvivors(vec![4242]),
22279                true,
22280                Some("waiting: container survivors (pids [4242])".to_owned()),
22281            ),
22282            (
22283                RetainedReason::ContainerUnverifiable("member inspection denied".into()),
22284                true,
22285                Some(
22286                    "waiting: container survivors could not be verified: member inspection denied"
22287                        .to_owned(),
22288                ),
22289            ),
22290            (RetainedReason::Survived, false, None),
22291        ] {
22292            let supervisor =
22293                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
22294            let spec = ModuleSpec {
22295                script: None,
22296                module_id: "retained-status-fixture".into(),
22297                program: PathBuf::from("/not-spawned"),
22298                args: Vec::new(),
22299                env: Vec::new(),
22300                reserved: false,
22301                reserved_prefixes: Vec::new(),
22302                protocol: ModuleProtocol::None,
22303                overlap: ModuleOverlap::Exclusive,
22304                carry_containment: carried,
22305            };
22306            let module = supervisor
22307                .supervise_configured(spec.clone(), false)
22308                .unwrap();
22309            // No process is launched. Invalid group zero is deliberate: if a
22310            // status read wrongly rechecks, verification changes the reason
22311            // and fails the assertions without signalling any real process.
22312            let guard = supervisor
22313                .child_roster
22314                .admit(
22315                    spec.module_id,
22316                    0,
22317                    ModuleProtocol::None,
22318                    None,
22319                    crate::child_roster::RecordedIdentity {
22320                        container: carried.then_some(ContainerIdentity {
22321                            pgid: Some(0),
22322                            created_start_time: Some(0),
22323                            cgroup_path: None,
22324                            ..ContainerIdentity::test_metadata()
22325                        }),
22326                        ..crate::child_roster::RecordedIdentity::default()
22327                    },
22328                )
22329                .unwrap();
22330            guard.retain(reason);
22331            let status = module.status().unwrap();
22332            assert_eq!(status.waiting_for_previous_detail, expected.clone());
22333            assert_eq!(status.health.detail, expected);
22334            assert!(!status.process_alive);
22335        }
22336    }
22337}
22338
22339fn registration_child_is_running(child: &mut SupervisedChild) -> bool {
22340    child.try_wait().is_ok_and(|status| status.is_none())
22341}