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;
103#[cfg(all(test, unix))]
104mod config_exit_hold_tests;
105pub(crate) mod containment;
106#[cfg(all(test, unix))]
107mod containment_tests;
108mod slow_retry;
109use slow_retry::{FailedRetry, FailureContext};
110mod host_health;
111use host_health::HostHealth;
112
113#[cfg(all(test, unix))]
114mod mark_readiness_tests;
115#[cfg(all(test, unix))]
116mod slow_retry_tests;
117
118/// Command-line flag used by supervised modules to find subc.
119///
120/// subc launches module-mode children as `<module> --subc <connection-file-path>`.
121/// The path points at the TCP+key connection file; it is not an ambient signal and
122/// is never inherited by standalone children.
123pub const SUBC_ARG: &str = "--subc";
124
125const DEFAULT_MAX_RESTARTS: u32 = 3;
126const DEFAULT_BACKOFF: Duration = Duration::from_millis(100);
127const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
128/// The span `DEFAULT_MAX_RESTARTS` is counted over. Ten minutes is long enough
129/// to contain a real crash loop (which respawns in seconds) and short enough
130/// that unrelated crashes hours apart never accumulate into a permanent stop.
131const DEFAULT_RESTART_WINDOW: Duration = Duration::from_secs(600);
132/// How long a drain waits for already-dispatched requests to finalize before
133/// the child is torn down. Sized for TOOL-SCALE work (bash, inspect, builds),
134/// not RPC-scale: the original 2s value silently cut nearly every real tool
135/// call at the fence, making the wait-for-finalize design decorative for the
136/// workloads it existed for. Quiescence short-circuits, so an idle module
137/// restarts immediately regardless of this value; the budget is spent only
138/// when a genuine in-flight request is worth finishing. Per-module override:
139/// `drain_timeout_ms` in subc.jsonc; per-restart override: the operator's
140/// `supervisor.restart{drain_timeout_ms}` (0 = cut now, for wedge bounces
141/// where a stuck request will never settle).
142pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
143// Child admission durably records identity before exec. Disk pressure can make
144// fsync slow without implying a failed child start, so allow a generous budget.
145#[cfg(any(unix, feature = "test-support"))]
146const ADMISSION_TIMEOUT: Duration = Duration::from_secs(30);
147
148/// Daemon-side child-admission budget, for integration-test RPC deadlines.
149#[cfg(feature = "test-support")]
150pub const CHILD_ADMISSION_TIMEOUT: Duration = ADMISSION_TIMEOUT;
151
152pub(crate) const DEFAULT_REGISTER_TIMEOUT: Duration = Duration::from_secs(120);
153const REGISTRY_RELEASE_TIMEOUT: Duration = Duration::from_secs(1);
154const REGISTRY_RELEASE_POLL: Duration = Duration::from_millis(10);
155/// How long a drain waits after one busy-gauge probe completes before it asks
156/// again.
157///
158/// A drain re-probes on this short interval of its own rather than on the
159/// module's health cadence. The default cadence (30 s) equals the default
160/// drain ceiling, so a cadence-paced drain that found the module busy at its
161/// first probe never asked a second time: it waited out the whole ceiling and
162/// forced GOODBYE even after the gauges had read zero. The interval is counted
163/// from the moment the previous probe finished, and probes run one at a time,
164/// so a slow module is never asked more often than it can answer. Periodic
165/// health checks outside a drain keep using the configured cadence.
166const DRAIN_BUSY_REPROBE_INTERVAL: Duration = Duration::from_millis(250);
167/// How long a restart waits per pipe for queued capture to finish.
168///
169/// A reader and writer still running at the bound are left running. Stderr
170/// stays in the exited process's section of the ring. Its tail reports
171/// `Incomplete` until EOF has reached the writer, and stays incomplete if
172/// backpressure forced capture to drop lines. Late output from either pipe
173/// can reach the capture file after the successor starts.
174const STDERR_PUMP_DRAIN_TIMEOUT: Duration = Duration::from_millis(250);
175/// Maximum number of supervised process spawn/exit facts retained per daemon incarnation.
176pub const SPAWN_EVENT_RING_CAPACITY: usize = 4096;
177const SPAWN_SUBSCRIBER_BUFFER: usize = SPAWN_EVENT_RING_CAPACITY + 1;
178/// Terminal Error code for a `supervisor.spawn_subscribe` stream the daemon
179/// dropped because the subscriber stopped draining its frames. The detail's
180/// `first_undelivered_cursor` names the first event it did not receive; the
181/// client resubscribes from the last cursor it did receive.
182pub(crate) const SPAWN_SUBSCRIBER_LAGGED_CODE: &str = "spawn_subscriber_lagged";
183
184#[cfg(target_os = "macos")]
185struct PrivacyExec {
186    content_check: Option<tokio::task::JoinHandle<Result<(), crate::config_gate::GateError>>>,
187    gated: bool,
188    admission_binding: Option<ProgramBindingPublication>,
189    reader: tokio::io::unix::AsyncFd<std::io::PipeReader>,
190    deadline: tokio::time::Instant,
191    expected: Option<subc_os::FileIdentity>,
192    trampoline: Option<subc_os::FileIdentity>,
193    signature: Option<Arc<subc_os::privacy_identity::SuspendedSignature>>,
194    module_id: String,
195    #[cfg(test)]
196    confirmation_pause: Option<(String, Option<tokio::net::TcpStream>)>,
197    #[cfg(test)]
198    image_probe: Option<fn(u32) -> Option<subc_os::Observation>>,
199    #[cfg(test)]
200    image_read_delay: Option<Duration>,
201}
202
203#[cfg(all(test, target_os = "macos"))]
204pub(crate) fn test_privacy_trampoline() -> PathBuf {
205    // The fixture bin lives in the profile folder the unit-test executable was
206    // built into. This honors custom CARGO_TARGET_DIR too.
207    let path = cortexkit_test_support::cargo_profile_bin("privacy-trampoline-fixture");
208    // Without the fixture every macOS spawn is refused, and the tests that
209    // spawn fail later as a module in state Failed, which names the wrong
210    // cause. `cargo test -p subc-daemon --lib` alone does not build it.
211    assert!(
212        path.exists(),
213        "privacy-trampoline-fixture not built at {}: run `cargo build -p subc-daemon \
214         --bins --features test-support` or `cargo test -p subc-daemon` first",
215        path.display()
216    );
217    path
218}
219
220#[cfg(target_os = "macos")]
221fn probe_privacy_trampoline(path: &std::path::Path) -> Result<(), String> {
222    use std::io::Read;
223    let mut probe = subc_os::child_spawn::spawn(
224        std::process::Command::new(path)
225            .args(["__disclaim-exec", "--probe-suspended"])
226            .stdin(Stdio::null())
227            .stdout(Stdio::piped())
228            .stderr(Stdio::piped()),
229    )
230    .map_err(|error| {
231        format!(
232            "privacy trampoline probe failed for {}: {error}",
233            path.display()
234        )
235    })?;
236    let deadline = std::time::Instant::now() + Duration::from_secs(5);
237    let status = loop {
238        match probe.try_wait() {
239            Ok(Some(status)) => break status,
240            Ok(None) if std::time::Instant::now() < deadline => {
241                std::thread::sleep(Duration::from_millis(5))
242            }
243            result => {
244                let _ = probe.kill();
245                let _ = probe.wait();
246                return Err(format!(
247                    "privacy trampoline probe failed or timed out for {}: {result:?}",
248                    path.display()
249                ));
250            }
251        }
252    };
253    let mut answer = String::new();
254    if let Some(stdout) = probe.stdout.take() {
255        let _ = stdout.take(256).read_to_string(&mut answer);
256    }
257    if status.success() && answer.trim() == subc_os::privacy_identity::SUSPENDED_TRAMPOLINE_PROBE {
258        return Ok(());
259    }
260    let mut diagnostic = String::new();
261    if let Some(stderr) = probe.stderr.take() {
262        let _ = stderr.take(1024).read_to_string(&mut diagnostic);
263    }
264    let cause = diagnostic
265        .trim()
266        .strip_prefix("ck-subc: own privacy identity refused: ")
267        .unwrap_or("binary does not implement the privacy trampoline protocol");
268    Err(format!(
269        "{cause}: probe of {} exited {status}",
270        path.display()
271    ))
272}
273
274#[cfg(target_os = "macos")]
275fn privacy_command(
276    spec: &ModuleSpec,
277    binding: &SpawnProgramBinding,
278    roster: &ChildRoster,
279    gated: bool,
280) -> Result<
281    (
282        Command,
283        Option<PrivacyExec>,
284        subc_os::privacy_identity::ExecAcknowledgement,
285    ),
286    SuperviseError,
287> {
288    let failure = |cause: String| {
289        warn!(module_id = %spec.module_id, %cause, "privacy identity trampoline refused module spawn");
290        SuperviseError::Spawn {
291            program: spec.program.clone(),
292            source: io::Error::other(cause),
293            cgroup_path: None,
294        }
295    };
296    let trampoline = roster.privacy_trampoline().map_err(failure)?;
297    let expected = Some(binding.identity);
298    let trampoline_image = subc_os::file_identity(&trampoline);
299    let signature = gated
300        .then(|| {
301            subc_os::privacy_identity::SuspendedSignature::capture(&binding._file, &binding.path)
302                .map(Arc::new)
303        })
304        .transpose()
305        .map_err(|error| failure(error.to_string()))?;
306    if expected == trampoline_image {
307        return Err(failure(
308            "privacy identity module executable is missing or is the trampoline itself".to_string(),
309        ));
310    }
311    let (reader, ack) = subc_os::privacy_identity::ExecAcknowledgement::pipe()
312        .map_err(|error| failure(error.to_string()))?;
313    let reader =
314        tokio::io::unix::AsyncFd::new(reader).map_err(|error| failure(error.to_string()))?;
315    let mut command = Command::new(&trampoline);
316    command
317        .arg(if gated {
318            "__disclaim-exec-suspended"
319        } else {
320            "__disclaim-exec"
321        })
322        .arg(ack.fd().to_string())
323        .arg(&binding.path);
324    Ok((
325        command,
326        Some(PrivacyExec {
327            gated,
328            admission_binding: None,
329            content_check: None,
330            reader,
331            deadline: tokio::time::Instant::now() + Duration::from_secs(5),
332            expected,
333            trampoline: trampoline_image,
334            signature,
335            module_id: spec.module_id.clone(),
336            #[cfg(test)]
337            image_probe: None,
338            #[cfg(test)]
339            image_read_delay: spec
340                .env
341                .iter()
342                .find(|(key, _)| key == "SUBC_TEST_PRIVACY_IMAGE_DELAY_MS")
343                .map(|(_, millis)| Duration::from_millis(millis.parse().unwrap())),
344            #[cfg(test)]
345            confirmation_pause: spec
346                .env
347                .iter()
348                .find(|(key, _)| key == "SUBC_TEST_BEFORE_EXEC_CONFIRM")
349                .map(|(_, address)| (address.clone(), None)),
350        }),
351        ack,
352    ))
353}
354
355#[cfg(unix)]
356type SpawnRegistrationChannel = std::os::unix::net::UnixStream;
357#[cfg(windows)]
358type SpawnRegistrationChannel = subc_os::registration_channel::RegistrationPipe;
359#[cfg(test)]
360type CapturedRegistrationChannels =
361    Arc<Mutex<Option<Vec<(Arc<RegistrationSpawn>, CapturedRegistrationEndpoint)>>>>;
362#[cfg(test)]
363struct CapturedRegistrationEndpoint {
364    _channel: SpawnRegistrationChannel,
365}
366#[cfg(test)]
367impl fmt::Debug for CapturedRegistrationEndpoint {
368    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369        f.write_str("CapturedRegistrationEndpoint")
370    }
371}
372
373struct SupervisedChild {
374    registration_spawn: Option<Arc<RegistrationSpawn>>,
375    /// Owned daemon endpoint, retained for the per-spawn registration service.
376    #[cfg(any(unix, windows))]
377    registration_channel: Option<SpawnRegistrationChannel>,
378    live_program_binding: Option<Arc<content_binding::LiveProgramBinding>>,
379    registered_config_connection: Option<ConnectionId>,
380    admission_base: Option<subc_config::Digest>,
381    registration_declaration: Option<String>,
382    _program_binding: Option<ProgramBindingPublication>,
383    subtree_target: crate::subtree_resources::Target,
384    child: containment::ProcessChild,
385    exec: crate::activity::ExecOwner,
386    #[cfg(windows)]
387    nonce_delivery: Option<subc_os::LaunchNoncePipeDelivery>,
388    #[cfg(target_os = "macos")]
389    privacy_exec: Option<PrivacyExec>,
390    /// Set once this launch's exec acknowledgement confirms the module image.
391    /// On macOS the pid first runs the `ck-subc` launch trampoline (see
392    /// `subc_os::privacy_identity`), which then replaces itself with the
393    /// module. The supervisor owns and can kill that pid from spawn, but
394    /// status readers report it only after this latch is set, so nothing
395    /// reports the trampoline's image as the module's.
396    #[cfg(target_os = "macos")]
397    report_ready: Arc<OnceLock<()>>,
398    /// Supervisor failure detail retained for the terminal record, including
399    /// image refusals and first-HELLO timeouts after a successful spawn.
400    spawn_failure: Option<String>,
401    /// Set only after a kill requested because launch admission failed was
402    /// accepted, never for an operator, health, or shutdown kill.
403    admission_kill_sent: bool,
404    /// The protocol this process was launched with. A reload can store a new
405    /// launch spec with a different protocol, but that takes effect only at the
406    /// next spawn, so this process keeps being handled by the protocol it
407    /// actually speaks.
408    protocol: ModuleProtocol,
409    /// This container's cgroup name: a bounded module/slot label followed by a
410    /// unique suffix (when cgroup placement is on). Carried replacements reuse
411    /// the name; ordinary launches each get a fresh container. A
412    /// retired process in a slot may still be draining when a later one is
413    /// spawned into that slot, so the suffix keeps the later process out of
414    /// the retired one's cgroup, which is the domain a kill applies to.
415    #[cfg(target_os = "linux")]
416    module_id: String,
417    #[cfg(target_os = "linux")]
418    cgroup_placement: Option<subc_cgroup::Placement>,
419    /// The job for an ordinary, non-carried launch. For carried
420    /// launches the actor owns it and the child holds only a weak container link.
421    ///
422    /// Dropping this handle is what reaps a surviving tree when no supervisor
423    /// code runs — a daemon crash — because the job carries
424    /// `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`.
425    ///
426    /// That limit is not crash-only, and the difference is worth knowing: a
427    /// Windows daemon *stop* is `taskkill` or the scheduler's `/End` — the
428    /// SIGTERM handler is `#[cfg(unix)]` — so the daemon dies with no stop
429    /// notice and the kernel closes the job handle, `TerminateProcess`ing every
430    /// module at once. Before this change they survived that, saw EOF on the
431    /// control socket, and ran their own teardown; Unix keeps that path
432    /// deliberately, so a module can seal a WAL or close a capture rather than
433    /// be killed mid-write. So this trades graceful teardown on every Windows
434    /// daemon stop for containment on a crash, which is the right way round
435    /// today: orphaned GPU workers are a reported, recurring problem, and the
436    /// modules that write most heavily do not run on Windows.
437    ///
438    /// The fix is a real Windows stop path — the daemon draining before it
439    /// exits, the twin of the Unix SIGTERM handler. Once it exists, this limit
440    /// reaches only what the drain left behind, which is what it should reach.
441    #[cfg(windows)]
442    job: Option<Arc<Mutex<subc_jobobject::JobObject>>>,
443    stdout_pump: Option<tokio::sync::oneshot::Receiver<()>>,
444    stderr_pump: Option<StderrPump>,
445    stderr_ring: Arc<Mutex<StderrRing>>,
446    /// Conservative monotonic bound sampled before `command.spawn()`, not when
447    /// identity recording finishes or the spawn generation is published.
448    spawned_at: Instant,
449    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
450    /// Ordinary spawns must send their first HELLO within this budget. Once
451    /// accepted, a later disconnect must not restart the registration clock.
452    registration_deadline: Option<Instant>,
453    registration_watch: Option<RegistrationWatch>,
454    spawned_at_ms: u64,
455    spawned_from: PathBuf,
456    launch_spec_digest: LaunchSpecDigest,
457    spawned_file_identity: Option<SpawnedFileIdentity>,
458    process_start_time: Option<u64>,
459    process_identity: Option<ProcessIdentity>,
460    pid: u32,
461    /// This process's entry in the daemon's child roster, released when the
462    /// process is reaped or this handle is dropped.
463    roster_guard: Option<crate::child_roster::RosterGuard>,
464}
465
466impl SupervisedChild {
467    fn retire_registration(&self) {
468        // All exit observers enter here before cleanup can await. The retired
469        // program-binding flag and the registration's Dead state make repeated
470        // observations harmless, even when another task observes the group
471        // leader retained unreaped to reserve its process-group id.
472        if let Some(spawn) = &self.registration_spawn {
473            spawn.retire();
474        } else if let Some(binding) = &self._program_binding {
475            binding.retire();
476        }
477        #[cfg(unix)]
478        if let Some(channel) = &self.registration_channel {
479            let _ = channel.shutdown(std::net::Shutdown::Both);
480        }
481        #[cfg(windows)]
482        if let Some(channel) = &self.registration_channel {
483            if let Ok(shutdown) = channel.shutdown_handle() {
484                shutdown.shutdown();
485            }
486        }
487    }
488    fn registered_since_spawn(&self) -> bool {
489        self.registration_watch
490            .as_ref()
491            .is_some_and(|watch| *watch.changes.borrow() != watch.baseline)
492    }
493
494    fn awaiting_registration(&self) -> bool {
495        // Admission failure retires the channel before its kill becomes
496        // waitable. That closure must not replace the admission failure with
497        // a registration failure and spend crash restart budget.
498        let admission_failed = self.admission_kill_sent && self.spawn_failure.is_some();
499        !admission_failed && !self.registered_since_spawn()
500    }
501
502    fn id(&self) -> Option<u32> {
503        Some(self.pid)
504    }
505
506    fn process_identity(&self) -> Option<ProcessIdentity> {
507        self.process_identity
508    }
509
510    fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
511        let result = self.child.try_wait();
512        if !matches!(result, Ok(None)) {
513            self.retire_registration();
514            #[cfg(any(unix, windows))]
515            self.registration_channel.take();
516            if let Some(binding) = &self._program_binding {
517                binding.retire();
518            }
519        }
520        result
521    }
522
523    async fn wait(&mut self) -> io::Result<ExitStatus> {
524        #[cfg(target_os = "macos")]
525        self.confirm_privacy_exec().await;
526        // The roster entry is NOT released here. A daemon shutdown waits for the
527        // roster to empty and then exits the process, so releasing at the reap
528        // let it exit before the exit handler wrote this child's terminal record
529        // (the stderr drain and snapshot update sit in between), and the
530        // shutdown's own `daemon_shutdown` record was intermittently lost. The
531        // caller releases it after recording the exit (`release_roster`), and
532        // dropping the handle releases it too.
533        let result = self.child.wait().await;
534        self.retire_registration();
535        #[cfg(any(unix, windows))]
536        self.registration_channel.take();
537        // All plain and swap waits pass here. Revoke the reaped child's nonce
538        // before cgroup cleanup, stderr draining or exit observation can await.
539        if let Some(binding) = &self._program_binding {
540            binding.retire();
541        }
542        #[cfg(all(test, target_os = "linux"))]
543        if let Some(binding) = &self._program_binding {
544            binding.pause_after_wait_for_test().await;
545        }
546        #[cfg(target_os = "linux")]
547        if result.is_ok() && self.child.container().is_none() {
548            if let Some(placement) = self.cgroup_placement.as_ref() {
549                // Ordinary children still own a per-spawn cgroup: returning
550                // from wait must leave it empty and removed, as before carry.
551                // Keep cleanup ownership across cancellation until it finishes.
552                cleanup_reaped_cgroup(placement, &self.module_id).await;
553                self.cgroup_placement = None;
554            }
555        }
556        result
557    }
558
559    async fn finish_exit(&mut self, carry: bool) -> io::Result<()> {
560        self.retire_registration();
561        // Idempotent fallback for cleanup paths that did not call wait.
562        if let Some(binding) = self._program_binding.take() {
563            binding.retire();
564        }
565        if self.child.container().is_some() {
566            if !carry {
567                self.child.terminate_container().await;
568            }
569        } else {
570            #[cfg(target_os = "linux")]
571            if let Some(placement) = self.cgroup_placement.as_ref() {
572                cleanup_reaped_cgroup(placement, &self.module_id).await;
573                self.cgroup_placement = None;
574            }
575        }
576        self.child.reap().await?;
577        self.release_roster();
578        Ok(())
579    }
580
581    #[cfg(target_os = "macos")]
582    async fn confirm_privacy_exec(&mut self) {
583        if self
584            .privacy_exec
585            .as_ref()
586            .is_some_and(|pending| pending.content_check.is_some())
587        {
588            self.finish_privacy_content_check().await;
589            return;
590        }
591        let Some(pending) = &mut self.privacy_exec else {
592            return;
593        };
594        let result = tokio::time::timeout_at(pending.deadline, async {
595            let mut record = Vec::new();
596            loop {
597                let mut ready = pending.reader.readable().await?;
598                let read = ready.try_io(|reader| {
599                    use std::io::Read;
600                    let mut reader = reader.get_ref();
601                    let mut buffer = [0u8; 256];
602                    reader.read(&mut buffer).map(|count| (count, buffer))
603                });
604                match read {
605                    Ok(Ok((0, _))) => return Ok::<_, io::Error>(record),
606                    Ok(Ok((count, buffer))) => {
607                        if record.len() + count > 1024 {
608                            return Err(io::Error::other(
609                                "privacy exec refusal record is too long",
610                            ));
611                        }
612                        record.extend_from_slice(&buffer[..count]);
613                    }
614                    Ok(Err(error)) => return Err(error),
615                    Err(_) => continue,
616                }
617            }
618        })
619        .await;
620        #[cfg(test)]
621        let result = if let Some((address, stream)) = &mut pending.confirmation_pause {
622            use tokio::io::{AsyncReadExt, AsyncWriteExt};
623            if stream.is_none() {
624                *stream = Some(
625                    tokio::net::TcpStream::connect(address.as_str())
626                        .await
627                        .unwrap(),
628                );
629                stream.as_mut().unwrap().write_all(b"R").await.unwrap();
630                stream
631                    .as_mut()
632                    .unwrap()
633                    .write_all(&self.pid.to_ne_bytes())
634                    .await
635                    .unwrap();
636            }
637            let mut reply = [0];
638            stream
639                .as_mut()
640                .unwrap()
641                .read_exact(&mut reply)
642                .await
643                .unwrap();
644            pending.confirmation_pause = None;
645            if &reply == b"F" {
646                Ok(Err(io::Error::other("injected late exec refusal")))
647            } else {
648                assert_eq!(&reply, b"X");
649                result
650            }
651        } else {
652            result
653        };
654        // Keep the reader in self across await: select cancellation must not
655        // discard the handshake or reset its original five-second deadline.
656        // Use try_wait so a child reaped during confirmation has its program
657        // binding retired before another command can use its nonce.
658        let waited = if matches!(&result, Ok(Ok(record)) if record.is_empty()) {
659            Some(self.try_wait())
660        } else {
661            None
662        };
663        let pending = self.privacy_exec.as_ref().expect("pending exec");
664        let cause = match result {
665            Err(_) => Some("privacy identity trampoline did not exec within 5s".to_string()),
666            Ok(Err(error)) => Some(format!(
667                "privacy identity exec acknowledgement failed: {error}"
668            )),
669            Ok(Ok(record)) if !record.is_empty() => Some(
670                std::str::from_utf8(&record)
671                    .ok()
672                    .and_then(|record| {
673                        record
674                            .trim()
675                            .strip_prefix(subc_os::privacy_identity::EXEC_REFUSAL_TAG)
676                    })
677                    .filter(|cause| !cause.is_empty())
678                    .unwrap_or("invalid privacy exec refusal record")
679                    .to_string(),
680            ),
681            Ok(Ok(_)) if !pending.gated => match waited.expect("exec EOF checked child") {
682                Ok(Some(_)) => None,
683                Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
684                Ok(None) => {
685                    #[cfg(test)]
686                    if let Some(delay) = pending.image_read_delay {
687                        tokio::time::sleep(delay).await;
688                    }
689                    let image = observe_spawned_image(self.pid);
690                    #[cfg(test)]
691                    let image = pending.image_probe.map_or(image, |probe| probe(self.pid));
692                    // An unstamped module can re-exec before we wake to read its
693                    // image. Only the trampoline image proves exec never happened;
694                    // retain the observed image for later orphan identification.
695                    if let Some(image) = image.filter(|image| {
696                        image.executable.is_some() && image.executable != pending.trampoline
697                    }) {
698                        match self
699                            .roster_guard
700                            .as_ref()
701                            .map(|guard| guard.confirm_executable(image))
702                            .transpose()
703                        {
704                            Err(error) => Some(format!(
705                                "could not durably record confirmed module image: {error}"
706                            )),
707                            Ok(_) => {
708                                let _ = self.report_ready.set(());
709                                None
710                            }
711                        }
712                    } else if image.is_none()
713                        || image.is_some_and(|image| image.executable.is_none())
714                    {
715                        // Empty EOF acknowledged exec. An image disappearing
716                        // during observation is an ordinary module exit.
717                        match tokio::time::timeout_at(pending.deadline, self.child.wait()).await {
718                            Ok(result) => {
719                                self.retire_registration();
720                                self.registration_channel.take();
721                                if let Some(binding) = &self._program_binding {
722                                    binding.retire();
723                                }
724                                result.err().map(|error| format!("privacy identity trampoline wait failed: {error}"))
725                            }
726                            Err(_) => Some("privacy identity module executable remained unreadable until the 5s exec deadline".to_string()),
727                        }
728                    } else {
729                        Some("privacy identity trampoline did not exec the module".to_string())
730                    }
731                }
732            },
733            Ok(Ok(_)) => match waited.expect("exec EOF checked child") {
734                Ok(Some(_)) => {
735                    Some("privacy identity target exited before suspended admission".to_string())
736                }
737                Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
738                Ok(None) => {
739                    // CLOEXEC closes the ack just before the kernel reports the
740                    // suspended target. EOF alone must never admit a running image.
741                    let stopped = tokio::time::timeout_at(pending.deadline, async {
742                        loop {
743                            if subc_os::privacy_identity::SuspendedSignature::is_suspended(
744                                self.pid,
745                            )? {
746                                return Ok::<_, io::Error>(());
747                            }
748                            tokio::time::sleep(Duration::from_millis(1)).await;
749                        }
750                    })
751                    .await;
752                    match stopped {
753                        Err(_) => {
754                            Some("privacy identity target was not suspended within 5s".to_string())
755                        }
756                        Ok(Err(error)) => Some(format!(
757                            "privacy identity suspended target unavailable: {error}"
758                        )),
759                        Ok(Ok(())) => {
760                            let image = observe_spawned_image(self.pid);
761                            if image.is_some_and(|image| {
762                                image.executable.is_some()
763                                    && image.executable != pending.trampoline
764                                    && image.executable == pending.expected
765                            }) {
766                                None
767                            } else {
768                                Some("privacy identity trampoline executable mismatch: expected the suspended module program".to_string())
769                            }
770                        }
771                    }
772                }
773            },
774        };
775        #[cfg(test)]
776        if let Some(binding) = &self._program_binding {
777            binding.pause_after_wait_for_test().await;
778        }
779        if cause.is_none() && pending.gated {
780            let publication = pending.admission_binding.clone();
781            let live = self.live_program_binding.clone();
782            let signature = Arc::clone(pending.signature.as_ref().expect("gated signature"));
783            let pid = self.pid;
784            let gated = pending.gated;
785            self.privacy_exec
786                .as_mut()
787                .expect("pending exec")
788                .content_check = Some(tokio::task::spawn_blocking(move || {
789                signature.verify(pid).map_err(|error| {
790                    crate::config_gate::GateError::new("program_refused", error)
791                })?;
792                if !gated {
793                    return Ok(());
794                }
795                match (publication, live) {
796                    (Some(publication), _) => publication.verify(),
797                    (None, Some(live)) => live.check(),
798                    _ => Err(crate::config_gate::GateError::new(
799                        "config_delivery_deferred",
800                        "live program witness is unavailable",
801                    )),
802                }
803            }));
804            self.finish_privacy_content_check().await;
805        } else {
806            self.finish_privacy_exec(cause);
807        }
808    }
809
810    #[cfg(target_os = "macos")]
811    async fn finish_privacy_content_check(&mut self) {
812        let result = self
813            .privacy_exec
814            .as_mut()
815            .expect("pending exec")
816            .content_check
817            .as_mut()
818            .expect("pending content check")
819            .await;
820        let cause = match result {
821            Ok(Ok(())) => None,
822            Ok(Err(error)) => Some(format!("{}: {}", error.code, error.detail)),
823            Err(error) => Some(format!(
824                "config_delivery_deferred: content check stopped: {error}"
825            )),
826        };
827        self.finish_privacy_exec(cause);
828    }
829
830    #[cfg(target_os = "macos")]
831    fn finish_privacy_exec(&mut self, mut cause: Option<String>) {
832        let mut pending = self.privacy_exec.take().expect("pending exec");
833        if cause.is_none() && pending.gated {
834            let admission = (|| -> io::Result<()> {
835                let image = observe_spawned_image(self.pid)
836                    .filter(|image| image.executable == pending.expected)
837                    .ok_or_else(|| io::Error::other("suspended executable mismatch"))?;
838                if let Some(guard) = &self.roster_guard {
839                    guard.confirm_executable(image)?;
840                }
841                pending
842                    .signature
843                    .as_ref()
844                    .expect("gated signature")
845                    .resume(self.pid)?;
846                let _ = self.report_ready.set(());
847                info!(module_id = %pending.module_id, pid = self.pid,
848                    "verified suspended module resumed with own privacy identity");
849                Ok(())
850            })();
851            if let Err(error) = admission {
852                cause = Some(format!("program_refused: {error}"));
853            }
854        }
855        if cause.is_some() {
856            if let Some(spawn) = &self.registration_spawn {
857                spawn.refuse();
858            }
859            if let Some(binding) = &mut pending.admission_binding {
860                binding.reject();
861            }
862        } else if let Some(spawn) = &self.registration_spawn {
863            spawn.ready();
864        }
865        // Exec confirmation describes launch success, not roster retirement.
866        // Keep even a reaped child recorded until its terminal history exists.
867        self.exec.0.finish(if cause.is_some() {
868            crate::activity::ExecState::Refused
869        } else {
870            crate::activity::ExecState::CommittedExec
871        });
872        if let Some(cause) = cause {
873            warn!(module_id = %pending.module_id, pid = self.pid, %cause, "privacy identity trampoline refused module spawn");
874            self.spawn_failure = Some(
875                if pending.gated
876                    && (cause.contains("executable mismatch")
877                        || cause.starts_with("program_refused:"))
878                {
879                    format!("program_refused: {cause}")
880                } else if pending.gated {
881                    format!("config_delivery_deferred: {cause}")
882                } else {
883                    cause
884                },
885            );
886            // No resume signal is sent on failure; kill the entire fresh group
887            // even if a faulty trampoline did not honor the suspended protocol.
888            let _ = self.start_admission_kill();
889        }
890    }
891
892    /// Releases the leader's roster entry after recording and finalizing its
893    /// exit. A carried container retains its separate roster entry and, for a
894    /// Unix process group, its unreaped first leader that reserves the group ID.
895    fn release_roster(&mut self) {
896        self.roster_guard = None;
897    }
898
899    /// Kill the child and, where containment is available, its process tree.
900    ///
901    /// `Child::kill` is `TerminateProcess` scoped to one pid, so a module with a
902    /// helper process leaked the helper — the Synapse embedding module's CUDA
903    /// worker holds the GPU allocation, so the leak cost VRAM until the next
904    /// restart of something else. Terminating the job reaches grandchildren that
905    /// a tree walk cannot, including one whose parent has already exited and
906    /// been reparented away.
907    ///
908    /// Best-effort like `request_graceful_stop`: a job failure is logged and the
909    /// direct-child kill still decides the outcome, so containment can never
910    /// change whether a module is reported as stopped.
911    fn start_kill(&mut self) -> io::Result<()> {
912        self.retire_registration();
913        if let Some(container) = self.child.container() {
914            container.hard_kill();
915            return self.kill_leader();
916        }
917        #[cfg(windows)]
918        if let Some(job) = &self.job {
919            if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
920                debug!(
921                    error = %error,
922                    "job termination failed; the direct-child kill still owns the outcome"
923                );
924            }
925        }
926        #[cfg(target_os = "linux")]
927        kill_module_cgroup(self.cgroup_placement.as_ref(), &self.module_id);
928        self.child.start_kill()
929    }
930
931    fn kill_leader(&mut self) -> io::Result<()> {
932        self.retire_registration();
933        self.child.start_kill()
934    }
935
936    fn start_admission_kill(&mut self) -> io::Result<()> {
937        self.retire_registration();
938        #[cfg(windows)]
939        let result = {
940            // Preserve the leader's distinctive status before ending the whole
941            // container/job; descendants must not wait for exit finalization.
942            let result = self
943                .spawned_file_identity
944                .as_ref()
945                .and_then(|identity| identity.windows_image.as_ref())
946                .ok_or_else(|| io::Error::other("admission child handle unavailable"))
947                .and_then(|image| {
948                    image.process().terminate_with_exit_code(
949                        admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE as u32,
950                    )
951                });
952            if let Some(container) = self.child.container() {
953                container.hard_kill();
954            } else if let Some(job) = &self.job {
955                if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
956                    debug!(%error, "job termination failed after admission leader termination");
957                }
958            }
959            result
960        };
961        #[cfg(not(windows))]
962        let result = self.start_kill().map(|()| true);
963        #[cfg(unix)]
964        let result = {
965            // A leader can exit before its helpers. Still end the fresh group
966            // even when the direct-child kill reports that the leader is gone.
967            let group_sent = self.child.container().is_none()
968                && rustix::process::Pid::from_raw(self.pid as i32).is_some_and(|group| {
969                    rustix::process::kill_process_group(group, rustix::process::Signal::KILL)
970                        .is_ok()
971                });
972            if group_sent {
973                Ok(true)
974            } else {
975                result
976            }
977        };
978        self.admission_kill_sent |= result?;
979        Ok(())
980    }
981
982    async fn drain_stderr(&mut self, module_id: &str) {
983        if let Some(pump) = self.stdout_pump.take() {
984            settle_stdout_pump(module_id, pump, STDERR_PUMP_DRAIN_TIMEOUT).await;
985        }
986
987        let Some(pump) = self.stderr_pump.take() else {
988            return;
989        };
990        settle_stderr_pump(
991            module_id,
992            &self.stderr_ring,
993            pump,
994            STDERR_PUMP_DRAIN_TIMEOUT,
995        )
996        .await;
997    }
998}
999
1000/// Bound the restart's wait. Dropping the completion future does not stop
1001/// the reader or the capture writer.
1002async fn settle_stdout_pump<E: std::fmt::Display>(
1003    module_id: &str,
1004    pump: impl std::future::Future<Output = Result<(), E>>,
1005    bound: Duration,
1006) {
1007    match timeout(bound, pump).await {
1008        Ok(Ok(())) => {}
1009        Ok(Err(error)) => {
1010            warn!(module_id, error = %error, "stdout pump ended unexpectedly");
1011        }
1012        Err(_) => {
1013            warn!(
1014                module_id,
1015                waited = ?bound,
1016                "stdout of the exited process has not finished capture; the reader and writer continue without delaying restart"
1017            );
1018        }
1019    }
1020}
1021
1022/// Retire an exited process's stderr reader and allow up to `bound` for its
1023/// output to reach the ring and sink. A late reader or writer keeps going,
1024/// and the tail reads `Incomplete` until it finishes.
1025async fn settle_stderr_pump<E: std::fmt::Display>(
1026    module_id: &str,
1027    ring: &Arc<Mutex<StderrRing>>,
1028    pump: StderrPump<impl std::future::Future<Output = Result<(), E>>>,
1029    bound: Duration,
1030) {
1031    let lock = || ring.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1032    let StderrPump { task, generation } = pump;
1033    lock().retire_pump(generation);
1034    match timeout(bound, task).await {
1035        Ok(Ok(())) => {}
1036        Ok(Err(err)) => {
1037            let mut ring = lock();
1038            ring.mark_incomplete_from(generation, format!("stderr pump ended unexpectedly: {err}"));
1039            ring.finish_pump(generation);
1040            warn!(module_id, error = %err, "stderr pump ended before clean EOF");
1041        }
1042        Err(_) => {
1043            lock().mark_pump_late(
1044                generation,
1045                format!(
1046                    "stderr of the exited process had not reached EOF or finished queued capture \
1047                     {bound:?} after it was retired; retained lines go in that process's section"
1048                ),
1049            );
1050            warn!(
1051                module_id,
1052                waited = ?bound,
1053                "stderr of the exited process has not finished capture; the reader and writer continue without delaying restart"
1054            );
1055        }
1056    }
1057}
1058
1059fn registration_release_events() -> &'static watch::Sender<u64> {
1060    static EVENTS: OnceLock<watch::Sender<u64>> = OnceLock::new();
1061    EVENTS.get_or_init(|| {
1062        let (sender, _receiver) = watch::channel(0);
1063        sender
1064    })
1065}
1066
1067pub(crate) fn notify_registration_release() {
1068    let events = registration_release_events();
1069    let next_generation = (*events.borrow()).wrapping_add(1);
1070    events.send_replace(next_generation);
1071}
1072
1073/// The installed companion that evaluates a script module.
1074#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1075#[non_exhaustive]
1076pub enum ScriptRuntime {
1077    Bun,
1078    Python,
1079}
1080
1081impl ScriptRuntime {
1082    pub const fn as_str(self) -> &'static str {
1083        match self {
1084            Self::Bun => "bun",
1085            Self::Python => "python",
1086        }
1087    }
1088}
1089
1090/// Script content and the runtime approved to evaluate it.
1091#[derive(Debug, Clone, PartialEq, Eq)]
1092#[non_exhaustive]
1093pub struct ScriptEntry {
1094    pub runtime: ScriptRuntime,
1095    pub path: PathBuf,
1096}
1097
1098impl ScriptEntry {
1099    pub fn new(runtime: ScriptRuntime, path: PathBuf) -> Self {
1100        Self { runtime, path }
1101    }
1102}
1103
1104/// How to launch one singleton module process.
1105#[derive(Debug, Clone, PartialEq, Eq)]
1106pub struct ModuleSpec {
1107    pub module_id: String,
1108    pub program: PathBuf,
1109    /// Bundled script content. The program is always the installed runtime runner.
1110    pub script: Option<ScriptEntry>,
1111    pub args: Vec<String>,
1112    pub env: Vec<(String, String)>,
1113    /// When true this is a reserved module: each spawn gets a fresh one-time launch
1114    /// nonce that the child must echo in its HELLO, so only the daemon-spawned
1115    /// process can register this module_id (a security-boundary module like the
1116    /// credential vault must not be impersonable while it is down/restarting).
1117    pub reserved: bool,
1118    /// Module-id prefixes this supervised module owns for reserved HELLO checks.
1119    /// Prefixes come from daemon config and must end in `:` before they reach the
1120    /// supervisor; the owner module's current spawn nonce authorizes claims under
1121    /// each prefix.
1122    pub reserved_prefixes: Vec<String>,
1123    /// The wire protocol this module speaks, as DECLARED in daemon config.
1124    ///
1125    /// [`ModuleProtocol::None`] changes five things and nothing else: wire health
1126    /// probing is suppressed (an optional HTTP probe can replace it), teardown sends SIGTERM before waiting,
1127    /// `route.open` is refused, the spawn passes NO `--subc <path>` argument
1128    /// and NO launch nonce, and a clean exit the daemon did not request is
1129    /// restarted as a crash rather than recorded as a stop (see `on_child_exit`:
1130    /// a stock program exits 0 on a stray SIGTERM, and a stop would leave it
1131    /// down for good). `SUBC_MODULE_ID` still goes into the environment,
1132    /// because a process ignores an environment variable it does not read.
1133    ///
1134    /// The argument is the part that cannot be "harmless to a process that
1135    /// ignores it": a stock binary exits on an unknown flag before it listens
1136    /// (`nats-server`: "flag provided but not defined: -subc"), which is how the
1137    /// first conformance run against this mode found it. The nonce is withheld
1138    /// because a process that will never present it gains nothing from holding
1139    /// it, and a secret in the environment of a process that does not need it is
1140    /// a leak surface for no benefit.
1141    pub protocol: ModuleProtocol,
1142    /// Whether two processes of this module may run at once, which is what a
1143    /// blue/green swap does for the length of its overlap. Declared in daemon
1144    /// config because the daemon must be able to answer it while the module is
1145    /// down, and so a module cannot talk itself into it after registering.
1146    pub overlap: ModuleOverlap,
1147    /// Keep module-started helpers in the same container across replacements.
1148    /// This is a daemon-config policy, fixed for the lifetime of a container;
1149    /// stopping the module or losing its supervisor still destroys the container.
1150    pub carry_containment: bool,
1151}
1152
1153/// Only the configured launch inputs enter this value; spawned connection paths,
1154/// nonces and inherited environment never do. Its bytes remain daemon-private.
1155#[derive(Clone, PartialEq, Eq)]
1156pub(crate) struct LaunchSpecDigest([u8; 32]);
1157
1158impl fmt::Debug for LaunchSpecDigest {
1159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1160        f.write_str("LaunchSpecDigest([redacted])")
1161    }
1162}
1163
1164impl LaunchSpecDigest {
1165    pub(crate) fn from_spec(spec: &ModuleSpec) -> Self {
1166        fn field(hash: &mut Sha256, bytes: &[u8]) {
1167            hash.update((bytes.len() as u64).to_le_bytes());
1168            hash.update(bytes);
1169        }
1170        let mut hash = Sha256::new();
1171        if let Some(script) = &spec.script {
1172            field(
1173                &mut hash,
1174                match script.runtime {
1175                    ScriptRuntime::Bun => b"bun-script",
1176                    ScriptRuntime::Python => b"python-script",
1177                },
1178            );
1179            field(&mut hash, script.path.as_os_str().as_encoded_bytes());
1180        }
1181        if let Some(program) = spec.program.to_str() {
1182            field(&mut hash, b"utf8-program");
1183            field(&mut hash, program.as_bytes());
1184        } else {
1185            // The daemon config is UTF-8, but in-process callers may provide
1186            // native paths: lossy conversion would collapse distinct programs.
1187            #[cfg(unix)]
1188            {
1189                use std::os::unix::ffi::OsStrExt;
1190                field(&mut hash, b"unix-program");
1191                field(&mut hash, spec.program.as_os_str().as_bytes());
1192            }
1193            #[cfg(windows)]
1194            {
1195                use std::os::windows::ffi::OsStrExt;
1196                field(&mut hash, b"windows-program");
1197                let bytes = spec
1198                    .program
1199                    .as_os_str()
1200                    .encode_wide()
1201                    .flat_map(u16::to_le_bytes)
1202                    .collect::<Vec<_>>();
1203                field(&mut hash, &bytes);
1204            }
1205            #[cfg(not(any(unix, windows)))]
1206            field(&mut hash, spec.program.to_string_lossy().as_bytes());
1207        }
1208        hash.update((spec.args.len() as u64).to_le_bytes());
1209        for arg in &spec.args {
1210            field(&mut hash, arg.as_bytes());
1211        }
1212        let mut env = spec.env.iter().collect::<Vec<_>>();
1213        env.sort_unstable();
1214        hash.update((env.len() as u64).to_le_bytes());
1215        for (key, value) in env {
1216            field(&mut hash, key.as_bytes());
1217            field(&mut hash, value.as_bytes());
1218        }
1219        field(
1220            &mut hash,
1221            match spec.protocol {
1222                ModuleProtocol::Subc => b"subc",
1223                ModuleProtocol::None => b"none",
1224            },
1225        );
1226        Self(hash.finalize().into())
1227    }
1228}
1229
1230/// Whether a module tolerates a second process of itself running alongside.
1231///
1232/// Most modules are single-writer on their store (a WAL, a capture log, a
1233/// resident index behind a writer barrier), and two processes on one store
1234/// corrupt it. So a swap, which overlaps the old and new process by design,
1235/// is refused unless the module's config opts in with `overlap: "safe"`.
1236#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1237pub enum ModuleOverlap {
1238    /// Never run two processes of this module at once. The default.
1239    #[default]
1240    Exclusive,
1241    /// The module has said a second process of itself is harmless for the
1242    /// length of a swap.
1243    ///
1244    /// Declare it only if a second instance can run for a few seconds without
1245    /// touching ANY single-writer store: every database, WAL, index, projector
1246    /// and scheduled job the module owns. A lease on part of that state is not
1247    /// enough. broca's session lease guards WAL appends while its run index, its
1248    /// store projector and its archive fold timer (which unlinks live WAL files)
1249    /// stay single-writer, so broca is exclusive despite holding a lease. The
1250    /// refusal only fires after this has been decided, so the decision is the
1251    /// check.
1252    Safe,
1253}
1254
1255impl ModuleOverlap {
1256    pub fn as_str(self) -> &'static str {
1257        match self {
1258            Self::Exclusive => "exclusive",
1259            Self::Safe => "safe",
1260        }
1261    }
1262}
1263
1264/// Environment variable telling a spawned module which case it was started
1265/// for, before it sends HELLO. Only a swap candidate carries it, as
1266/// [`SPAWN_ROLE_SWAP_CANDIDATE`]; every other spawn has it removed.
1267///
1268/// It chooses a warm-up budget, nothing else: a swap candidate can warm for
1269/// longer because nobody waits on it, while a plain restart must flip ready
1270/// quickly because callers see `module_warming` until it does. Absence means
1271/// plain restart, the safe reading. The daemon trusts nothing about it; the
1272/// candidate is proven by its launch nonce at HELLO.
1273pub const SUBC_SPAWN_ROLE_ENV: &str = "SUBC_SPAWN_ROLE";
1274/// The one value of [`SUBC_SPAWN_ROLE_ENV`] the daemon sets.
1275pub const SPAWN_ROLE_SWAP_CANDIDATE: &str = "swap_candidate";
1276/// How long a swap waits for its candidate to register and declare itself
1277/// ready when the operator does not say. A module warming as a swap candidate
1278/// may take up to 90 s (aft's ceiling, the largest in the fleet), so the
1279/// daemon allows that plus time to start the process and send HELLO.
1280pub const DEFAULT_SWAP_READY_TIMEOUT: Duration = Duration::from_secs(100);
1281
1282/// Bounded restart policy for crash exits.
1283///
1284/// `max_restarts` is the number of replacement processes allowed after the
1285/// initial spawn WITHIN `window`. After that many crash restarts inside one
1286/// window the module enters [`ModuleState::Failed`] and the supervisor stops
1287/// the crash loop.
1288///
1289/// The budget is a RATE, not a lifetime total. It used to be a lifetime total,
1290/// and that only survived because crashes were rare: a module that crashed
1291/// three times across a week was disabled forever by crashes that had nothing
1292/// to do with each other. That stopped being survivable once modules began
1293/// exiting non-zero whenever the daemon's connection to them drops, because
1294/// then every daemon-side connection drop spends a unit of the same budget and
1295/// one flappy hour permanently stops a healthy module. Restarts older than
1296/// `window` release their slot, so a module that crashed twice yesterday has a
1297/// full budget today, while a genuine crash loop -- which is fast by
1298/// definition -- still reaches the cap and stops.
1299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1300pub struct RestartPolicy {
1301    pub max_restarts: u32,
1302    /// Base delay before a crash replacement. The actual delay escalates with
1303    /// the number of recent crash replacements and is capped by `max_backoff`.
1304    pub backoff: Duration,
1305    /// Maximum delay before a crash replacement.
1306    pub max_backoff: Duration,
1307    /// The span `max_restarts` is counted over. `Duration::ZERO` makes the
1308    /// budget effectively infinite (nothing is ever in-window), which is why
1309    /// daemon config refuses `window_secs: 0` rather than quietly accepting it.
1310    pub window: Duration,
1311}
1312
1313impl RestartPolicy {
1314    /// A policy with the default crash window. Callers that care about the
1315    /// window say so with [`Self::with_window`]; the ones that do not are
1316    /// asking for the standard rate limit, not for no limit.
1317    pub fn new(max_restarts: u32, backoff: Duration) -> Self {
1318        Self {
1319            max_restarts,
1320            backoff,
1321            max_backoff: DEFAULT_MAX_BACKOFF,
1322            window: DEFAULT_RESTART_WINDOW,
1323        }
1324    }
1325
1326    pub fn with_max_backoff(mut self, max_backoff: Duration) -> Self {
1327        self.max_backoff = max_backoff;
1328        self
1329    }
1330
1331    pub fn with_window(mut self, window: Duration) -> Self {
1332        self.window = window;
1333        self
1334    }
1335
1336    /// Calculate the capped exponential delay for the next crash replacement.
1337    /// `restart_in_window` is zero for the first replacement after an operator
1338    /// action (restart, reload, re-enable) cleared the crash ring, or after all
1339    /// older crash replacements have aged out of the window.
1340    fn delay_for_restart(&self, restart_in_window: u32) -> Duration {
1341        if self.backoff.is_zero() || self.max_backoff.is_zero() {
1342            return Duration::ZERO;
1343        }
1344
1345        let mut delay = self.backoff;
1346        for _ in 0..restart_in_window {
1347            if delay >= self.max_backoff {
1348                return self.max_backoff;
1349            }
1350            delay = delay
1351                .checked_mul(10)
1352                .unwrap_or(self.max_backoff)
1353                .min(self.max_backoff);
1354        }
1355        delay.min(self.max_backoff)
1356    }
1357
1358    /// The one sentence that explains a budget-exhausted stop, used for both the
1359    /// log line and the terminal record so the two cannot drift. It names the
1360    /// window because `max_restarts=3` alone reads as a lifetime cap, which is
1361    /// exactly what this budget is not.
1362    fn budget_exhausted_detail(&self) -> String {
1363        format!(
1364            "crash budget exhausted: max_restarts={} within window_secs={}",
1365            self.max_restarts,
1366            self.window.as_secs()
1367        )
1368    }
1369}
1370
1371impl Default for RestartPolicy {
1372    fn default() -> Self {
1373        Self {
1374            max_restarts: DEFAULT_MAX_RESTARTS,
1375            backoff: DEFAULT_BACKOFF,
1376            max_backoff: DEFAULT_MAX_BACKOFF,
1377            window: DEFAULT_RESTART_WINDOW,
1378        }
1379    }
1380}
1381
1382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1383struct CrashRestartSchedule {
1384    restart_in_window: u32,
1385    delay: Duration,
1386}
1387
1388/// Whether the daemon itself will bring this module back after the exit being
1389/// handled: it is enabled AND its in-window crash restarts are below the cap.
1390///
1391/// Takes `&mut` because reading the budget prunes it. Instants that fell out of
1392/// the window are dropped here rather than by a timer, so the count is right
1393/// the moment somebody asks and no bookkeeping runs for idle modules.
1394fn daemon_will_restart(
1395    state: &mut SupervisorSnapshot,
1396    policy: &RestartPolicy,
1397    now: Instant,
1398) -> bool {
1399    state.enabled && state.crash_restarts_in_window(policy.window, now) < policy.max_restarts
1400}
1401
1402const DEFAULT_HEALTH_CADENCE: Duration = Duration::from_secs(30);
1403const DEFAULT_HEALTH_DEADLINE: Duration = Duration::from_secs(5);
1404const DEFAULT_HEALTH_FAILURE_THRESHOLD: u32 = 3;
1405const MAX_HEALTH_METRICS_BYTES: usize = 16 * 1024;
1406
1407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1408pub enum HealthAction {
1409    Report,
1410    Restart,
1411    Alert,
1412}
1413
1414impl fmt::Display for HealthAction {
1415    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1416        f.write_str(match self {
1417            Self::Report => "report",
1418            Self::Restart => "restart",
1419            Self::Alert => "alert",
1420        })
1421    }
1422}
1423
1424#[derive(Debug, Clone, PartialEq, Eq)]
1425pub struct HealthConfig {
1426    /// Optional loopback HTTP endpoint for a managed non-wire process.
1427    /// Changing it applies live on rescan; the process protocol changes only
1428    /// at its next spawn.
1429    pub http: Option<String>,
1430    pub cadence: Duration,
1431    pub deadline: Duration,
1432    pub failure_threshold: u32,
1433    pub on_degraded: HealthAction,
1434    pub on_failing: HealthAction,
1435    pub critical: bool,
1436}
1437
1438impl Default for HealthConfig {
1439    fn default() -> Self {
1440        Self {
1441            http: None,
1442            cadence: DEFAULT_HEALTH_CADENCE,
1443            deadline: DEFAULT_HEALTH_DEADLINE,
1444            failure_threshold: DEFAULT_HEALTH_FAILURE_THRESHOLD,
1445            on_degraded: HealthAction::Report,
1446            on_failing: HealthAction::Report,
1447            critical: false,
1448        }
1449    }
1450}
1451
1452/// The supervisor's view of one module's health, relayed to clients over
1453/// channel-0 and rendered by `ck health`.
1454///
1455/// THIS TYPE IS WHERE THE ABSENCE MEANINGS ARE CREATED, which is why they are
1456/// stated here rather than only at the wire type a consumer reads. A reader can
1457/// look up what `None` means; only a writer can silently change it, and the
1458/// writer has no reason to go looking at a downstream contract before editing.
1459///
1460/// `last_probe_ms: None` MEANS NEVER PROBED, not probed-long-ago. It is cleared
1461/// back to `None` on re-registration precisely so a respawned module does not
1462/// carry its predecessor's timestamp — so an old value and an absent one call for
1463/// opposite readings, and anything that defaulted this to a number would make a
1464/// never-probed module indistinguishable from one probed at the epoch.
1465///
1466/// `detail` and `metrics` are `None` when the module published none on this
1467/// probe, which does not mean it reported nothing wrong — it is also the shape
1468/// when the probe never reached it. `last_probe_ms` is what separates those.
1469#[derive(Debug, Clone, PartialEq)]
1470pub struct ModuleHealthStatus {
1471    pub status: SupervisorHealthStatus,
1472    pub last_probe_ms: Option<u64>,
1473    pub detail: Option<String>,
1474    pub metrics: Option<Value>,
1475    pub consecutive_failures: u32,
1476    /// Number of replies received after a recurring health probe's deadline.
1477    /// Unlike a timeout, every increment proves the module was alive.
1478    pub late_answer_count: u64,
1479    /// End-to-end latency of the newest late reply, measured from probe start.
1480    pub last_late_answer_latency_ms: Option<u64>,
1481    pub last_action: Option<String>,
1482    /// Set together with `last_action`; the pair moves as one, and both being
1483    /// absent means no escalation has ever been taken rather than that the last
1484    /// one succeeded.
1485    pub last_action_ms: Option<u64>,
1486}
1487
1488impl Default for ModuleHealthStatus {
1489    fn default() -> Self {
1490        Self {
1491            status: SupervisorHealthStatus::Unknown,
1492            last_probe_ms: None,
1493            detail: None,
1494            metrics: None,
1495            consecutive_failures: 0,
1496            late_answer_count: 0,
1497            last_late_answer_latency_ms: None,
1498            last_action: None,
1499            last_action_ms: None,
1500        }
1501    }
1502}
1503
1504/// Typed lifecycle state for a supervised module.
1505#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1506pub enum ModuleState {
1507    Starting,
1508    Running,
1509    Unresponsive,
1510    Restarting,
1511    Draining,
1512    Stopped,
1513    Failed,
1514    Disabled,
1515}
1516
1517impl fmt::Display for ModuleState {
1518    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1519        f.write_str(match self {
1520            Self::Starting => "starting",
1521            Self::Running => "running",
1522            Self::Unresponsive => "unresponsive",
1523            Self::Restarting => "restarting",
1524            Self::Draining => "draining",
1525            Self::Stopped => "stopped",
1526            Self::Failed => "failed",
1527            Self::Disabled => "disabled",
1528        })
1529    }
1530}
1531
1532/// Supervisor classification of a child-process exit.
1533#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1534pub enum ExitKind {
1535    Clean,
1536    Crash,
1537    DeliberateSeverance,
1538}
1539
1540impl From<ExitKind> for TerminalExitKind {
1541    fn from(kind: ExitKind) -> Self {
1542        match kind {
1543            ExitKind::Clean => Self::Clean,
1544            ExitKind::Crash => Self::Crash,
1545            ExitKind::DeliberateSeverance => Self::DeliberateSeverance,
1546        }
1547    }
1548}
1549
1550/// Exact process identity retained when a supervised module registers its
1551/// connection. PID reuse makes a PID alone insufficient evidence of ownership.
1552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1553pub(crate) struct ProcessIdentity {
1554    pub(crate) pid: u32,
1555    pub(crate) start_time: u64,
1556}
1557
1558/// Last observed child exit, if any.
1559#[derive(Debug, Clone, PartialEq, Eq)]
1560pub struct ExitReport {
1561    pub kind: ExitKind,
1562    pub code: Option<i32>,
1563    pub signal: Option<i32>,
1564    pub at_ms: u64,
1565}
1566
1567/// Point-in-time module status answerable by subc without forwarding to the
1568/// module process.
1569#[derive(Debug, Clone, PartialEq)]
1570pub struct ModuleStatus {
1571    pub(crate) admission_refused: Option<String>,
1572    pub(crate) legacy_registration_spawn: bool,
1573    pub(crate) registration_declaration: Option<String>,
1574    pub module_id: String,
1575    /// Retained configuration-exit infrastructure failure. Cleared only after a
1576    /// successful launch; an ordinary stop has no infrastructure stop reason.
1577    pub stop_reason: Option<ModuleStopReason>,
1578    /// A previous daemon's unresolved process, not a child owned by this supervisor.
1579    pub waiting_for_previous_pid: Option<u32>,
1580    /// Why the previous instance still prevents a new start.
1581    pub waiting_for_previous_detail: Option<String>,
1582    /// The daemon's Windows per-spawn record: `pipe` after the process it
1583    /// spawned read all nonce bytes, otherwise `env` for the offered copy.
1584    /// List/status reports use this record, not the source the module sends
1585    /// in its registration message's manifest.provenance.launch_nonce_source.
1586    pub launch_nonce_source: Option<String>,
1587    pub state: ModuleState,
1588    pub enabled: bool,
1589    pub process_alive: bool,
1590    pub registration_active: bool,
1591    /// The module's declared wire protocol, carried beside `live` because it is
1592    /// what makes `live` readable: the two fields answer one question together.
1593    /// While a process is alive this is its launch declaration, not a later
1594    /// pending-reload edit. When down it is the configured next launch protocol.
1595    pub protocol: ModuleProtocol,
1596    /// Whether the module is serving, under the strongest definition the daemon
1597    /// can assert for its protocol.
1598    ///
1599    /// A subc module must also be REGISTERED: its process being alive says
1600    /// nothing about whether it can take a request. A `protocol: "none"` module
1601    /// never registers, so that term is dropped and this falls back to "enabled,
1602    /// running, and the process the daemon launched is alive" -- which is all
1603    /// the daemon observes about a process that speaks no subc wire. It stays a
1604    /// `bool` on the wire for compatibility; renderers pair it with `protocol`
1605    /// rather than printing it bare.
1606    pub live: bool,
1607    /// Crash restarts spent INSIDE `restart_window` as of this read. Older
1608    /// restarts have already released their slot, so this count can go down
1609    /// without anybody touching the module.
1610    pub restart_count: u32,
1611    /// Replacement processes spawned over this module's entire supervisor lifetime;
1612    /// unlike `restart_count`, this value is never reset by an operator action
1613    /// and never falls out of a window.
1614    pub lifetime_restarts: u32,
1615    pub spawn_generation: u64,
1616    /// Retained daemon-local outcome; the legacy control response omits it.
1617    pub swap_outcome: Option<SwapOutcome>,
1618    /// The budget `restart_count` is spent against. Carried alongside the count
1619    /// because the count alone does not say how close the module is to being
1620    /// disabled, and reporting one without the other is what makes an
1621    /// about-to-be-retired module look ordinary.
1622    pub max_restarts: u32,
1623    /// The span `restart_count` is counted over. Carried with the pair above for
1624    /// the same reason they are carried together: "2 of 3" means one thing for a
1625    /// ten-minute window and something else entirely for a lifetime.
1626    pub restart_window: Duration,
1627    /// Effective drain and restart timing policy used by this running module.
1628    /// These values are carried together with the restart budget so status
1629    /// readers can compare configured intent with what the supervisor applied.
1630    pub drain_timeout: Duration,
1631    pub restart_backoff: Duration,
1632    pub restart_max_backoff: Duration,
1633    /// The module's process. On macOS this stays absent while the `ck-subc`
1634    /// launch trampoline is still running in that pid, and appears once the
1635    /// exec acknowledgement confirms the module image has replaced it. Launch
1636    /// time and the supervisor's own hold on the process are unaffected.
1637    pub pid: Option<u32>,
1638    pub spawned_at_ms: Option<u64>,
1639    pub spawned_from: Option<PathBuf>,
1640    pub(crate) launch_spec_digest: Option<LaunchSpecDigest>,
1641    pub process_start_time: Option<u64>,
1642    pub last_exit: Option<ExitReport>,
1643    pub health: ModuleHealthStatus,
1644}
1645
1646#[cfg(test)]
1647#[derive(Debug, Clone, Copy, PartialEq)]
1648struct ActorSelectCheckpoint {
1649    generation: u64,
1650    turn: u64,
1651    registered_connection: Option<ConnectionId>,
1652    next_probe_at: Option<Instant>,
1653    wake_after: Option<Duration>,
1654}
1655
1656#[derive(Debug, Clone, PartialEq)]
1657struct SupervisorSnapshot {
1658    admission_refused: Option<String>,
1659    /// Distinguishes an admission-parked actor from an unrelated terminal exit.
1660    config_hold_parked: bool,
1661    /// Preserve daemon attribution for a paused start so a failing release can
1662    /// schedule the next slow retry instead of treating the start as operator work.
1663    config_hold_daemon_initiated: bool,
1664    /// The approval that owns the parked attempt, not whichever approval is latest.
1665    config_hold_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
1666    /// Retain an approved launch failure across competing reconciliation passes.
1667    approved_start_failure: Option<(crate::config_gate::runtime::ApprovalIdentity, String)>,
1668    legacy_registration_spawn: bool,
1669    registration_declaration: Option<String>,
1670    stop_reason: Option<ModuleStopReason>,
1671    config_exit_failed_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
1672    subtree_target: crate::subtree_resources::Target,
1673    failed_retry: FailedRetry,
1674    exec_outcome: Option<Arc<crate::activity::ExecOutcome>>,
1675    #[cfg(windows)]
1676    pipe_consumed: Option<Arc<OnceLock<()>>>,
1677    /// Counts running-child loop turns, not executor polls of a parked wait.
1678    #[cfg(test)]
1679    actor_turns: u64,
1680    /// Running select after exec confirmation and with no unconsumed registry
1681    /// event. Recording a spawn or starting a loop turn is not this barrier.
1682    #[cfg(test)]
1683    actor_select: Option<ActorSelectCheckpoint>,
1684    state: ModuleState,
1685    enabled: bool,
1686    process_alive: bool,
1687    spawned_protocol: Option<ModuleProtocol>,
1688    spawn_failure: Option<String>,
1689    waiting_for_previous_pid: Option<u32>,
1690    waiting_for_previous_detail: Option<String>,
1691    /// When each crash restart was spent, oldest first. This IS the crash
1692    /// budget: its in-window length is the count an operator sees and the count
1693    /// the restart decision is made against, so there is no second counter that
1694    /// can disagree with it. Bounded by `max_restarts`, and cleared by the same
1695    /// operator actions that used to zero the old lifetime counter.
1696    crash_restarts: VecDeque<Instant>,
1697    lifetime_restarts: u32,
1698    /// Successful child spawns in this daemon incarnation.
1699    ///
1700    /// `lifetime_restarts` was considered and rejected: it starts at zero
1701    /// (line 640), successful initial/operator spawns in `set_running` do not
1702    /// increment it (lines 5264-5274), and crash/deliberate retry bookkeeping
1703    /// increments before a successful replacement exists (lines 604, 3846,
1704    /// and 3921), so a failed spawn can consume it. This counter moves only
1705    /// when a live PID is accepted below.
1706    spawn_generation: u64,
1707    swap_outcome: Option<SwapOutcome>,
1708    pid: Option<u32>,
1709    #[cfg(target_os = "macos")]
1710    report_ready: Option<Arc<OnceLock<()>>>,
1711    /// Last reaped child, retained after current process facts are cleared.
1712    reaped_pid: Option<u32>,
1713    /// Whether a replacement has already been scheduled for the current process.
1714    respawn_pending: bool,
1715    /// A second restart is waiting for the replacement already scheduled.
1716    coalesced_restart_pending: bool,
1717    spawned_at_ms: Option<u64>,
1718    spawned_from: Option<PathBuf>,
1719    launch_spec_digest: Option<LaunchSpecDigest>,
1720    spawned_file_identity: Option<SpawnedFileIdentity>,
1721    process_start_time: Option<u64>,
1722    deliberate_severance: Option<ProcessIdentity>,
1723    last_exit: Option<ExitReport>,
1724    /// Diagnostic attached to the next drain's terminal record, if any.
1725    drain_disposition_detail: Option<String>,
1726    health: ModuleHealthStatus,
1727    last_probe_evidence: Option<HealthProbeEvidence>,
1728    /// Whether the current process was started as a swap candidate and so
1729    /// lives in the module's alternate cgroup. The next swap's candidate takes
1730    /// the other one, so the two processes of a swap never share a cgroup. A
1731    /// plain spawn always uses the primary cgroup.
1732    in_alternate_slot: bool,
1733    /// Whether the current `Draining` state ends in a replacement process
1734    /// (restart, reload, health restart) rather than a stop. Only meaningful
1735    /// while `state` is `Draining`; every entry into that state rewrites it.
1736    /// It is what lets route.open answer the retryable `module_reloading` to a
1737    /// consumer that reaches a still-registered process mid-restart, instead of
1738    /// the `supervisor_not_live` a stop or disable deserves.
1739    draining_to_replace: bool,
1740    /// Whether a configuration update has been applied since the current
1741    /// process was spawned, so that process runs an older spec than the one
1742    /// the supervisor now holds. A queued restart is only coalesced into a
1743    /// fresher process when this is false: a restart requested to pick up a
1744    /// new configuration must not be satisfied by a process that predates it.
1745    configuration_updated_since_spawn: bool,
1746}
1747
1748impl SupervisorSnapshot {
1749    /// The pid that status, provenance and resource readings may report. While
1750    /// the launch trampoline still runs in the pid, reading its executable or
1751    /// resource use would describe `ck-subc`, not the module, so none is
1752    /// reported until the exec acknowledgement confirms the module image.
1753    fn reported_pid(&self) -> Option<u32> {
1754        #[cfg(target_os = "macos")]
1755        if self
1756            .report_ready
1757            .as_ref()
1758            .is_some_and(|ready| ready.get().is_none())
1759        {
1760            return None;
1761        }
1762        self.pid
1763    }
1764
1765    fn starting() -> Self {
1766        Self::new(ModuleState::Starting, true)
1767    }
1768
1769    fn disabled() -> Self {
1770        Self::new(ModuleState::Disabled, false)
1771    }
1772
1773    /// Crash restarts still inside `window`, having dropped the ones that are
1774    /// not. Pruning on read is what makes the budget a rate: an instant older
1775    /// than the window stops holding a slot the moment anybody counts.
1776    fn crash_restarts_in_window(&mut self, window: Duration, now: Instant) -> u32 {
1777        while let Some(oldest) = self.crash_restarts.front() {
1778            if now.duration_since(*oldest) > window {
1779                self.crash_restarts.pop_front();
1780            } else {
1781                break;
1782            }
1783        }
1784        u32::try_from(self.crash_restarts.len()).unwrap_or(u32::MAX)
1785    }
1786
1787    /// Spend one unit of the crash budget and record the restart in the ledger.
1788    ///
1789    /// The ring is bounded by the cap because more than `max_restarts` in-window
1790    /// instants can never be reached (the caller refuses the restart first), so
1791    /// anything beyond that is an unbounded queue waiting to happen.
1792    fn record_crash_restart(&mut self, policy: &RestartPolicy, now: Instant) {
1793        self.crash_restarts.push_back(now);
1794        while self.crash_restarts.len() > policy.max_restarts as usize {
1795            self.crash_restarts.pop_front();
1796        }
1797        self.lifetime_restarts += 1;
1798    }
1799
1800    /// Reserve one crash-restart slot and calculate the delay before respawning.
1801    /// The count is captured before recording this restart, so the first retry
1802    /// uses the base delay and each later in-window retry escalates once.
1803    fn next_crash_restart(
1804        &mut self,
1805        policy: &RestartPolicy,
1806        now: Instant,
1807    ) -> Option<CrashRestartSchedule> {
1808        let restart_in_window = self.crash_restarts_in_window(policy.window, now);
1809        if restart_in_window >= policy.max_restarts {
1810            return None;
1811        }
1812        self.record_crash_restart(policy, now);
1813        Some(CrashRestartSchedule {
1814            restart_in_window,
1815            delay: policy.delay_for_restart(restart_in_window),
1816        })
1817    }
1818
1819    /// Give the module its full budget back, as an operator restart, reload, or
1820    /// re-enable does. `lifetime_restarts` deliberately does not move: it is the
1821    /// ledger of what actually happened, and an operator action does not unmake
1822    /// the crashes.
1823    fn clear_crash_restarts(&mut self) {
1824        self.crash_restarts.clear();
1825    }
1826
1827    fn new(state: ModuleState, enabled: bool) -> Self {
1828        Self {
1829            admission_refused: None,
1830            config_hold_parked: false,
1831            config_hold_daemon_initiated: false,
1832            config_hold_approval: None,
1833            approved_start_failure: None,
1834            legacy_registration_spawn: false,
1835            registration_declaration: None,
1836            stop_reason: None,
1837            config_exit_failed_approval: None,
1838            subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
1839            failed_retry: FailedRetry::default(),
1840            exec_outcome: None,
1841            #[cfg(test)]
1842            actor_turns: 0,
1843            #[cfg(test)]
1844            actor_select: None,
1845            state,
1846            enabled,
1847            process_alive: false,
1848            #[cfg(windows)]
1849            pipe_consumed: None,
1850            spawned_protocol: None,
1851            spawn_failure: None,
1852            waiting_for_previous_pid: None,
1853            waiting_for_previous_detail: None,
1854            crash_restarts: VecDeque::new(),
1855            lifetime_restarts: 0,
1856            spawn_generation: 0,
1857            swap_outcome: None,
1858            pid: None,
1859            #[cfg(target_os = "macos")]
1860            report_ready: None,
1861            reaped_pid: None,
1862            respawn_pending: false,
1863            coalesced_restart_pending: false,
1864            spawned_at_ms: None,
1865            spawned_from: None,
1866            launch_spec_digest: None,
1867            spawned_file_identity: None,
1868            process_start_time: None,
1869            deliberate_severance: None,
1870            last_exit: None,
1871            drain_disposition_detail: None,
1872            health: ModuleHealthStatus::default(),
1873            last_probe_evidence: None,
1874            in_alternate_slot: false,
1875            draining_to_replace: false,
1876            configuration_updated_since_spawn: false,
1877        }
1878    }
1879}
1880
1881type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
1882
1883type SpawnSubscriberKey = (ConnectionId, u64);
1884
1885#[derive(Debug)]
1886struct SpawnSubscriber {
1887    version: u8,
1888    frames: mpsc::Sender<Frame>,
1889    /// Tells this subscriber's forwarder that it was dropped for lagging, and
1890    /// from which event. The full frame channel cannot carry that news, so it
1891    /// travels beside it; see `SpawnEventFeed::subscribe`.
1892    lagged: Option<oneshot::Sender<SpawnCursor>>,
1893}
1894
1895#[derive(Debug)]
1896struct SpawnEventState {
1897    daemon_incarnation: String,
1898    seq: u64,
1899    capacity: usize,
1900    live: HashMap<String, LiveSpawn>,
1901    generations: HashMap<String, u64>,
1902    events: VecDeque<SpawnEvent>,
1903    subscribers: HashMap<SpawnSubscriberKey, SpawnSubscriber>,
1904    process_changes: HashMap<String, tokio::sync::watch::Sender<u64>>,
1905}
1906
1907impl Default for SpawnEventState {
1908    fn default() -> Self {
1909        Self {
1910            daemon_incarnation: "unconfigured".to_string(),
1911            seq: 0,
1912            capacity: SPAWN_EVENT_RING_CAPACITY,
1913            live: HashMap::new(),
1914            generations: HashMap::new(),
1915            events: VecDeque::new(),
1916            subscribers: HashMap::new(),
1917            process_changes: HashMap::new(),
1918        }
1919    }
1920}
1921
1922#[derive(Debug, Clone, Default)]
1923struct SpawnEventFeed(
1924    Arc<Mutex<SpawnEventState>>,
1925    #[cfg(test)] Arc<Mutex<Option<std::net::TcpStream>>>,
1926);
1927
1928#[derive(Debug, Clone, PartialEq, Eq)]
1929pub(crate) enum SpawnSubscribeRefusal {
1930    ForeignIncarnation { current: String },
1931    TooOld { oldest: SpawnCursor },
1932    Frame(String),
1933}
1934
1935impl SpawnEventFeed {
1936    fn configure_incarnation(&self, daemon_incarnation: String) {
1937        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1938        state.daemon_incarnation = daemon_incarnation;
1939        state.seq = 0;
1940        state.live.clear();
1941        state.generations.clear();
1942        state.events.clear();
1943        state.subscribers.clear();
1944        for changed in state.process_changes.values() {
1945            changed.send_replace(0);
1946        }
1947    }
1948
1949    fn cursor(state: &SpawnEventState) -> SpawnCursor {
1950        SpawnCursor {
1951            daemon_incarnation: state.daemon_incarnation.clone(),
1952            seq: state.seq,
1953        }
1954    }
1955
1956    fn snapshot(&self) -> SpawnSnapshot {
1957        let state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1958        let mut live = state.live.values().cloned().collect::<Vec<_>>();
1959        live.sort_by(|left, right| left.module_id.cmp(&right.module_id));
1960        SpawnSnapshot {
1961            cursor: Self::cursor(&state),
1962            ring_bound: state.capacity as u64,
1963            live,
1964        }
1965    }
1966
1967    fn allocate_generation_locked(state: &mut SpawnEventState, module_id: &str) -> u64 {
1968        let generation = state
1969            .generations
1970            .get(module_id)
1971            .copied()
1972            .unwrap_or(0)
1973            .checked_add(1)
1974            .expect("spawn generation exhausted");
1975        state.generations.insert(module_id.to_string(), generation);
1976        generation
1977    }
1978
1979    /// Allocate the spawn generation of a launch that is about to start, with
1980    /// the daemon incarnation it belongs to. The number names the launch from
1981    /// this moment, before its process runs; a launch that never runs keeps
1982    /// its number, so the generations a subscriber sees may skip.
1983    fn allocate_generation(&self, module_id: &str) -> (String, u64) {
1984        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1985        let generation = Self::allocate_generation_locked(&mut state, module_id);
1986        (state.daemon_incarnation.clone(), generation)
1987    }
1988
1989    /// Publish a running process. `allocated` is the generation its launch
1990    /// was given before it started; a launch without one (a process with no
1991    /// registration channel) is numbered here.
1992    fn emit_spawned(
1993        &self,
1994        module_id: &str,
1995        allocated: Option<u64>,
1996        pid: u32,
1997        spawned_at_ms: u64,
1998    ) -> u64 {
1999        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2000        let generation = match allocated {
2001            Some(generation) => generation,
2002            None => Self::allocate_generation_locked(&mut state, module_id),
2003        };
2004        let live = LiveSpawn {
2005            module_id: module_id.to_string(),
2006            spawn_generation: generation,
2007            pid,
2008            spawned_at_ms,
2009        };
2010        state.live.insert(module_id.to_string(), live);
2011        Self::emit_locked(
2012            &mut state,
2013            SpawnEventKind::Spawned,
2014            module_id.to_string(),
2015            generation,
2016            pid,
2017            None,
2018            None,
2019        );
2020        generation
2021    }
2022
2023    fn emit_exited(&self, module_id: &str, exit_code: Option<i32>, exit_signal: Option<i32>) {
2024        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2025        let Some(live) = state.live.remove(module_id) else {
2026            warn!(
2027                module_id,
2028                "terminal record had no live spawn event identity"
2029            );
2030            return;
2031        };
2032        Self::emit_locked(
2033            &mut state,
2034            SpawnEventKind::Exited,
2035            module_id.to_string(),
2036            live.spawn_generation,
2037            live.pid,
2038            exit_code,
2039            exit_signal,
2040        );
2041    }
2042
2043    /// Report the exit of a process that a swap has already replaced.
2044    ///
2045    /// `emit_exited` removes the module's live entry, which after a swap's
2046    /// cutover describes the promoted candidate, not the old process now
2047    /// exiting. This emits the old generation's exit and leaves the live entry
2048    /// alone unless it still names that generation.
2049    fn emit_superseded_exited(
2050        &self,
2051        module_id: &str,
2052        spawn_generation: u64,
2053        pid: u32,
2054        exit_code: Option<i32>,
2055        exit_signal: Option<i32>,
2056    ) {
2057        let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2058        if state
2059            .live
2060            .get(module_id)
2061            .is_some_and(|live| live.spawn_generation == spawn_generation)
2062        {
2063            state.live.remove(module_id);
2064        }
2065        Self::emit_locked(
2066            &mut state,
2067            SpawnEventKind::Exited,
2068            module_id.to_string(),
2069            spawn_generation,
2070            pid,
2071            exit_code,
2072            exit_signal,
2073        );
2074    }
2075
2076    #[allow(clippy::too_many_arguments)]
2077    fn emit_locked(
2078        state: &mut SpawnEventState,
2079        kind: SpawnEventKind,
2080        module_id: String,
2081        spawn_generation: u64,
2082        pid: u32,
2083        exit_code: Option<i32>,
2084        exit_signal: Option<i32>,
2085    ) {
2086        state.seq = state
2087            .seq
2088            .checked_add(1)
2089            .expect("spawn event sequence exhausted");
2090        let event = SpawnEvent {
2091            cursor: Self::cursor(state),
2092            kind,
2093            module_id,
2094            spawn_generation,
2095            pid,
2096            exit_code,
2097            exit_signal,
2098        };
2099        state
2100            .process_changes
2101            .retain(|_, changed| changed.receiver_count() > 0);
2102        if let Some(changed) = state.process_changes.get(&event.module_id) {
2103            changed.send_replace(state.seq);
2104        }
2105        state.events.push_back(event.clone());
2106        while state.events.len() > state.capacity {
2107            state.events.pop_front();
2108        }
2109        let body = match serde_json::to_vec(&event) {
2110            Ok(body) => body,
2111            Err(error) => {
2112                error!(%error, "failed to serialize supervisor spawn event");
2113                return;
2114            }
2115        };
2116        state.subscribers.retain(|(connection_id, corr), subscriber| {
2117            let frame = Frame::build_with_version(
2118                subscriber.version,
2119                FrameType::StreamData,
2120                control_flags(),
2121                0,
2122                0,
2123                *corr,
2124                body.clone(),
2125            );
2126            match frame {
2127                Ok(frame) => {
2128                    if subscriber.frames.try_send(frame).is_ok() {
2129                        true
2130                    } else {
2131                        warn!(connection_id = connection_id.get(), corr, "dropping lagged supervisor spawn subscriber");
2132                        if let Some(lagged) = subscriber.lagged.take() {
2133                            let _ = lagged.send(event.cursor.clone());
2134                        }
2135                        false
2136                    }
2137                }
2138                Err(error) => {
2139                    warn!(connection_id = connection_id.get(), corr, %error, "dropping supervisor spawn subscriber after frame build failure");
2140                    false
2141                }
2142            }
2143        });
2144    }
2145
2146    fn subscribe(
2147        &self,
2148        connection_id: ConnectionId,
2149        corr: u64,
2150        version: u8,
2151        since: Option<SpawnCursor>,
2152        sink: FrameSink,
2153    ) -> Result<(), SpawnSubscribeRefusal> {
2154        let (frames, mut receiver) = mpsc::channel(SPAWN_SUBSCRIBER_BUFFER);
2155        let (lagged, mut lagged_rx) = oneshot::channel::<SpawnCursor>();
2156        {
2157            let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2158            let replay = if let Some(since) = since {
2159                if since.daemon_incarnation != state.daemon_incarnation {
2160                    return Err(SpawnSubscribeRefusal::ForeignIncarnation {
2161                        current: state.daemon_incarnation.clone(),
2162                    });
2163                }
2164                if let Some(oldest) = state.events.front().map(|event| event.cursor.clone()) {
2165                    if since.seq < oldest.seq.saturating_sub(1) {
2166                        return Err(SpawnSubscribeRefusal::TooOld { oldest });
2167                    }
2168                }
2169                state
2170                    .events
2171                    .iter()
2172                    .filter(|event| event.cursor.seq > since.seq)
2173                    .cloned()
2174                    .collect::<Vec<_>>()
2175            } else {
2176                Vec::new()
2177            };
2178            for event in replay {
2179                let body = serde_json::to_vec(&event)
2180                    .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2181                let frame = Frame::build_with_version(
2182                    version,
2183                    FrameType::StreamData,
2184                    control_flags(),
2185                    0,
2186                    0,
2187                    corr,
2188                    body,
2189                )
2190                .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2191                frames
2192                    .try_send(frame)
2193                    .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2194            }
2195            state.subscribers.insert(
2196                (connection_id, corr),
2197                SpawnSubscriber {
2198                    version,
2199                    frames,
2200                    lagged: Some(lagged),
2201                },
2202            );
2203        }
2204        // The lagged terminal is sent here, by the forwarder, rather than by
2205        // the emitter: at the moment of the drop the subscriber's own channel
2206        // is full, and writing to the connection sink directly from the emitter
2207        // would put the Error AHEAD of the events still queued in that channel
2208        // (and the emitter holds the feed lock, so it cannot await the sink).
2209        // Dropping the subscriber drops the only sender, so `recv` drains every
2210        // queued event and then returns `None`; only then is the Error sent, so
2211        // the client sees each event it can keep, then the reason it was cut.
2212        // Cancel and connection removal drop the oneshot unsent, so they end
2213        // the stream with no Error.
2214        tokio::spawn(async move {
2215            while let Some(frame) = receiver.recv().await {
2216                if sink.send(frame).await.is_err() {
2217                    return;
2218                }
2219            }
2220            let Ok(first_undelivered) = lagged_rx.try_recv() else {
2221                return;
2222            };
2223            match spawn_subscriber_lagged_frame(version, corr, first_undelivered) {
2224                Ok(frame) => {
2225                    let _ = sink.send(frame).await;
2226                }
2227                Err(error) => {
2228                    error!(%error, corr, "failed to build lagged spawn subscriber terminal frame");
2229                }
2230            }
2231        });
2232        Ok(())
2233    }
2234
2235    fn cancel(&self, connection_id: ConnectionId, corr: u64) -> bool {
2236        let Some(subscriber) = self
2237            .0
2238            .lock()
2239            .unwrap_or_else(|p| p.into_inner())
2240            .subscribers
2241            .remove(&(connection_id, corr))
2242        else {
2243            return false;
2244        };
2245        if let Ok(frame) = Frame::build_with_version(
2246            subscriber.version,
2247            FrameType::StreamEnd,
2248            control_flags(),
2249            0,
2250            0,
2251            corr,
2252            Vec::new(),
2253        ) {
2254            tokio::spawn(async move {
2255                let _ = subscriber.frames.send(frame).await;
2256            });
2257        }
2258        true
2259    }
2260
2261    fn remove_connection(&self, connection_id: ConnectionId) {
2262        self.0
2263            .lock()
2264            .unwrap_or_else(|p| p.into_inner())
2265            .subscribers
2266            .retain(|(subscriber_connection, _), _| *subscriber_connection != connection_id);
2267    }
2268
2269    #[cfg(any(test, feature = "test-support"))]
2270    fn set_capacity(&self, capacity: usize) {
2271        self.0.lock().unwrap_or_else(|p| p.into_inner()).capacity = capacity;
2272    }
2273
2274    #[cfg(any(test, feature = "test-support"))]
2275    fn subscriber_count(&self) -> usize {
2276        self.0
2277            .lock()
2278            .unwrap_or_else(|p| p.into_inner())
2279            .subscribers
2280            .len()
2281    }
2282}
2283
2284/// Narrow process-liveness signal published by supervisors and consumed by passive liveness polls.
2285/// The terminal Error a lagged spawn subscriber receives after its queued events.
2286fn spawn_subscriber_lagged_frame(
2287    version: u8,
2288    corr: u64,
2289    first_undelivered: SpawnCursor,
2290) -> Result<Frame, String> {
2291    // The daemon authors this terminal Error, so it carries the daemon-origin bit.
2292    let body = serde_json::to_vec(&subc_protocol::ErrorBody {
2293        code: SPAWN_SUBSCRIBER_LAGGED_CODE.to_string(),
2294        message: "spawn subscriber fell behind and was dropped; resubscribe from the last cursor received"
2295            .to_string(),
2296        detail: Some(serde_json::json!({
2297            "first_undelivered_cursor": first_undelivered
2298        })),
2299    })
2300    .map_err(|error| error.to_string())?;
2301    Frame::build_with_version(
2302        version,
2303        FrameType::Error,
2304        crate::router::daemon_error_flags(),
2305        0,
2306        0,
2307        corr,
2308        body,
2309    )
2310    .map_err(|error| error.to_string())
2311}
2312
2313pub trait ModuleProcessLiveness: Send + Sync {
2314    fn process_live(&self, module_id: &str) -> Option<bool>;
2315
2316    /// Whether the supervisor is replacing this module's process right now: an
2317    /// operator restart or reload, a health restart, or a crash respawn whose
2318    /// backoff is running. A module in that state is not live, but a consumer
2319    /// refused now should retry shortly rather than treat the target as gone.
2320    /// Stopped, failed, and disabled modules are not replacing.
2321    fn process_replacing(&self, _module_id: &str) -> bool {
2322        false
2323    }
2324}
2325
2326/// Shared process-liveness registry keyed by supervised `module_id`.
2327#[derive(Debug, Clone, Default)]
2328pub struct SupervisorProcessLiveness {
2329    snapshots: Arc<Mutex<HashMap<String, SharedSnapshot>>>,
2330}
2331
2332impl SupervisorProcessLiveness {
2333    pub fn new() -> Self {
2334        Self::default()
2335    }
2336
2337    fn track(&self, module_id: String, snapshot: SharedSnapshot) {
2338        let mut snapshots = self
2339            .snapshots
2340            .lock()
2341            .unwrap_or_else(|poisoned| poisoned.into_inner());
2342        snapshots.insert(module_id, snapshot);
2343    }
2344
2345    fn untrack_if_current(&self, module_id: &str, snapshot: &SharedSnapshot) {
2346        let mut snapshots = self
2347            .snapshots
2348            .lock()
2349            .unwrap_or_else(|poisoned| poisoned.into_inner());
2350        let is_current = snapshots
2351            .get(module_id)
2352            .map(|tracked| Arc::ptr_eq(tracked, snapshot))
2353            .unwrap_or(false);
2354        if is_current {
2355            snapshots.remove(module_id);
2356        }
2357    }
2358}
2359
2360impl ModuleProcessLiveness for SupervisorProcessLiveness {
2361    fn process_live(&self, module_id: &str) -> Option<bool> {
2362        let snapshot = {
2363            let snapshots = self
2364                .snapshots
2365                .lock()
2366                .unwrap_or_else(|poisoned| poisoned.into_inner());
2367            snapshots.get(module_id).cloned()
2368        }?;
2369        let snapshot = snapshot
2370            .lock()
2371            .unwrap_or_else(|poisoned| poisoned.into_inner());
2372        Some(snapshot.state == ModuleState::Running && snapshot.process_alive)
2373    }
2374
2375    fn process_replacing(&self, module_id: &str) -> bool {
2376        let Some(snapshot) = self
2377            .snapshots
2378            .lock()
2379            .unwrap_or_else(|poisoned| poisoned.into_inner())
2380            .get(module_id)
2381            .cloned()
2382        else {
2383            return false;
2384        };
2385        let snapshot = snapshot
2386            .lock()
2387            .unwrap_or_else(|poisoned| poisoned.into_inner());
2388        snapshot.enabled
2389            && match snapshot.state {
2390                ModuleState::Restarting => true,
2391                ModuleState::Draining => snapshot.draining_to_replace,
2392                ModuleState::Starting
2393                | ModuleState::Running
2394                | ModuleState::Unresponsive
2395                | ModuleState::Stopped
2396                | ModuleState::Failed
2397                | ModuleState::Disabled => false,
2398            }
2399    }
2400}
2401
2402#[cfg(test)]
2403#[derive(Debug, Default)]
2404struct ReloadExitRecordGate {
2405    reached: tokio::sync::Notify,
2406    resume: tokio::sync::Notify,
2407}
2408
2409#[derive(Debug, Clone, Copy)]
2410enum RespawnKind {
2411    Spawn,
2412    Reload,
2413}
2414
2415#[derive(Debug, Clone)]
2416struct PendingRespawn {
2417    deadline: Instant,
2418    kind: RespawnKind,
2419    daemon_initiated: bool,
2420    approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
2421}
2422
2423impl PendingRespawn {
2424    fn failure_context(&self, runtime: &SupervisorRuntimeConfig) -> FailureContext {
2425        FailureContext {
2426            approval: self.approval.clone(),
2427            ..runtime.failure_context(self.daemon_initiated)
2428        }
2429    }
2430}
2431
2432type ReloadReply = oneshot::Sender<Result<(), SuperviseError>>;
2433
2434#[derive(Debug, Clone)]
2435struct SupervisorRuntimeConfig {
2436    registry: Arc<Registry>,
2437    config_delivery: Option<config_delivery::ConfigDelivery>,
2438    /// Retained across an operation's deferred backoff, until its child starts.
2439    recovery_is_daemon: bool,
2440    start_requester: Option<Principal>,
2441    pending_activity_restart: bool,
2442    provenance_probe: ExecutableIdentityProbe,
2443    /// Restart operations hand their backoff to the loop, which keeps serving commands.
2444    scheduled_respawn: Arc<Mutex<Option<PendingRespawn>>>,
2445    /// A reload acknowledges completion only after its replacement registers.
2446    deferred_reload_reply: Arc<Mutex<Option<ReloadReply>>>,
2447    restart_policy: RestartPolicy,
2448    register_timeout: Duration,
2449    /// This module's RESOLVED drain budget: per-module config when present,
2450    /// else `default_drain_timeout`.
2451    drain_timeout: Duration,
2452    /// Shared with the status handle so the attested value changes atomically
2453    /// when a rescan updates the running drain policy.
2454    effective_drain_timeout: Arc<Mutex<Duration>>,
2455    /// The supervisor-wide fallback, kept so a configuration update that
2456    /// REMOVES the per-module override can re-resolve to it.
2457    default_drain_timeout: Duration,
2458    health: HealthConfig,
2459    host_health: HostHealth,
2460    connection_file_path: Option<PathBuf>,
2461    capture_logs_dir: Option<PathBuf>,
2462    forwarding: Option<Arc<ForwardingTable>>,
2463    /// The shared handle, so every spawn path (initial, restart, reload) records the
2464    /// reserved-module launch nonce the HELLO verifier checks against.
2465    supervisor_handle: Option<SupervisorHandle>,
2466    /// This module's stderr tail, shared with the [`SupervisedModule`] that answers
2467    /// status queries.
2468    ///
2469    /// One ring per module, held across every respawn. The lines explaining an exit
2470    /// are written BEFORE that exit, so a ring recreated per process would be empty
2471    /// exactly when it is asked for.
2472    stderr_ring: Arc<Mutex<StderrRing>>,
2473    terminal_ring: Arc<Mutex<TerminalRing>>,
2474    spawn_events: SpawnEventFeed,
2475    child_roster: ChildRoster,
2476    #[cfg(target_os = "linux")]
2477    cgroup_placement: Option<subc_cgroup::Placement>,
2478    #[cfg(test)]
2479    test_seed_stale_facts_before_enable_spawn: bool,
2480    #[cfg(test)]
2481    test_reload_exit_record_gate: Option<Arc<ReloadExitRecordGate>>,
2482}
2483
2484impl SupervisorRuntimeConfig {
2485    fn failure_context(&self, daemon_initiated: bool) -> FailureContext {
2486        FailureContext {
2487            daemon_initiated,
2488            approval: None,
2489            shutdown: self.child_roster.shutdown_flag(),
2490        }
2491    }
2492}
2493
2494#[derive(Debug, Clone, PartialEq, Eq)]
2495struct SupervisedConfiguration {
2496    spec: ModuleSpec,
2497    enabled: bool,
2498    health: HealthConfig,
2499    register_timeout: Duration,
2500    restart_policy: RestartPolicy,
2501}
2502
2503/// Shared daemon lookup table for supervised module handles.
2504///
2505/// Shared by clone between the [`Supervisor`] (which spawns processes) and the
2506/// channel-0 control handler (which verifies HELLOs and consumer route opens), so
2507/// launch nonces recorded at spawn are checked by the same daemon instance.
2508#[derive(Debug, Clone, Default)]
2509pub struct SupervisorHandle {
2510    #[cfg(test)]
2511    resource_commit_pause: Arc<Mutex<Option<resource_launch::ResourceCommitPause>>>,
2512    #[cfg(test)]
2513    registration_test_channels: CapturedRegistrationChannels,
2514    registration_service: Arc<Mutex<Option<registration::RegistrationService>>>,
2515    registration_connections: Arc<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
2516    registration_launches: Arc<Mutex<Vec<std::sync::Weak<RegistrationSpawn>>>>,
2517    gate_runtime: Arc<Mutex<Option<std::sync::Weak<crate::config_gate::runtime::RuntimeOwner>>>>,
2518    program_bindings: program_binding::ProgramBindings,
2519    #[cfg(test)]
2520    identity_sample_pause: Arc<Mutex<Option<IdentitySamplePause>>>,
2521    #[cfg(all(test, unix))]
2522    plain_identity_policy_pause: Arc<Mutex<Option<(String, IdentitySamplePause)>>>,
2523    host_health: HostHealth,
2524    restart_intent: Arc<Mutex<DaemonRestartIntent>>,
2525    activity: Arc<Mutex<Option<crate::activity::ActivityLedger>>>,
2526    activity_images: Arc<Mutex<HashMap<String, activity::ActivityImage>>>,
2527    modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
2528    /// Module ids the supervisor has taken on. An id is added BEFORE the
2529    /// module's first process is spawned and removed only when the module
2530    /// leaves the roster (see [`Self::retire`]), so it is always a superset of
2531    /// the keys of `modules`.
2532    ///
2533    /// `modules` cannot answer "is this module configured?" on its own: a
2534    /// [`SupervisedModule`] only exists once its process has been spawned, and
2535    /// a fast child can connect, register, sync its scopes and ask about them
2536    /// before the supervisor has inserted it. Answering "not configured" in that
2537    /// gap makes scope admission refuse with the terminal "will never sync"
2538    /// instead of the retryable "has not synced yet".
2539    configured_ids: Arc<Mutex<HashSet<String>>>,
2540    spawn_events: SpawnEventFeed,
2541    /// The current expected launch nonce for each reserved module_id. Set when the
2542    /// supervisor spawns the reserved module; checked when a HELLO claims that id. A
2543    /// non-reserved module never has an entry here and is never nonce-checked.
2544    /// Reserved module ids and the nonce that authorizes their next HELLO.
2545    /// `None` means RESERVED WITH NO LEGITIMATE HOLDER — a reserved module that
2546    /// has never been spawned (e.g. configured `enabled: false`) — and refuses
2547    /// every HELLO. Before this was expressible, a reserved-but-never-spawned id
2548    /// had NO entry and admitted anyone: the reservation protected the nonce
2549    /// holder, not the NAME (found live by CKCRED's canary probe registering
2550    /// against a reserved scratch id).
2551    reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
2552    /// Reservations installed only to prevent HELLO for a protocol:none process.
2553    /// Replacement by a subc process releases them; explicitly reserved ids are
2554    /// never placed in this set and still require an operator release.
2555    implicit_protocol_none: Arc<Mutex<HashSet<String>>>,
2556    /// Module ids removed by an executed rescan and the unix-millisecond removal time.
2557    ///
2558    /// This is deliberately in-memory only: subc is state-free across daemon
2559    /// restarts, and the tombstone only explains the hours-after-removal window
2560    /// while this executing daemon is still alive. Do not persist it in a store.
2561    removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
2562    /// The current launch nonce for every supervised spawn. This is separate from
2563    /// reserved_nonces because consumer route.open attestation applies to all spawned
2564    /// modules, while HELLO id-squatting protection remains opt-in via `reserved`.
2565    spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
2566    /// The launch each live launch nonce was minted for, keyed by nonce, with
2567    /// the launch's module id, so a nonce-attested consumer or registration
2568    /// resolves to that launch's authority record. An entry whose launch has
2569    /// ended stays while its nonce still authorizes, so a nonce whose record
2570    /// is gone is told apart from one that never had a record.
2571    nonce_launches: Arc<Mutex<NonceLaunches>>,
2572    /// Reserved namespace prefixes mapped to the supervised owner module whose
2573    /// current spawn nonce authorizes HELLO claims below the prefix.
2574    ///
2575    /// Per §2.6 this is not a same-user security barrier: a same-user process can
2576    /// read the key file and launch nonce env. Like exact reserved ids, it prevents
2577    /// accidental collisions and lower-trust processes from squatting protected
2578    /// namespaces.
2579    reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
2580    /// Blue/green swaps in progress, by module id. An entry exists from just
2581    /// before the candidate process is spawned until the swap has failed, or
2582    /// has cut over and the old process is gone. While it exists, HELLO for the
2583    /// id is gated on the swap token (see [`Self::swap_hello_admission`]) and
2584    /// consumer attestation accepts both processes' nonces.
2585    swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
2586    /// Told when a swap promotes its candidate; see [`SwapPromotionObserver`].
2587    promotion_observer: PromotionObserverSlot,
2588    /// Serializes module-set reconciliation with operator lifecycle commands. Without
2589    /// this daemon-wide ordering, a rescan could retire or update a module while a
2590    /// concurrent reload still held its old handle and launch specification.
2591    operation_lock: Arc<AsyncMutex<()>>,
2592}
2593
2594#[cfg(test)]
2595#[derive(Debug)]
2596struct IdentitySamplePause {
2597    reached: std::sync::mpsc::Sender<()>,
2598    release: std::sync::mpsc::Receiver<()>,
2599}
2600
2601/// Told when a swap has promoted its candidate to be the module's active
2602/// registration.
2603///
2604/// An ordinary HELLO runs the control plane's registration side effects (the
2605/// capability cache, the deny census, the requirement recompute) as it
2606/// registers. A swap candidate's HELLO does not, because it is not routable;
2607/// promotion is when those must run instead, and promotion happens in the
2608/// supervisor, which has no other way into the control handler.
2609pub(crate) trait SwapPromotionObserver: Send + Sync {
2610    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration);
2611}
2612
2613/// The installed [`SwapPromotionObserver`], held weakly: the observer (the
2614/// control handler) owns this handle, so a strong reference back would be a
2615/// cycle that keeps both alive.
2616#[derive(Clone, Default)]
2617struct PromotionObserverSlot(Arc<Mutex<Option<std::sync::Weak<dyn SwapPromotionObserver>>>>);
2618
2619impl fmt::Debug for PromotionObserverSlot {
2620    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2621        f.write_str("PromotionObserverSlot")
2622    }
2623}
2624
2625/// The nonces of one open swap.
2626#[derive(Debug, Clone)]
2627struct OpenSwap {
2628    /// Legacy candidate token. A gated candidate has an empty lifecycle
2629    /// placeholder instead; only its own channel admits its HELLO.
2630    candidate_nonce: String,
2631    /// Incumbent token accepted before cutover, then cleared by promotion even
2632    /// while the incumbent's process is still draining.
2633    incumbent_nonce: Option<String>,
2634    /// Set once a HELLO has been admitted with the swap token, so the token
2635    /// admits one registration and cannot be replayed after cutover empties
2636    /// the candidate slot.
2637    candidate_admitted: bool,
2638}
2639
2640/// What the swap gate says about a HELLO. See
2641/// [`SupervisorHandle::swap_hello_admission`].
2642#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2643pub(crate) enum SwapHelloAdmission {
2644    /// No swap is open for the id (or the HELLO carries the incumbent's own
2645    /// nonce); the ordinary gates decide.
2646    NotSwapping,
2647    /// The HELLO carries the swap token: register it into the candidate slot.
2648    Candidate,
2649    /// A swap is open and the HELLO carries a nonce the supervisor did not
2650    /// mint for this id, no nonce, or a token already used.
2651    Refused,
2652    /// The id belongs to a supervised `protocol: none` module. Such a module
2653    /// never registers, so no HELLO may claim its id, with or without a nonce.
2654    ProtocolNone,
2655    /// The id is gated. Its supervised child registers only over the
2656    /// registration channel it inherited at launch, never by HELLO alone.
2657    ChannelRequired,
2658}
2659
2660#[derive(Debug, Clone, PartialEq, Eq)]
2661pub(crate) enum ReservedHelloRejection {
2662    Exact {
2663        module_id: String,
2664    },
2665    Prefix {
2666        prefix: String,
2667        owner_module_id: String,
2668    },
2669}
2670
2671/// Identity facts established by the reserved-module policy for one HELLO.
2672#[derive(Debug, Default)]
2673pub(crate) struct ReservedHelloVerification {
2674    pub(crate) nonce_verified: bool,
2675    pub(crate) prefix_owner: Option<String>,
2676}
2677
2678#[derive(Debug)]
2679struct DaemonRestartIntent {
2680    expires: Option<Duration>,
2681    window: Duration,
2682}
2683
2684impl Default for DaemonRestartIntent {
2685    fn default() -> Self {
2686        Self {
2687            expires: None,
2688            window: Duration::from_secs(120),
2689        }
2690    }
2691}
2692
2693impl SupervisorHandle {
2694    pub(crate) fn module_is_gated(&self, module: &str) -> bool {
2695        let runtime = {
2696            let Ok(runtime) = self.gate_runtime.lock() else {
2697                return true;
2698            };
2699            runtime.clone()
2700        };
2701        runtime.is_some_and(|runtime| {
2702            runtime
2703                .upgrade()
2704                .is_none_or(|owner| owner.module_is_gated(module))
2705        })
2706    }
2707    pub(crate) fn announce_daemon_restart(&self) -> u64 {
2708        let mut intent = self
2709            .restart_intent
2710            .lock()
2711            .unwrap_or_else(|p| p.into_inner());
2712        intent.expires = Some(subc_uptime::suspend_inclusive_now() + intent.window);
2713        unix_ms_now().saturating_add(intent.window.as_millis() as u64)
2714    }
2715
2716    #[cfg(feature = "test-support")]
2717    pub(crate) fn set_shutdown_intent_window(&self, window: Duration) {
2718        self.restart_intent
2719            .lock()
2720            .unwrap_or_else(|p| p.into_inner())
2721            .window = window;
2722    }
2723
2724    #[cfg(unix)]
2725    fn take_daemon_shutdown_reason(&self) -> RouteCloseReason {
2726        let expiry = self
2727            .restart_intent
2728            .lock()
2729            .unwrap_or_else(|p| p.into_inner())
2730            .expires
2731            .take();
2732        if expiry.is_some_and(|expiry| subc_uptime::suspend_inclusive_now() < expiry) {
2733            RouteCloseReason::Restart
2734        } else {
2735            RouteCloseReason::Disable
2736        }
2737    }
2738
2739    pub fn new() -> Self {
2740        Self::default()
2741    }
2742
2743    pub(crate) fn spawn_snapshot(&self) -> SpawnSnapshot {
2744        self.spawn_events.snapshot()
2745    }
2746
2747    /// Subscribe before reading the bound process. A coalesced wake is enough:
2748    /// readers compare its exact generation and PID, not the last event kind.
2749    pub(crate) fn subscribe_process_changes(
2750        &self,
2751        module: &str,
2752    ) -> tokio::sync::watch::Receiver<u64> {
2753        let mut state = self
2754            .spawn_events
2755            .0
2756            .lock()
2757            .unwrap_or_else(|p| p.into_inner());
2758        state
2759            .process_changes
2760            .retain(|_, changed| changed.receiver_count() > 0);
2761        let seq = state.seq;
2762        state
2763            .process_changes
2764            .entry(module.into())
2765            .or_insert_with(|| tokio::sync::watch::channel(seq).0)
2766            .subscribe()
2767    }
2768
2769    pub(crate) fn current_spawn(&self, module: &str) -> Option<LiveSpawn> {
2770        self.spawn_events
2771            .0
2772            .lock()
2773            .unwrap_or_else(|p| p.into_inner())
2774            .live
2775            .get(module)
2776            .cloned()
2777    }
2778
2779    pub(crate) fn subscribe_spawns(
2780        &self,
2781        connection_id: ConnectionId,
2782        corr: u64,
2783        version: u8,
2784        since: Option<SpawnCursor>,
2785        sink: FrameSink,
2786    ) -> Result<(), SpawnSubscribeRefusal> {
2787        self.spawn_events
2788            .subscribe(connection_id, corr, version, since, sink)
2789    }
2790
2791    pub(crate) fn cancel_spawn_subscription(&self, connection_id: ConnectionId, corr: u64) -> bool {
2792        self.spawn_events.cancel(connection_id, corr)
2793    }
2794
2795    pub(crate) fn remove_spawn_subscribers(&self, connection_id: ConnectionId) {
2796        self.spawn_events.remove_connection(connection_id);
2797    }
2798
2799    #[cfg(any(test, feature = "test-support"))]
2800    pub fn set_spawn_event_capacity_for_test(&self, capacity: usize) {
2801        assert!(capacity > 0, "spawn event capacity must be non-zero");
2802        self.spawn_events.set_capacity(capacity);
2803    }
2804
2805    #[cfg(any(test, feature = "test-support"))]
2806    pub fn spawn_subscriber_count_for_test(&self) -> usize {
2807        self.spawn_events.subscriber_count()
2808    }
2809
2810    /// Record the launch nonce from a supervised spawn, replacing any prior nonce so
2811    /// a respawn invalidates stale consumer identities.
2812    pub fn set_spawn_nonce(&self, module_id: &str, nonce: String) {
2813        self.spawn_nonces
2814            .lock()
2815            .unwrap_or_else(|poisoned| poisoned.into_inner())
2816            .insert(module_id.to_string(), nonce);
2817        self.refresh_program_binding_nonces(module_id);
2818    }
2819
2820    /// Record the launch nonce expected from the next HELLO for a reserved module,
2821    /// replacing any prior nonce (a respawn invalidates the previous one).
2822    pub fn set_reserved_nonce(&self, module_id: &str, nonce: String) {
2823        {
2824            let mut reserved = self
2825                .reserved_nonces
2826                .lock()
2827                .unwrap_or_else(|p| p.into_inner());
2828            self.implicit_protocol_none
2829                .lock()
2830                .unwrap_or_else(|p| p.into_inner())
2831                .remove(module_id);
2832            reserved.insert(module_id.to_string(), Some(nonce));
2833        }
2834        self.refresh_program_binding_nonces(module_id);
2835    }
2836
2837    /// Record namespace prefixes owned by a supervised module.
2838    pub fn set_reserved_prefixes(&self, owner_module_id: &str, prefixes: &[String]) {
2839        let mut owners = self
2840            .reserved_prefix_owners
2841            .lock()
2842            .unwrap_or_else(|poisoned| poisoned.into_inner());
2843        owners.retain(|_, owner| owner != owner_module_id);
2844        for prefix in prefixes {
2845            owners.insert(prefix.clone(), owner_module_id.to_string());
2846        }
2847    }
2848
2849    /// The launch nonce most recently minted for a module's spawn, if any.
2850    pub(crate) fn spawn_nonce(&self, module_id: &str) -> Option<String> {
2851        if self.module_is_gated(module_id) {
2852            return None;
2853        }
2854        self.spawn_nonces
2855            .lock()
2856            .unwrap_or_else(|poisoned| poisoned.into_inner())
2857            .get(module_id)
2858            .cloned()
2859    }
2860
2861    #[cfg(all(test, unix))]
2862    pub(crate) fn legacy_nonce_present_for_test(&self, module: &str) -> bool {
2863        self.spawn_nonces.lock().unwrap().contains_key(module)
2864    }
2865
2866    pub(crate) fn apply_identity_configuration(&self, spec: &ModuleSpec) {
2867        // Prefix ownership follows staged configuration, not the running
2868        // child's launch settings. A respawn may still carry an older spec.
2869        self.set_reserved_prefixes(&spec.module_id, &spec.reserved_prefixes);
2870        let protocol = self
2871            .get(&spec.module_id)
2872            .and_then(|module| {
2873                let snapshot = module.inner.snapshot.lock().ok()?;
2874                snapshot
2875                    .process_alive
2876                    .then_some(snapshot.spawned_protocol.unwrap_or(spec.protocol))
2877            })
2878            .unwrap_or(spec.protocol);
2879        self.apply_identity_policy(spec, protocol);
2880    }
2881
2882    #[cfg(all(test, unix))]
2883    pub(crate) fn pause_plain_identity_policy_for_test(
2884        &self,
2885        module: &str,
2886    ) -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
2887        let (reached, waiting) = std::sync::mpsc::channel();
2888        let (release, paused) = std::sync::mpsc::channel();
2889        *self.plain_identity_policy_pause.lock().unwrap() = Some((
2890            module.to_owned(),
2891            IdentitySamplePause {
2892                reached,
2893                release: paused,
2894            },
2895        ));
2896        (waiting, release)
2897    }
2898
2899    fn apply_identity_policy(&self, spec: &ModuleSpec, protocol: ModuleProtocol) {
2900        let channel_only = self.module_is_gated(&spec.module_id);
2901        let mut current_nonces = self
2902            .spawn_nonces
2903            .lock()
2904            .unwrap_or_else(|poisoned| poisoned.into_inner());
2905        if protocol == ModuleProtocol::None || channel_only {
2906            current_nonces.remove(&spec.module_id);
2907        }
2908        let spawn_nonce = current_nonces.get(&spec.module_id).cloned();
2909        #[cfg(test)]
2910        if let Some(pause) = self.identity_sample_pause.lock().unwrap().take() {
2911            pause.reached.send(()).unwrap();
2912            pause.release.recv().unwrap();
2913        }
2914        let mut reserved_nonces = self
2915            .reserved_nonces
2916            .lock()
2917            .unwrap_or_else(|poisoned| poisoned.into_inner());
2918        let mut implicit = self
2919            .implicit_protocol_none
2920            .lock()
2921            .unwrap_or_else(|p| p.into_inner());
2922        if spec.reserved {
2923            implicit.remove(&spec.module_id);
2924        } else if protocol == ModuleProtocol::None {
2925            if !reserved_nonces.contains_key(&spec.module_id) {
2926                implicit.insert(spec.module_id.clone());
2927            }
2928        } else if implicit.remove(&spec.module_id) {
2929            reserved_nonces.remove(&spec.module_id);
2930        }
2931        if spec.reserved || protocol == ModuleProtocol::None {
2932            // `None` (no spawn nonce minted) is INSERTED, not skipped: a
2933            // reserved name whose module has never spawned has no legitimate
2934            // holder, and the entry's absence is what used to leave the name
2935            // open to the first claimant.
2936            reserved_nonces.insert(spec.module_id.clone(), spawn_nonce);
2937        }
2938        drop(implicit);
2939        drop(reserved_nonces);
2940        drop(current_nonces);
2941        self.refresh_program_binding_nonces(&spec.module_id);
2942        // A later unreserved declaration must not silently unreserve an id that
2943        // was retained after its reserved configuration was removed. The explicit
2944        // release ceremony is the only operation that retires that gate.
2945        self.removal_tombstones
2946            .lock()
2947            .unwrap_or_else(|poisoned| poisoned.into_inner())
2948            .remove(&spec.module_id);
2949    }
2950
2951    /// Whether a HELLO claiming `module_id` is authorized. An exact reserved id is
2952    /// authorized only by its expected nonce; otherwise a matching reserved prefix
2953    /// is authorized by the owner module's current spawn nonce. Non-reserved ids
2954    /// with no matching prefix are always authorized.
2955    pub fn reserved_hello_authorized(&self, module_id: &str, presented: Option<&str>) -> bool {
2956        self.reserved_hello_verification(module_id, presented)
2957            .is_ok()
2958    }
2959
2960    /// Whether HELLO passed a nonce check that was actually required by reserved
2961    /// module policy, or the refusal explaining why a required check failed.
2962    pub(crate) fn reserved_hello_verification(
2963        &self,
2964        module_id: &str,
2965        presented: Option<&str>,
2966    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
2967        if self.module_is_gated(module_id) {
2968            return Err(ReservedHelloRejection::Exact {
2969                module_id: module_id.into(),
2970            });
2971        }
2972        self.hello_verification(module_id, presented, false)
2973    }
2974
2975    pub(crate) fn channel_hello_verification(
2976        &self,
2977        module_id: &str,
2978    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
2979        if self
2980            .get(module_id)
2981            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
2982        {
2983            return Err(ReservedHelloRejection::Exact {
2984                module_id: module_id.into(),
2985            });
2986        }
2987        let mut verification = self.hello_verification(module_id, None, true)?;
2988        verification.nonce_verified = true;
2989        Ok(verification)
2990    }
2991
2992    pub(crate) fn prefix_claim_authorized(&self, owner: &str, module_id: &str) -> bool {
2993        self.prefix_claim_publication(owner, module_id).is_some()
2994    }
2995
2996    #[cfg(all(test, unix))]
2997    pub(crate) fn prefix_publication_locked_for_test(&self) -> bool {
2998        matches!(
2999            self.reserved_prefix_owners.try_lock(),
3000            Err(std::sync::TryLockError::WouldBlock)
3001        )
3002    }
3003
3004    // Keep this guard through registry/forwarding publication. Rescans replace
3005    // prefix owners without stopping their launches, so the spawn guard alone
3006    // cannot fence a reservation transfer.
3007    pub(crate) fn prefix_claim_publication(
3008        &self,
3009        owner: &str,
3010        module_id: &str,
3011    ) -> Option<std::sync::MutexGuard<'_, HashMap<String, String>>> {
3012        if subc_protocol::manifest::validate_module_id(module_id).is_err()
3013            || self.module_is_gated(module_id)
3014            || self
3015                .reserved_nonces
3016                .lock()
3017                .unwrap_or_else(|p| p.into_inner())
3018                .contains_key(module_id)
3019        {
3020            return None;
3021        }
3022        let owners = self
3023            .reserved_prefix_owners
3024            .lock()
3025            .unwrap_or_else(|p| p.into_inner());
3026        let authorized = owners
3027            .iter()
3028            .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
3029            .max_by_key(|(prefix, _)| prefix.len())
3030            .is_some_and(|(prefix, holder)| holder == owner && module_id.len() > prefix.len());
3031        authorized.then_some(owners)
3032    }
3033
3034    fn hello_verification(
3035        &self,
3036        module_id: &str,
3037        presented: Option<&str>,
3038        channel: bool,
3039    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
3040        let nonces = self
3041            .reserved_nonces
3042            .lock()
3043            .unwrap_or_else(|poisoned| poisoned.into_inner());
3044        if let Some(expected) = nonces.get(module_id) {
3045            // `None` = reserved with no legitimate holder: refuse every
3046            // presentation, because no process can hold a nonce that was never
3047            // minted. Only a real minted nonce admits, in constant time.
3048            let authorized = channel
3049                || match expected {
3050                    Some(expected) => presented.is_some_and(|p| {
3051                        !p.is_empty() && constant_time_eq(expected.as_bytes(), p.as_bytes())
3052                    }),
3053                    None => false,
3054                };
3055            if authorized {
3056                return Ok(ReservedHelloVerification {
3057                    nonce_verified: true,
3058                    prefix_owner: None,
3059                });
3060            }
3061            return Err(ReservedHelloRejection::Exact {
3062                module_id: module_id.to_string(),
3063            });
3064        }
3065        drop(nonces);
3066
3067        let matched_prefix = self
3068            .reserved_prefix_owners
3069            .lock()
3070            .unwrap_or_else(|poisoned| poisoned.into_inner())
3071            .iter()
3072            .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
3073            .max_by_key(|(prefix, _)| prefix.len())
3074            .map(|(prefix, owner)| (prefix.clone(), owner.clone()));
3075        let Some((prefix, owner_module_id)) = matched_prefix else {
3076            return Ok(ReservedHelloVerification::default());
3077        };
3078
3079        if module_id.len() == prefix.len()
3080            || (!channel
3081                && (self.module_is_gated(&owner_module_id) || self.protocol_none(&owner_module_id)))
3082        {
3083            return Err(ReservedHelloRejection::Prefix {
3084                prefix,
3085                owner_module_id,
3086            });
3087        }
3088
3089        let authorized = if channel {
3090            owner_module_id == module_id
3091        } else {
3092            presented.is_some_and(|presented| {
3093                self.spawn_nonces
3094                .lock()
3095                .unwrap_or_else(|poisoned| poisoned.into_inner())
3096                .get(&owner_module_id)
3097                .is_some_and(|expected| !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes()))
3098                // While the owner is being swapped, children started by
3099                // either of its two processes hold that process's nonce.
3100                || self.swap_nonce_matches(&owner_module_id, presented)
3101            })
3102        };
3103        if authorized {
3104            Ok(ReservedHelloVerification {
3105                nonce_verified: true,
3106                prefix_owner: (owner_module_id != module_id).then_some(owner_module_id),
3107            })
3108        } else {
3109            Err(ReservedHelloRejection::Prefix {
3110                prefix,
3111                owner_module_id,
3112            })
3113        }
3114    }
3115
3116    /// Whether a consumer connection proved it came from a daemon-spawned module.
3117    ///
3118    /// Absence of an expected spawn nonce is a hard failure: consumer_identity is
3119    /// accepted only for module ids the supervisor has spawned.
3120    pub fn spawned_consumer_authorized(&self, module_id: &str, presented: &str) -> bool {
3121        if self.module_is_gated(module_id) || self.protocol_none(module_id) {
3122            return false;
3123        }
3124        let nonces = self
3125            .spawn_nonces
3126            .lock()
3127            .unwrap_or_else(|poisoned| poisoned.into_inner());
3128        let current = nonces.get(module_id).is_some_and(|expected| {
3129            !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes())
3130        });
3131        drop(nonces);
3132        // Before cutover both launches may attest. Promotion removes the
3133        // incumbent's token even if its process still needs time to drain.
3134        current || self.swap_nonce_matches(module_id, presented)
3135    }
3136
3137    /// Whether `presented` is either nonce of an open swap for `module_id`.
3138    fn swap_nonce_matches(&self, module_id: &str, presented: &str) -> bool {
3139        if self.module_is_gated(module_id) || self.protocol_none(module_id) || presented.is_empty()
3140        {
3141            return false;
3142        }
3143        let swaps = self
3144            .swaps
3145            .lock()
3146            .unwrap_or_else(|poisoned| poisoned.into_inner());
3147        swaps.get(module_id).is_some_and(|swap| {
3148            constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes())
3149                || swap.incumbent_nonce.as_deref().is_some_and(|incumbent| {
3150                    constant_time_eq(incumbent.as_bytes(), presented.as_bytes())
3151                })
3152        })
3153    }
3154
3155    /// Open a swap for `module_id` with the candidate's freshly minted nonce.
3156    /// Called before the candidate process exists.
3157    pub(crate) fn open_swap(&self, module_id: &str, candidate_nonce: String) {
3158        let incumbent_nonce = self
3159            .spawn_nonces
3160            .lock()
3161            .unwrap_or_else(|poisoned| poisoned.into_inner())
3162            .get(module_id)
3163            .cloned();
3164        self.swaps
3165            .lock()
3166            .unwrap_or_else(|poisoned| poisoned.into_inner())
3167            .insert(
3168                module_id.to_string(),
3169                OpenSwap {
3170                    candidate_nonce,
3171                    incumbent_nonce,
3172                    candidate_admitted: false,
3173                },
3174            );
3175        self.refresh_program_binding_nonces(module_id);
3176    }
3177
3178    /// Close the swap for `module_id`, releasing whichever nonce is no longer
3179    /// the module's recorded one.
3180    pub(crate) fn close_swap(&self, module_id: &str) {
3181        self.swaps
3182            .lock()
3183            .unwrap_or_else(|poisoned| poisoned.into_inner())
3184            .remove(module_id);
3185        self.refresh_program_binding_nonces(module_id);
3186    }
3187
3188    /// Install the observer told about swap promotions, replacing any earlier
3189    /// one.
3190    pub(crate) fn set_swap_promotion_observer(
3191        &self,
3192        observer: std::sync::Weak<dyn SwapPromotionObserver>,
3193    ) {
3194        *self
3195            .promotion_observer
3196            .0
3197            .lock()
3198            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer);
3199    }
3200
3201    /// Tell the installed observer, if it is still alive, that a swap promoted
3202    /// `registration`.
3203    fn notify_swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
3204        let observer = self
3205            .promotion_observer
3206            .0
3207            .lock()
3208            .unwrap_or_else(|poisoned| poisoned.into_inner())
3209            .as_ref()
3210            .and_then(std::sync::Weak::upgrade);
3211        if let Some(observer) = observer {
3212            observer.swap_promoted(registration);
3213        }
3214    }
3215
3216    /// Whether a swap is open for `module_id`.
3217    pub(crate) fn swap_open(&self, module_id: &str) -> bool {
3218        self.swaps
3219            .lock()
3220            .unwrap_or_else(|poisoned| poisoned.into_inner())
3221            .contains_key(module_id)
3222    }
3223
3224    /// Make the candidate's nonce the module's recorded spawn nonce, as a plain
3225    /// respawn would, once cutover has made the candidate the module's process.
3226    /// Promotion revokes the incumbent's tokens; the swap record stays open
3227    /// only for lifecycle cleanup while the old process drains.
3228    fn promote_swap_nonce(&self, module_id: &str, reserved: bool) {
3229        let candidate_nonce = self
3230            .swaps
3231            .lock()
3232            .unwrap_or_else(|poisoned| poisoned.into_inner())
3233            .get_mut(module_id)
3234            .map(|swap| {
3235                swap.incumbent_nonce = None;
3236                swap.candidate_nonce.clone()
3237            });
3238        self.spawn_nonces
3239            .lock()
3240            .unwrap_or_else(|p| p.into_inner())
3241            .remove(module_id);
3242        {
3243            let mut nonces = self
3244                .reserved_nonces
3245                .lock()
3246                .unwrap_or_else(|p| p.into_inner());
3247            if reserved || nonces.contains_key(module_id) {
3248                nonces.insert(module_id.into(), None);
3249            }
3250        }
3251        if self.module_is_gated(module_id) {
3252            return;
3253        }
3254        let Some(nonce) = candidate_nonce.filter(|nonce| !nonce.is_empty()) else {
3255            return;
3256        };
3257        self.set_spawn_nonce(module_id, nonce.clone());
3258        if reserved {
3259            self.set_reserved_nonce(module_id, nonce);
3260        }
3261    }
3262
3263    /// The swap gate for a HELLO claiming `module_id`.
3264    ///
3265    /// This runs BEFORE the reserved-module gate. A reserved module's candidate
3266    /// presents the candidate nonce, which the reserved gate (holding the
3267    /// incumbent's nonce) would refuse as `reserved_module` before swap
3268    /// admission was ever reached. And it applies to unreserved ids too: for an
3269    /// unreserved id the only thing that ever stopped a second process claiming
3270    /// a live id was the `duplicate_module_id` refusal, which is exactly the
3271    /// refusal a swap lifts for its candidate.
3272    ///
3273    /// The incumbent's own nonce falls through to the ordinary gates, which
3274    /// treat it as they always have (a live incumbent is refused as a
3275    /// duplicate). Anything else while a swap is open is refused, including an
3276    /// absent nonce.
3277    pub(crate) fn swap_hello_admission(
3278        &self,
3279        module_id: &str,
3280        presented: Option<&str>,
3281    ) -> SwapHelloAdmission {
3282        if self.protocol_none(module_id) {
3283            return SwapHelloAdmission::ProtocolNone;
3284        }
3285        if self.module_is_gated(module_id) {
3286            return SwapHelloAdmission::ChannelRequired;
3287        }
3288        let swaps = self
3289            .swaps
3290            .lock()
3291            .unwrap_or_else(|poisoned| poisoned.into_inner());
3292        let Some(swap) = swaps.get(module_id) else {
3293            return SwapHelloAdmission::NotSwapping;
3294        };
3295        let Some(presented) = presented.filter(|nonce| !nonce.is_empty()) else {
3296            return SwapHelloAdmission::Refused;
3297        };
3298        if constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes()) {
3299            return if swap.candidate_admitted {
3300                SwapHelloAdmission::Refused
3301            } else {
3302                SwapHelloAdmission::Candidate
3303            };
3304        }
3305        if swap
3306            .incumbent_nonce
3307            .as_deref()
3308            .is_some_and(|incumbent| constant_time_eq(incumbent.as_bytes(), presented.as_bytes()))
3309        {
3310            return SwapHelloAdmission::NotSwapping;
3311        }
3312        SwapHelloAdmission::Refused
3313    }
3314
3315    fn protocol_none(&self, module: &str) -> bool {
3316        self.get(module)
3317            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
3318    }
3319
3320    /// Exclude swap closure through the short, synchronous candidate publication.
3321    pub(crate) fn with_swap_candidate_admission<T>(
3322        &self,
3323        module_id: &str,
3324        publish: impl FnOnce() -> (T, bool),
3325    ) -> Option<T> {
3326        let mut swaps = self.swaps.lock().unwrap_or_else(|p| p.into_inner());
3327        let swap = swaps
3328            .get_mut(module_id)
3329            .filter(|swap| !swap.candidate_admitted)?;
3330        let (result, admitted) = publish();
3331        swap.candidate_admitted = admitted;
3332        Some(result)
3333    }
3334
3335    /// Test/support lookup for the current launch nonce of a supervised spawn.
3336    pub fn spawn_launch_nonce_for(&self, module_id: &str) -> Option<String> {
3337        self.spawn_nonce(module_id)
3338    }
3339
3340    /// Test/support lookup for the HELLO-gating nonce of a reserved module.
3341    pub fn reserved_launch_nonce_for(&self, module_id: &str) -> Option<String> {
3342        if self.module_is_gated(module_id) {
3343            return None;
3344        }
3345        self.reserved_nonces
3346            .lock()
3347            .unwrap_or_else(|poisoned| poisoned.into_inner())
3348            .get(module_id)
3349            .cloned()
3350            .flatten()
3351    }
3352
3353    pub fn insert(&self, module: SupervisedModule) -> Option<SupervisedModule> {
3354        // Normally already marked before the process was spawned; marking here
3355        // too keeps `configured_ids` a superset of the roster for any caller
3356        // that inserts a module directly.
3357        self.mark_configured(module.module_id());
3358        let mut modules = self
3359            .modules
3360            .lock()
3361            .unwrap_or_else(|poisoned| poisoned.into_inner());
3362        modules.insert(module.module_id().to_string(), module)
3363    }
3364
3365    /// Record that the supervisor has taken on `module_id`. Called before the
3366    /// module's first process is spawned, so that by the time that process can
3367    /// register, [`Self::is_configured`] already answers true.
3368    fn mark_configured(&self, module_id: &str) {
3369        self.update_configured_ids(|ids| {
3370            ids.insert(module_id.to_string());
3371        });
3372    }
3373
3374    fn publish_configured_ids(&self, ids: Option<&HashSet<String>>) {
3375        let owner = self
3376            .gate_runtime
3377            .lock()
3378            .unwrap_or_else(|p| p.into_inner())
3379            .clone()
3380            .and_then(|owner| owner.upgrade());
3381        if let Some(owner) = owner {
3382            owner.observe_supervisor_configured_ids(ids, Arc::downgrade(&self.configured_ids));
3383        }
3384    }
3385
3386    fn update_configured_ids(&self, update: impl FnOnce(&mut HashSet<String>)) {
3387        match self.configured_ids.lock() {
3388            Ok(mut ids) => {
3389                update(&mut ids);
3390                // Publish while this roster mutation is serialized, so an
3391                // older snapshot can never overwrite a later configured id.
3392                self.publish_configured_ids(Some(&ids));
3393            }
3394            Err(poisoned) => {
3395                update(&mut poisoned.into_inner());
3396                self.publish_configured_ids(None);
3397            }
3398        }
3399    }
3400
3401    /// Undo [`Self::mark_configured`] for a module whose first spawn failed
3402    /// before it was ever put on the roster. A module already on the roster
3403    /// keeps its mark: only [`Self::retire`] takes a rostered module off.
3404    fn unmark_configured_unless_rostered(&self, module_id: &str) {
3405        let modules = self
3406            .modules
3407            .lock()
3408            .unwrap_or_else(|poisoned| poisoned.into_inner());
3409        if !modules.contains_key(module_id) {
3410            self.update_configured_ids(|ids| {
3411                ids.remove(module_id);
3412            });
3413        }
3414    }
3415
3416    /// Whether `module_id` is a module this daemon supervises: on the roster,
3417    /// or about to be (its process is being spawned right now).
3418    ///
3419    /// This, not `get(..).is_some()`, is what "the owner is configured" means
3420    /// for scopes: a supervised module's process can register and sync before
3421    /// [`Self::get`] can return it, and in that window it is still a module
3422    /// that will sync, not one that never will.
3423    pub(crate) fn is_configured(&self, module_id: &str) -> bool {
3424        self.configured_ids
3425            .lock()
3426            .unwrap_or_else(|poisoned| poisoned.into_inner())
3427            .contains(module_id)
3428    }
3429
3430    pub fn get(&self, module_id: &str) -> Option<SupervisedModule> {
3431        let modules = self
3432            .modules
3433            .lock()
3434            .unwrap_or_else(|poisoned| poisoned.into_inner());
3435        modules.get(module_id).cloned()
3436    }
3437
3438    pub(crate) fn record_late_health_answer(
3439        &self,
3440        module_id: &str,
3441        latency_ms: u64,
3442    ) -> Result<bool, SuperviseError> {
3443        let Some(module) = self.get(module_id) else {
3444            return Ok(false);
3445        };
3446        self.host_health.record_late_module(module_id);
3447        update_snapshot(&module.inner.snapshot, Some(module_id), |state| {
3448            state.health.late_answer_count = state.health.late_answer_count.saturating_add(1);
3449            state.health.last_late_answer_latency_ms = Some(latency_ms);
3450            // A late answer is an answer: the module served the probe, just past
3451            // the deadline. Leaving the miss streak in place while logging
3452            // "proves the module is alive" is how a CPU-starved module that
3453            // answers every probe a few seconds late still marches to the
3454            // threshold and gets killed — the exact kill class `NoAnswer` is
3455            // excluded from `is_proof_of_death` to prevent. Slow-but-answering
3456            // is degradation, and degradation reports; it does not restart.
3457            state.health.consecutive_failures = 0;
3458        })?;
3459        Ok(true)
3460    }
3461
3462    pub(crate) fn spawn_host_health_monitor(&self) -> JoinHandle<()> {
3463        self.host_health.spawn_monitor()
3464    }
3465
3466    /// Arm the one-shot marker for the module process that this caller
3467    /// deliberately initiated severance against. Generic connection teardown
3468    /// must not call this:
3469    /// a surviving process would otherwise retain an exemption for a later
3470    /// genuine crash.
3471    pub fn record_deliberate_severance(&self, module_id: &str) -> Result<bool, SuperviseError> {
3472        let Some(module) = self.get(module_id) else {
3473            return Ok(false);
3474        };
3475        let snapshot = lock_snapshot(&module.inner.snapshot)?;
3476        let Some((pid, start_time)) = snapshot.pid.zip(snapshot.process_start_time) else {
3477            return Ok(false);
3478        };
3479        drop(snapshot);
3480        module.record_deliberate_severance(ProcessIdentity { pid, start_time })
3481    }
3482
3483    pub fn list(&self) -> Vec<SupervisedModule> {
3484        let modules = self
3485            .modules
3486            .lock()
3487            .unwrap_or_else(|poisoned| poisoned.into_inner());
3488        let mut modules = modules.values().cloned().collect::<Vec<_>>();
3489        modules.sort_by(|left, right| left.module_id().cmp(right.module_id()));
3490        modules
3491    }
3492
3493    pub(crate) fn retire(&self, module_id: &str) -> Option<SupervisedModule> {
3494        self.activity_images
3495            .lock()
3496            .unwrap_or_else(|p| p.into_inner())
3497            .remove(module_id);
3498        self.spawn_nonces
3499            .lock()
3500            .unwrap_or_else(|poisoned| poisoned.into_inner())
3501            .remove(module_id);
3502        self.close_swap(module_id);
3503        let mut reserved_nonces = self
3504            .reserved_nonces
3505            .lock()
3506            .unwrap_or_else(|poisoned| poisoned.into_inner());
3507        if reserved_nonces.contains_key(module_id) {
3508            // The old nonce must die with the removed process, but the exact-id
3509            // gate remains until an operator explicitly releases it.
3510            reserved_nonces.insert(module_id.to_string(), None);
3511        }
3512        drop(reserved_nonces);
3513        self.reserved_prefix_owners
3514            .lock()
3515            .unwrap_or_else(|poisoned| poisoned.into_inner())
3516            .retain(|_, owner| owner != module_id);
3517        let removed = self
3518            .modules
3519            .lock()
3520            .unwrap_or_else(|poisoned| poisoned.into_inner())
3521            .remove(module_id);
3522        self.update_configured_ids(|ids| {
3523            ids.remove(module_id);
3524        });
3525        self.remove_program_binding_records(module_id);
3526        removed
3527    }
3528
3529    /// Remember a module removed by a non-preview rescan so route.open can
3530    /// distinguish that intentional removal from an unknown id.
3531    pub(crate) fn record_rescan_removal(&self, module_id: &str) {
3532        self.removal_tombstones
3533            .lock()
3534            .unwrap_or_else(|poisoned| poisoned.into_inner())
3535            .insert(module_id.to_string(), unix_ms_now());
3536    }
3537
3538    /// Return how long ago a rescan removed this module in milliseconds.
3539    pub(crate) fn removal_tombstone_age_ms(&self, module_id: &str) -> Option<u64> {
3540        self.removal_tombstones
3541            .lock()
3542            .unwrap_or_else(|poisoned| poisoned.into_inner())
3543            .get(module_id)
3544            .copied()
3545            .map(|removed_at_ms| unix_ms_now().saturating_sub(removed_at_ms))
3546    }
3547
3548    /// Retire a reserved-id gate only after its module has left supervision.
3549    ///
3550    /// A retained gate has no live nonce (`None`), so releasing any other entry
3551    /// would weaken a currently configured or otherwise active reservation.
3552    pub(crate) fn release_retained_reserved_gate(&self, module_id: &str) -> bool {
3553        if self.get(module_id).is_some() {
3554            return false;
3555        }
3556        let mut reserved_nonces = self
3557            .reserved_nonces
3558            .lock()
3559            .unwrap_or_else(|poisoned| poisoned.into_inner());
3560        if !matches!(reserved_nonces.get(module_id), Some(None)) {
3561            return false;
3562        }
3563        reserved_nonces.remove(module_id);
3564        self.implicit_protocol_none
3565            .lock()
3566            .unwrap_or_else(|p| p.into_inner())
3567            .remove(module_id);
3568        true
3569    }
3570
3571    pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
3572        Arc::clone(&self.operation_lock)
3573    }
3574}
3575
3576/// Process supervisor for subc-owned singleton modules.
3577#[derive(Debug, Clone)]
3578pub struct Supervisor {
3579    registry: Arc<Registry>,
3580    config_delivery: Option<config_delivery::ConfigDelivery>,
3581    restart_policy: RestartPolicy,
3582    drain_timeout: Duration,
3583    connection_file_path: Option<PathBuf>,
3584    capture_logs_dir: Option<PathBuf>,
3585    forwarding: Option<Arc<ForwardingTable>>,
3586    process_liveness: Arc<SupervisorProcessLiveness>,
3587    supervisor_handle: Option<SupervisorHandle>,
3588    health: HealthConfig,
3589    host_health: HostHealth,
3590    daemon_start_clock: crate::clock::StartClock,
3591    terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
3592    spawn_events: SpawnEventFeed,
3593    provenance_probe: ExecutableIdentityProbe,
3594    /// Every process spawned through this supervisor (and its clones) and not
3595    /// yet reaped, so daemon shutdown can end them.
3596    child_roster: ChildRoster,
3597    #[cfg(target_os = "linux")]
3598    cgroup_placement: Option<subc_cgroup::Placement>,
3599    #[cfg(test)]
3600    test_after_first_spawn: AfterFirstSpawnHook,
3601}
3602
3603/// A roster entry whose monitor and first process have not started yet.
3604/// Keeping the command receiver here lets discovery serve status immediately
3605/// while start/stop requests wait until bootstrap has published the connection file.
3606pub(crate) struct RegisteredConfiguredModule {
3607    spec: ModuleSpec,
3608    runtime: SupervisorRuntimeConfig,
3609    module: SupervisedModule,
3610    commands: mpsc::Receiver<SupervisorCommand>,
3611}
3612
3613/// Test-only hook run on the path that takes on a new module, right after its
3614/// first `spawn_child` returns (the process exists and could already be
3615/// registering) and before that process is handed to the module's supervise
3616/// loop and put on the roster. Lets a test observe what a fast child would see
3617/// in that window without racing a real one.
3618#[cfg(test)]
3619#[derive(Clone, Default)]
3620struct AfterFirstSpawnHook(Option<AfterFirstSpawnFn>);
3621
3622#[cfg(test)]
3623type AfterFirstSpawnFn = Arc<dyn Fn(&str) + Send + Sync>;
3624
3625#[cfg(test)]
3626impl fmt::Debug for AfterFirstSpawnHook {
3627    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3628        f.write_str("AfterFirstSpawnHook")
3629    }
3630}
3631
3632#[cfg(test)]
3633impl AfterFirstSpawnHook {
3634    fn run(&self, module_id: &str) {
3635        if let Some(hook) = &self.0 {
3636            hook(module_id);
3637        }
3638    }
3639}
3640
3641impl Supervisor {
3642    #[cfg(all(test, target_os = "linux"))]
3643    pub(crate) fn set_admission_hook_for_test(
3644        &self,
3645        hook: impl Fn(&str, &'static str, Option<u32>) -> bool + Send + Sync + 'static,
3646    ) {
3647        self.child_roster.set_admission_hook_for_test(hook);
3648    }
3649
3650    #[cfg(test)]
3651    pub(crate) fn new_for_test(registry: Arc<Registry>, policy: RestartPolicy) -> Self {
3652        let supervisor = Self::new(registry, policy);
3653        #[cfg(target_os = "macos")]
3654        let supervisor = supervisor.with_privacy_trampoline(test_privacy_trampoline());
3655        supervisor
3656    }
3657    /// Verify the trampoline once when configured. Missing private OS support
3658    /// refuses every macOS launch by name but does not stop the daemon's control
3659    /// server. Embedders must explicitly provide a binary with the subc-os hidden
3660    /// entry point; the library must not exec an arbitrary hosting program.
3661    pub fn with_privacy_trampoline(self, path: impl Into<PathBuf>) -> Self {
3662        let path = path.into();
3663        #[cfg(target_os = "macos")]
3664        {
3665            let result = probe_privacy_trampoline(&path).map(|()| path);
3666            if let Err(cause) = &result {
3667                error!(%cause, "macOS privacy identity unavailable; supervised launches will refuse");
3668            }
3669            self.child_roster.set_privacy_trampoline(result);
3670        }
3671        #[cfg(not(target_os = "macos"))]
3672        let _ = path;
3673        self
3674    }
3675    /// The flag [`Self::begin_daemon_shutdown`] sets, for the control handler's
3676    /// capability-requirement log to read.
3677    pub(crate) fn daemon_shutdown_flag(&self) -> crate::child_roster::DaemonShutdownFlag {
3678        self.child_roster.shutdown_flag()
3679    }
3680
3681    /// The first step of an announced daemon shutdown, before the notice and
3682    /// before any connection is closed.
3683    ///
3684    /// Sets the daemon-shutdown flag first: from here on no module is
3685    /// respawned (crash restart, operator restart, or swap), and every child
3686    /// exit is recorded as `daemon_shutdown` rather than as a crash, whether
3687    /// the module exits on the EOF this shutdown gives it or is signalled by a
3688    /// service manager that kills the whole cgroup. Then writes the journal's
3689    /// shutdown marker, which records the instant and closes this daemon
3690    /// incarnation's stretch of the journal.
3691    #[cfg(unix)]
3692    pub(crate) fn begin_daemon_shutdown(&self) {
3693        self.child_roster.close();
3694        if let Some(journal) = &self.terminal_journal {
3695            journal.stamp_shutdown();
3696        }
3697    }
3698
3699    /// Announce a cut while established connections can still carry replies.
3700    /// These budgets bound the attempt to deliver notices and the wait for
3701    /// routes to drain; neither guarantees delivery or child completion, and
3702    /// they are local policy, not an estimate of launchd's unknown kill ceiling.
3703    #[cfg(unix)]
3704    pub(crate) async fn drain_for_daemon_shutdown(&self) -> Result<(), SuperviseError> {
3705        const NOTICE_BUDGET: Duration = Duration::from_millis(500);
3706        const DRAIN_BUDGET: Duration = Duration::from_secs(2);
3707        let Some(forwarding) = &self.forwarding else {
3708            return Ok(());
3709        };
3710        let notice_started = Instant::now();
3711        let modules = forwarding
3712            .begin_daemon_drain()
3713            .map_err(SuperviseError::Forwarding)?;
3714        let deadline_ms =
3715            unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
3716        let shutdown_reason = self
3717            .supervisor_handle
3718            .as_ref()
3719            .map(SupervisorHandle::take_daemon_shutdown_reason)
3720            .unwrap_or(RouteCloseReason::Disable);
3721        let mut modules_told = 0;
3722        let mut notices = tokio::task::JoinSet::new();
3723        let mut drains = Vec::new();
3724        for connection in forwarding
3725            .module_connections()
3726            .map_err(SuperviseError::Forwarding)?
3727        {
3728            let target = ModuleDrainTarget {
3729                endpoint: connection.endpoint,
3730                sink: connection.sink,
3731                negotiated_ver: connection.negotiated_ver,
3732                abandoned_bindings: Vec::new(),
3733                excluded_subscriptions: 0,
3734            };
3735            notices.spawn(async move {
3736                (
3737                    true,
3738                    send_module_draining(
3739                        &connection.module_id,
3740                        shutdown_reason,
3741                        deadline_ms,
3742                        &target,
3743                        true,
3744                    )
3745                    .await,
3746                )
3747            });
3748        }
3749        for (module_id, endpoint) in modules {
3750            let Some(target) = forwarding
3751                .begin_endpoint_drain(endpoint, RouteCloseReason::Restart)
3752                .map_err(SuperviseError::Forwarding)?
3753            else {
3754                continue;
3755            };
3756            let routes = forwarding
3757                .endpoint_routes(target.endpoint)
3758                .map_err(SuperviseError::Forwarding)?;
3759            // Only an announced restart promises that modules are coming back.
3760            // Client route notices retain their existing reconnect semantics.
3761            let mut recipients = Vec::new();
3762            let mut clients: Vec<(crate::forwarding::GoodbyeTarget, Vec<u16>)> = Vec::new();
3763            for route in routes {
3764                let client = route.goodbye_target;
3765                if let Some((_, channels)) = clients
3766                    .iter_mut()
3767                    .find(|(existing, _)| existing.connection_id == client.connection_id)
3768                {
3769                    channels.push(client.channel);
3770                } else {
3771                    let channel = client.channel;
3772                    clients.push((client, vec![channel]));
3773                }
3774            }
3775            for (client, mut channels) in clients {
3776                channels.sort_unstable();
3777                channels.dedup();
3778                let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
3779                    module_id: module_id.clone(),
3780                    channels,
3781                    reason: RouteCloseReason::Restart,
3782                })
3783                .expect("route closing serializes");
3784                recipients.push((client.sink, client.negotiated_ver, closing));
3785            }
3786            for (sink, version, body) in recipients {
3787                notices.spawn(async move {
3788                    let frame = Frame::build_with_version(
3789                        version,
3790                        FrameType::Push,
3791                        control_flags(),
3792                        0,
3793                        0,
3794                        0,
3795                        body,
3796                    )
3797                    .expect("bounded lifecycle notice frame builds");
3798                    (false, sink.send_flushed(frame).await.is_ok())
3799                });
3800            }
3801            let gauges = declared_busy_gauges(&self.registry, &module_id)?;
3802            drains.push((module_id, target.endpoint, gauges));
3803        }
3804        // A quiet forwarding table is not proof that queued notices reached the
3805        // socket. Wait for writer flush acknowledgements before testing quiescence.
3806        let notice_deadline = Instant::now() + NOTICE_BUDGET;
3807        while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
3808            match result {
3809                Ok((true, true)) => modules_told += 1,
3810                Ok((false, true)) => {}
3811                result => warn!(?result, "daemon shutdown notice delivery failed"),
3812            }
3813        }
3814        notices.abort_all();
3815        info!(
3816            ?shutdown_reason,
3817            modules_told, "daemon shutdown module notices delivered"
3818        );
3819        let notice_elapsed = notice_started.elapsed();
3820        let drain_started = Instant::now();
3821        let deadline = drain_started + DRAIN_BUDGET;
3822        let mut waits = tokio::task::JoinSet::new();
3823        for (module_id, endpoint, gauges) in drains {
3824            let forwarding = Arc::clone(forwarding);
3825            let mut runtime = self.runtime_config();
3826            runtime.health.cadence = Duration::from_millis(100);
3827            waits.spawn(async move {
3828                let wait_result = wait_for_forwarding_quiescence(
3829                    &forwarding,
3830                    &module_id,
3831                    &runtime,
3832                    endpoint,
3833                    deadline,
3834                    &gauges,
3835                    DrainScope::Endpoint(endpoint),
3836                    &mut DrainGaugeTrace::new(&gauges),
3837                )
3838                .await;
3839                // Store the measurement before the task returns: quiescence
3840                // may be reached just as the deadline stops the join loop from
3841                // collecting results. Unfinished or failed waits report false.
3842                forwarding
3843                    .record_daemon_drain_result(
3844                        endpoint,
3845                        drained_after_quiescence_wait(&wait_result),
3846                    )
3847                    .map_err(SuperviseError::Forwarding)?;
3848                wait_result
3849            });
3850        }
3851        while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
3852            if !matches!(result, Ok(Ok(true))) {
3853                warn!(?result, "daemon shutdown drain did not reach quiescence");
3854            }
3855        }
3856        // Measure only the forwarding drain, not child teardown or the caller's
3857        // signal delivery and process-reaping delays.
3858        info!(
3859            notice_elapsed_ms = notice_elapsed.as_millis() as u64,
3860            drain_elapsed_ms = drain_started.elapsed().as_millis() as u64,
3861            "daemon shutdown forwarding drain complete"
3862        );
3863        Ok(())
3864    }
3865
3866    /// The last step of a graceful daemon shutdown, after the notice and the
3867    /// drain: send every registered module a module GOODBYE, the same planned
3868    /// stop signal `ck module stop` gives, then close every connection so each
3869    /// subc module sees EOF and starts its own teardown, then end every
3870    /// supervised child that has not exited
3871    /// by its own deadline (its drain budget, capped). Modules lead their own
3872    /// process groups, so a
3873    /// service manager's group kill no longer reaches them; without this a
3874    /// child that does not stop on EOF (every `protocol: "none"` child, which
3875    /// has no connection) would outlive the daemon. Every wait is bounded (see
3876    /// `child_roster`), and `escalate` resolving (a second SIGTERM) cuts them.
3877    #[cfg(unix)]
3878    pub(crate) async fn end_children_for_daemon_shutdown(
3879        &self,
3880        already_escalated: bool,
3881        escalate: impl std::future::Future<Output = ()>,
3882    ) {
3883        tokio::pin!(escalate);
3884        let mut escalated = already_escalated;
3885        if let Some(forwarding) = &self.forwarding {
3886            let reason = CloseReason::new(
3887                "daemon_shutdown",
3888                "the daemon is exiting after its shutdown notice and drain",
3889            );
3890            if escalated {
3891                // The operator asked to stop waiting: queue the GOODBYEs but
3892                // do not wait for them to be written.
3893                send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, false).await;
3894            } else {
3895                tokio::select! {
3896                    biased;
3897                    _ = escalate.as_mut() => {
3898                        info!("second SIGTERM: abandoning module GOODBYE delivery");
3899                        escalated = true;
3900                    }
3901                    _ = send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, true) => {}
3902                }
3903            }
3904            let closed = forwarding.close_all_connections(&reason);
3905            debug!(closed, "closed established connections for daemon shutdown");
3906        }
3907        // If the second SIGTERM arrived during GOODBYE delivery, `escalate` has
3908        // already completed and must not be polled again; the child shutdown
3909        // wait is told it is escalated and gets a future that never fires.
3910        let escalated_here = escalated && !already_escalated;
3911        let remaining_escalate = async move {
3912            if escalated_here {
3913                std::future::pending::<()>().await;
3914            } else {
3915                escalate.await;
3916            }
3917        };
3918        crate::child_roster::end_children_for_daemon_shutdown(
3919            &self.child_roster,
3920            escalated,
3921            remaining_escalate,
3922        )
3923        .await;
3924    }
3925
3926    pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
3927        Self {
3928            registry,
3929            config_delivery: None,
3930            restart_policy,
3931            drain_timeout: DEFAULT_DRAIN_TIMEOUT,
3932            connection_file_path: None,
3933            capture_logs_dir: None,
3934            forwarding: None,
3935            process_liveness: Arc::new(SupervisorProcessLiveness::default()),
3936            supervisor_handle: None,
3937            health: HealthConfig::default(),
3938            host_health: HostHealth::default(),
3939            daemon_start_clock: crate::clock::StartClock::capture(),
3940            terminal_journal: None,
3941            spawn_events: SpawnEventFeed::default(),
3942            provenance_probe: ExecutableIdentityProbe::default(),
3943            child_roster: ChildRoster::default(),
3944            #[cfg(target_os = "linux")]
3945            cgroup_placement: None,
3946            #[cfg(test)]
3947            test_after_first_spawn: AfterFirstSpawnHook::default(),
3948        }
3949    }
3950
3951    pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
3952        self.drain_timeout = drain_timeout;
3953        self
3954    }
3955
3956    /// The drain budget a module gets when its config entry sets none.
3957    pub(crate) fn default_drain_timeout(&self) -> Duration {
3958        self.drain_timeout
3959    }
3960
3961    pub fn with_process_liveness(
3962        mut self,
3963        process_liveness: Arc<SupervisorProcessLiveness>,
3964    ) -> Self {
3965        self.process_liveness = process_liveness;
3966        self
3967    }
3968
3969    /// Connect configuration delivery to observed process lifecycle events.
3970    pub fn with_config_runtime(
3971        mut self,
3972        owner: Arc<crate::config_gate::runtime::RuntimeOwner>,
3973    ) -> Self {
3974        if let Some(handle) = &self.supervisor_handle {
3975            handle.install_binding_retirement(&owner);
3976        }
3977        self.config_delivery = Some(config_delivery::ConfigDelivery(owner));
3978        self
3979    }
3980
3981    pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
3982        self.connection_file_path = Some(connection_file_path.into());
3983        self
3984    }
3985
3986    /// Enables daemon-owned capture files for supervised stdout and stderr.
3987    pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
3988        self.capture_logs_dir = Some(logs_dir.into());
3989        self
3990    }
3991
3992    /// Names this daemon lifetime in spawn events, independently of whether a
3993    /// terminal journal is configured.
3994    pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
3995        // A millisecond start stamp can repeat after clock rollback or a rapid
3996        // restart. Use the connection file's random daemon_id instead: it already
3997        // identifies this daemon lifetime independently of the wall clock.
3998        self.spawn_events.configure_incarnation(daemon_incarnation);
3999        self
4000    }
4001
4002    /// Enables best-effort history shared by every supervised module. Without
4003    /// it, terminal history is kept only in each module's in-memory ring.
4004    pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
4005        let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
4006        this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
4007            path,
4008            daemon_incarnation,
4009        )));
4010        this
4011    }
4012
4013    pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
4014        self.child_roster.counters = forwarding.counters();
4015        self.forwarding = Some(forwarding);
4016        self
4017    }
4018
4019    pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
4020        if let Some(delivery) = &self.config_delivery {
4021            supervisor_handle.install_binding_retirement(&delivery.0);
4022        }
4023        self.host_health = supervisor_handle.host_health.clone();
4024        self.spawn_events = supervisor_handle.spawn_events.clone();
4025        self.supervisor_handle = Some(supervisor_handle);
4026        self
4027    }
4028
4029    pub fn with_health_config(mut self, health: HealthConfig) -> Self {
4030        self.health = health;
4031        self
4032    }
4033
4034    /// Keeps a record of every live child at `path`, rewritten on each spawn and
4035    /// reap, for the orphan sweep a later daemon runs at boot. Without it no
4036    /// record is kept.
4037    pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
4038        self.child_roster.record_to(path.into());
4039        self
4040    }
4041
4042    #[cfg(target_os = "linux")]
4043    pub fn with_cgroup_placement(
4044        mut self,
4045        cgroup_placement: Option<subc_cgroup::Placement>,
4046    ) -> Self {
4047        self.child_roster
4048            .set_cgroup_placement(cgroup_placement.clone());
4049        self.cgroup_placement = cgroup_placement;
4050        self
4051    }
4052
4053    /// Spawn `spec.program` and start monitoring it.
4054    ///
4055    /// The child is expected to parse `--subc <connection-file-path>`, read the
4056    /// TCP+key connection file, authenticate to the already-running listener, and
4057    /// register with channel-0 `HELLO` using `spec.module_id` as its manifest id.
4058    ///
4059    /// This synchronous embedder API blocks on launch admission and store I/O.
4060    /// Do not call it on an async runtime thread; use [`Self::spawn_async`].
4061    pub fn spawn(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
4062        validate_spec(&spec)?;
4063        self.establish_identity(&spec);
4064
4065        let runtime = self.runtime_config();
4066        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
4067        let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4068        let registration_watch = watch_registration(&self.registry, &spec);
4069        let spawned = spawn_child(
4070            &spec,
4071            runtime.connection_file_path.as_deref(),
4072            self.supervisor_handle.as_ref(),
4073            &runtime.stderr_ring,
4074            runtime.capture_logs_dir.as_deref(),
4075            &runtime.child_roster,
4076            runtime.spawn_delivery(),
4077            #[cfg(target_os = "linux")]
4078            runtime.cgroup_placement.as_ref(),
4079            runtime.register_timeout,
4080        );
4081        #[cfg(test)]
4082        self.test_after_first_spawn.run(&spec.module_id);
4083        let mut child = match spawned {
4084            Ok(child) => child,
4085            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4086                defer_config_spawn(
4087                    &spec,
4088                    &runtime,
4089                    &snapshot,
4090                    RespawnKind::Spawn,
4091                    &runtime.failure_context(runtime.recovery_is_daemon),
4092                )?;
4093                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4094            }
4095            Err(SuperviseError::ConfigHeld { .. }) => {
4096                hold_config_spawn(
4097                    &spec,
4098                    &runtime,
4099                    &snapshot,
4100                    &runtime.failure_context(runtime.recovery_is_daemon),
4101                )?;
4102                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4103            }
4104            Err(err) => {
4105                // Unlike the configured paths, a failed `spawn` leaves nothing
4106                // on the roster, so the module must not stay marked configured.
4107                self.abandon_unrostered(&spec.module_id);
4108                return Err(err);
4109            }
4110        };
4111        arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
4112        self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
4113        if let Some(spawn) = activity_spawn {
4114            spawn.complete(&snapshot);
4115        }
4116
4117        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
4118    }
4119
4120    /// Spawn without running configuration integrity or keychain checks on the
4121    /// runtime thread. Cancellation during preparation cannot create a child.
4122    pub async fn spawn_async(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
4123        validate_spec(&spec)?;
4124        self.establish_identity(&spec);
4125        let mut identity = AsyncInitialIdentity {
4126            supervisor: self,
4127            module: spec.module_id.clone(),
4128            committed: false,
4129        };
4130        let runtime = self.runtime_config();
4131        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
4132        let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4133        let registration_watch = watch_registration(&self.registry, &spec);
4134        let spawned = spawn_child_async(&spec, &runtime).await;
4135        #[cfg(test)]
4136        self.test_after_first_spawn.run(&spec.module_id);
4137        let mut child = match spawned {
4138            Ok(child) => child,
4139            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4140                defer_config_spawn(
4141                    &spec,
4142                    &runtime,
4143                    &snapshot,
4144                    RespawnKind::Spawn,
4145                    &runtime.failure_context(runtime.recovery_is_daemon),
4146                )?;
4147                identity.committed = true;
4148                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4149            }
4150            Err(SuperviseError::ConfigHeld { .. }) => {
4151                hold_config_spawn(
4152                    &spec,
4153                    &runtime,
4154                    &snapshot,
4155                    &runtime.failure_context(runtime.recovery_is_daemon),
4156                )?;
4157                identity.committed = true;
4158                return Ok(self.supervised_module(spec, runtime, snapshot, None));
4159            }
4160            Err(err) => {
4161                self.abandon_unrostered(&spec.module_id);
4162                return Err(err);
4163            }
4164        };
4165        arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
4166        self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
4167        if let Some(spawn) = activity_spawn {
4168            spawn.complete(&snapshot);
4169        }
4170        identity.committed = true;
4171        Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
4172    }
4173
4174    /// Make `spec`'s module count as configured, with its identity gates
4175    /// (reserved id, reserved prefixes) in place, BEFORE any process of it
4176    /// exists.
4177    ///
4178    /// Every path that takes on a new module calls this before `spawn_child`.
4179    /// The order is the point: the child can connect, register, sync its
4180    /// scopes and ask about them as soon as it is spawned, and the module is
4181    /// only put on the roster after `spawn_child` returns. Were the mark set
4182    /// with the roster entry, a fast child would see its own owner reported
4183    /// as not configured, and a scoped `route.open` in that window would be
4184    /// refused as terminal `scope_not_live` ("will never sync") instead of
4185    /// retryable `scope_not_synced`.
4186    fn establish_identity(&self, spec: &ModuleSpec) {
4187        if let Some(supervisor_handle) = &self.supervisor_handle {
4188            supervisor_handle.apply_identity_configuration(spec);
4189            supervisor_handle.mark_configured(&spec.module_id);
4190        }
4191    }
4192
4193    /// Take back [`Self::establish_identity`]'s configured mark when the
4194    /// module will not be put on the roster after all.
4195    fn abandon_unrostered(&self, module_id: &str) {
4196        if let Some(supervisor_handle) = &self.supervisor_handle {
4197            supervisor_handle.unmark_configured_unless_rostered(module_id);
4198        }
4199    }
4200
4201    /// Record a freshly spawned first process as running. On failure the
4202    /// module never reaches the roster, so its configured mark is taken back.
4203    fn mark_first_process_running(
4204        &self,
4205        spec: &ModuleSpec,
4206        runtime: &SupervisorRuntimeConfig,
4207        snapshot: &SharedSnapshot,
4208        child: &mut SupervisedChild,
4209    ) -> Result<(), SuperviseError> {
4210        if let Err(err) = set_running(snapshot, child, &spec.module_id, &runtime.spawn_events) {
4211            containment::terminate_blocking(&runtime.child_roster.containment);
4212            self.abandon_unrostered(&spec.module_id);
4213            return Err(err);
4214        }
4215        self.process_liveness
4216            .track(spec.module_id.clone(), Arc::clone(snapshot));
4217        Ok(())
4218    }
4219
4220    /// Start supervising a module declared in daemon configuration.
4221    ///
4222    /// Unlike [`Self::spawn`], this records disabled modules and immediate spawn
4223    /// failures in the supervisor handle so operator-facing `supervisor.list`
4224    /// reflects every configured module while daemon startup continues.
4225    pub fn supervise_configured(
4226        &self,
4227        spec: ModuleSpec,
4228        enabled: bool,
4229    ) -> Result<SupervisedModule, SuperviseError> {
4230        self.supervise_configured_requested(
4231            spec,
4232            enabled,
4233            self.health.clone(),
4234            None,
4235            self.restart_policy,
4236            DEFAULT_REGISTER_TIMEOUT,
4237            None,
4238        )
4239    }
4240
4241    /// Supervise a configured module with its own health, drain, and crash
4242    /// budget. The restart policy is per-module because the config file is:
4243    /// `modules.<id>.restart` resolves to a full policy at parse time, and a
4244    /// module that is expensive to restart should not be forced onto the same
4245    /// budget as one that is cheap.
4246    pub fn supervise_configured_with_health(
4247        &self,
4248        spec: ModuleSpec,
4249        enabled: bool,
4250        health: HealthConfig,
4251        drain_timeout_ms: Option<u64>,
4252        restart_policy: RestartPolicy,
4253    ) -> Result<SupervisedModule, SuperviseError> {
4254        self.supervise_configured_requested(
4255            spec,
4256            enabled,
4257            health,
4258            drain_timeout_ms,
4259            restart_policy,
4260            DEFAULT_REGISTER_TIMEOUT,
4261            None,
4262        )
4263    }
4264
4265    #[allow(clippy::too_many_arguments)]
4266    pub(crate) fn supervise_configured_requested(
4267        &self,
4268        spec: ModuleSpec,
4269        enabled: bool,
4270        health: HealthConfig,
4271        drain_timeout_ms: Option<u64>,
4272        restart_policy: RestartPolicy,
4273        register_timeout: Duration,
4274        requester: Option<Principal>,
4275    ) -> Result<SupervisedModule, SuperviseError> {
4276        let registered = self.register_configured_with_health(
4277            spec,
4278            enabled,
4279            health,
4280            drain_timeout_ms,
4281            restart_policy,
4282            register_timeout,
4283        )?;
4284        let daemon_initiated = requester.is_none();
4285        self.start_registered_configured(registered, requester, daemon_initiated)
4286    }
4287
4288    #[allow(clippy::too_many_arguments)]
4289    pub(crate) async fn supervise_configured_requested_async(
4290        &self,
4291        spec: ModuleSpec,
4292        enabled: bool,
4293        health: HealthConfig,
4294        drain_timeout_ms: Option<u64>,
4295        restart_policy: RestartPolicy,
4296        register_timeout: Duration,
4297        requester: Option<Principal>,
4298    ) -> Result<SupervisedModule, SuperviseError> {
4299        let registered = self.register_configured_with_health(
4300            spec,
4301            enabled,
4302            health,
4303            drain_timeout_ms,
4304            restart_policy,
4305            register_timeout,
4306        )?;
4307        let daemon_initiated = requester.is_none();
4308        self.start_registered_configured_async(registered, requester, daemon_initiated)
4309            .await
4310    }
4311
4312    /// Record a configured module as starting or disabled, without launching a
4313    /// process or running its monitor. Bootstrap registers the entire roster
4314    /// before publishing discovery, then activates it once children can read
4315    /// the connection file passed in their `--subc` argument.
4316    pub(crate) fn register_configured_with_health(
4317        &self,
4318        spec: ModuleSpec,
4319        enabled: bool,
4320        health: HealthConfig,
4321        drain_timeout_ms: Option<u64>,
4322        restart_policy: RestartPolicy,
4323        register_timeout: Duration,
4324    ) -> Result<RegisteredConfiguredModule, SuperviseError> {
4325        validate_spec(&spec)?;
4326        self.establish_identity(&spec);
4327
4328        let mut runtime = self.runtime_config();
4329        runtime.health = health;
4330        runtime.restart_policy = restart_policy;
4331        runtime.register_timeout = register_timeout;
4332        if let Some(ms) = drain_timeout_ms {
4333            runtime.drain_timeout = Duration::from_millis(ms);
4334            *runtime
4335                .effective_drain_timeout
4336                .lock()
4337                .unwrap_or_else(|poisoned| poisoned.into_inner()) = runtime.drain_timeout;
4338        }
4339        let snapshot = if enabled {
4340            SupervisorSnapshot::starting()
4341        } else {
4342            SupervisorSnapshot::disabled()
4343        };
4344        let snapshot = {
4345            let mut snapshot = snapshot;
4346            if enabled {
4347                if let Some((pid, reason)) = runtime.child_roster.previous_instance(&spec.module_id)
4348                {
4349                    snapshot.waiting_for_previous_pid = Some(pid);
4350                    snapshot.waiting_for_previous_detail = Some(reason.waiting_message(pid));
4351                }
4352            }
4353            snapshot
4354        };
4355        let (module, commands) =
4356            self.register_module(&spec, &runtime, Arc::new(Mutex::new(snapshot)));
4357        Ok(RegisteredConfiguredModule {
4358            spec,
4359            runtime,
4360            module,
4361            commands,
4362        })
4363    }
4364
4365    /// Activate a previously registered module. Queued control requests are
4366    /// served by the monitor after the initial configured spawn has settled.
4367    pub(crate) fn start_registered_configured(
4368        &self,
4369        registered: RegisteredConfiguredModule,
4370        requester: Option<Principal>,
4371        daemon_initiated: bool,
4372    ) -> Result<SupervisedModule, SuperviseError> {
4373        let RegisteredConfiguredModule {
4374            spec,
4375            mut runtime,
4376            module,
4377            commands,
4378        } = registered;
4379        runtime.start_requester = requester;
4380        runtime.recovery_is_daemon = daemon_initiated;
4381        let snapshot = &module.inner.snapshot;
4382        let should_spawn = {
4383            let state = lock_snapshot(snapshot)?;
4384            state.enabled && state.waiting_for_previous_pid.is_none()
4385        };
4386        let child = if should_spawn {
4387            let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4388            let registration_watch = watch_registration(&self.registry, &spec);
4389            let spawned = spawn_child(
4390                &spec,
4391                runtime.connection_file_path.as_deref(),
4392                self.supervisor_handle.as_ref(),
4393                &runtime.stderr_ring,
4394                runtime.capture_logs_dir.as_deref(),
4395                &runtime.child_roster,
4396                runtime.spawn_delivery(),
4397                #[cfg(target_os = "linux")]
4398                runtime.cgroup_placement.as_ref(),
4399                runtime.register_timeout,
4400            );
4401            #[cfg(test)]
4402            self.test_after_first_spawn.run(&spec.module_id);
4403            match spawned {
4404                Ok(mut child) => {
4405                    arm_registration_deadline(
4406                        &mut child,
4407                        runtime.register_timeout,
4408                        registration_watch,
4409                    );
4410                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
4411                    if let Some(spawn) = activity_spawn {
4412                        spawn.complete(snapshot);
4413                    }
4414                    Some(child)
4415                }
4416                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4417                    defer_config_spawn(
4418                        &spec,
4419                        &runtime,
4420                        snapshot,
4421                        RespawnKind::Spawn,
4422                        &runtime.failure_context(daemon_initiated),
4423                    )?;
4424                    None
4425                }
4426                Err(mut err) => {
4427                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
4428                        match hold_config_spawn(
4429                            &spec,
4430                            &runtime,
4431                            snapshot,
4432                            &runtime.failure_context(daemon_initiated),
4433                        ) {
4434                            Ok(()) => {
4435                                self.start_monitor(spec, runtime, &module, None, commands);
4436                                return Ok(module);
4437                            }
4438                            Err(parking_error) => err = parking_error,
4439                        }
4440                    }
4441                    if runtime.health.critical {
4442                        error!(
4443                            module_id = %spec.module_id,
4444                            program = %spec.program.display(),
4445                            error = %err,
4446                            "critical configured module failed to spawn; marking failed and alerting"
4447                        );
4448                    } else {
4449                        error!(
4450                            module_id = %spec.module_id,
4451                            program = %spec.program.display(),
4452                            error = %err,
4453                            "configured module failed to spawn; marking failed and continuing"
4454                        );
4455                    }
4456                    fail_snapshot(
4457                        snapshot,
4458                        Some(&spec.module_id),
4459                        None,
4460                        &runtime.failure_context(daemon_initiated),
4461                    );
4462                    None
4463                }
4464            }
4465        } else {
4466            None
4467        };
4468        self.start_monitor(spec, runtime, &module, child, commands);
4469        Ok(module)
4470    }
4471
4472    pub(crate) async fn start_registered_configured_async(
4473        &self,
4474        registered: RegisteredConfiguredModule,
4475        requester: Option<Principal>,
4476        daemon_initiated: bool,
4477    ) -> Result<SupervisedModule, SuperviseError> {
4478        self.start_registered_with_failure_policy(registered, requester, daemon_initiated, None)
4479            .await
4480    }
4481
4482    pub(crate) async fn start_registered_approved_async(
4483        &self,
4484        registered: RegisteredConfiguredModule,
4485        requester: Principal,
4486        generation: crate::config_gate::runtime::ApprovalIdentity,
4487    ) -> Result<SupervisedModule, SuperviseError> {
4488        self.start_registered_with_failure_policy(
4489            registered,
4490            Some(requester),
4491            false,
4492            Some(generation),
4493        )
4494        .await
4495    }
4496
4497    async fn start_registered_with_failure_policy(
4498        &self,
4499        registered: RegisteredConfiguredModule,
4500        requester: Option<Principal>,
4501        daemon_initiated: bool,
4502        approved_generation: Option<crate::config_gate::runtime::ApprovalIdentity>,
4503    ) -> Result<SupervisedModule, SuperviseError> {
4504        let RegisteredConfiguredModule {
4505            spec,
4506            mut runtime,
4507            module,
4508            commands,
4509        } = registered;
4510        runtime.start_requester = requester;
4511        runtime.recovery_is_daemon = daemon_initiated;
4512        let snapshot = &module.inner.snapshot;
4513        let mut startup_error = None;
4514        let failure = FailureContext {
4515            approval: approved_generation.clone(),
4516            ..runtime.failure_context(daemon_initiated)
4517        };
4518        let should_spawn = {
4519            let state = lock_snapshot(snapshot)?;
4520            state.enabled && state.waiting_for_previous_pid.is_none()
4521        };
4522        let child = if should_spawn {
4523            let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4524            let registration_watch = watch_registration(&self.registry, &spec);
4525            let spawned = spawn_child_async(&spec, &runtime).await;
4526            #[cfg(test)]
4527            self.test_after_first_spawn.run(&spec.module_id);
4528            match spawned {
4529                Ok(mut child) => {
4530                    arm_registration_deadline(
4531                        &mut child,
4532                        runtime.register_timeout,
4533                        registration_watch,
4534                    );
4535                    self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
4536                    if let Some(spawn) = activity_spawn {
4537                        spawn.complete(snapshot);
4538                    }
4539                    Some(child)
4540                }
4541                Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4542                    defer_config_spawn(&spec, &runtime, snapshot, RespawnKind::Spawn, &failure)?;
4543                    None
4544                }
4545                Err(mut err) => {
4546                    if matches!(err, SuperviseError::ConfigHeld { .. }) {
4547                        match hold_config_spawn(&spec, &runtime, snapshot, &failure) {
4548                            Ok(()) => {
4549                                self.start_monitor(spec, runtime, &module, None, commands);
4550                                return Ok(module);
4551                            }
4552                            Err(parking_error) => err = parking_error,
4553                        }
4554                    }
4555                    if runtime.health.critical {
4556                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
4557                            "critical configured module failed to spawn; marking failed and alerting");
4558                    } else {
4559                        error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
4560                            "configured module failed to spawn; marking failed and continuing");
4561                    }
4562                    fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
4563                    if let Some(generation) = approved_generation {
4564                        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
4565                            state.approved_start_failure = Some((generation, err.to_string()));
4566                        });
4567                        startup_error = Some(err);
4568                    }
4569                    None
4570                }
4571            }
4572        } else {
4573            None
4574        };
4575        self.start_monitor(spec, runtime, &module, child, commands);
4576        // Applying an operator-approved configuration must report a spawn error
4577        // without removing the failed module or its monitor. Bootstrap instead
4578        // tolerates failed starts so other configured modules can still run.
4579        startup_error.map_or(Ok(module), Err)
4580    }
4581
4582    fn runtime_config(&self) -> SupervisorRuntimeConfig {
4583        let effective_drain_timeout = Arc::new(Mutex::new(self.drain_timeout));
4584        SupervisorRuntimeConfig {
4585            registry: self.registry.clone(),
4586            config_delivery: self.config_delivery.clone(),
4587            recovery_is_daemon: true,
4588            start_requester: None,
4589            pending_activity_restart: false,
4590            provenance_probe: self.provenance_probe.clone(),
4591            scheduled_respawn: Arc::default(),
4592            deferred_reload_reply: Arc::default(),
4593            restart_policy: self.restart_policy,
4594            register_timeout: DEFAULT_REGISTER_TIMEOUT,
4595            drain_timeout: self.drain_timeout,
4596            // Shared with this module's roster copy: daemon shutdown waits on
4597            // each child for the module's own drain budget, as resolved now.
4598            child_roster: self
4599                .child_roster
4600                .for_module(Arc::clone(&effective_drain_timeout)),
4601            effective_drain_timeout,
4602            default_drain_timeout: self.drain_timeout,
4603            health: self.health.clone(),
4604            host_health: self.host_health.clone(),
4605            connection_file_path: self.connection_file_path.clone(),
4606            capture_logs_dir: self.capture_logs_dir.clone(),
4607            forwarding: self.forwarding.clone(),
4608            supervisor_handle: self.supervisor_handle.clone(),
4609            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
4610            terminal_ring: Arc::new(Mutex::new(
4611                TerminalRing::new(
4612                    TerminalRingConfig::default(),
4613                    self.daemon_start_clock.started_at_ms(),
4614                )
4615                .with_start_clock(self.daemon_start_clock)
4616                .with_journal(self.terminal_journal.clone())
4617                .with_daemon_shutdown(self.child_roster.shutdown_flag()),
4618            )),
4619            spawn_events: self.spawn_events.clone(),
4620            #[cfg(target_os = "linux")]
4621            cgroup_placement: self.cgroup_placement.clone(),
4622            #[cfg(test)]
4623            test_seed_stale_facts_before_enable_spawn: false,
4624            #[cfg(test)]
4625            test_reload_exit_record_gate: None,
4626        }
4627    }
4628
4629    fn supervised_module(
4630        &self,
4631        spec: ModuleSpec,
4632        runtime: SupervisorRuntimeConfig,
4633        snapshot: SharedSnapshot,
4634        child: Option<SupervisedChild>,
4635    ) -> SupervisedModule {
4636        let (module, commands) = self.register_module(&spec, &runtime, snapshot);
4637        self.start_monitor(spec, runtime, &module, child, commands);
4638        module
4639    }
4640
4641    fn register_module(
4642        &self,
4643        spec: &ModuleSpec,
4644        runtime: &SupervisorRuntimeConfig,
4645        snapshot: SharedSnapshot,
4646    ) -> (SupervisedModule, mpsc::Receiver<SupervisorCommand>) {
4647        runtime.host_health.track(spec, &snapshot);
4648        let configuration = Arc::new(Mutex::new(SupervisedConfiguration {
4649            spec: spec.clone(),
4650            enabled: snapshot.lock().unwrap_or_else(|p| p.into_inner()).enabled,
4651            health: runtime.health.clone(),
4652            register_timeout: runtime.register_timeout,
4653            restart_policy: runtime.restart_policy,
4654        }));
4655        let stderr_ring = Arc::clone(&runtime.stderr_ring);
4656        let terminal_ring = Arc::clone(&runtime.terminal_ring);
4657        let effective_drain_timeout = Arc::clone(&runtime.effective_drain_timeout);
4658        let (tx, rx) = mpsc::channel(4);
4659        let module_id = spec.module_id.clone();
4660        let module = SupervisedModule {
4661            inner: Arc::new(SupervisedModuleInner {
4662                module_id: module_id.clone(),
4663                registry: Arc::clone(&self.registry),
4664                snapshot,
4665                configuration,
4666                stderr_ring,
4667                terminal_ring,
4668                commands: tx,
4669                monitor: Mutex::new(None),
4670                effective_drain_timeout,
4671                provenance_probe: self.provenance_probe.clone(),
4672                retained: runtime.child_roster.retained_view(),
4673            }),
4674        };
4675        // Identity gates and the configured mark must precede the roster entry,
4676        // so a client never sees a module without its admission policy.
4677        if let Some(supervisor_handle) = &self.supervisor_handle {
4678            supervisor_handle.insert(module.clone());
4679        }
4680        (module, rx)
4681    }
4682
4683    fn start_monitor(
4684        &self,
4685        spec: ModuleSpec,
4686        runtime: SupervisorRuntimeConfig,
4687        module: &SupervisedModule,
4688        child: Option<SupervisedChild>,
4689        commands: mpsc::Receiver<SupervisorCommand>,
4690    ) {
4691        let monitor = tokio::spawn(supervise_loop(
4692            spec,
4693            runtime,
4694            Arc::clone(&self.registry),
4695            Arc::clone(&self.process_liveness),
4696            Arc::clone(&module.inner.snapshot),
4697            child,
4698            commands,
4699        ));
4700        *module
4701            .inner
4702            .monitor
4703            .lock()
4704            .unwrap_or_else(|p| p.into_inner()) = Some(monitor);
4705    }
4706}
4707
4708impl Default for Supervisor {
4709    fn default() -> Self {
4710        Self::new(Arc::new(Registry::default()), RestartPolicy::default())
4711    }
4712}
4713
4714/// Handle to one supervised child process.
4715#[derive(Clone)]
4716pub struct SupervisedModule {
4717    inner: Arc<SupervisedModuleInner>,
4718}
4719
4720struct SupervisedModuleInner {
4721    retained: crate::child_roster::RetainedView,
4722    module_id: String,
4723    registry: Arc<Registry>,
4724    snapshot: SharedSnapshot,
4725    configuration: Arc<Mutex<SupervisedConfiguration>>,
4726    stderr_ring: Arc<Mutex<StderrRing>>,
4727    terminal_ring: Arc<Mutex<TerminalRing>>,
4728    commands: mpsc::Sender<SupervisorCommand>,
4729    monitor: Mutex<Option<JoinHandle<()>>>,
4730    effective_drain_timeout: Arc<Mutex<Duration>>,
4731    provenance_probe: ExecutableIdentityProbe,
4732}
4733
4734impl fmt::Debug for SupervisedModule {
4735    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4736        f.debug_struct("SupervisedModule")
4737            .field("module_id", &self.inner.module_id)
4738            .field("status", &self.status())
4739            .finish_non_exhaustive()
4740    }
4741}
4742
4743impl SupervisedModule {
4744    pub(crate) fn check_approved_start_failure(
4745        &self,
4746        generation: &crate::config_gate::runtime::ApprovalIdentity,
4747    ) -> Result<bool, SuperviseError> {
4748        let state = lock_snapshot(&self.inner.snapshot)?;
4749        if let Some((failed_generation, detail)) = &state.approved_start_failure {
4750            if failed_generation == generation {
4751                return Err(SuperviseError::ReloadFailed {
4752                    module_id: self.inner.module_id.clone(),
4753                    reason: detail.clone(),
4754                });
4755            }
4756        }
4757        Ok(state.approved_start_failure.is_some())
4758    }
4759
4760    pub(crate) fn has_approved_start_failure(
4761        &self,
4762        identity: &crate::config_gate::runtime::ApprovalIdentity,
4763    ) -> bool {
4764        lock_snapshot(&self.inner.snapshot).is_ok_and(|state| {
4765            state
4766                .approved_start_failure
4767                .as_ref()
4768                .is_some_and(|(failed, _)| failed == identity)
4769        })
4770    }
4771
4772    pub(crate) fn needs_approved_gate_restart(
4773        &self,
4774        approval: &crate::config_gate::runtime::ApprovalIdentity,
4775    ) -> bool {
4776        lock_snapshot(&self.inner.snapshot)
4777            .is_ok_and(|state| state.needs_approved_gate_restart(approval))
4778    }
4779
4780    #[cfg(all(test, unix))]
4781    pub(crate) fn config_hold_origin_for_test(
4782        &self,
4783    ) -> (bool, Option<crate::config_gate::runtime::ApprovalIdentity>) {
4784        let state = lock_snapshot(&self.inner.snapshot).unwrap();
4785        (
4786            state.config_hold_daemon_initiated,
4787            state.config_hold_approval.clone(),
4788        )
4789    }
4790
4791    pub(crate) async fn config_policy_probe(
4792        &self,
4793        connection: crate::ConnectionId,
4794        generation: u64,
4795        attempt: u64,
4796    ) -> Result<(), SuperviseError> {
4797        self.inner
4798            .commands
4799            .send(SupervisorCommand::ConfigPolicyProbe {
4800                connection,
4801                generation,
4802                attempt,
4803            })
4804            .await
4805            .map_err(|_| SuperviseError::CommandClosed {
4806                module_id: self.inner.module_id.clone(),
4807            })
4808    }
4809    pub(crate) async fn config_exit_hold(&self) -> Result<(), SuperviseError> {
4810        let (reply, result) = oneshot::channel();
4811        self.inner
4812            .commands
4813            .send(SupervisorCommand::ConfigExitHold { reply })
4814            .await
4815            .map_err(|_| SuperviseError::CommandClosed {
4816                module_id: self.module_id().to_string(),
4817            })?;
4818        result.await.map_err(|_| SuperviseError::CommandClosed {
4819            module_id: self.module_id().to_string(),
4820        })?
4821    }
4822    pub(crate) async fn config_delivery_failed(
4823        &self,
4824        connection: crate::ConnectionId,
4825        hold: bool,
4826    ) -> Result<(), SuperviseError> {
4827        self.inner
4828            .commands
4829            .send(SupervisorCommand::ConfigDeliveryFailed { connection, hold })
4830            .await
4831            .map_err(|_| SuperviseError::CommandClosed {
4832                module_id: self.module_id().to_string(),
4833            })
4834    }
4835
4836    pub(crate) async fn config_apply_restart(&self, generation: u64) -> Result<(), SuperviseError> {
4837        self.inner
4838            .commands
4839            .send(SupervisorCommand::ConfigApplyRestart {
4840                generation,
4841                supersedes_swap: false,
4842            })
4843            .await
4844            .map_err(|_| SuperviseError::CommandClosed {
4845                module_id: self.inner.module_id.clone(),
4846            })
4847    }
4848    pub fn module_id(&self) -> &str {
4849        &self.inner.module_id
4850    }
4851
4852    /// Test-only: put one probe miss on the streak, the way
4853    /// `handle_health_probe_failure` does, so tests can assert what a later
4854    /// event does to the streak without driving the whole probe loop.
4855    #[cfg(test)]
4856    pub(crate) fn record_health_probe_failure_for_test(
4857        &self,
4858        detail: &str,
4859    ) -> Result<(), SuperviseError> {
4860        update_snapshot(&self.inner.snapshot, Some(&self.inner.module_id), |state| {
4861            state.health.consecutive_failures = state.health.consecutive_failures.saturating_add(1);
4862            state.health.detail = Some(detail.to_string());
4863        })
4864    }
4865
4866    pub fn state(&self) -> Result<ModuleState, SuperviseError> {
4867        Ok(lock_snapshot(&self.inner.snapshot)?.state)
4868    }
4869
4870    pub(crate) fn registration_end_reason(
4871        &self,
4872    ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
4873        let snapshot = lock_snapshot(&self.inner.snapshot)?;
4874        Ok(match snapshot.state {
4875            ModuleState::Draining if snapshot.draining_to_replace => {
4876                Some(RegistrationEndReason::SupervisorRestart)
4877            }
4878            ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
4879            ModuleState::Restarting if snapshot.draining_to_replace => {
4880                Some(RegistrationEndReason::SupervisorRestart)
4881            }
4882            _ => None,
4883        })
4884    }
4885
4886    /// The module's retained stderr, newest lines last.
4887    ///
4888    /// Deliberately NOT on [`Self::status`]: a bounded tail is kilobytes per
4889    /// module, `supervisor.list` renders every module, and putting it in the
4890    /// shared snapshot would make each status read carry a payload almost nobody
4891    /// asked for. Callers that want the text ask for it.
4892    pub fn stderr_tail(
4893        &self,
4894        max_lines: Option<usize>,
4895        max_bytes: Option<usize>,
4896    ) -> StderrTailSnapshot {
4897        self.inner
4898            .stderr_ring
4899            .lock()
4900            .unwrap_or_else(|poisoned| poisoned.into_inner())
4901            .snapshot(max_lines, max_bytes)
4902    }
4903
4904    /// The module's bounded terminal history, oldest retained exit first.
4905    ///
4906    /// The daemon-start stamp distinguishes a quiet supervisor from a replacement
4907    /// daemon whose in-memory history was necessarily reset.
4908    pub fn terminal_history(&self) -> TerminalHistorySnapshot {
4909        self.inner
4910            .terminal_ring
4911            .lock()
4912            .unwrap_or_else(|poisoned| poisoned.into_inner())
4913            .snapshot()
4914    }
4915
4916    /// Retained observations from the current ring and all journal generations.
4917    ///
4918    /// Blocking: this reads the journal files. Async callers use
4919    /// `Self::read_durable_terminal_history`.
4920    pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
4921        durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
4922    }
4923
4924    /// [`Self::durable_terminal_history`] on a blocking thread, so the journal
4925    /// read (up to every retained generation) never occupies a runtime worker.
4926    /// Fails only if the blocking task could not finish (runtime shutdown or a
4927    /// panic in the read).
4928    pub(crate) async fn read_durable_terminal_history(
4929        &self,
4930    ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
4931        let terminal_ring = Arc::clone(&self.inner.terminal_ring);
4932        let module_id = self.inner.module_id.clone();
4933        tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
4934            .await
4935    }
4936
4937    pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
4938        self.status_with_snapshot_lock(&self.inner.snapshot, None)
4939            .map(|(status, _)| status)
4940    }
4941
4942    pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
4943        let state = lock_snapshot(&self.inner.snapshot)?;
4944        Ok(state
4945            .failed_retry
4946            .pending
4947            .filter(|_| state.state == ModuleState::Failed && state.enabled)
4948            .map(|retry| {
4949                unix_ms_now().saturating_add(
4950                    u64::try_from(
4951                        retry
4952                            .deadline
4953                            .saturating_duration_since(Instant::now())
4954                            .as_millis(),
4955                    )
4956                    .unwrap_or(u64::MAX),
4957                )
4958            }))
4959    }
4960
4961    #[cfg(all(test, unix))]
4962    pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
4963        lock_snapshot(&self.inner.snapshot)
4964            .unwrap()
4965            .failed_retry
4966            .pending
4967            .map(|retry| retry.deadline)
4968    }
4969
4970    pub(crate) fn record_deliberate_severance(
4971        &self,
4972        identity: ProcessIdentity,
4973    ) -> Result<bool, SuperviseError> {
4974        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
4975        if snapshot.pid != Some(identity.pid)
4976            || snapshot.process_start_time != Some(identity.start_time)
4977        {
4978            return Ok(false);
4979        }
4980        snapshot.deliberate_severance = Some(identity);
4981        Ok(true)
4982    }
4983
4984    /// Read status for a channel-0 renderer and report a contended snapshot lock.
4985    ///
4986    /// Internal supervision callers use [`Self::status`] so writer-side machinery
4987    /// does not produce reader-observability logs.
4988    pub(crate) fn status_for_control(
4989        &self,
4990        caller: &'static str,
4991    ) -> Result<ModuleStatus, SuperviseError> {
4992        self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
4993            .map(|(status, _)| status)
4994    }
4995
4996    fn status_with_snapshot_lock(
4997        &self,
4998        snapshot: &SharedSnapshot,
4999        caller: Option<&'static str>,
5000    ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
5001        let restart_policy = self
5002            .inner
5003            .configuration
5004            .lock()
5005            .map_err(|_| SuperviseError::StatePoisoned {
5006                module_id: Some(self.inner.module_id.clone()),
5007            })?
5008            .restart_policy;
5009        let mut guard = match caller {
5010            Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
5011            None => lock_snapshot(snapshot)?,
5012        };
5013        // Read the budget through the pruning path so a reader sees the same
5014        // in-window count the restart decision would use, not a stale total.
5015        let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
5016        let snapshot = guard.clone();
5017        drop(guard);
5018        let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
5019            SuperviseError::StatePoisoned {
5020                module_id: Some(self.inner.module_id.clone()),
5021            }
5022        })?;
5023        let registration_active = self
5024            .inner
5025            .registry
5026            .get_module(&self.inner.module_id)
5027            .map_err(SuperviseError::Registry)?
5028            .is_some();
5029        let protocol = snapshot
5030            .spawned_protocol
5031            .unwrap_or(self.declared_protocol()?);
5032        let running_process =
5033            snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
5034        // Registration is the difference between the two protocols and the only
5035        // one: a subc module that has not registered cannot serve a request even
5036        // though its process is up, and a `none` module never registers at all,
5037        // so requiring it there would pin `live` to false for the whole life of
5038        // a perfectly healthy process.
5039        let live = match protocol {
5040            ModuleProtocol::Subc => running_process && registration_active,
5041            ModuleProtocol::None => running_process,
5042        };
5043        // Read only the retained cache: a status read must not resend signals,
5044        // rewrite the record, or keep the containment resource alive.
5045        let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
5046        let carry_configured = self
5047            .inner
5048            .configuration
5049            .lock()
5050            .map_err(|_| SuperviseError::StatePoisoned {
5051                module_id: Some(self.inner.module_id.clone()),
5052            })?
5053            .spec
5054            .carry_containment;
5055        let recovery_block = carries_containment(
5056            carry_configured,
5057            self.inner
5058                .retained
5059                .has_carried_container(&self.inner.module_id),
5060        )
5061        .then(|| self.inner.retained.recovery_block())
5062        .flatten();
5063        let launch_nonce_source = observed_launch_nonce_source(&snapshot);
5064        let pid = snapshot.reported_pid();
5065        let mut health = snapshot.health;
5066        if let Some(detail) = recovery_block
5067            .as_ref()
5068            .or_else(|| retained.as_ref().map(|(_, detail)| detail))
5069        {
5070            health.detail = Some(match health.detail {
5071                Some(previous) => format!("{previous}; {detail}"),
5072                None => detail.clone(),
5073            });
5074        }
5075
5076        Ok((
5077            ModuleStatus {
5078                admission_refused: snapshot.admission_refused,
5079                legacy_registration_spawn: snapshot.legacy_registration_spawn,
5080                registration_declaration: snapshot.registration_declaration.clone(),
5081                stop_reason: snapshot.stop_reason,
5082                waiting_for_previous_pid: retained
5083                    .as_ref()
5084                    .map(|(pid, _)| *pid)
5085                    .filter(|pid| *pid > 0)
5086                    .or(snapshot.waiting_for_previous_pid),
5087                waiting_for_previous_detail: recovery_block
5088                    .or_else(|| retained.map(|(_, detail)| detail))
5089                    .or(snapshot.waiting_for_previous_detail),
5090                module_id: self.inner.module_id.clone(),
5091                launch_nonce_source,
5092                state: snapshot.state,
5093                enabled: snapshot.enabled,
5094                process_alive: snapshot.process_alive,
5095                registration_active,
5096                protocol,
5097                live,
5098                restart_count,
5099                lifetime_restarts: snapshot.lifetime_restarts,
5100                spawn_generation: snapshot.spawn_generation,
5101                swap_outcome: snapshot.swap_outcome,
5102                max_restarts: restart_policy.max_restarts,
5103                restart_window: restart_policy.window,
5104                drain_timeout,
5105                restart_backoff: restart_policy.backoff,
5106                restart_max_backoff: restart_policy.max_backoff,
5107                pid,
5108                spawned_at_ms: snapshot.spawned_at_ms,
5109                spawned_from: snapshot.spawned_from,
5110                launch_spec_digest: snapshot.launch_spec_digest,
5111                process_start_time: snapshot.process_start_time,
5112                last_exit: snapshot.last_exit,
5113                health,
5114            },
5115            snapshot.spawned_file_identity.clone(),
5116        ))
5117    }
5118
5119    #[cfg(test)]
5120    pub(crate) fn hold_snapshot_for_test(
5121        &self,
5122        acquired: std::sync::mpsc::Sender<()>,
5123        hold: Duration,
5124    ) -> std::thread::JoinHandle<()> {
5125        let snapshot = Arc::clone(&self.inner.snapshot);
5126        std::thread::spawn(move || {
5127            let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
5128            acquired
5129                .send(())
5130                .expect("test receiver waits for snapshot lock");
5131            std::thread::sleep(hold);
5132        })
5133    }
5134
5135    /// The status and the running-image check for `supervisor.provenance`,
5136    /// taken from one status read. The exec acknowledgement can land between
5137    /// two separate reads, and the reply would then pair "no pid yet" with an
5138    /// image observed after the module started, which describes no single
5139    /// moment.
5140    pub(crate) async fn status_and_running_image_agreement(
5141        &self,
5142    ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
5143        let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
5144        let image = self
5145            .inner
5146            .provenance_probe
5147            .observe(
5148                status.pid,
5149                status.spawned_from.as_deref(),
5150                identity,
5151                status.process_start_time,
5152            )
5153            .await;
5154        Ok((status, image))
5155    }
5156
5157    pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
5158        let snapshot = match lock_snapshot(&self.inner.snapshot) {
5159            Ok(snapshot) => snapshot.clone(),
5160            Err(_) => {
5161                return subc_control::RunningImageAgreement::Unavailable {
5162                    reason: subc_control::RunningImageUnavailableReason::NotRunning,
5163                };
5164            }
5165        };
5166        self.inner
5167            .provenance_probe
5168            .observe(
5169                snapshot.reported_pid(),
5170                snapshot.spawned_from.as_deref(),
5171                snapshot.spawned_file_identity.clone(),
5172                snapshot.process_start_time,
5173            )
5174            .await
5175    }
5176
5177    /// Memory and CPU time of the module's current process, read now. Only the
5178    /// process the supervisor spawned is read, not processes it has started.
5179    pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
5180        #[cfg(windows)]
5181        {
5182            let image = lock_snapshot(&self.inner.snapshot)
5183                .ok()
5184                .and_then(|snapshot| {
5185                    snapshot
5186                        .spawned_file_identity
5187                        .as_ref()
5188                        .and_then(|identity| identity.windows_image.clone())
5189                });
5190            match image {
5191                Some(image) => {
5192                    crate::child_resources::read_windows_handle(image.process(), image.start_time())
5193                }
5194                None => subc_control::ChildResourceUsage::Unavailable {
5195                    reason: subc_control::ChildResourceUnavailableReason::NotRunning,
5196                },
5197            }
5198        }
5199        #[cfg(not(windows))]
5200        {
5201            let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
5202                Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
5203                Err(_) => {
5204                    return subc_control::ChildResourceUsage::Unavailable {
5205                        reason: subc_control::ChildResourceUnavailableReason::Unreadable,
5206                    }
5207                }
5208            };
5209            crate::child_resources::read(pid, start_time)
5210        }
5211    }
5212
5213    #[cfg(all(test, any(target_os = "linux", windows)))]
5214    pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
5215        self.inner
5216            .snapshot
5217            .try_lock()
5218            .map(|snapshot| snapshot.subtree_target.clone())
5219            .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
5220    }
5221
5222    #[cfg(test)]
5223    pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
5224        self.inner.snapshot.lock().unwrap().subtree_target = target;
5225    }
5226
5227    pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
5228        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
5229        Ok(match snapshot.state {
5230            ModuleState::Restarting => true,
5231            ModuleState::Failed | ModuleState::Disabled => false,
5232            _ if snapshot.enabled && snapshot.respawn_pending => true,
5233            _ => daemon_will_restart(
5234                &mut snapshot,
5235                &self
5236                    .inner
5237                    .configuration
5238                    .lock()
5239                    .map_err(|_| SuperviseError::StatePoisoned {
5240                        module_id: Some(self.inner.module_id.clone()),
5241                    })?
5242                    .restart_policy,
5243                Instant::now(),
5244            ),
5245        })
5246    }
5247
5248    #[cfg(test)]
5249    pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
5250        self.is_warming_with_snapshot_lock(None)
5251    }
5252
5253    pub(crate) fn is_warming_for_control(
5254        &self,
5255        caller: &'static str,
5256    ) -> Result<bool, SuperviseError> {
5257        self.is_warming_with_snapshot_lock(Some(caller))
5258    }
5259
5260    fn is_warming_with_snapshot_lock(
5261        &self,
5262        caller: Option<&'static str>,
5263    ) -> Result<bool, SuperviseError> {
5264        let snapshot = match caller {
5265            Some(caller) => {
5266                lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
5267            }
5268            None => lock_snapshot(&self.inner.snapshot)?,
5269        }
5270        .clone();
5271        Ok(matches!(
5272            snapshot.state,
5273            ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
5274        ))
5275    }
5276
5277    /// Drain the module and stop monitoring it.
5278    pub async fn drain(&self) -> Result<(), SuperviseError> {
5279        self.stop().await
5280    }
5281
5282    pub(crate) async fn retire_requested(
5283        &self,
5284        requester: Option<Principal>,
5285    ) -> Result<(), SuperviseError> {
5286        match self.state()? {
5287            ModuleState::Stopped => return Ok(()),
5288            ModuleState::Failed
5289                if lock_snapshot(&self.inner.snapshot)?
5290                    .failed_retry
5291                    .pending
5292                    .is_none() =>
5293            {
5294                return Ok(())
5295            }
5296            ModuleState::Failed
5297            | ModuleState::Starting
5298            | ModuleState::Running
5299            | ModuleState::Unresponsive
5300            | ModuleState::Restarting
5301            | ModuleState::Draining
5302            | ModuleState::Disabled => {}
5303        }
5304
5305        let (reply_tx, reply_rx) = oneshot::channel();
5306        self.inner
5307            .commands
5308            .send(SupervisorCommand::Retire {
5309                requester,
5310                reply: reply_tx,
5311            })
5312            .await
5313            .map_err(|_| SuperviseError::CommandClosed {
5314                module_id: self.inner.module_id.clone(),
5315            })?;
5316        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5317            module_id: self.inner.module_id.clone(),
5318        })?
5319    }
5320
5321    pub async fn stop(&self) -> Result<(), SuperviseError> {
5322        self.stop_requested(None).await
5323    }
5324
5325    pub(crate) async fn stop_requested(
5326        &self,
5327        requester: Option<Principal>,
5328    ) -> Result<(), SuperviseError> {
5329        match self.state()? {
5330            ModuleState::Stopped => return Ok(()),
5331            ModuleState::Failed
5332                if lock_snapshot(&self.inner.snapshot)?
5333                    .failed_retry
5334                    .pending
5335                    .is_none() =>
5336            {
5337                return Ok(())
5338            }
5339            ModuleState::Failed
5340            | ModuleState::Starting
5341            | ModuleState::Running
5342            | ModuleState::Unresponsive
5343            | ModuleState::Restarting
5344            | ModuleState::Draining
5345            | ModuleState::Disabled => {}
5346        }
5347
5348        let (reply_tx, reply_rx) = oneshot::channel();
5349        self.inner
5350            .commands
5351            .send(SupervisorCommand::Drain {
5352                requester,
5353                reply: reply_tx,
5354            })
5355            .await
5356            .map_err(|_| SuperviseError::CommandClosed {
5357                module_id: self.inner.module_id.clone(),
5358            })?;
5359        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5360            module_id: self.inner.module_id.clone(),
5361        })?
5362    }
5363
5364    pub async fn restart(&self, drain_timeout_ms: Option<u64>) -> Result<(), SuperviseError> {
5365        self.restart_requested(drain_timeout_ms, None).await
5366    }
5367
5368    pub(crate) async fn restart_requested(
5369        &self,
5370        drain_timeout_ms: Option<u64>,
5371        requester: Option<Principal>,
5372    ) -> Result<(), SuperviseError> {
5373        let queued_at = Instant::now();
5374        let received_at_generation = lock_snapshot(&self.inner.snapshot)?.spawn_generation;
5375        let (reply_tx, reply_rx) = oneshot::channel();
5376        self.inner
5377            .commands
5378            .send(SupervisorCommand::Restart {
5379                requester,
5380                drain_timeout_ms,
5381                received_at_generation,
5382                queued_at,
5383                reply: reply_tx,
5384            })
5385            .await
5386            .map_err(|_| SuperviseError::CommandClosed {
5387                module_id: self.inner.module_id.clone(),
5388            })?;
5389        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5390            module_id: self.inner.module_id.clone(),
5391        })?
5392    }
5393
5394    /// Blue/green restart: see `SupervisorCommand::Swap` and the
5395    /// `supervisor_swap` module. Returns once the swap has cut over (the old
5396    /// process then drains in the background of the supervise loop), has been
5397    /// superseded by an approved configuration restart, or has failed. Both
5398    /// supersession and failure leave the old process serving until replacement.
5399    pub async fn swap(
5400        &self,
5401        ready_timeout: Option<Duration>,
5402    ) -> Result<SwapOutcome, SuperviseError> {
5403        self.swap_requested(ready_timeout, None).await
5404    }
5405
5406    pub(crate) async fn swap_requested(
5407        &self,
5408        ready_timeout: Option<Duration>,
5409        requester: Option<Principal>,
5410    ) -> Result<SwapOutcome, SuperviseError> {
5411        let (reply_tx, reply_rx) = oneshot::channel();
5412        self.inner
5413            .commands
5414            .send(SupervisorCommand::Swap {
5415                requester,
5416                ready_timeout,
5417                reply: reply_tx,
5418            })
5419            .await
5420            .map_err(|_| SuperviseError::CommandClosed {
5421                module_id: self.inner.module_id.clone(),
5422            })?;
5423        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5424            module_id: self.inner.module_id.clone(),
5425        })?
5426    }
5427
5428    pub async fn reload(&self) -> Result<(), SuperviseError> {
5429        self.reload_requested(None).await
5430    }
5431
5432    pub(crate) async fn reload_requested(
5433        &self,
5434        requester: Option<Principal>,
5435    ) -> Result<(), SuperviseError> {
5436        let (reply_tx, reply_rx) = oneshot::channel();
5437        self.inner
5438            .commands
5439            .send(SupervisorCommand::Reload {
5440                requester,
5441                reply: reply_tx,
5442            })
5443            .await
5444            .map_err(|_| SuperviseError::CommandClosed {
5445                module_id: self.inner.module_id.clone(),
5446            })?;
5447        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5448            module_id: self.inner.module_id.clone(),
5449        })?
5450    }
5451
5452    pub async fn set_enabled(&self, enabled: bool) -> Result<bool, SuperviseError> {
5453        self.set_enabled_requested(enabled, None).await
5454    }
5455
5456    pub(crate) async fn set_enabled_requested(
5457        &self,
5458        enabled: bool,
5459        requester: Option<Principal>,
5460    ) -> Result<bool, SuperviseError> {
5461        self.set_enabled_with_budget_policy(enabled, requester, true)
5462            .await
5463    }
5464
5465    pub(crate) async fn release_config_hold(&self) -> Result<bool, SuperviseError> {
5466        self.set_enabled_with_budget_policy(true, None, false).await
5467    }
5468
5469    #[cfg(all(test, unix))]
5470    pub(crate) fn seed_crash_budget_for_test(&self, count: u32) {
5471        let policy = self.inner.configuration.lock().unwrap().restart_policy;
5472        let mut state = self.inner.snapshot.lock().unwrap();
5473        for _ in 0..count {
5474            state.record_crash_restart(&policy, Instant::now());
5475        }
5476    }
5477
5478    async fn set_enabled_with_budget_policy(
5479        &self,
5480        enabled: bool,
5481        requester: Option<Principal>,
5482        reset_budget: bool,
5483    ) -> Result<bool, SuperviseError> {
5484        let (reply_tx, reply_rx) = oneshot::channel();
5485        self.inner
5486            .commands
5487            .send(SupervisorCommand::SetEnabled {
5488                requester,
5489                enabled,
5490                reset_budget,
5491                reply: reply_tx,
5492            })
5493            .await
5494            .map_err(|_| SuperviseError::CommandClosed {
5495                module_id: self.inner.module_id.clone(),
5496            })?;
5497        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5498            module_id: self.inner.module_id.clone(),
5499        })?
5500    }
5501
5502    /// The current process's protocol, or the configured protocol when down.
5503    /// A rescan stores the next launch spec without changing how an existing
5504    /// process registers, serves routes, is probed, or exits.
5505    pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
5506        let configured = self
5507            .inner
5508            .configuration
5509            .lock()
5510            .map_err(|_| SuperviseError::StatePoisoned {
5511                module_id: Some(self.inner.module_id.clone()),
5512            })?
5513            .spec
5514            .protocol;
5515        let state = lock_snapshot(&self.inner.snapshot)?;
5516        Ok(state.spawned_protocol.unwrap_or(configured))
5517    }
5518
5519    pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
5520        let configuration =
5521            self.inner
5522                .configuration
5523                .lock()
5524                .map_err(|_| SuperviseError::StatePoisoned {
5525                    module_id: Some(self.inner.module_id.clone()),
5526                })?;
5527        Ok((configuration.spec.clone(), configuration.health.clone()))
5528    }
5529
5530    pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
5531        self.inner
5532            .configuration
5533            .lock()
5534            .map(|configuration| configuration.register_timeout)
5535            .map_err(|_| SuperviseError::StatePoisoned {
5536                module_id: Some(self.inner.module_id.clone()),
5537            })
5538    }
5539
5540    pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
5541        self.inner
5542            .configuration
5543            .lock()
5544            .map(|configuration| configuration.enabled)
5545            .map_err(|_| SuperviseError::StatePoisoned {
5546                module_id: Some(self.inner.module_id.clone()),
5547            })
5548    }
5549
5550    /// Replace this module's launch spec, keeping its health and drain policy,
5551    /// the way a rescan does for a changed config entry. The running process is
5552    /// untouched; the next spawn (a restart, or a swap's candidate) uses it.
5553    #[cfg(any(test, feature = "test-support"))]
5554    pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
5555        let (_, health) = self.configuration()?;
5556        let drain_timeout_ms = u64::try_from(
5557            self.inner
5558                .effective_drain_timeout
5559                .lock()
5560                .unwrap_or_else(|poisoned| poisoned.into_inner())
5561                .as_millis(),
5562        )
5563        .ok();
5564        self.update_configuration(spec, health, drain_timeout_ms)
5565            .await
5566    }
5567
5568    pub(crate) async fn reconcile_approved_configuration(
5569        &self,
5570        approved: crate::config_gate::runtime::ApprovedDaemonConfiguration,
5571    ) -> Result<(), SuperviseError> {
5572        let entry = approved
5573            .module_entry(&self.inner.module_id)
5574            .map_err(|error| SuperviseError::InvalidSpec {
5575                reason: error.to_string(),
5576            })?;
5577        validate_spec(&entry.module_spec())?;
5578        let (reply, received) = oneshot::channel();
5579        self.inner
5580            .commands
5581            .send(SupervisorCommand::ApprovedConfiguration { approved, reply })
5582            .await
5583            .map_err(|_| SuperviseError::CommandClosed {
5584                module_id: self.inner.module_id.clone(),
5585            })?;
5586        received.await.map_err(|_| SuperviseError::CommandClosed {
5587            module_id: self.inner.module_id.clone(),
5588        })??;
5589        let mut configuration =
5590            self.inner
5591                .configuration
5592                .lock()
5593                .map_err(|_| SuperviseError::StatePoisoned {
5594                    module_id: Some(self.inner.module_id.clone()),
5595                })?;
5596        configuration.spec = entry.module_spec();
5597        configuration.enabled = entry.enabled;
5598        configuration.health = entry.health;
5599        configuration.register_timeout = entry.register_timeout;
5600        configuration.restart_policy = entry.restart;
5601        Ok(())
5602    }
5603
5604    pub(crate) async fn update_configuration(
5605        &self,
5606        spec: ModuleSpec,
5607        health: HealthConfig,
5608        drain_timeout_ms: Option<u64>,
5609    ) -> Result<(), SuperviseError> {
5610        if spec.module_id != self.inner.module_id {
5611            return Err(SuperviseError::InvalidSpec {
5612                reason: "a supervised module's module_id cannot be changed".to_string(),
5613            });
5614        }
5615        validate_spec(&spec)?;
5616        let (reply_tx, reply_rx) = oneshot::channel();
5617        self.inner
5618            .commands
5619            .send(SupervisorCommand::UpdateConfiguration {
5620                spec: spec.clone(),
5621                health: health.clone(),
5622                drain_timeout_ms,
5623                reply: reply_tx,
5624            })
5625            .await
5626            .map_err(|_| SuperviseError::CommandClosed {
5627                module_id: self.inner.module_id.clone(),
5628            })?;
5629        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5630            module_id: self.inner.module_id.clone(),
5631        })??;
5632        let mut configuration =
5633            self.inner
5634                .configuration
5635                .lock()
5636                .map_err(|_| SuperviseError::StatePoisoned {
5637                    module_id: Some(self.inner.module_id.clone()),
5638                })?;
5639        configuration.spec = spec;
5640        configuration.health = health;
5641        Ok(())
5642    }
5643}
5644
5645impl Drop for SupervisedModuleInner {
5646    fn drop(&mut self) {
5647        let Ok(mut monitor) = self.monitor.lock() else {
5648            return;
5649        };
5650        if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
5651            let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
5652                state.state = ModuleState::Stopped;
5653                clear_current_process_facts(state);
5654            });
5655            monitor.abort();
5656        }
5657        let _ = monitor.take();
5658    }
5659}
5660
5661#[derive(Debug)]
5662enum SupervisorCommand {
5663    ApprovedConfiguration {
5664        approved: crate::config_gate::runtime::ApprovedDaemonConfiguration,
5665        reply: oneshot::Sender<Result<(), SuperviseError>>,
5666    },
5667    ConfigPolicyProbe {
5668        connection: crate::ConnectionId,
5669        generation: u64,
5670        attempt: u64,
5671    },
5672    ConfigApplyRestart {
5673        generation: u64,
5674        supersedes_swap: bool,
5675    },
5676    ConfigExitHold {
5677        reply: oneshot::Sender<Result<(), SuperviseError>>,
5678    },
5679    ConfigDeliveryFailed {
5680        connection: crate::ConnectionId,
5681        hold: bool,
5682    },
5683    Drain {
5684        requester: Option<Principal>,
5685        reply: oneshot::Sender<Result<(), SuperviseError>>,
5686    },
5687    Retire {
5688        requester: Option<Principal>,
5689        reply: oneshot::Sender<Result<(), SuperviseError>>,
5690    },
5691    Restart {
5692        requester: Option<Principal>,
5693        /// Operator override for this one restart's drain budget, in ms. `None`
5694        /// uses the module's configured/default budget; `Some(0)` cuts
5695        /// immediately (wedge bounce: a stuck request never settles, so
5696        /// waiting only delays recovery).
5697        drain_timeout_ms: Option<u64>,
5698        /// The module's `spawn_generation` when the request was received, before
5699        /// it waited in the command queue. A queued restart whose module has
5700        /// since spawned a newer process is already satisfied (see the handler).
5701        received_at_generation: u64,
5702        /// When the request entered the command queue, so the handler can log
5703        /// how long it waited behind the loop's other work.
5704        queued_at: Instant,
5705        reply: oneshot::Sender<Result<(), SuperviseError>>,
5706    },
5707    Reload {
5708        requester: Option<Principal>,
5709        reply: oneshot::Sender<Result<(), SuperviseError>>,
5710    },
5711    SetEnabled {
5712        reset_budget: bool,
5713        requester: Option<Principal>,
5714        enabled: bool,
5715        reply: oneshot::Sender<Result<bool, SuperviseError>>,
5716    },
5717    UpdateConfiguration {
5718        spec: ModuleSpec,
5719        health: HealthConfig,
5720        /// Per-module drain override from the new config; `None` re-resolves to
5721        /// the supervisor-wide default.
5722        drain_timeout_ms: Option<u64>,
5723        reply: oneshot::Sender<Result<(), SuperviseError>>,
5724    },
5725    Swap {
5726        requester: Option<Principal>,
5727        /// How long the candidate may take to register and declare itself
5728        /// ready. `None` uses [`DEFAULT_SWAP_READY_TIMEOUT`].
5729        ready_timeout: Option<Duration>,
5730        /// Answered at cutover or failure; the incumbent's drain follows.
5731        reply: oneshot::Sender<Result<SwapOutcome, SuperviseError>>,
5732    },
5733}
5734
5735/// Successful daemon-local swap disposition. Supersession leaves the incumbent
5736/// serving until an approved replacement starts with the latest configured
5737/// command; the legacy control acknowledgment does not carry this disposition.
5738#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5739pub enum SwapOutcome {
5740    Cutover,
5741    SupersededByConfigRestart,
5742}
5743
5744impl SwapOutcome {
5745    pub fn as_str(self) -> &'static str {
5746        match self {
5747            Self::Cutover => "cutover",
5748            Self::SupersededByConfigRestart => "superseded_by_config_restart",
5749        }
5750    }
5751}
5752
5753#[derive(Debug)]
5754pub enum SuperviseError {
5755    ConfigHeld {
5756        module_id: String,
5757        code: String,
5758        detail: String,
5759    },
5760    ConfigDeliveryDeferred {
5761        module_id: String,
5762    },
5763    InvalidSpec {
5764        reason: String,
5765    },
5766    Spawn {
5767        program: PathBuf,
5768        source: io::Error,
5769        cgroup_path: Option<PathBuf>,
5770    },
5771    Cgroup {
5772        module_id: String,
5773        source: io::Error,
5774    },
5775    /// CSPRNG failure generating a reserved module's launch nonce. Fail loud rather
5776    /// than spawn a reserved module without its identity binding.
5777    LaunchNonce {
5778        reason: String,
5779    },
5780    Wait {
5781        module_id: String,
5782        source: io::Error,
5783    },
5784    Kill {
5785        module_id: String,
5786        source: io::Error,
5787    },
5788    Forwarding(ForwardingError),
5789    Registry(RegistryError),
5790    ReloadUnavailable {
5791        module_id: String,
5792        reason: String,
5793    },
5794    /// An operator restart/reload was requested for a module that is currently
5795    /// disabled. Restart/reload cycle a *running* module; a disabled module must
5796    /// be explicitly re-enabled (set_enabled(true)) rather than silently started
5797    /// by a restart, so these commands are rejected instead of re-enabling it.
5798    Disabled {
5799        module_id: String,
5800    },
5801    ReloadFailed {
5802        module_id: String,
5803        reason: String,
5804    },
5805    RegistrationStillActive {
5806        module_id: String,
5807        waited: Duration,
5808    },
5809    StatePoisoned {
5810        module_id: Option<String>,
5811    },
5812    CommandClosed {
5813        module_id: String,
5814    },
5815    /// A restart or reload arrived while a swap's candidate was warming. The
5816    /// swap owns the module until it cuts over or fails; a stop or disable
5817    /// would have aborted it instead.
5818    SwapInProgress {
5819        module_id: String,
5820    },
5821    /// A swap was refused before anything was spawned.
5822    SwapRefused {
5823        module_id: String,
5824        reason: SwapRefusal,
5825    },
5826    /// A swap spawned a candidate and gave up on it. The candidate has been
5827    /// killed and its slot freed; the incumbent was left serving and was never
5828    /// drained, except in the one `CutoverLost` case described on that arm.
5829    SwapFailed {
5830        module_id: String,
5831        arm: SwapFailureArm,
5832        detail: String,
5833        /// How the candidate exited, when it exited on its own before the
5834        /// supervisor gave up on it.
5835        candidate_exit: Option<ExitReport>,
5836    },
5837}
5838
5839/// Why a swap was refused before a candidate was spawned.
5840#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5841pub enum SwapRefusal {
5842    /// The module's config does not declare `overlap: "safe"`.
5843    OverlapExclusive,
5844    /// The module is not registered, so there is no incumbent to keep serving
5845    /// and nothing a swap would improve on; a plain restart is the tool.
5846    NotRegistered,
5847    /// The module does not speak the subc wire, so a candidate could never
5848    /// register or declare itself ready.
5849    ProtocolNone,
5850    /// The supervisor lacks the forwarding table (to cut routes over) or the
5851    /// shared handle (to admit the candidate's HELLO) that a swap needs.
5852    NotConfigured,
5853    /// A swap is already open for this module.
5854    AlreadySwapping,
5855}
5856
5857impl SwapRefusal {
5858    pub fn as_str(self) -> &'static str {
5859        match self {
5860            Self::OverlapExclusive => "overlap_exclusive",
5861            Self::NotRegistered => "not_registered",
5862            Self::ProtocolNone => "protocol_none",
5863            Self::NotConfigured => "not_configured",
5864            Self::AlreadySwapping => "already_swapping",
5865        }
5866    }
5867}
5868
5869/// Which failure arm ended a swap. Every arm but one leaves the incumbent
5870/// serving and undrained; see `CutoverLost`.
5871#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5872pub enum SwapFailureArm {
5873    /// The candidate process could not be started.
5874    SpawnFailed,
5875    /// The candidate did not register within the readiness budget.
5876    NeverRegistered,
5877    /// The candidate registered but did not declare itself ready in time.
5878    NeverReady,
5879    /// The candidate exited before cutover.
5880    CandidateExited,
5881    /// The candidate declared itself ready but failed its health probe.
5882    CandidateUnhealthy,
5883    /// An operator stop, disable or retire arrived while the candidate warmed.
5884    /// The candidate was killed and the operator's command then carried out on
5885    /// the incumbent.
5886    Interrupted,
5887    /// The candidate's connection closed at the moment of cutover. If it
5888    /// closed before forwarding moved, the incumbent is untouched. If it closed
5889    /// between the forwarding and registry halves of cutover, forwarding can no
5890    /// longer route to the incumbent, so the module is restarted plainly.
5891    CutoverLost,
5892}
5893
5894impl SwapFailureArm {
5895    pub fn as_str(self) -> &'static str {
5896        match self {
5897            Self::SpawnFailed => "spawn_failed",
5898            Self::NeverRegistered => "never_registered",
5899            Self::NeverReady => "never_ready",
5900            Self::CandidateExited => "candidate_exited",
5901            Self::CandidateUnhealthy => "candidate_unhealthy",
5902            Self::Interrupted => "interrupted",
5903            Self::CutoverLost => "cutover_lost",
5904        }
5905    }
5906}
5907
5908impl SuperviseError {
5909    pub(crate) fn is_config_gate_error(&self) -> bool {
5910        match self {
5911            Self::ConfigHeld { .. } => true,
5912            Self::Spawn { source, .. } => source
5913                .get_ref()
5914                .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
5915            _ => false,
5916        }
5917    }
5918}
5919
5920impl fmt::Display for SuperviseError {
5921    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5922        match self {
5923            Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
5924            Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
5925            Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
5926            Self::Spawn {
5927                program,
5928                source,
5929                cgroup_path: Some(cgroup_path),
5930            } => write!(
5931                f,
5932                "failed to place module in cgroup '{}' while spawning '{}': {source}",
5933                cgroup_path.display(),
5934                program.display()
5935            ),
5936            Self::Spawn {
5937                program,
5938                source,
5939                cgroup_path: None,
5940            } => write!(
5941                f,
5942                "failed to spawn module '{}': {source}",
5943                program.display()
5944            ),
5945            Self::Cgroup { module_id, source } => {
5946                write!(
5947                    f,
5948                    "failed to prepare cgroup for module '{module_id}': {source}"
5949                )
5950            }
5951            Self::LaunchNonce { reason } => {
5952                write!(
5953                    f,
5954                    "failed to generate reserved-module launch nonce: {reason}"
5955                )
5956            }
5957            Self::Wait { module_id, source } => {
5958                write!(f, "failed to wait for module '{module_id}': {source}")
5959            }
5960            Self::Kill { module_id, source } => {
5961                write!(f, "failed to kill module '{module_id}': {source}")
5962            }
5963            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
5964            Self::Registry(err) => write!(f, "registry error: {err}"),
5965            Self::ReloadUnavailable { module_id, reason } => {
5966                write!(f, "reload unavailable for module '{module_id}': {reason}")
5967            }
5968            Self::Disabled { module_id } => {
5969                write!(
5970                    f,
5971                    "module '{module_id}' is disabled; enable it before restart or reload"
5972                )
5973            }
5974            Self::ReloadFailed { module_id, reason } => {
5975                write!(f, "reload failed for module '{module_id}': {reason}")
5976            }
5977            Self::RegistrationStillActive { module_id, waited } => write!(
5978                f,
5979                "module '{module_id}' registration remained active after waiting {waited:?}"
5980            ),
5981            Self::StatePoisoned { module_id } => match module_id {
5982                Some(module_id) => {
5983                    write!(f, "supervisor state for module '{module_id}' was poisoned")
5984                }
5985                None => write!(f, "supervisor state was poisoned"),
5986            },
5987            Self::CommandClosed { module_id } => {
5988                write!(
5989                    f,
5990                    "supervisor command channel for module '{module_id}' is closed"
5991                )
5992            }
5993            Self::SwapInProgress { module_id } => write!(
5994                f,
5995                "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
5996            ),
5997            Self::SwapRefused { module_id, reason } => match reason {
5998                SwapRefusal::OverlapExclusive => write!(
5999                    f,
6000                    "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"
6001                ),
6002                SwapRefusal::NotRegistered => write!(
6003                    f,
6004                    "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
6005                ),
6006                SwapRefusal::ProtocolNone => write!(
6007                    f,
6008                    "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
6009                ),
6010                SwapRefusal::NotConfigured => write!(
6011                    f,
6012                    "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
6013                ),
6014                SwapRefusal::AlreadySwapping => {
6015                    write!(f, "module '{module_id}' is already being swapped")
6016                }
6017            },
6018            Self::SwapFailed {
6019                module_id,
6020                arm,
6021                detail,
6022                ..
6023            } => write!(
6024                f,
6025                "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
6026                arm.as_str()
6027            ),
6028        }
6029    }
6030}
6031
6032impl Error for SuperviseError {
6033    fn source(&self) -> Option<&(dyn Error + 'static)> {
6034        match self {
6035            Self::Spawn { source, .. }
6036            | Self::Cgroup { source, .. }
6037            | Self::Wait { source, .. }
6038            | Self::Kill { source, .. } => Some(source),
6039            Self::Forwarding(err) => Some(err),
6040            Self::Registry(err) => Some(err),
6041            Self::LaunchNonce { .. }
6042            | Self::ConfigDeliveryDeferred { .. }
6043            | Self::ConfigHeld { .. }
6044            | Self::InvalidSpec { .. }
6045            | Self::ReloadUnavailable { .. }
6046            | Self::Disabled { .. }
6047            | Self::ReloadFailed { .. }
6048            | Self::RegistrationStillActive { .. }
6049            | Self::StatePoisoned { .. }
6050            | Self::CommandClosed { .. }
6051            | Self::SwapInProgress { .. }
6052            | Self::SwapRefused { .. }
6053            | Self::SwapFailed { .. } => None,
6054        }
6055    }
6056}
6057
6058pub(crate) fn validate_spec(spec: &ModuleSpec) -> Result<(), SuperviseError> {
6059    if spec.carry_containment && spec.overlap == ModuleOverlap::Safe {
6060        return Err(SuperviseError::InvalidSpec {
6061            reason: "carry_containment cannot be combined with overlap: safe".to_owned(),
6062        });
6063    }
6064    if spec.module_id.trim().is_empty() {
6065        return Err(SuperviseError::InvalidSpec {
6066            reason: "module_id must not be empty".to_string(),
6067        });
6068    }
6069
6070    Ok(())
6071}
6072
6073#[derive(Debug, Default)]
6074struct HealthProbeRuntime {
6075    spawn_generation: Option<u64>,
6076    configured_health: Option<HealthConfig>,
6077    registered_connection: Option<crate::ConnectionId>,
6078    advertised: bool,
6079    next_probe_at: Option<Instant>,
6080    probe_index: u64,
6081}
6082
6083fn running_protocol(spec: &ModuleSpec, snapshot: &SharedSnapshot) -> ModuleProtocol {
6084    lock_snapshot(snapshot)
6085        .ok()
6086        .and_then(|state| state.spawned_protocol)
6087        .unwrap_or(spec.protocol)
6088}
6089
6090impl HealthProbeRuntime {
6091    fn refresh_registration(
6092        &mut self,
6093        spec: &ModuleSpec,
6094        runtime: &SupervisorRuntimeConfig,
6095        registry: &Registry,
6096        snapshot: &SharedSnapshot,
6097    ) {
6098        let generation = lock_snapshot(snapshot)
6099            .ok()
6100            .map(|state| state.spawn_generation);
6101        if self.spawn_generation != generation {
6102            // A replacement cannot reuse a deadline that is already due for its
6103            // predecessor. HTTP children get a full cadence to start; wire
6104            // children still wait for their own health-advertising HELLO.
6105            *self = Self {
6106                spawn_generation: generation,
6107                ..Self::default()
6108            };
6109        }
6110        if self.configured_health.as_ref() != Some(&runtime.health) {
6111            self.configured_health = Some(runtime.health.clone());
6112            self.next_probe_at = None;
6113            self.registered_connection = None;
6114            self.probe_index = 0;
6115        }
6116        // A non-wire process never registers. Only an explicitly configured
6117        // HTTP endpoint can arm its health probe; an absent HELLO is not a
6118        // health failure for that kind of process.
6119        if running_protocol(spec, snapshot) == ModuleProtocol::None {
6120            self.registered_connection = None;
6121            self.advertised = runtime.health.http.is_some();
6122            if !self.advertised {
6123                self.next_probe_at = None;
6124                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6125                    let unknown = ModuleHealthStatus::default();
6126                    if state.health != unknown {
6127                        state.health = unknown;
6128                        state.last_probe_evidence = None;
6129                    }
6130                });
6131            } else if self.next_probe_at.is_none() {
6132                self.next_probe_at = Some(
6133                    Instant::now()
6134                        + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
6135                );
6136            }
6137            return;
6138        }
6139
6140        let registration = match registry.get_module(&spec.module_id) {
6141            Ok(registration) => registration,
6142            Err(err) => {
6143                warn!(module_id = %spec.module_id, error = %err, "health prober could not read registry");
6144                self.advertised = false;
6145                self.next_probe_at = None;
6146                return;
6147            }
6148        };
6149
6150        let Some(registration) = registration else {
6151            self.registered_connection = None;
6152            self.advertised = false;
6153            self.next_probe_at = None;
6154            return;
6155        };
6156
6157        let advertised = registration
6158            .control_ops
6159            .iter()
6160            .any(|op| op == MODULE_CONTROL_OP_HEALTH_CHECK);
6161        if !advertised {
6162            self.registered_connection = Some(registration.connection_id);
6163            self.advertised = false;
6164            self.next_probe_at = None;
6165            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6166                if state.health.status != SupervisorHealthStatus::Unknown
6167                    || state.health.consecutive_failures != 0
6168                    || state.health.last_probe_ms.is_some()
6169                    || state.health.detail.is_some()
6170                    || state.health.metrics.is_some()
6171                {
6172                    state.health.status = SupervisorHealthStatus::Unknown;
6173                    state.last_probe_evidence = None;
6174                    state.health.consecutive_failures = 0;
6175                    state.health.last_probe_ms = None;
6176                    state.health.detail = None;
6177                    state.health.metrics = None;
6178                }
6179            });
6180            return;
6181        }
6182
6183        let reregistered = self.registered_connection != Some(registration.connection_id);
6184        self.registered_connection = Some(registration.connection_id);
6185        self.advertised = true;
6186        if reregistered || self.next_probe_at.is_none() {
6187            self.probe_index = 0;
6188            self.next_probe_at = Some(
6189                Instant::now() + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
6190            );
6191            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6192                state.health.status = SupervisorHealthStatus::Unknown;
6193                state.last_probe_evidence = None;
6194                state.health.consecutive_failures = 0;
6195                state.health.detail = None;
6196                state.health.metrics = None;
6197            });
6198        }
6199    }
6200
6201    fn wake_at(&self) -> Option<Instant> {
6202        if !self.advertised {
6203            return None;
6204        }
6205        self.next_probe_at
6206    }
6207
6208    fn due(&self) -> bool {
6209        self.advertised
6210            && self
6211                .next_probe_at
6212                .is_some_and(|next| Instant::now() >= next)
6213    }
6214
6215    fn schedule_next(&mut self, spec: &ModuleSpec, cadence: Duration) {
6216        self.probe_index = self.probe_index.wrapping_add(1);
6217        self.next_probe_at = Some(
6218            Instant::now() + jittered_health_delay(&spec.module_id, self.probe_index, cadence),
6219        );
6220    }
6221}
6222
6223/// Evidence is separate from diagnostic prose so host starvation can hold only
6224/// silence-based restarts. A missing lane is still actionable during overload;
6225/// a timeout can instead mean the host has not scheduled a healthy module.
6226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6227enum HealthProbeEvidence {
6228    /// The module's control lane is gone. Proof of death.
6229    LaneDead,
6230    /// No reply within the deadline. Proves nothing about the module's state.
6231    NoAnswer,
6232    /// The module replied, but not with a usable health report. Proves it is alive.
6233    BadAnswer,
6234    /// The daemon could not ask. Says nothing about the module.
6235    Misconfigured,
6236}
6237
6238#[derive(Debug)]
6239struct HealthProbeError {
6240    evidence: HealthProbeEvidence,
6241    message: String,
6242}
6243
6244impl HealthProbeError {
6245    fn lane_dead(message: impl Into<String>) -> Self {
6246        Self::with(HealthProbeEvidence::LaneDead, message)
6247    }
6248
6249    fn no_answer(message: impl Into<String>) -> Self {
6250        Self::with(HealthProbeEvidence::NoAnswer, message)
6251    }
6252
6253    fn bad_answer(message: impl Into<String>) -> Self {
6254        Self::with(HealthProbeEvidence::BadAnswer, message)
6255    }
6256
6257    fn misconfigured(message: impl Into<String>) -> Self {
6258        Self::with(HealthProbeEvidence::Misconfigured, message)
6259    }
6260
6261    fn with(evidence: HealthProbeEvidence, message: impl Into<String>) -> Self {
6262        Self {
6263            evidence,
6264            message: message.into(),
6265        }
6266    }
6267
6268    /// Whether this observation is proof the module cannot serve.
6269    ///
6270    /// Only `LaneDead` qualifies. `NoAnswer` is deliberately excluded: it is the
6271    /// variant that fires under CPU starvation, and treating it as proof is the
6272    /// defect this enum exists to make impossible to reintroduce silently.
6273    ///
6274    /// Outside a host-overload hold, silence still reaches the normal failure
6275    /// threshold so an isolated, genuinely wedged module can recover.
6276    #[allow(dead_code)]
6277    fn is_proof_of_death(&self) -> bool {
6278        matches!(self.evidence, HealthProbeEvidence::LaneDead)
6279    }
6280
6281    /// Short stable label for logs and the health snapshot.
6282    ///
6283    /// An operator reading `ck health` currently cannot tell "the module is gone"
6284    /// from "the module did not answer in five seconds", because both render as
6285    /// prose in the same field. These labels are what make the two
6286    /// distinguishable at a glance, and they are what a later restart-policy
6287    /// change will be argued from.
6288    fn label(&self) -> &'static str {
6289        match self.evidence {
6290            HealthProbeEvidence::LaneDead => "lane-dead",
6291            HealthProbeEvidence::NoAnswer => "no-answer",
6292            HealthProbeEvidence::BadAnswer => "bad-answer",
6293            HealthProbeEvidence::Misconfigured => "daemon-misconfigured",
6294        }
6295    }
6296}
6297
6298impl fmt::Display for HealthProbeError {
6299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6300        f.write_str(&self.message)
6301    }
6302}
6303
6304async fn run_health_probe_cycle(
6305    spec: &ModuleSpec,
6306    runtime: &SupervisorRuntimeConfig,
6307    registry: &Registry,
6308    process_liveness: &SupervisorProcessLiveness,
6309    snapshot: &SharedSnapshot,
6310    child: &mut Option<SupervisedChild>,
6311) {
6312    let now_ms = unix_ms_now();
6313    let delivery_probe = match &runtime.config_delivery {
6314        Some(delivery) => {
6315            delivery
6316                .health_probe(&spec.module_id, runtime.forwarding.as_deref(), registry)
6317                .await
6318        }
6319        None => None,
6320    };
6321    let http = (running_protocol(spec, snapshot) == ModuleProtocol::None)
6322        .then_some(runtime.health.http.as_deref())
6323        .flatten();
6324    let result = match http {
6325        Some(url) => probe_http_health(url, runtime.health.deadline)
6326            .await
6327            .map(|report| (report, None)),
6328        None => probe_module_health_from(&spec.module_id, runtime, None)
6329            .await
6330            .map(|(report, probed)| (report, Some(probed))),
6331    };
6332    match result {
6333        Ok((report, probed)) => {
6334            handle_health_report(
6335                spec,
6336                runtime,
6337                registry,
6338                process_liveness,
6339                snapshot,
6340                child,
6341                report,
6342                now_ms,
6343                delivery_probe,
6344                probed,
6345            )
6346            .await;
6347        }
6348        Err(err) => {
6349            if http.is_some() {
6350                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6351                    state.health.status = SupervisorHealthStatus::Failing;
6352                });
6353            }
6354            handle_health_probe_failure(
6355                spec,
6356                runtime,
6357                registry,
6358                process_liveness,
6359                snapshot,
6360                child,
6361                err,
6362                now_ms,
6363                delivery_probe,
6364            )
6365            .await;
6366        }
6367    }
6368}
6369
6370pub(crate) struct HttpProbeTarget<'a> {
6371    address: std::net::SocketAddr,
6372    localhost: bool,
6373    authority: &'a str,
6374    path: String,
6375}
6376
6377/// Resolve only literal loopback endpoints, without DNS, redirects, proxies,
6378/// or TLS. A URL cannot turn a local health check into an outbound connection.
6379pub(crate) fn parse_http_probe_url(url: &str) -> Result<HttpProbeTarget<'_>, String> {
6380    if url.bytes().any(|b| b <= b' ' || b == 127) || url.contains('#') {
6381        return Err("must not contain whitespace, controls, or a fragment".into());
6382    }
6383    let rest = url
6384        .strip_prefix("http://")
6385        .ok_or("must use plain http://")?;
6386    let split = rest.find(['/', '?']).unwrap_or(rest.len());
6387    let (authority, suffix) = rest.split_at(split);
6388    let (host, port) = if let Some(rest) = authority.strip_prefix("[::1]") {
6389        ("::1", rest)
6390    } else {
6391        let split = authority.find(':').unwrap_or(authority.len());
6392        authority.split_at(split)
6393    };
6394    let ip: std::net::IpAddr = match host {
6395        "127.0.0.1" | "localhost" => std::net::Ipv4Addr::LOCALHOST.into(),
6396        "::1" => std::net::Ipv6Addr::LOCALHOST.into(),
6397        _ => return Err("host must be 127.0.0.1, [::1], or localhost".into()),
6398    };
6399    let port = if port.is_empty() {
6400        80
6401    } else {
6402        port.strip_prefix(':')
6403            .and_then(|p| p.parse::<u16>().ok())
6404            .filter(|p| *p > 0)
6405            .ok_or("must have a valid nonzero TCP port")?
6406    };
6407    let path = if suffix.is_empty() {
6408        "/".into()
6409    } else if suffix.starts_with('?') {
6410        format!("/{suffix}")
6411    } else {
6412        suffix.into()
6413    };
6414    Ok(HttpProbeTarget {
6415        address: std::net::SocketAddr::new(ip, port),
6416        localhost: host == "localhost",
6417        authority,
6418        path,
6419    })
6420}
6421
6422async fn probe_http_health(
6423    url: &str,
6424    deadline: Duration,
6425) -> Result<HealthReport, HealthProbeError> {
6426    use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
6427    let target = parse_http_probe_url(url).map_err(HealthProbeError::misconfigured)?;
6428    // Keep partial diagnostics outside the timed future so cancellation does
6429    // not discard a status line or body bytes already received.
6430    let mut response_status = String::new();
6431    let mut body = Vec::new();
6432    let probe = async {
6433        // Resolve localhost ourselves so a hosts-file override cannot turn
6434        // this into an outbound request, while IPv6-only local servers work.
6435        let connection = match tokio::net::TcpStream::connect(target.address).await {
6436            Err(_) if target.localhost => {
6437                tokio::net::TcpStream::connect((
6438                    std::net::Ipv6Addr::LOCALHOST,
6439                    target.address.port(),
6440                ))
6441                .await
6442            }
6443            result => result,
6444        };
6445        let mut stream = connection.map_err(|error| {
6446            HealthProbeError::no_answer(format!("HTTP connect failed: {error}"))
6447        })?;
6448        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
6449            .map_err(|error| HealthProbeError::no_answer(format!("HTTP write failed: {error}")))?;
6450        let mut reader = BufReader::new(stream);
6451        let mut budget = 16 * 1024;
6452        let status = http_line(&mut reader, &mut budget).await?;
6453        let mut words = status.split_ascii_whitespace();
6454        let version = words.next();
6455        let code = words
6456            .next()
6457            .filter(|word| word.len() == 3)
6458            .and_then(|word| word.parse::<u16>().ok());
6459        if !matches!(version, Some("HTTP/1.1" | "HTTP/1.0"))
6460            || !code.is_some_and(|code| (100..600).contains(&code))
6461        {
6462            return Err(HealthProbeError::bad_answer(format!(
6463                "invalid HTTP status: {status}"
6464            )));
6465        }
6466        let code = code.expect("validated status code");
6467        response_status = status.clone();
6468        let mut length = None;
6469        let mut chunked = false;
6470        loop {
6471            let line = http_line(&mut reader, &mut budget).await?;
6472            if line.is_empty() {
6473                break;
6474            }
6475            if let Some((name, value)) = line.split_once(':') {
6476                if name.eq_ignore_ascii_case("content-length") {
6477                    length = Some(value.trim().parse::<u64>().map_err(|_| {
6478                        HealthProbeError::bad_answer("invalid HTTP Content-Length")
6479                    })?);
6480                } else if name.eq_ignore_ascii_case("transfer-encoding") {
6481                    chunked = value.trim().eq_ignore_ascii_case("chunked");
6482                }
6483            }
6484        }
6485        if chunked {
6486            while body.len() < 200 {
6487                let line = http_line(&mut reader, &mut budget).await?;
6488                let size = u64::from_str_radix(line.split(';').next().unwrap_or("").trim(), 16)
6489                    .map_err(|_| HealthProbeError::bad_answer("invalid HTTP chunk size"))?;
6490                if size == 0 {
6491                    break;
6492                }
6493                let count = size.min((200 - body.len()) as u64) as usize;
6494                let start = body.len();
6495                (&mut reader)
6496                    .take(count as u64)
6497                    .read_to_end(&mut body)
6498                    .await
6499                    .map_err(|error| {
6500                        HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
6501                    })?;
6502                if body.len() - start != count {
6503                    return Err(HealthProbeError::bad_answer("truncated HTTP chunk"));
6504                }
6505                if size > count as u64 || body.len() == 200 {
6506                    break;
6507                }
6508                if !http_line(&mut reader, &mut budget).await?.is_empty() {
6509                    return Err(HealthProbeError::bad_answer("invalid HTTP chunk delimiter"));
6510                }
6511            }
6512        } else {
6513            reader
6514                .take(length.unwrap_or(200).min(200))
6515                .read_to_end(&mut body)
6516                .await
6517                .map_err(|error| {
6518                    HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
6519                })?;
6520        }
6521        if (200..300).contains(&code) {
6522            Ok(HealthReport::ok())
6523        } else {
6524            Err(HealthProbeError::bad_answer(
6525                "HTTP health endpoint returned non-2xx",
6526            ))
6527        }
6528    };
6529    let mut result = timeout(deadline, probe).await.unwrap_or_else(|_| {
6530        Err(HealthProbeError::no_answer(format!(
6531            "HTTP probe timed out after {deadline:?}"
6532        )))
6533    });
6534    if let Err(error) = &mut result {
6535        if !response_status.is_empty() {
6536            error.message = format!(
6537                "{}; {response_status}: {}",
6538                error.message,
6539                String::from_utf8_lossy(&body)
6540            );
6541        }
6542    }
6543    result
6544}
6545
6546async fn http_line(
6547    reader: &mut tokio::io::BufReader<tokio::net::TcpStream>,
6548    remaining: &mut usize,
6549) -> Result<String, HealthProbeError> {
6550    use tokio::io::{AsyncBufReadExt, AsyncReadExt};
6551    let mut line = Vec::new();
6552    (&mut *reader)
6553        .take(*remaining as u64)
6554        .read_until(b'\n', &mut line)
6555        .await
6556        .map_err(|error| {
6557            HealthProbeError::no_answer(format!("HTTP header read failed: {error}"))
6558        })?;
6559    *remaining -= line.len();
6560    if !line.ends_with(b"\r\n") {
6561        return Err(HealthProbeError::bad_answer(
6562            "HTTP headers are incomplete or exceed 16 KiB",
6563        ));
6564    }
6565    line.truncate(line.len() - 2);
6566    String::from_utf8(line).map_err(|_| HealthProbeError::bad_answer("HTTP header is not UTF-8"))
6567}
6568
6569async fn probe_module_health(
6570    module_id: &str,
6571    runtime: &SupervisorRuntimeConfig,
6572    drain_deadline: Option<Instant>,
6573) -> Result<HealthReport, HealthProbeError> {
6574    probe_module_health_from(module_id, runtime, drain_deadline)
6575        .await
6576        .map(|(report, _)| report)
6577}
6578
6579/// [`probe_module_health`], also returning the connection whose registration
6580/// answered, so its answer is credited to that registration and no other.
6581async fn probe_module_health_from(
6582    module_id: &str,
6583    runtime: &SupervisorRuntimeConfig,
6584    drain_deadline: Option<Instant>,
6585) -> Result<(HealthReport, ConnectionId), HealthProbeError> {
6586    let Some(forwarding) = runtime.forwarding.as_ref() else {
6587        return Err(HealthProbeError::misconfigured(
6588            "supervisor was not configured with a forwarding table",
6589        ));
6590    };
6591    let probe_started_at = Instant::now();
6592    let mut deadline = probe_started_at + runtime.health.deadline;
6593    if let Some(drain_deadline) = drain_deadline {
6594        deadline = deadline.min(drain_deadline);
6595    }
6596    let pending = if drain_deadline.is_some() {
6597        forwarding.begin_drain_health_probe_rpc_for(
6598            module_id,
6599            MODULE_CONTROL_OP_HEALTH_CHECK,
6600            probe_started_at,
6601            deadline,
6602        )
6603    } else {
6604        forwarding.begin_health_probe_rpc_for(
6605            module_id,
6606            MODULE_CONTROL_OP_HEALTH_CHECK,
6607            probe_started_at,
6608            deadline,
6609        )
6610    }
6611    .map_err(|err| {
6612        // The endpoint is not registered, so there is no live control lane to
6613        // ask. That is the module being absent, not slow.
6614        HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
6615    })?;
6616    let probed = pending.endpoint.connection_id;
6617    await_health_probe(forwarding, pending, deadline, runtime.health.deadline)
6618        .await
6619        .map(|report| (report, probed))
6620}
6621
6622/// [`probe_module_health`] for one endpoint rather than the id's active one.
6623///
6624/// A swap probes two processes that no by-id lookup reaches: its candidate
6625/// before cutover, and its superseded incumbent (for busy gauges) while the
6626/// incumbent drains. `deadline_cap` bounds the probe the way a drain deadline
6627/// bounds the by-id drain probe.
6628async fn probe_endpoint_health(
6629    endpoint: crate::ModuleEndpointId,
6630    runtime: &SupervisorRuntimeConfig,
6631    deadline_cap: Option<Instant>,
6632) -> Result<HealthReport, HealthProbeError> {
6633    let Some(forwarding) = runtime.forwarding.as_ref() else {
6634        return Err(HealthProbeError::misconfigured(
6635            "supervisor was not configured with a forwarding table",
6636        ));
6637    };
6638    let probe_started_at = Instant::now();
6639    let mut deadline = probe_started_at + runtime.health.deadline;
6640    if let Some(cap) = deadline_cap {
6641        deadline = deadline.min(cap);
6642    }
6643    let pending = forwarding
6644        .begin_endpoint_health_probe_rpc_for(
6645            endpoint,
6646            MODULE_CONTROL_OP_HEALTH_CHECK,
6647            probe_started_at,
6648            deadline,
6649        )
6650        .map_err(|err| {
6651            HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
6652        })?;
6653    await_health_probe(forwarding, pending, deadline, runtime.health.deadline).await
6654}
6655
6656/// Send a begun health probe and classify its answer.
6657async fn await_health_probe(
6658    forwarding: &ForwardingTable,
6659    pending: PendingModuleControlRpc,
6660    deadline: Instant,
6661    probe_budget: Duration,
6662) -> Result<HealthReport, HealthProbeError> {
6663    let PendingModuleControlRpc {
6664        endpoint,
6665        module_sink,
6666        negotiated_ver,
6667        corr,
6668        receiver,
6669    } = pending;
6670    let body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).map_err(|err| {
6671        HealthProbeError::misconfigured(format!("failed to encode health.check: {err}"))
6672    })?;
6673    let frame = Frame::build_with_version(
6674        negotiated_ver,
6675        FrameType::Request,
6676        control_flags(),
6677        0,
6678        0,
6679        corr,
6680        body,
6681    )
6682    .map_err(|err| {
6683        HealthProbeError::misconfigured(format!("failed to build health.check frame: {err}"))
6684    })?;
6685
6686    // The enqueue itself must be bounded by the probe deadline: FrameSink.send
6687    // blocks waiting for capacity when the module's egress queue is full, and an
6688    // unbounded await here freezes the whole supervision actor (it stops polling
6689    // Child::wait and supervisor commands), making the module unrecoverable
6690    // in-band. On timeout the probe fails like any transport failure.
6691    match timeout_at(deadline, module_sink.send(frame)).await {
6692        Ok(Ok(())) => {}
6693        Ok(Err(err)) => {
6694            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
6695            // A closed sink means the module's egress channel is gone -- the
6696            // receiving half is dropped when its connection tears down. Proof.
6697            return Err(HealthProbeError::lane_dead(format!(
6698                "failed to send health.check: {err}"
6699            )));
6700        }
6701        Err(_elapsed) => {
6702            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
6703            // A full egress queue means the module is not draining its socket, which
6704            // is consistent with a wedged module AND with one whose reader is merely
6705            // starved. Silence, not proof.
6706            return Err(HealthProbeError::no_answer(
6707                "health.check send timed out before enqueue (module egress full)",
6708            ));
6709        }
6710    }
6711
6712    match timeout_at(deadline, receiver).await {
6713        Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => Err(HealthProbeError::bad_answer(
6714            "health.check returned an unexpected config response",
6715        )),
6716        // Each arm records WHAT WAS OBSERVED. Four of them are the module
6717        // demonstrably answering -- rejected, non-health, malformed, wrong op --
6718        // and those prove it is alive even though the probe failed.
6719        Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
6720            response.health_report().ok_or_else(|| {
6721                HealthProbeError::bad_answer("health.check RPC returned a non-health response")
6722            })
6723        }
6724        Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => Err(HealthProbeError::bad_answer(
6725            format!("health.check rejected: {}", body.message),
6726        )),
6727        Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
6728            Err(HealthProbeError::lane_dead(message))
6729        }
6730        Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
6731            Err(HealthProbeError::bad_answer(message))
6732        }
6733        Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
6734            Err(HealthProbeError::bad_answer(format!(
6735                "expected module-control op '{expected}', got '{actual}'"
6736            )))
6737        }
6738        // A reply that crosses the deadline before this waiter observes it is
6739        // still proof of life. The forwarding path records its end-to-end latency
6740        // before delivering this classification.
6741        Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => Err(HealthProbeError::bad_answer(
6742            "module answered health.check after its daemon deadline",
6743        )),
6744        Ok(Err(_)) => Err(HealthProbeError::misconfigured(
6745            "health.check waiter was canceled before the module responded",
6746        )),
6747        Err(_) => {
6748            let _ = forwarding.tombstone_health_probe_rpc(endpoint, corr);
6749            Err(HealthProbeError::no_answer(format!(
6750                "module did not answer health.check within {probe_budget:?}"
6751            )))
6752        }
6753    }
6754}
6755
6756/// Act on a health probe's answer. `probed` is the connection whose
6757/// registration answered (`None` for an HTTP probe, which reaches no
6758/// registration); only that registration's spawn is credited with readiness.
6759#[allow(clippy::too_many_arguments)]
6760async fn handle_health_report(
6761    spec: &ModuleSpec,
6762    runtime: &SupervisorRuntimeConfig,
6763    registry: &Registry,
6764    process_liveness: &SupervisorProcessLiveness,
6765    snapshot: &SharedSnapshot,
6766    child: &mut Option<SupervisedChild>,
6767    report: HealthReport,
6768    now_ms: u64,
6769    delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
6770    probed: Option<ConnectionId>,
6771) {
6772    let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
6773        (Some(delivery), Some(probe)) => {
6774            delivery
6775                .health_result(
6776                    &spec.module_id,
6777                    runtime.forwarding.as_deref(),
6778                    registry,
6779                    probe,
6780                    report.status == HealthStatus::Ok,
6781                )
6782                .await
6783        }
6784        _ => false,
6785    };
6786    if let (Some(delivery), Some(spawn)) = (
6787        &runtime.config_delivery,
6788        child
6789            .as_ref()
6790            .and_then(|child| child.config_delivery.as_ref()),
6791    ) {
6792        delivery
6793            .mark_readiness(
6794                &spec.module_id,
6795                runtime.forwarding.as_deref(),
6796                probed,
6797                spawn,
6798                report.status == HealthStatus::Ok,
6799            )
6800            .await;
6801    }
6802    let status = supervisor_health_status(report.status);
6803    let detail = report.detail.clone();
6804    let metrics = truncate_health_metrics(report.metrics);
6805    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6806        state.health.status = status;
6807        state.last_probe_evidence = None;
6808        state.health.last_probe_ms = Some(now_ms);
6809        state.health.detail = detail.clone();
6810        state.health.metrics = metrics.clone();
6811        state.health.consecutive_failures = 0;
6812        state.failed_retry.observe_health(
6813            report.status == HealthStatus::Ok,
6814            runtime.restart_policy.window,
6815        );
6816    });
6817
6818    if delivery_failed {
6819        return;
6820    }
6821    let action = match report.status {
6822        HealthStatus::Ok => return,
6823        HealthStatus::Degraded => runtime.health.on_degraded,
6824        HealthStatus::Failing => runtime.health.on_failing,
6825    };
6826    apply_l3_health_action(
6827        spec,
6828        runtime,
6829        registry,
6830        process_liveness,
6831        snapshot,
6832        child,
6833        status,
6834        detail.as_deref(),
6835        action,
6836        now_ms,
6837    )
6838    .await;
6839}
6840
6841#[allow(clippy::too_many_arguments)]
6842async fn handle_health_probe_failure(
6843    spec: &ModuleSpec,
6844    runtime: &SupervisorRuntimeConfig,
6845    registry: &Registry,
6846    process_liveness: &SupervisorProcessLiveness,
6847    snapshot: &SharedSnapshot,
6848    child: &mut Option<SupervisedChild>,
6849    err: HealthProbeError,
6850    now_ms: u64,
6851    delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
6852) {
6853    let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
6854        (Some(delivery), Some(probe)) => {
6855            delivery
6856                .health_result(
6857                    &spec.module_id,
6858                    runtime.forwarding.as_deref(),
6859                    registry,
6860                    probe,
6861                    false,
6862                )
6863                .await
6864        }
6865        _ => false,
6866    };
6867    let threshold = runtime.health.failure_threshold.max(1);
6868    let held = if err.evidence == HealthProbeEvidence::NoAnswer {
6869        runtime.host_health.record_late_module(&spec.module_id)
6870    } else {
6871        false
6872    };
6873    let mut failures = 0;
6874    // Carry the evidence class into the operator-visible detail. Without it,
6875    // "module did not answer within 5s" and "the control lane is gone" are two
6876    // prose strings in the same field, and the reader has to know the codebase to
6877    // tell which one is proof of anything.
6878    let detail = if held {
6879        format!("[{}] {err}; host overloaded", err.label())
6880    } else {
6881        format!("[{}] {err}", err.label())
6882    };
6883    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6884        state.last_probe_evidence = Some(err.evidence);
6885        state
6886            .failed_retry
6887            .observe_health(false, runtime.restart_policy.window);
6888        // A failed wire probe invalidates the last report, even before the
6889        // restart threshold. HTTP probes already mark failures as Failing.
6890        if held {
6891            state.health.status = SupervisorHealthStatus::Degraded;
6892        } else if state.spawned_protocol.unwrap_or(spec.protocol) == ModuleProtocol::Subc {
6893            state.health.status = SupervisorHealthStatus::Unknown;
6894        }
6895        state.health.last_probe_ms = Some(now_ms);
6896        // Held silence breaks the streak: after the host recovers, only new
6897        // failures count. Replaying pre-overload misses would restart immediately.
6898        state.health.consecutive_failures = if held {
6899            0
6900        } else {
6901            state.health.consecutive_failures.saturating_add(1)
6902        };
6903        state.health.detail = Some(detail.clone());
6904        state.health.metrics = None;
6905        failures = state.health.consecutive_failures;
6906    });
6907
6908    if delivery_failed {
6909        return;
6910    }
6911    if held || failures < threshold {
6912        warn!(
6913            module_id = %spec.module_id,
6914            consecutive_failures = failures,
6915            threshold,
6916            evidence = err.label(),
6917            detail = %detail,
6918            "health.check probe failed"
6919        );
6920        return;
6921    }
6922
6923    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6924        state.state = ModuleState::Unresponsive;
6925        state.health.status = SupervisorHealthStatus::Unresponsive;
6926    });
6927    // The evidence class is logged at the kill site because this is the line an
6928    // operator reads after an unexplained restart. A streak of `no-answer` under
6929    // machine load is the known false-positive shape; a `lane-dead` is not.
6930    if runtime.health.critical {
6931        error!(
6932            module_id = %spec.module_id,
6933            status = "unresponsive",
6934            evidence = err.label(),
6935            detail = %detail,
6936            "critical module health alert"
6937        );
6938    } else {
6939        warn!(
6940            module_id = %spec.module_id,
6941            status = "unresponsive",
6942            evidence = err.label(),
6943            detail = %detail,
6944            "module health threshold breached"
6945        );
6946    }
6947    if let Err(err) = health_restart_child(
6948        spec,
6949        runtime,
6950        registry,
6951        process_liveness,
6952        snapshot,
6953        child,
6954        SupervisorHealthStatus::Unresponsive,
6955        Some(&detail),
6956        now_ms,
6957    )
6958    .await
6959    {
6960        error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
6961    }
6962}
6963
6964#[allow(clippy::too_many_arguments)]
6965async fn apply_l3_health_action(
6966    spec: &ModuleSpec,
6967    runtime: &SupervisorRuntimeConfig,
6968    registry: &Registry,
6969    process_liveness: &SupervisorProcessLiveness,
6970    snapshot: &SharedSnapshot,
6971    child: &mut Option<SupervisedChild>,
6972    status: SupervisorHealthStatus,
6973    detail: Option<&str>,
6974    action: HealthAction,
6975    now_ms: u64,
6976) {
6977    record_health_action(snapshot, &spec.module_id, action.to_string(), now_ms);
6978    match action {
6979        HealthAction::Report => {
6980            info!(
6981                module_id = %spec.module_id,
6982                status = ?status,
6983                detail,
6984                "module reported non-ok health"
6985            );
6986        }
6987        HealthAction::Alert => {
6988            error!(
6989                module_id = %spec.module_id,
6990                status = ?status,
6991                detail,
6992                "module health alert"
6993            );
6994        }
6995        HealthAction::Restart => {
6996            if let Err(err) = health_restart_child(
6997                spec,
6998                runtime,
6999                registry,
7000                process_liveness,
7001                snapshot,
7002                child,
7003                status,
7004                detail,
7005                now_ms,
7006            )
7007            .await
7008            {
7009                error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
7010            }
7011        }
7012    }
7013}
7014
7015#[allow(clippy::too_many_arguments)]
7016async fn health_restart_child(
7017    spec: &ModuleSpec,
7018    runtime: &SupervisorRuntimeConfig,
7019    registry: &Registry,
7020    process_liveness: &SupervisorProcessLiveness,
7021    snapshot: &SharedSnapshot,
7022    child: &mut Option<SupervisedChild>,
7023    status: SupervisorHealthStatus,
7024    detail: Option<&str>,
7025    now_ms: u64,
7026) -> Result<(), SuperviseError> {
7027    budgeted_restart_child(
7028        spec,
7029        runtime,
7030        registry,
7031        process_liveness,
7032        snapshot,
7033        child,
7034        status,
7035        detail,
7036        now_ms,
7037        true,
7038    )
7039    .await
7040}
7041
7042#[allow(clippy::too_many_arguments)]
7043async fn budgeted_restart_child(
7044    spec: &ModuleSpec,
7045    runtime: &SupervisorRuntimeConfig,
7046    registry: &Registry,
7047    process_liveness: &SupervisorProcessLiveness,
7048    snapshot: &SharedSnapshot,
7049    child: &mut Option<SupervisedChild>,
7050    status: SupervisorHealthStatus,
7051    detail: Option<&str>,
7052    now_ms: u64,
7053    health_failure: bool,
7054) -> Result<(), SuperviseError> {
7055    if let Some(error) = runtime
7056        .config_delivery
7057        .as_ref()
7058        .and_then(|delivery| delivery.0.check_module_hold(&spec.module_id).err())
7059        .filter(|error| error.code != "config_delivery_deferred")
7060    {
7061        return Err(config_delivery::gate_hold_error(
7062            spec,
7063            error,
7064            runtime.config_delivery.as_ref(),
7065        ));
7066    }
7067    let recovery_reason = if health_failure {
7068        "health_check"
7069    } else {
7070        "configuration_delivery"
7071    };
7072    let (enabled, schedule) = {
7073        let mut state = lock_snapshot(snapshot)?;
7074        let enabled = state.enabled;
7075        let schedule = if enabled {
7076            state.next_crash_restart(&runtime.restart_policy, Instant::now())
7077        } else {
7078            None
7079        };
7080        (enabled, schedule)
7081    };
7082
7083    if !enabled {
7084        return Err(SuperviseError::Disabled {
7085            module_id: spec.module_id.clone(),
7086        });
7087    }
7088
7089    if schedule.is_none() {
7090        if health_failure {
7091            record_health_action(snapshot, &spec.module_id, "failed".to_string(), now_ms);
7092        }
7093        error!(
7094            module_id = %spec.module_id,
7095            status = ?status,
7096            detail,
7097            max_restarts = runtime.restart_policy.max_restarts,
7098            window_secs = runtime.restart_policy.window.as_secs(),
7099            reason = %runtime.restart_policy.budget_exhausted_detail(),
7100            recovery_reason,
7101            "automatic restart budget exhausted; marking module failed"
7102        );
7103        let stop_notice = begin_forwarding_drain_if_configured(
7104            spec,
7105            runtime,
7106            registry,
7107            snapshot,
7108            Some(true),
7109            RouteCloseReason::Disable,
7110        )
7111        .await?;
7112        update_snapshot(snapshot, Some(&spec.module_id), |state| {
7113            state.drain_disposition_detail = Some(runtime.restart_policy.budget_exhausted_detail());
7114        })?;
7115        let result = drain_optional_child(
7116            &spec.module_id,
7117            spec.protocol,
7118            stop_notice,
7119            registry,
7120            runtime.forwarding.as_deref(),
7121            snapshot,
7122            &runtime.terminal_ring,
7123            &runtime.spawn_events,
7124            child,
7125            runtime.drain_timeout,
7126            ModuleState::Failed,
7127            Some(true),
7128            &runtime.failure_context(true),
7129        )
7130        .await;
7131        update_snapshot(snapshot, Some(&spec.module_id), |state| {
7132            if state.state == ModuleState::Failed && !runtime.child_roster.is_closed() {
7133                state.failed_retry.schedule(&spec.module_id);
7134            }
7135        })?;
7136        result?;
7137        process_liveness.untrack_if_current(&spec.module_id, snapshot);
7138        return Ok(());
7139    }
7140
7141    let schedule = schedule.expect("a health restart must have a crash-restart schedule");
7142    let mut restart_count = 0;
7143    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7144        restart_count = state.crash_restarts.len();
7145        state.state = ModuleState::Unresponsive;
7146        if health_failure {
7147            state.health.status = status;
7148            state.health.last_action = Some(HealthAction::Restart.to_string());
7149            state.health.last_action_ms = Some(now_ms);
7150        }
7151    })?;
7152    warn!(
7153        module_id = %spec.module_id,
7154        status = ?status,
7155        detail,
7156        restart_count,
7157        restart_in_window = schedule.restart_in_window,
7158        delay_ms = schedule.delay.as_millis() as u64,
7159        recovery_reason,
7160        "automatic module restart"
7161    );
7162
7163    let stop_notice = begin_forwarding_drain_if_configured(
7164        spec,
7165        runtime,
7166        registry,
7167        snapshot,
7168        Some(true),
7169        RouteCloseReason::Restart,
7170    )
7171    .await?;
7172    drain_optional_child(
7173        &spec.module_id,
7174        spec.protocol,
7175        stop_notice,
7176        registry,
7177        runtime.forwarding.as_deref(),
7178        snapshot,
7179        &runtime.terminal_ring,
7180        &runtime.spawn_events,
7181        child,
7182        runtime.drain_timeout,
7183        ModuleState::Restarting,
7184        Some(true),
7185        &runtime.failure_context(true),
7186    )
7187    .await?;
7188    schedule_respawn(
7189        runtime,
7190        snapshot,
7191        &spec.module_id,
7192        schedule.delay,
7193        RespawnKind::Spawn,
7194        true,
7195    )
7196}
7197
7198fn cancel_deferred_reload(runtime: &SupervisorRuntimeConfig, module_id: &str, reason: &str) {
7199    if let Some(reply) = runtime
7200        .deferred_reload_reply
7201        .lock()
7202        .unwrap_or_else(|p| p.into_inner())
7203        .take()
7204    {
7205        let _ = reply.send(Err(SuperviseError::ReloadFailed {
7206            module_id: module_id.to_string(),
7207            reason: reason.to_string(),
7208        }));
7209    }
7210}
7211
7212fn park_config_spawn(
7213    spec: &ModuleSpec,
7214    runtime: &SupervisorRuntimeConfig,
7215    snapshot: &SharedSnapshot,
7216    failure: &FailureContext,
7217    admission_refused: Option<String>,
7218) -> Result<(), SuperviseError> {
7219    *runtime
7220        .scheduled_respawn
7221        .lock()
7222        .unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
7223    if let Some(reply) = runtime
7224        .deferred_reload_reply
7225        .lock()
7226        .unwrap_or_else(|poisoned| poisoned.into_inner())
7227        .take()
7228    {
7229        let _ = reply.send(Err(SuperviseError::ConfigHeld {
7230            module_id: spec.module_id.clone(),
7231            code: "config_gated".into(),
7232            detail: "module is held by configuration admission".into(),
7233        }));
7234    }
7235    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7236        state.admission_refused = admission_refused;
7237        state.config_hold_daemon_initiated = failure.daemon_initiated;
7238        state.config_hold_approval = failure.approval.clone();
7239        state.config_hold_parked = true;
7240        state.state = ModuleState::Stopped;
7241        state.respawn_pending = false;
7242        state.failed_retry.pending = None;
7243        // Parking ends this attempt and discards its failure timestamp. If a
7244        // later release fails, its retry delay starts at that new failure.
7245        state.failed_retry.failed_at = None;
7246        clear_current_process_facts(state);
7247    })
7248}
7249
7250fn try_park_config_attempt(
7251    spec: &ModuleSpec,
7252    runtime: &SupervisorRuntimeConfig,
7253    snapshot: &SharedSnapshot,
7254    failure: &FailureContext,
7255    program_base: Option<&subc_config::Digest>,
7256) -> Result<bool, SuperviseError> {
7257    let result = (|| {
7258        if !lock_snapshot(snapshot)?.enabled {
7259            return Ok(false);
7260        }
7261        #[cfg(test)]
7262        if let Some(delivery) = &runtime.config_delivery {
7263            delivery.0.pause_before_config_park_for_test();
7264        }
7265        let Some(delivery) = &runtime.config_delivery else {
7266            return Ok(false);
7267        };
7268        let parked = delivery
7269            .0
7270            .with_recorded_admission_hold(&spec.module_id, program_base, |refusal| {
7271                park_config_spawn(spec, runtime, snapshot, failure, refusal)
7272            })
7273            .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(delivery)))?;
7274        if let Some(result) = parked {
7275            result?;
7276            Ok(true)
7277        } else {
7278            Ok(false)
7279        }
7280    })();
7281    if let Err(error) = &result {
7282        // A failed park still belongs to the attempt that tried to park. Mark it
7283        // Failed here, before the monitor can use a daemon/operator origin saved
7284        // for a different attempt to decide whether to schedule a slow retry.
7285        fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
7286        record_approved_attempt_failure(spec, snapshot, failure, error);
7287    }
7288    result
7289}
7290
7291fn record_approved_attempt_failure(
7292    spec: &ModuleSpec,
7293    snapshot: &SharedSnapshot,
7294    failure: &FailureContext,
7295    error: &SuperviseError,
7296) {
7297    let Some(approval) = &failure.approval else {
7298        return;
7299    };
7300    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
7301        if state.enabled
7302            && state.state == ModuleState::Failed
7303            && state
7304                .approved_start_failure
7305                .as_ref()
7306                .is_none_or(|(identity, _)| identity != approval)
7307        {
7308            state.approved_start_failure = Some((approval.clone(), error.to_string()));
7309        }
7310    });
7311}
7312
7313fn hold_config_spawn(
7314    spec: &ModuleSpec,
7315    runtime: &SupervisorRuntimeConfig,
7316    snapshot: &SharedSnapshot,
7317    failure: &FailureContext,
7318) -> Result<(), SuperviseError> {
7319    if !lock_snapshot(snapshot)?.enabled {
7320        return Ok(());
7321    }
7322    if !try_park_config_attempt(spec, runtime, snapshot, failure, None)? {
7323        // This caller consumed an actual start attempt. If its hold ended before
7324        // parking, retain that attempt instead of waiting for a lost release.
7325        defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
7326    }
7327    Ok(())
7328}
7329
7330fn schedule_respawn(
7331    runtime: &SupervisorRuntimeConfig,
7332    snapshot: &SharedSnapshot,
7333    module_id: &str,
7334    delay: Duration,
7335    kind: RespawnKind,
7336    daemon_initiated: bool,
7337) -> Result<(), SuperviseError> {
7338    cancel_deferred_reload(runtime, module_id, "respawn superseded by another restart");
7339    update_snapshot(snapshot, Some(module_id), |state| {
7340        state.respawn_pending = true
7341    })?;
7342    *runtime
7343        .scheduled_respawn
7344        .lock()
7345        .unwrap_or_else(|p| p.into_inner()) = Some(PendingRespawn {
7346        deadline: Instant::now() + delay,
7347        kind,
7348        daemon_initiated,
7349        approval: None,
7350    });
7351    Ok(())
7352}
7353
7354const CONFIG_ADMISSION_RETRY_DELAY: Duration = Duration::from_millis(100);
7355
7356fn defer_config_spawn(
7357    spec: &ModuleSpec,
7358    runtime: &SupervisorRuntimeConfig,
7359    snapshot: &SharedSnapshot,
7360    kind: RespawnKind,
7361    failure: &FailureContext,
7362) -> Result<(), SuperviseError> {
7363    update_snapshot(snapshot, Some(&spec.module_id), |state| {
7364        state.state = ModuleState::Restarting;
7365        state.respawn_pending = true;
7366        clear_current_process_facts(state);
7367    })?;
7368    *runtime
7369        .scheduled_respawn
7370        .lock()
7371        .unwrap_or_else(|p| p.into_inner()) = Some(PendingRespawn {
7372        deadline: Instant::now() + CONFIG_ADMISSION_RETRY_DELAY,
7373        kind,
7374        daemon_initiated: failure.daemon_initiated,
7375        approval: failure.approval.clone(),
7376    });
7377    Ok(())
7378}
7379
7380fn record_health_action(snapshot: &SharedSnapshot, module_id: &str, action: String, now_ms: u64) {
7381    let _ = update_snapshot(snapshot, Some(module_id), |state| {
7382        state.health.last_action = Some(action);
7383        state.health.last_action_ms = Some(now_ms);
7384    });
7385}
7386
7387fn supervisor_health_status(status: HealthStatus) -> SupervisorHealthStatus {
7388    match status {
7389        HealthStatus::Ok => SupervisorHealthStatus::Ok,
7390        HealthStatus::Degraded => SupervisorHealthStatus::Degraded,
7391        HealthStatus::Failing => SupervisorHealthStatus::Failing,
7392    }
7393}
7394
7395/// Caps the metrics blob stored in the cached supervisor snapshot, which is
7396/// returned to every `supervisor.list` and `supervisor.health` caller.
7397///
7398/// This cap is deliberately NOT applied on the one-shot `supervisor.health_probe`
7399/// path: that request exists to return a module's complete metrics object, and
7400/// `ck health <module-id>` documents it as the way to see what the cached view
7401/// truncates. The asymmetry is the feature.
7402///
7403/// So a new caller must decide which side it is on rather than assume the cap is
7404/// universal. Reaching for it on a fresh-probe path would silently reintroduce
7405/// the truncation that path exists to avoid.
7406fn truncate_health_metrics(metrics: Option<Value>) -> Option<Value> {
7407    let metrics = metrics?;
7408    match serde_json::to_vec(&metrics) {
7409        Ok(encoded) if encoded.len() > MAX_HEALTH_METRICS_BYTES => Some(serde_json::json!({
7410            "truncated": true,
7411            "original_bytes": encoded.len(),
7412        })),
7413        Ok(_) | Err(_) => Some(metrics),
7414    }
7415}
7416
7417/// Spread health probes so a fleet-wide restart does not converge them.
7418///
7419/// The delay is derived from the module id and probe index rather than a random
7420/// source, so it is deterministic per module: a module keeps its own offset
7421/// across daemon restarts instead of re-rolling into a collision.
7422fn jittered_health_delay(module_id: &str, probe_index: u64, cadence: Duration) -> Duration {
7423    if cadence.is_zero() {
7424        return Duration::ZERO;
7425    }
7426    let cadence_ms = cadence.as_millis() as u64;
7427    // This early return is REDUNDANT, deliberately, and a mutation run will show
7428    // it surviving removal. Recording why here so the next person to notice does
7429    // not have to re-derive it:
7430    //
7431    // - It is unreachable in practice. `positive_millis` in daemon_config rejects
7432    //   a zero cadence and builds the Duration from whole milliseconds, so a
7433    //   sub-millisecond cadence cannot come from config.
7434    // - Even if reached it changes no answer. The `.max(1)` below makes the span
7435    //   1, and `hash % 1` is 0, so the fall-through returns `cadence` unchanged
7436    //   -- exactly what this returns.
7437    //
7438    // Kept as a guard against a future widening of the config parser (accepting
7439    // microseconds, say), which would make the sub-millisecond case reachable.
7440    // The `.max(1)` is the load-bearing half TODAY: remove it and the modulo
7441    // divides by zero. Remove this and nothing changes.
7442    if cadence_ms == 0 {
7443        return cadence;
7444    }
7445    // Note that this never returns less than one cadence, including for the FIRST
7446    // probe. So a freshly registered module reports health `unknown` for a full
7447    // cadence plus jitter -- 30-33s at the default -- no matter how quickly it is
7448    // ready to answer.
7449    //
7450    // That is a property of the supervisor's schedule, not of any module: an
7451    // operator watching a restart sees `unknown` and cannot tell it from a module
7452    // that is slow to warm. Measured on two unrelated modules, both flipping to
7453    // `ok` between 22s and 32s after restart.
7454    //
7455    // Left as-is because spreading the first probe is what keeps a fleet-wide
7456    // restart from firing fourteen simultaneous probes into a cold machine. The
7457    // alternative -- probe at t+0 and jitter only from the second onward -- trades
7458    // that thundering herd for a faster first reading.
7459    let jitter_span = (cadence_ms / 10).max(1);
7460    let hash = module_id.as_bytes().iter().fold(
7461        probe_index.wrapping_mul(0x9E37_79B9_7F4A_7C15),
7462        |acc, byte| {
7463            acc.wrapping_mul(1099511628211)
7464                .wrapping_add(u64::from(*byte))
7465        },
7466    );
7467    cadence + Duration::from_millis(hash % jitter_span)
7468}
7469
7470#[cfg(test)]
7471mod tests {
7472    use super::*;
7473
7474    #[test]
7475    fn registration_retirement_self_prefixed_owner_is_not_a_prefix_submodule() {
7476        let handle = SupervisorHandle::new();
7477        handle.set_spawn_nonce("prefix:owner", "owner-nonce".into());
7478        handle.set_reserved_prefixes("prefix:owner", &["prefix:".into()]);
7479        let owner = handle
7480            .reserved_hello_verification("prefix:owner", Some("owner-nonce"))
7481            .unwrap();
7482        assert!(owner.nonce_verified);
7483        assert!(
7484            owner.prefix_owner.is_none(),
7485            "an unreserved programmatic owner is not its own prefix child"
7486        );
7487        let child = handle
7488            .reserved_hello_verification("prefix:child", Some("owner-nonce"))
7489            .unwrap();
7490        assert!(child.nonce_verified);
7491        assert_eq!(child.prefix_owner.as_deref(), Some("prefix:owner"));
7492    }
7493
7494    #[test]
7495    fn readding_a_module_clears_its_rescan_removal_tombstone() {
7496        let handle = SupervisorHandle::new();
7497        let module_id = "readded-tombstone";
7498        handle.record_rescan_removal(module_id);
7499        assert!(handle.removal_tombstone_age_ms(module_id).is_some());
7500
7501        handle.apply_identity_configuration(&ModuleSpec {
7502            script: None,
7503            module_id: module_id.to_string(),
7504            program: PathBuf::from("/test/module"),
7505            args: Vec::new(),
7506            env: Vec::new(),
7507            reserved: false,
7508            reserved_prefixes: Vec::new(),
7509            protocol: ModuleProtocol::Subc,
7510            overlap: Default::default(),
7511            carry_containment: false,
7512        });
7513
7514        assert!(
7515            handle.removal_tombstone_age_ms(module_id).is_none(),
7516            "a re-added module must not retain a stale removal tombstone"
7517        );
7518    }
7519
7520    /// What one module's owner looked like from the control plane at the
7521    /// instant after its first process was spawned.
7522    #[derive(Debug, PartialEq, Eq)]
7523    struct OwnerInSpawnWindow {
7524        module_id: String,
7525        configured: bool,
7526        on_roster: bool,
7527        admission_refusal: Option<&'static str>,
7528    }
7529
7530    /// A supervised module's process can connect, register, sync its scopes
7531    /// and describe them as soon as it is spawned. A plain `spawn` does not put
7532    /// the module on the roster until afterward; configured supervision does
7533    /// so before spawning. In both cases the owner must
7534    /// already read as configured, so a scoped `route.open` against it is
7535    /// refused as retryable `scope_not_synced` and not as terminal
7536    /// `scope_not_live` ("will never sync").
7537    ///
7538    /// The hook runs just after each initial spawn attempt, before returning to
7539    /// the caller, so no race with a real child's registration is needed.
7540    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7541    async fn a_new_module_is_configured_before_its_first_process_can_register() {
7542        use crate::scopes::ScopeTable;
7543        use subc_protocol::{error_codes, scope::ScopeSelector, Principal};
7544
7545        let dir = cortexkit_test_support::ScratchDir::new("configured-before-spawn");
7546        let stub = |module_id: &str, program: PathBuf| ModuleSpec {
7547            script: None,
7548            module_id: module_id.to_string(),
7549            program,
7550            args: Vec::new(),
7551            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7552                .into_iter()
7553                .map(|key| (key.to_string(), dir.path().display().to_string()))
7554                .chain([("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())])
7555                .collect(),
7556            reserved: false,
7557            reserved_prefixes: Vec::new(),
7558            protocol: ModuleProtocol::Subc,
7559            overlap: Default::default(),
7560            carry_containment: false,
7561        };
7562        let live = super::terminal_history_tests::fake_aft_stub_path();
7563        let missing = dir.path().join("definitely-missing-module");
7564
7565        let handle = SupervisorHandle::new();
7566        let mut supervisor =
7567            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7568                .with_handle(handle.clone());
7569        let observed = Arc::new(Mutex::new(Vec::<OwnerInSpawnWindow>::new()));
7570        let hook_handle = handle.clone();
7571        let hook_observed = Arc::clone(&observed);
7572        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |module_id| {
7573            // Exactly what the control plane computes for a scoped route.open
7574            // naming this module as the owner of a scope it has not synced.
7575            let configured = hook_handle.is_configured(module_id);
7576            let selector = ScopeSelector::new(
7577                Principal::Reserved {
7578                    module_id: module_id.to_string(),
7579                },
7580                "s".to_string(),
7581                Some(1),
7582            );
7583            let carrier = Principal::Reserved {
7584                module_id: "carrier".to_string(),
7585            };
7586            let admission_refusal = match ScopeTable::new(Vec::<String>::new())
7587                .admit(&carrier, module_id, &selector, configured)
7588            {
7589                Ok(_) => None,
7590                Err(refusal) => Some(refusal.code),
7591            };
7592            hook_observed.lock().unwrap().push(OwnerInSpawnWindow {
7593                module_id: module_id.to_string(),
7594                configured,
7595                on_roster: hook_handle.get(module_id).is_some(),
7596                admission_refusal,
7597            });
7598        })));
7599
7600        let plain = supervisor.spawn(stub("plain", live.clone())).unwrap();
7601        let configured = supervisor
7602            .supervise_configured(stub("configured", live.clone()), true)
7603            .unwrap();
7604        let with_health = supervisor
7605            .supervise_configured_with_health(
7606                stub("with-health", live.clone()),
7607                true,
7608                HealthConfig::default(),
7609                None,
7610                RestartPolicy::default(),
7611            )
7612            .unwrap();
7613        // The failed-spawn path still puts the module on the roster (as
7614        // failed), so it is configured throughout.
7615        let failed = supervisor
7616            .supervise_configured_with_health(
7617                stub("failed-spawn", missing.clone()),
7618                true,
7619                HealthConfig::default(),
7620                None,
7621                RestartPolicy::default(),
7622            )
7623            .unwrap();
7624        // A failed plain `spawn` puts nothing on the roster, so its mark is
7625        // taken back once the spawn has failed.
7626        assert!(supervisor.spawn(stub("spawn-error", missing)).is_err());
7627
7628        let expected = [
7629            "plain",
7630            "configured",
7631            "with-health",
7632            "failed-spawn",
7633            "spawn-error",
7634        ]
7635        .into_iter()
7636        .map(|module_id| OwnerInSpawnWindow {
7637            module_id: module_id.to_string(),
7638            configured: true,
7639            on_roster: !matches!(module_id, "plain" | "spawn-error"),
7640            admission_refusal: Some(error_codes::SCOPE_NOT_SYNCED),
7641        })
7642        .collect::<Vec<_>>();
7643        assert_eq!(*observed.lock().unwrap(), expected);
7644
7645        for module_id in ["plain", "configured", "with-health", "failed-spawn"] {
7646            assert!(
7647                handle.get(module_id).is_some(),
7648                "{module_id} is on the roster"
7649            );
7650            assert!(
7651                handle.is_configured(module_id),
7652                "{module_id} stays configured"
7653            );
7654        }
7655        assert!(handle.get("spawn-error").is_none());
7656        assert!(
7657            !handle.is_configured("spawn-error"),
7658            "a plain spawn that failed must not leave its module marked configured"
7659        );
7660
7661        // Leaving the roster clears the mark with it.
7662        handle.retire("failed-spawn");
7663        assert!(!handle.is_configured("failed-spawn"));
7664
7665        for module in [plain, configured, with_health] {
7666            module.stop().await.unwrap();
7667        }
7668        drop(failed);
7669    }
7670
7671    /// A configured module reads as starting until the supervisor has admitted
7672    /// its first process (exec confirmed, identity durably recorded), even
7673    /// though that process is already running by then and can register over
7674    /// HELLO, which is what lists it in catalog.list. So a client that needs
7675    /// the supervisor state must wait for that state; seeing the module in
7676    /// the catalog does not mean supervisor.list already says running.
7677    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7678    async fn a_configured_module_reads_starting_while_its_first_process_already_runs() {
7679        let dir = cortexkit_test_support::ScratchDir::new("starting-while-spawned");
7680        let spec = ModuleSpec {
7681            script: None,
7682            module_id: "spawned-not-admitted".to_string(),
7683            program: super::terminal_history_tests::fake_aft_stub_path(),
7684            args: Vec::new(),
7685            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7686                .into_iter()
7687                .map(|key| (key.to_string(), dir.path().display().to_string()))
7688                .chain([("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())])
7689                .collect(),
7690            reserved: false,
7691            reserved_prefixes: Vec::new(),
7692            protocol: ModuleProtocol::Subc,
7693            overlap: Default::default(),
7694            carry_containment: false,
7695        };
7696        let handle = SupervisorHandle::new();
7697        let mut supervisor =
7698            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7699                .with_handle(handle.clone());
7700        let observed = Arc::new(Mutex::new(None));
7701        let hook_handle = handle.clone();
7702        let hook_observed = Arc::clone(&observed);
7703        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |module_id| {
7704            let state = hook_handle
7705                .get(module_id)
7706                .expect("a configured module is on the roster before it is spawned")
7707                .state()
7708                .unwrap();
7709            *hook_observed.lock().unwrap() = Some(state);
7710        })));
7711
7712        let module = supervisor.supervise_configured(spec, true).unwrap();
7713        assert_eq!(
7714            *observed.lock().unwrap(),
7715            Some(ModuleState::Starting),
7716            "between the spawn and its admission the supervisor still reports starting"
7717        );
7718        assert_eq!(module.state().unwrap(), ModuleState::Running);
7719        module.stop().await.unwrap();
7720    }
7721
7722    fn stale_process_snapshot(state: ModuleState, enabled: bool) -> SharedSnapshot {
7723        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(state, enabled)));
7724        update_snapshot(&snapshot, Some("stale-process-facts"), |snapshot| {
7725            snapshot.process_alive = true;
7726            snapshot.pid = Some(41);
7727            snapshot.spawned_at_ms = Some(42);
7728            snapshot.spawned_from = Some(PathBuf::from("/spawned/module"));
7729            snapshot.launch_spec_digest = Some(LaunchSpecDigest([0xA5; 32]));
7730            snapshot.spawned_file_identity = Some(SpawnedFileIdentity {
7731                device: 43,
7732                inode: 44,
7733                #[cfg(windows)]
7734                windows_image: None,
7735            });
7736        })
7737        .unwrap();
7738        snapshot
7739    }
7740
7741    fn assert_snapshot_process_facts_cleared(snapshot: &SharedSnapshot) {
7742        let snapshot = lock_snapshot(snapshot).unwrap();
7743        assert!(!snapshot.process_alive);
7744        assert_eq!(snapshot.pid, None);
7745        assert_eq!(snapshot.spawned_at_ms, None);
7746        assert_eq!(snapshot.spawned_from, None);
7747        assert_eq!(snapshot.launch_spec_digest, None);
7748        assert_eq!(snapshot.spawned_file_identity, None);
7749    }
7750
7751    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7752    async fn failed_enable_spawn_clears_preexisting_current_process_facts() {
7753        let supervisor =
7754            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7755        let mut runtime = supervisor.runtime_config();
7756        runtime.test_seed_stale_facts_before_enable_spawn = true;
7757        let snapshot = stale_process_snapshot(ModuleState::Disabled, false);
7758        let mut child = None;
7759        let spec = ModuleSpec {
7760            script: None,
7761            module_id: "failed-enable-clears-facts".to_string(),
7762            program: PathBuf::from("/definitely/missing/failed-enable-module"),
7763            args: Vec::new(),
7764            env: Vec::new(),
7765            reserved: false,
7766            reserved_prefixes: Vec::new(),
7767            protocol: ModuleProtocol::Subc,
7768            overlap: Default::default(),
7769            carry_containment: false,
7770        };
7771
7772        let result = set_child_enabled(
7773            &spec,
7774            &runtime,
7775            &supervisor.registry,
7776            &supervisor.process_liveness,
7777            &snapshot,
7778            &mut child,
7779            true,
7780            &runtime.failure_context(false),
7781        )
7782        .await;
7783
7784        assert!(matches!(result, Err(SuperviseError::Spawn { .. })));
7785        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
7786        assert_snapshot_process_facts_cleared(&snapshot);
7787    }
7788
7789    #[tokio::test]
7790    async fn start_revives_stranded_restarting_but_not_pending_backoff() {
7791        let supervisor =
7792            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7793        let runtime = supervisor.runtime_config();
7794        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
7795            ModuleState::Restarting,
7796            true,
7797        )));
7798        let spec = ModuleSpec {
7799            script: None,
7800            module_id: "start-stranded-restarting".to_string(),
7801            program: super::terminal_history_tests::fake_aft_stub_path(),
7802            args: Vec::new(),
7803            env: vec![("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())],
7804            reserved: false,
7805            reserved_prefixes: Vec::new(),
7806            protocol: ModuleProtocol::None,
7807            overlap: Default::default(),
7808            carry_containment: false,
7809        };
7810        let mut child = None;
7811        lock_snapshot(&snapshot).unwrap().respawn_pending = true;
7812        assert!(!super::set_child_enabled(
7813            &spec,
7814            &runtime,
7815            &Registry::default(),
7816            &supervisor.process_liveness,
7817            &snapshot,
7818            &mut child,
7819            true,
7820            &runtime.failure_context(false),
7821        )
7822        .await
7823        .unwrap());
7824        assert!(child.is_none());
7825        lock_snapshot(&snapshot).unwrap().respawn_pending = false;
7826        assert!(super::set_child_enabled(
7827            &spec,
7828            &runtime,
7829            &Registry::default(),
7830            &supervisor.process_liveness,
7831            &snapshot,
7832            &mut child,
7833            true,
7834            &runtime.failure_context(false),
7835        )
7836        .await
7837        .unwrap());
7838        assert_eq!(
7839            lock_snapshot(&snapshot).unwrap().state,
7840            ModuleState::Running
7841        );
7842        let mut child = child.unwrap();
7843        child.start_kill().unwrap();
7844        child.wait().await.unwrap();
7845    }
7846
7847    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7848    async fn failed_reload_spawn_clears_current_process_facts() {
7849        let supervisor =
7850            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7851        let mut runtime = supervisor.runtime_config();
7852        runtime.restart_policy = RestartPolicy::new(0, Duration::ZERO);
7853        let snapshot = stale_process_snapshot(ModuleState::Running, true);
7854        let mut child = None;
7855        let spec = ModuleSpec {
7856            script: None,
7857            module_id: "failed-reload-clears-facts".to_string(),
7858            program: PathBuf::from("/unused/failed-reload-module"),
7859            args: Vec::new(),
7860            env: Vec::new(),
7861            reserved: false,
7862            reserved_prefixes: Vec::new(),
7863            protocol: ModuleProtocol::Subc,
7864            overlap: Default::default(),
7865            carry_containment: false,
7866        };
7867
7868        let result = handle_reload_spawn_failure(
7869            &spec,
7870            &runtime,
7871            &supervisor.process_liveness,
7872            &snapshot,
7873            &mut child,
7874            "forced reload spawn failure".to_string(),
7875        )
7876        .await;
7877
7878        assert!(matches!(result, Err(SuperviseError::ReloadFailed { .. })));
7879        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
7880        assert_snapshot_process_facts_cleared(&snapshot);
7881    }
7882
7883    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7884    async fn dropping_a_module_with_an_active_monitor_clears_current_process_facts() {
7885        let supervisor =
7886            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7887        let snapshot = stale_process_snapshot(ModuleState::Running, true);
7888        let module = supervisor.supervised_module(
7889            ModuleSpec {
7890                script: None,
7891                module_id: "drop-clears-facts".to_string(),
7892                program: PathBuf::from("/unused/drop-module"),
7893                args: Vec::new(),
7894                env: Vec::new(),
7895                reserved: false,
7896                reserved_prefixes: Vec::new(),
7897                protocol: ModuleProtocol::Subc,
7898                overlap: Default::default(),
7899                carry_containment: false,
7900            },
7901            supervisor.runtime_config(),
7902            Arc::clone(&snapshot),
7903            None,
7904        );
7905        assert!(!module
7906            .inner
7907            .monitor
7908            .lock()
7909            .unwrap()
7910            .as_ref()
7911            .unwrap()
7912            .is_finished());
7913
7914        drop(module);
7915
7916        assert_eq!(
7917            lock_snapshot(&snapshot).unwrap().state,
7918            ModuleState::Stopped
7919        );
7920        assert_snapshot_process_facts_cleared(&snapshot);
7921    }
7922
7923    #[cfg(unix)]
7924    #[tokio::test]
7925    async fn rescan_preserves_running_protocol_until_respawn() {
7926        let dir = cortexkit_test_support::ScratchDir::new("rescan-protocol");
7927        let initial = ModuleSpec {
7928            script: None,
7929            module_id: "rescan-protocol".into(),
7930            program: PathBuf::from("/bin/sleep"),
7931            args: vec!["60".into()],
7932            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7933                .into_iter()
7934                .map(|key| (key.into(), dir.path().to_string_lossy().into_owned()))
7935                .collect(),
7936            reserved: false,
7937            reserved_prefixes: vec![],
7938            protocol: ModuleProtocol::None,
7939            overlap: Default::default(),
7940            carry_containment: false,
7941        };
7942        let supervisor =
7943            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7944        let module = supervisor.spawn(initial.clone()).unwrap();
7945        assert!(module.status().unwrap().live);
7946        let mut next = initial;
7947        next.protocol = ModuleProtocol::Subc;
7948        module
7949            .update_configuration(next.clone(), HealthConfig::default(), None)
7950            .await
7951            .unwrap();
7952        assert!(
7953            module.status().unwrap().live,
7954            "rescan must not require HELLO from the old non-wire process"
7955        );
7956        let runtime = supervisor.runtime_config();
7957        let action = on_child_exit(
7958            &next,
7959            RestartPolicy::default(),
7960            &supervisor.registry,
7961            &module.inner.snapshot,
7962            &runtime.terminal_ring,
7963            &runtime.spawn_events,
7964            &runtime.child_roster,
7965            ExitReport {
7966                kind: ExitKind::Clean,
7967                code: Some(0),
7968                signal: None,
7969                at_ms: unix_ms_now(),
7970            },
7971            true,
7972        )
7973        .await;
7974        assert!(
7975            matches!(action, NextAction::Restart { .. }),
7976            "the old non-wire process's clean exit must restart"
7977        );
7978        module.drain().await.unwrap();
7979    }
7980
7981    #[cfg(unix)]
7982    #[tokio::test]
7983    async fn orphan_identity_matches_path_names_and_shebang_interpreters() {
7984        use std::os::unix::fs::PermissionsExt;
7985        let dir = cortexkit_test_support::ScratchDir::new("spawn-image-identity");
7986        let script = dir.join("module.sh");
7987        std::fs::write(&script, "#!/bin/sh\nwhile :; do sleep 0.1; done\n").unwrap();
7988        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
7989        let record_path = dir.join("live-children.json");
7990        let supervisor =
7991            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7992                .with_live_children_record(&record_path);
7993        for (program, args) in [
7994            (PathBuf::from("sleep"), vec!["60".into()]),
7995            (script, vec![]),
7996        ] {
7997            let spec = ModuleSpec {
7998                script: None,
7999                module_id: "image-identity".into(),
8000                program: program.clone(),
8001                args,
8002                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
8003                    .into_iter()
8004                    .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
8005                    .collect(),
8006                reserved: false,
8007                reserved_prefixes: vec![],
8008                protocol: ModuleProtocol::None,
8009                overlap: Default::default(),
8010                carry_containment: false,
8011            };
8012            let module = supervisor.spawn(spec).unwrap();
8013            #[cfg(target_os = "macos")]
8014            {
8015                // SETEXEC confirmation is asynchronous; the orphan record must
8016                // identify the final image, never the intermediate trampoline.
8017                let deadline = Instant::now() + Duration::from_secs(5);
8018                while crate::live_children::read_record(&record_path)
8019                    .unwrap()
8020                    .iter()
8021                    .all(|entry| entry.executable.is_none())
8022                {
8023                    assert!(Instant::now() < deadline, "module image was not confirmed");
8024                    tokio::time::sleep(Duration::from_millis(5)).await;
8025                }
8026            }
8027            let entry = crate::live_children::read_record(&record_path)
8028                .unwrap()
8029                .pop()
8030                .unwrap();
8031            let observed = subc_os::Process::open(entry.pid)
8032                .unwrap()
8033                .unwrap()
8034                .observe()
8035                .unwrap();
8036            let verdict = crate::live_children::identity_verdict(&entry, entry.pid, &observed);
8037            module.drain().await.unwrap();
8038            assert_eq!(
8039                verdict,
8040                crate::live_children::IdentityVerdict::Matches,
8041                "program {program:?}: recorded {entry:?}, observed {observed:?}"
8042            );
8043        }
8044    }
8045
8046    #[cfg(unix)]
8047    fn http_fixture(
8048        dir: &std::path::Path,
8049        url: &str,
8050        threshold: u32,
8051    ) -> crate::daemon_config::ConfiguredModule {
8052        let path = dir.join("subc.jsonc");
8053        std::fs::write(&path, serde_json::json!({"version": 1, "modules": {"http-process": {
8054            "program": "/bin/sleep", "args": ["60"], "protocol": "none",
8055            "env": {"XDG_DATA_HOME":dir,"XDG_RUNTIME_DIR":dir,"XDG_CONFIG_HOME":dir},
8056            "health": {"http":url,"cadence_ms":20,"deadline_ms":200,"failure_threshold":threshold},
8057            "restart": {"backoff_ms":1,"max_backoff_ms":1}, "drain_timeout_ms":10
8058        }}}).to_string()).unwrap();
8059        crate::daemon_config::load(&path)
8060            .unwrap()
8061            .unwrap()
8062            .modules
8063            .pop()
8064            .unwrap()
8065    }
8066
8067    #[cfg(unix)]
8068    async fn wait_http_health(module: &SupervisedModule, status: SupervisorHealthStatus) {
8069        timeout(Duration::from_secs(5), async {
8070            loop {
8071                if module.status().unwrap().health.status == status {
8072                    break;
8073                }
8074                sleep(Duration::from_millis(5)).await;
8075            }
8076        })
8077        .await
8078        .unwrap_or_else(|_| {
8079            panic!(
8080                "expected {status:?}, got {:?}",
8081                module.status().unwrap().health
8082            )
8083        });
8084    }
8085
8086    #[cfg(unix)]
8087    #[tokio::test]
8088    async fn http_health_status_flips_ok_failing_ok() {
8089        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8090        let dir = cortexkit_test_support::ScratchDir::new("http-status-flips");
8091        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8092        let status = Arc::new(std::sync::atomic::AtomicU16::new(200));
8093        let serving_status = status.clone();
8094        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8095        let server = tokio::spawn(async move {
8096            loop {
8097                let (mut stream, _) = listener.accept().await.unwrap();
8098                let mut request = [0u8; 2048];
8099                let count = stream.read(&mut request).await.unwrap();
8100                assert!(count > 0, "a probe must send an HTTP request");
8101                let code = serving_status.load(std::sync::atomic::Ordering::SeqCst);
8102                let body = if code == 200 {
8103                    "ready"
8104                } else {
8105                    "{\"status\":\"unavailable\",\"error\":\"scratch failure\"}"
8106                };
8107                let response = format!("HTTP/1.1 {code} scratch\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
8108                let _ = stream.write_all(response.as_bytes()).await;
8109            }
8110        });
8111        let configured = http_fixture(&dir, &url, 1000);
8112        let module =
8113            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8114                .supervise_configured_with_health(
8115                    configured.module_spec(),
8116                    true,
8117                    configured.health,
8118                    configured.drain_timeout_ms,
8119                    configured.restart,
8120                )
8121                .unwrap();
8122        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8123        status.store(503, std::sync::atomic::Ordering::SeqCst);
8124        wait_http_health(&module, SupervisorHealthStatus::Failing).await;
8125        assert!(module
8126            .status()
8127            .unwrap()
8128            .health
8129            .detail
8130            .unwrap()
8131            .contains("scratch failure"));
8132        status.store(200, std::sync::atomic::Ordering::SeqCst);
8133        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8134        assert_eq!(module.status().unwrap().health.consecutive_failures, 0);
8135        let before = module.status().unwrap();
8136        let (spec, mut health) = module.configuration().unwrap();
8137        health.http = None;
8138        module
8139            .update_configuration(spec.clone(), health.clone(), Some(10))
8140            .await
8141            .unwrap();
8142        wait_http_health(&module, SupervisorHealthStatus::Unknown).await;
8143        health.http = Some(url);
8144        module
8145            .update_configuration(spec, health, Some(10))
8146            .await
8147            .unwrap();
8148        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8149        assert_eq!(
8150            module.status().unwrap().pid,
8151            before.pid,
8152            "changing a probe must apply live, not restart its process"
8153        );
8154        let (spec, mut health) = module.configuration().unwrap();
8155        health.failure_threshold = 2;
8156        module
8157            .update_configuration(spec, health, Some(10))
8158            .await
8159            .unwrap();
8160        status.store(503, std::sync::atomic::Ordering::SeqCst);
8161        timeout(Duration::from_secs(5), async {
8162            while module.status().unwrap().spawn_generation == before.spawn_generation {
8163                sleep(Duration::from_millis(5)).await;
8164            }
8165        })
8166        .await
8167        .expect("sustained HTTP 503 responses must trigger the health restart policy");
8168        module.drain().await.unwrap();
8169        server.abort();
8170    }
8171
8172    #[cfg(unix)]
8173    #[tokio::test]
8174    async fn http_health_replacement_recovers_after_one_restart() {
8175        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8176        let dir = cortexkit_test_support::ScratchDir::new("http-replacement-recovers");
8177        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8178        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8179        let mut configured = http_fixture(&dir, &url, 2);
8180        configured.restart.max_restarts = 2;
8181        let module =
8182            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8183                .supervise_configured_with_health(
8184                    configured.module_spec(),
8185                    true,
8186                    configured.health,
8187                    configured.drain_timeout_ms,
8188                    configured.restart,
8189                )
8190                .unwrap();
8191        let first_generation = module.status().unwrap().spawn_generation;
8192        let observed = module.clone();
8193        let (healthy_tx, mut healthy_rx) = mpsc::channel(8);
8194        let server = tokio::spawn(async move {
8195            let mut generation = first_generation;
8196            let mut probes = 0;
8197            loop {
8198                let (mut stream, _) = listener.accept().await.unwrap();
8199                let mut request = [0; 2048];
8200                assert!(stream.read(&mut request).await.unwrap() > 0);
8201                let current = observed.status().unwrap().spawn_generation;
8202                if current != generation {
8203                    generation = current;
8204                    probes = 0;
8205                }
8206                probes += 1;
8207                // The original process never recovers. Each replacement has one
8208                // transient miss, then answers successfully for its remaining life.
8209                let healthy = generation != first_generation && probes > 1;
8210                let code = if healthy { 200 } else { 503 };
8211                let response = format!(
8212                    "HTTP/1.1 {code} scratch\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
8213                );
8214                let _ = stream.write_all(response.as_bytes()).await;
8215                if healthy {
8216                    healthy_tx.send(()).await.unwrap();
8217                }
8218            }
8219        });
8220        timeout(Duration::from_secs(5), async {
8221            let mut healthy_probes = 0;
8222            loop {
8223                if module.state().unwrap() == ModuleState::Failed {
8224                    break;
8225                }
8226                while healthy_rx.try_recv().is_ok() {
8227                    healthy_probes += 1;
8228                }
8229                if healthy_probes >= 3
8230                    && module.status().unwrap().health.status == SupervisorHealthStatus::Ok
8231                {
8232                    break;
8233                }
8234                sleep(Duration::from_millis(5)).await;
8235            }
8236        })
8237        .await
8238        .expect("the replacement must settle healthy without exhausting its restart budget");
8239        let status = module.status().unwrap();
8240        module.drain().await.unwrap();
8241        server.abort();
8242        assert_eq!(status.state, ModuleState::Running);
8243        assert_eq!(status.health.status, SupervisorHealthStatus::Ok);
8244        assert_eq!(status.health.consecutive_failures, 0);
8245        assert_eq!(status.lifetime_restarts, 1);
8246        assert_eq!(status.restart_count, 1);
8247    }
8248
8249    #[cfg(unix)]
8250    #[tokio::test]
8251    async fn http_health_sustained_failure_exhausts_restart_budget() {
8252        use std::collections::BTreeMap;
8253        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8254        let dir = cortexkit_test_support::ScratchDir::new("http-health-budget");
8255        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8256        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8257        let mut configured = http_fixture(&dir, &url, 2);
8258        configured.restart.max_restarts = 2;
8259        let module =
8260            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8261                .supervise_configured_with_health(
8262                    configured.module_spec(),
8263                    true,
8264                    configured.health,
8265                    configured.drain_timeout_ms,
8266                    configured.restart,
8267                )
8268                .unwrap();
8269        let observed = module.clone();
8270        let probes = Arc::new(Mutex::new(BTreeMap::<u64, u32>::new()));
8271        let served = probes.clone();
8272        let server = tokio::spawn(async move {
8273            loop {
8274                let (mut stream, _) = listener.accept().await.unwrap();
8275                let mut request = [0; 2048];
8276                assert!(stream.read(&mut request).await.unwrap() > 0);
8277                *served
8278                    .lock()
8279                    .unwrap()
8280                    .entry(observed.status().unwrap().spawn_generation)
8281                    .or_default() += 1;
8282                let _ = stream
8283                    .write_all(b"HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
8284                    .await;
8285            }
8286        });
8287        timeout(Duration::from_secs(5), async {
8288            while module.state().unwrap() != ModuleState::Failed {
8289                sleep(Duration::from_millis(5)).await;
8290            }
8291        })
8292        .await
8293        .expect("sustained failures must still exhaust the health restart budget");
8294        let status = module.status().unwrap();
8295        server.abort();
8296        assert_eq!(status.restart_count, 2);
8297        assert_eq!(status.lifetime_restarts, 2);
8298        assert!(!status.process_alive);
8299        assert_eq!(
8300            probes.lock().unwrap().values().copied().collect::<Vec<_>>(),
8301            vec![2, 2, 2]
8302        );
8303    }
8304
8305    #[cfg(unix)]
8306    #[tokio::test]
8307    async fn spawn_clears_the_previous_process_health() {
8308        let dir = cortexkit_test_support::ScratchDir::new("spawn-fresh-health");
8309        let mut configured = http_fixture(&dir, "http://127.0.0.1:1/healthz", 2);
8310        configured.health.cadence = Duration::from_secs(3600);
8311        let module =
8312            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8313                .supervise_configured_with_health(
8314                    configured.module_spec(),
8315                    false,
8316                    configured.health,
8317                    configured.drain_timeout_ms,
8318                    configured.restart,
8319                )
8320                .unwrap();
8321        update_snapshot(&module.inner.snapshot, Some(module.module_id()), |state| {
8322            state.health.status = SupervisorHealthStatus::Unresponsive;
8323            state.health.consecutive_failures = 3;
8324            state.health.detail = Some("old process refused connections".into());
8325            state.health.metrics = Some(serde_json::json!({"old": true}));
8326            state.health.last_probe_ms = Some(123);
8327            state.health.last_action = Some("restart".into());
8328            state.health.last_action_ms = Some(124);
8329        })
8330        .unwrap();
8331        module.set_enabled(true).await.unwrap();
8332        let health = module.status().unwrap().health;
8333        module.drain().await.unwrap();
8334        assert_eq!(health.consecutive_failures, 0);
8335        assert_eq!(health.status, SupervisorHealthStatus::Unknown);
8336        assert_eq!(health.detail, None);
8337        assert_eq!(health.metrics, None);
8338        assert_eq!(health.last_probe_ms, None);
8339        assert_eq!(health.last_action.as_deref(), Some("restart"));
8340        assert_eq!(health.last_action_ms, Some(124));
8341    }
8342
8343    #[cfg(unix)]
8344    #[tokio::test]
8345    async fn http_health_no_listener_restarts_after_consecutive_failures() {
8346        let dir = cortexkit_test_support::ScratchDir::new("http-refused");
8347        let unused = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8348        let url = format!("http://{}/healthz", unused.local_addr().unwrap());
8349        drop(unused);
8350        let configured = http_fixture(&dir, &url, 2);
8351        let module =
8352            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8353                .supervise_configured_with_health(
8354                    configured.module_spec(),
8355                    true,
8356                    configured.health,
8357                    configured.drain_timeout_ms,
8358                    configured.restart,
8359                )
8360                .unwrap();
8361        let before = module.status().unwrap().spawn_generation;
8362        timeout(Duration::from_secs(5), async {
8363            loop {
8364                let status = module.status().unwrap();
8365                if status.spawn_generation > before {
8366                    assert!(status.lifetime_restarts > 0);
8367                    break;
8368                }
8369                sleep(Duration::from_millis(5)).await;
8370            }
8371        })
8372        .await
8373        .expect("sustained HTTP refusal must trigger the health restart policy");
8374        module.drain().await.unwrap();
8375    }
8376
8377    #[cfg(unix)]
8378    #[tokio::test]
8379    async fn http_health_timeout_honours_deadline() {
8380        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8381        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8382        let server = tokio::spawn(async move {
8383            let _held = listener.accept().await.unwrap();
8384            std::future::pending::<()>().await;
8385        });
8386        let error = timeout(
8387            Duration::from_secs(1),
8388            probe_http_health(&url, Duration::from_millis(10)),
8389        )
8390        .await
8391        .expect("the probe must enforce its own deadline")
8392        .unwrap_err();
8393        server.abort();
8394        assert!(error.to_string().contains("timed out"));
8395    }
8396
8397    #[cfg(unix)]
8398    #[tokio::test]
8399    async fn http_health_localhost_reaches_an_ipv6_only_listener() {
8400        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8401        let listener = tokio::net::TcpListener::bind("[::1]:0").await.unwrap();
8402        let url = format!(
8403            "http://localhost:{}/healthz",
8404            listener.local_addr().unwrap().port()
8405        );
8406        let server = tokio::spawn(async move {
8407            let (mut stream, _) = listener.accept().await.unwrap();
8408            let mut request = [0u8; 2048];
8409            assert!(stream.read(&mut request).await.unwrap() > 0);
8410            stream
8411                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
8412                .await
8413                .unwrap();
8414        });
8415        // The deadline only bounds a hang. A probe that never tried the IPv6
8416        // address would be refused on 127.0.0.1 and fail at once, so a longer
8417        // deadline does not weaken the assertion; one second timed out under a
8418        // loaded parallel test run.
8419        assert_eq!(
8420            probe_http_health(&url, Duration::from_secs(10))
8421                .await
8422                .unwrap()
8423                .status,
8424            HealthStatus::Ok
8425        );
8426        server.await.unwrap();
8427    }
8428
8429    #[cfg(unix)]
8430    #[tokio::test]
8431    async fn http_health_timeout_keeps_partial_status_and_body() {
8432        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8433        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8434        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8435        let server = tokio::spawn(async move {
8436            let (mut stream, _) = listener.accept().await.unwrap();
8437            let mut request = [0u8; 2048];
8438            assert!(stream.read(&mut request).await.unwrap() > 0);
8439            stream
8440                .write_all(
8441                    b"HTTP/1.1 503 Unavailable\r\nContent-Length: 100\r\n\r\npartial diagnostic",
8442                )
8443                .await
8444                .unwrap();
8445            std::future::pending::<()>().await;
8446        });
8447        let error = probe_http_health(&url, Duration::from_secs(1))
8448            .await
8449            .unwrap_err()
8450            .to_string();
8451        server.abort();
8452        assert!(
8453            error.contains("timed out")
8454                && error.contains("503 Unavailable")
8455                && error.contains("partial diagnostic"),
8456            "{error}"
8457        );
8458    }
8459
8460    #[cfg(unix)]
8461    #[tokio::test]
8462    async fn http_health_diagnostic_body_is_bounded_to_200_bytes() {
8463        use tokio::io::{AsyncReadExt, AsyncWriteExt};
8464        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8465        let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8466        let server = tokio::spawn(async move {
8467            let (mut stream, _) = listener.accept().await.unwrap();
8468            let mut request = [0u8; 2048];
8469            assert!(stream.read(&mut request).await.unwrap() > 0);
8470            let body = format!("{}not-in-diagnostic", "x".repeat(400));
8471            let response = format!(
8472                "HTTP/1.1 503 Unavailable\r\nContent-Length: {}\r\n\r\n{body}",
8473                body.len()
8474            );
8475            stream.write_all(response.as_bytes()).await.unwrap();
8476        });
8477        let error = probe_http_health(&url, Duration::from_secs(1))
8478            .await
8479            .unwrap_err()
8480            .to_string();
8481        server.await.unwrap();
8482        assert!(error.ends_with(&"x".repeat(200)), "{error}");
8483        assert_eq!(error.split(": ").last().unwrap().len(), 200);
8484        assert!(!error.contains("not-in-diagnostic"));
8485    }
8486
8487    #[cfg(unix)]
8488    #[tokio::test]
8489    async fn http_health_real_nats_server_monitoring() {
8490        if std::process::Command::new("nats-server")
8491            .arg("--version")
8492            .env("XDG_DATA_HOME", std::env::temp_dir())
8493            .env("XDG_RUNTIME_DIR", std::env::temp_dir())
8494            .env("XDG_CONFIG_HOME", std::env::temp_dir())
8495            .output()
8496            .is_err()
8497        {
8498            eprintln!(
8499                "skipped: http_health_real_nats_server_monitoring (nats-server is not on PATH)"
8500            );
8501            return;
8502        }
8503        let dir = cortexkit_test_support::ScratchDir::new("nats-http-monitoring");
8504        let monitor = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8505        let port = monitor.local_addr().unwrap().port();
8506        let client = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8507        let client_port = client.local_addr().unwrap().port();
8508        let config = dir.join("server.conf");
8509        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();
8510        let mut configured = http_fixture(&dir, &format!("http://127.0.0.1:{port}/healthz"), 1000);
8511        configured.program = PathBuf::from("nats-server");
8512        configured.args = vec!["-c".into(), config.to_string_lossy().into_owned()];
8513        drop(monitor);
8514        drop(client);
8515        let module =
8516            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8517                .supervise_configured_with_health(
8518                    configured.module_spec(),
8519                    true,
8520                    configured.health,
8521                    configured.drain_timeout_ms,
8522                    configured.restart,
8523                )
8524                .unwrap();
8525        wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8526        module.drain().await.unwrap();
8527    }
8528
8529    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8530    async fn configuration_update_does_not_replace_captured_running_process_facts() {
8531        let supervisor =
8532            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
8533        let snapshot = stale_process_snapshot(ModuleState::Running, true);
8534        let initial = ModuleSpec {
8535            script: None,
8536            module_id: "rescan-preserves-spawn-facts".to_string(),
8537            program: PathBuf::from("/spawned/module"),
8538            args: Vec::new(),
8539            env: Vec::new(),
8540            reserved: false,
8541            reserved_prefixes: Vec::new(),
8542            protocol: ModuleProtocol::Subc,
8543            overlap: Default::default(),
8544            carry_containment: false,
8545        };
8546        let module = supervisor.supervised_module(
8547            initial.clone(),
8548            supervisor.runtime_config(),
8549            snapshot,
8550            None,
8551        );
8552        let before = module.status().unwrap();
8553        let mut replacement = initial;
8554        replacement.program = PathBuf::from("/rescanned/replacement-module");
8555
8556        module
8557            .update_configuration(replacement, HealthConfig::default(), None)
8558            .await
8559            .unwrap();
8560
8561        let after = module.status().unwrap();
8562        assert_eq!(after.pid, before.pid);
8563        assert_eq!(after.spawned_at_ms, before.spawned_at_ms);
8564        assert_eq!(after.spawned_from, before.spawned_from);
8565        drop(module);
8566    }
8567}
8568
8569fn unix_ms_now() -> u64 {
8570    SystemTime::now()
8571        .duration_since(UNIX_EPOCH)
8572        .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
8573        .unwrap_or(0)
8574}
8575
8576async fn supervise_loop(
8577    mut spec: ModuleSpec,
8578    mut runtime: SupervisorRuntimeConfig,
8579    registry: Arc<Registry>,
8580    process_liveness: Arc<SupervisorProcessLiveness>,
8581    snapshot: SharedSnapshot,
8582    mut child: Option<SupervisedChild>,
8583    mut commands: mpsc::Receiver<SupervisorCommand>,
8584) {
8585    let mut health_probe = HealthProbeRuntime::default();
8586    // Registry writes (including embedded callers) notify this module only.
8587    // Subscribe before the first refresh; watch retains changes that arrive
8588    // while commands or probes are running. No polling fallback is needed.
8589    let mut registration_changes = match registry.subscribe_module_changes(&spec.module_id) {
8590        Ok(changes) => Some(changes),
8591        Err(err) => {
8592            // A poisoned registry cannot accept further writes, so it cannot
8593            // recover via a timer. Keep exit and command handling alive.
8594            warn!(module_id = %spec.module_id, error = %err, "health prober could not subscribe to registry");
8595            None
8596        }
8597    };
8598    // All restart backoffs run here, including health and operator requests.
8599    // While one is pending the loop serves commands, so disable or drain can
8600    // cancel the replacement without spawning a process just to stop it.
8601    let mut pending_respawn: Option<PendingRespawn> = None;
8602    // Commands a swap handed back to run next (see `swap::SwapEnd`). Served
8603    // before anything else so a stop that interrupted a swap runs at once.
8604    let mut requeued: VecDeque<SupervisorCommand> = VecDeque::new();
8605    let mut previous_instance_recheck = tokio::time::interval_at(
8606        Instant::now() + Duration::from_secs(5),
8607        Duration::from_secs(5),
8608    );
8609    previous_instance_recheck.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
8610    'supervision: loop {
8611        #[cfg(test)]
8612        {
8613            lock_snapshot(&snapshot).unwrap().actor_select = None;
8614        }
8615        #[cfg(target_os = "macos")]
8616        if let Some(active) = child.as_mut() {
8617            active.confirm_privacy_exec().await;
8618        }
8619        if let Some(scheduled) = runtime
8620            .scheduled_respawn
8621            .lock()
8622            .unwrap_or_else(|p| p.into_inner())
8623            .take()
8624        {
8625            runtime.recovery_is_daemon = scheduled.daemon_initiated;
8626            pending_respawn = Some(scheduled);
8627        }
8628        if pending_respawn.is_some() && (child.is_some() || !respawn_still_pending(&snapshot)) {
8629            pending_respawn = None;
8630            cancel_deferred_reload(
8631                &runtime,
8632                &spec.module_id,
8633                "respawn cancelled by a supervisor command",
8634            );
8635        }
8636        if child.is_none()
8637            && pending_respawn.is_none()
8638            && lock_snapshot(&snapshot).is_ok_and(|state| state.waiting_for_previous_pid.is_none())
8639        {
8640            cancel_deferred_reload(
8641                &runtime,
8642                &spec.module_id,
8643                "respawn cancelled before a replacement was spawned",
8644            );
8645            let mut stranded = false;
8646            let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8647                state.respawn_pending = false;
8648                state.coalesced_restart_pending = false;
8649                if matches!(
8650                    state.state,
8651                    ModuleState::Restarting
8652                        | ModuleState::Starting
8653                        | ModuleState::Draining
8654                        | ModuleState::Unresponsive
8655                ) {
8656                    error!(module_id = %spec.module_id, state = ?state.state,
8657                        "supervision operation ended without a child or pending respawn; marking failed so start can retry");
8658                    stranded = true;
8659                }
8660            });
8661            if stranded {
8662                fail_snapshot(
8663                    &snapshot,
8664                    Some(&spec.module_id),
8665                    None,
8666                    &runtime.failure_context(runtime.recovery_is_daemon),
8667                );
8668            }
8669        }
8670        if child.is_none()
8671            && (runtime.child_roster.is_closed()
8672                || pending_respawn.is_none()
8673                || !lock_snapshot(&snapshot)
8674                    .is_ok_and(|state| state.enabled && state.state == ModuleState::Restarting))
8675        {
8676            containment::terminate(&runtime.child_roster.containment).await;
8677        }
8678        if let Some(command) = requeued.pop_front() {
8679            if !handle_supervisor_command(
8680                command,
8681                &mut spec,
8682                &mut runtime,
8683                &registry,
8684                &process_liveness,
8685                &snapshot,
8686                &mut child,
8687                &mut commands,
8688                &mut requeued,
8689            )
8690            .await
8691            {
8692                containment::terminate(&runtime.child_roster.containment).await;
8693                return;
8694            }
8695            if child.is_some() || !respawn_still_pending(&snapshot) {
8696                pending_respawn = None;
8697                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8698                    state.respawn_pending = false
8699                });
8700            }
8701            continue;
8702        }
8703        if child.is_some() {
8704            runtime.recovery_is_daemon = true;
8705            #[cfg(test)]
8706            {
8707                lock_snapshot(&snapshot).unwrap().actor_turns += 1;
8708            }
8709            health_probe.refresh_registration(&spec, &runtime, &registry, &snapshot);
8710            let active = child.as_mut().expect("child checked above");
8711            if active.registered_since_spawn() {
8712                if let Some(delivery) = &runtime.config_delivery {
8713                    delivery.queue_registered(
8714                        &spec.module_id,
8715                        runtime.forwarding.as_ref(),
8716                        &registry,
8717                        active,
8718                    );
8719                }
8720            }
8721            if runtime.child_roster.is_closed() || !active.awaiting_registration() {
8722                active.registration_deadline = None;
8723            }
8724            let registration_deadline = active.registration_deadline;
8725            let no_checks = runtime.health.http.is_none()
8726                && (running_protocol(&spec, &snapshot) == ModuleProtocol::None
8727                    || (health_probe.registered_connection.is_some() && !health_probe.advertised));
8728            let uptime_reset = lock_snapshot(&snapshot).ok().and_then(|mut state| {
8729                state
8730                    .failed_retry
8731                    .uptime_reset_at(no_checks, runtime.restart_policy.window)
8732            });
8733            let wake_at = match (health_probe.wake_at(), uptime_reset) {
8734                (probe, Some(reset)) => Some(probe.map_or(reset, |probe| probe.min(reset))),
8735                (probe, None) => probe,
8736            };
8737            let wake_at = match (wake_at, registration_deadline) {
8738                (Some(wake), Some(register)) => Some(wake.min(register)),
8739                (wake, register) => wake.or(register),
8740            };
8741            #[cfg(test)]
8742            let wake_after = wake_at.map(|at| at.saturating_duration_since(Instant::now()));
8743            let probe_sleep = supervisor_sleep(wake_at);
8744            tokio::pin!(probe_sleep);
8745            // A `protocol: "none"` child (a plain process that never registers
8746            // over the subc wire, such as nats-server) with no HTTP health
8747            // check has nothing to probe, so it waits only for its exit or a
8748            // supervisor command. A rescan that adds an HTTP check is a command.
8749            let wire_child = running_protocol(&spec, &snapshot) == ModuleProtocol::Subc;
8750            #[cfg(test)]
8751            {
8752                let registration_pending = wire_child
8753                    && registration_changes
8754                        .as_ref()
8755                        .is_some_and(|changes| changes.has_changed().unwrap());
8756                let mut state = lock_snapshot(&snapshot).unwrap();
8757                state.actor_select = (!registration_pending).then_some(ActorSelectCheckpoint {
8758                    generation: state.spawn_generation,
8759                    turn: state.actor_turns,
8760                    registered_connection: health_probe.registered_connection,
8761                    next_probe_at: health_probe.next_probe_at,
8762                    wake_after,
8763                });
8764            }
8765            let registration = active
8766                .awaiting_registration()
8767                .then(|| active.registration_spawn.clone())
8768                .flatten();
8769            #[cfg(all(test, target_os = "linux"))]
8770            let registration_before_exit = !runtime.child_roster.admission_event_for_test(
8771                &spec.module_id,
8772                "observe_registration_before_exit",
8773                Some(active.pid),
8774            ) && registration.is_some();
8775            #[cfg(not(all(test, target_os = "linux")))]
8776            let registration_before_exit = false;
8777            #[cfg(all(test, target_os = "linux"))]
8778            let registration_child_is_running = |child: &mut SupervisedChild| {
8779                // Model the interval after SIGKILL is accepted but before the
8780                // child becomes waitable, without delaying the actual kill.
8781                registration_before_exit || registration_child_is_running(child)
8782            };
8783            let registration_failed = async {
8784                match &registration {
8785                    Some(spawn) => spawn.wait_registration_failure().await,
8786                    None => std::future::pending().await,
8787                }
8788            };
8789            let active_child = child.as_mut().expect("child checked above");
8790            tokio::select! {
8791                _ = registration_failed => {
8792                    if !active_child.registered_since_spawn() && registration_child_is_running(active_child) {
8793                        active_child.registration_deadline = None;
8794                        active_child.spawn_failure = Some("registration_channel_closed".into());
8795                        if let Err(error) = stop_unregistered_child(active_child).await {
8796                            fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
8797                                &runtime.spawn_events, format!("registration_channel_closed: {error}"),
8798                                &runtime.failure_context(true));
8799                            child = None;
8800                        }
8801                    }
8802                    continue;
8803                }
8804                wait_result = active_child.wait(), if !registration_before_exit => {
8805                    if let Ok(mut state) = lock_snapshot(&snapshot) {
8806                        state.failed_retry.uptime_reset_at(no_checks, runtime.restart_policy.window);
8807                    }
8808                    #[cfg(test)]
8809                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8810                    // Every arm below that gives up on the CHILD must keep the
8811                    // supervision task itself alive (child = None, loop
8812                    // continues into command-serving mode). Returning here
8813                    // closes the command channel, which makes the module
8814                    // permanently unrestartable in-band: a clean child exit
8815                    // of an enabled module once wedged the fleet this way
8816                    // ('supervisor command channel is closed') and required a
8817                    // full daemon restart to recover.
8818                    let exit_report = match wait_result {
8819                        Ok(status) => classify_reaped_child_exit(&snapshot, active_child, &status),
8820                        Err(err) => {
8821                            active_child.drain_stderr(&spec.module_id).await;
8822                            fail_after_wait_error(
8823                                &spec.module_id,
8824                                &snapshot,
8825                                &runtime.terminal_ring,
8826                                &runtime.spawn_events,
8827                                format!("failed to wait for supervised module: {err}"),
8828                            &runtime.failure_context(true),
8829                            );
8830                            untrack_if_registration_released(
8831                                &process_liveness,
8832                                &registry,
8833                                &spec.module_id,
8834                                &snapshot,
8835                            );
8836                            error!(module_id = %spec.module_id, error = %err, "failed to wait for supervised module");
8837                            child = None;
8838                            continue;
8839                        }
8840                    };
8841                    active_child.drain_stderr(&spec.module_id).await;
8842
8843                    let delivery=runtime.config_delivery.clone();
8844                    let exited_spawn=active_child.spawned_at;
8845                    let spawn=active_child.config_delivery.clone();
8846                    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())));
8847                    let module_id=spec.module_id.clone();
8848                    // Publication may own the store mutex for local durable I/O.
8849                    // Keep commands selectable until the child's exit is recorded;
8850                    // no respawn disposition is chosen before that observation.
8851                    let observed=async move {
8852                        if let Some(delivery)=delivery {
8853                            delivery.0.on_blocking(move |owner| {
8854                                if let Some(spawn)=spawn { owner.delivery_child_exited(&spawn)?; }
8855                                if let Some((base,identity))=refusal {owner.record_program_refusal(&module_id,&base,identity)?;}
8856                                Ok(())
8857                            }).await
8858                        } else {Ok(())}
8859                    };
8860                    tokio::pin!(observed);
8861                    loop {
8862                        tokio::select! {
8863                            result=&mut observed=>{
8864                                if let Err(error)=result {warn!(module_id=%spec.module_id,%error,"configuration exit observation failed");}
8865                                break;
8866                            }
8867                            command=commands.recv()=>{
8868                                let Some(command)=command else {containment::terminate(&runtime.child_roster.containment).await;return;};
8869                                let deferred=||SuperviseError::ConfigDeliveryDeferred {module_id:spec.module_id.clone()};
8870                                let command=match command {
8871                                    SupervisorCommand::Restart {reply,..}|SupervisorCommand::Reload {reply,..}=>{let _=reply.send(Err(deferred()));continue;}
8872                                    SupervisorCommand::Swap {reply,..}=>{let _=reply.send(Err(deferred()));continue;}
8873                                    command @ (SupervisorCommand::ConfigApplyRestart {..}|SupervisorCommand::ConfigPolicyProbe {..}|SupervisorCommand::ConfigDeliveryFailed {..})=>{requeued.push_back(command);continue;}
8874                                    command=>command,
8875                                };
8876                                if !handle_supervisor_command(command,&mut spec,&mut runtime,&registry,&process_liveness,&snapshot,&mut child,&mut commands,&mut requeued).await {
8877                                    containment::terminate(&runtime.child_roster.containment).await;return;
8878                                }
8879                                if child.as_ref().is_none_or(|current|current.spawned_at!=exited_spawn) {continue 'supervision;}
8880                            }
8881                        }
8882                    }
8883                    let active_child=child.as_mut().expect("exit observation retained its child");
8884                    // An unavailable image can race the program's own exit.
8885                    // Only the admission kill is budget-free; another exit must
8886                    // retain its ordinary crash/clean-exit accounting.
8887                    let admission_kill = admission_exit::is_admission_kill(active_child.admission_kill_sent, &exit_report);
8888                    let deferred_spawn=admission_kill && active_child.spawn_failure.as_deref().is_some_and(|detail|detail.starts_with("config_delivery_deferred:"));
8889                    let refused_program = active_child.live_program_binding.as_ref().is_some_and(|binding| binding.is_refused());
8890                    let exit_held = !deferred_spawn && (refused_program || runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.exit_is_held(&spec.module_id)));
8891                    let parked = exit_held && (!refused_program || active_child.admission_base.is_some())
8892                        && try_park_config_attempt(&spec, &runtime, &snapshot, &runtime.failure_context(true),
8893                            if refused_program { active_child.admission_base.as_ref() } else { None })
8894                            .unwrap_or_else(|error| { warn!(module_id=%spec.module_id, %error, "exit hold could not be recorded; using ordinary exit accounting"); false });
8895                    let next = if deferred_spawn {
8896                        record_terminal_with_detail(&spec.module_id,&runtime.terminal_ring,&runtime.spawn_events,&exit_report,TerminalDisposition::Restarting,active_child.spawn_failure.clone());
8897                        let _=update_snapshot(&snapshot,Some(&spec.module_id),|state| {
8898                            state.state=ModuleState::Restarting;
8899                            clear_current_process_facts(state);
8900                            state.last_exit=Some(exit_report.clone());
8901                        });
8902                        NextAction::Restart {schedule:None}
8903                    } else if parked {
8904                        record_terminal_with_detail(&spec.module_id, &runtime.terminal_ring, &runtime.spawn_events, &exit_report, TerminalDisposition::Stopped, active_child.spawn_failure.clone().or_else(|| Some("config_gated".into())));
8905                        NextAction::Stop { registration_released: registry.get_module(&spec.module_id).ok().flatten().is_none() }
8906                    } else { on_child_exit(
8907                        &spec,
8908                        runtime.restart_policy,
8909                        &registry,
8910                        &snapshot,
8911                        &runtime.terminal_ring,
8912                        &runtime.spawn_events,
8913                        &runtime.child_roster,
8914                        exit_report,
8915                        true,
8916                    ).await };
8917                    runtime.start_requester = None;
8918                    runtime.pending_activity_restart = false;
8919                    // The exit is recorded, so a daemon shutdown may stop
8920                    // waiting for this child (see `SupervisedChild::wait`).
8921                    let carry = matches!(next, NextAction::Restart { .. })
8922                        && active_child.spawn_failure.is_none()
8923                        && !runtime.child_roster.is_closed();
8924                    if let Err(error) = active_child.finish_exit(carry).await {
8925                        containment::terminate(&runtime.child_roster.containment).await;
8926                        fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
8927                            &runtime.spawn_events, format!("failed to reap classified exit: {error}"),
8928                            &runtime.failure_context(true));
8929                        child = None;
8930                        continue;
8931                    }
8932                    match next {
8933                        NextAction::Stop { registration_released } => {
8934                            if registration_released {
8935                                process_liveness.untrack_if_current(&spec.module_id, &snapshot);
8936                            }
8937                            child = None;
8938                        }
8939                        NextAction::Restart { schedule } => {
8940                            let delay = if deferred_spawn {CONFIG_ADMISSION_RETRY_DELAY} else {schedule.map_or(
8941                                runtime.restart_policy.delay_for_restart(0),
8942                                |schedule| schedule.delay,
8943                            )};
8944                            if let Some(schedule) = schedule {
8945                                log_crash_respawn(&spec.module_id, schedule);
8946                            }
8947                            // The exited child is fully recorded at this point,
8948                            // so release it and count the backoff down in the
8949                            // command-serving branch below rather than sleeping
8950                            // here: commands cannot be received from inside this
8951                            // select arm, and an operator disable or drain that
8952                            // arrives during the backoff must cancel the pending
8953                            // respawn instead of waiting for it to spawn first.
8954                            child = None;
8955                            pending_respawn = Some(PendingRespawn { deadline: Instant::now() + delay, kind: RespawnKind::Spawn, daemon_initiated: true, approval: None });
8956                             let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = true);
8957                        }
8958                    }
8959                }
8960                command = commands.recv() => {
8961                    #[cfg(test)]
8962                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8963                    let Some(command) = command else {
8964                        containment::terminate(&runtime.child_roster.containment).await;
8965                        return;
8966                    };
8967                    if !handle_supervisor_command(
8968                        command,
8969                        &mut spec,
8970                        &mut runtime,
8971                        &registry,
8972                        &process_liveness,
8973                        &snapshot,
8974                        &mut child,
8975                        &mut commands,
8976                        &mut requeued,
8977                    ).await {
8978                        containment::terminate(&runtime.child_roster.containment).await;
8979                        return;
8980                    }
8981                }
8982                _ = async {
8983                    match registration_changes.as_mut() {
8984                        Some(changes) => { let _ = changes.changed().await; }
8985                        None => std::future::pending().await,
8986                    }
8987                }, if wire_child => {
8988                    #[cfg(test)]
8989                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8990                }
8991                _ = &mut probe_sleep => {
8992                    #[cfg(test)]
8993                    { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8994                    if registration_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
8995                        // Recheck after the wake: HELLO, exit or shutdown may
8996                        // have become ready in the same executor tick.
8997                        active_child.registration_deadline = None;
8998                        if !runtime.child_roster.is_closed()
8999                            && !active_child.registered_since_spawn()
9000                            && registration_child_is_running(active_child)
9001                        {
9002                            warn!(module_id = %spec.module_id, pid = active_child.pid,
9003                                wait_secs = runtime.register_timeout.as_secs(),
9004                                "supervised module registration_timeout: first HELLO deadline expired; stopping child");
9005                            active_child.spawn_failure = Some("registration_timeout".into());
9006                            if let Err(error) = stop_unregistered_child(active_child).await {
9007                                error!(module_id = %spec.module_id, %error, "failed to stop unregistered child");
9008                                fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
9009                                    &runtime.spawn_events, format!("registration_timeout: {error}"),
9010                                    &runtime.failure_context(true));
9011                                child = None;
9012                            }
9013                            // The ordinary exit handler records the child's exit,
9014                            // spends crash budget, and schedules recovery.
9015                            continue;
9016                        }
9017                    }
9018                    if health_probe.due() {
9019                        run_health_probe_cycle(
9020                            &spec,
9021                            &runtime,
9022                            &registry,
9023                            &process_liveness,
9024                            &snapshot,
9025                            &mut child,
9026                        ).await;
9027                        if child.is_none() {
9028                            runtime.start_requester = None;
9029                            runtime.pending_activity_restart = false;
9030                        }
9031                        if child.is_some() {
9032                            health_probe.schedule_next(&spec, runtime.health.cadence);
9033                        }
9034                    }
9035                }
9036            }
9037        } else if let Some(pending) = pending_respawn.clone() {
9038            tokio::select! {
9039                _ = runtime.child_roster.closed() => {
9040                    pending_respawn = None;
9041                    let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9042                        state.state = ModuleState::Stopped;
9043                        state.respawn_pending = false;
9044                    });
9045                    containment::terminate(&runtime.child_roster.containment).await;
9046                }
9047                _ = async {
9048                    sleep_until(pending.deadline).await;
9049                    if let Some(delivery) = &runtime.config_delivery {
9050                        delivery.unfenced(&spec.module_id).await;
9051                    }
9052                } => {
9053                    pending_respawn = None;
9054                    let failure = pending.failure_context(&runtime);
9055                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = false);
9056                    // A command handled below while the backoff elapsed may
9057                    // have stopped the module; never respawn past an operator's
9058                    // disable or drain.
9059                    if !respawn_still_pending(&snapshot) {
9060                        continue;
9061                    }
9062                    // The daemon began shutting down during the backoff: the
9063                    // spawn would be refused anyway, and refusing it here
9064                    // leaves the module stopped instead of reporting a
9065                    // failed restart.
9066                    if runtime.child_roster.is_closed() {
9067                        let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9068                            state.state = ModuleState::Stopped;
9069                        });
9070                        debug!(module_id = %spec.module_id, "crash respawn cancelled by daemon shutdown");
9071                        continue;
9072                    }
9073                    if let Err(err) = release_dead_registration(
9074                        &registry,
9075                        runtime.forwarding.as_deref(),
9076                        &snapshot,
9077                        &spec.module_id,
9078                        &failure,
9079                    ).await {
9080                        record_approved_attempt_failure(&spec, &snapshot, &failure, &err);
9081                        error!(module_id = %spec.module_id, error = %err, "registration did not release before restart");
9082                        continue;
9083                    }
9084
9085                    if matches!(pending.kind, RespawnKind::Reload) {
9086                        let reply = runtime.deferred_reload_reply.lock().unwrap_or_else(|p| p.into_inner()).take();
9087                        let result = finish_reload_child(&spec, &runtime, &registry, &process_liveness, &snapshot, &mut child).await;
9088                        if matches!(result, Err(SuperviseError::ConfigDeliveryDeferred { .. })) {
9089                            *runtime.deferred_reload_reply.lock().unwrap_or_else(|p| p.into_inner()) = reply;
9090                            continue;
9091                        }
9092                        if result.is_ok() && runtime.pending_activity_restart {
9093                            runtime.record_activity_transition("subc.module_restarted", &spec.module_id, runtime.start_requester.clone());
9094                        }
9095                        runtime.pending_activity_restart = false;
9096                        if let Some(reply) = reply { let _ = reply.send(result); }
9097                        continue;
9098                    }
9099                    process_liveness.track(spec.module_id.clone(), Arc::clone(&snapshot));
9100                    match spawn_and_mark_running_async(&spec, &runtime, &snapshot).await {
9101                        Ok(next_child) => {
9102                            child = Some(next_child);
9103                            if runtime.pending_activity_restart {
9104                                runtime.record_activity_transition("subc.module_restarted", &spec.module_id, runtime.start_requester.clone());
9105                                runtime.pending_activity_restart = false;
9106                            }
9107                            debug!(module_id = %spec.module_id, "supervised module restarted after crash");
9108                        }
9109                        Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9110                            pending_respawn = Some(PendingRespawn { deadline:Instant::now()+CONFIG_ADMISSION_RETRY_DELAY, ..pending });
9111                            let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = true);
9112                        }
9113                        Err(SuperviseError::ConfigHeld { .. }) => {
9114                            let _ = hold_config_spawn(&spec, &runtime, &snapshot, &failure);
9115                            runtime.pending_activity_restart = false;
9116                            process_liveness.untrack_if_current(&spec.module_id, &snapshot);
9117                        }
9118                        Err(err) => {
9119                            fail_snapshot(&snapshot, Some(&spec.module_id), None, &failure);
9120                            record_approved_attempt_failure(&spec, &snapshot, &failure, &err);
9121                            process_liveness.untrack_if_current(&spec.module_id, &snapshot);
9122                            error!(module_id = %spec.module_id, error = %err, "failed to restart supervised module");
9123                        }
9124                    }
9125                }
9126                command = commands.recv() => {
9127                    let Some(command) = command else {
9128                        containment::terminate(&runtime.child_roster.containment).await;
9129                        return;
9130                    };
9131                    if !handle_supervisor_command(
9132                        command,
9133                        &mut spec,
9134                        &mut runtime,
9135                        &registry,
9136                        &process_liveness,
9137                        &snapshot,
9138                        &mut child,
9139                        &mut commands,
9140                        &mut requeued,
9141                    ).await {
9142                        containment::terminate(&runtime.child_roster.containment).await;
9143                        return;
9144                    }
9145                    // Reconcile the pending respawn with what the command did:
9146                    // a start may already have spawned a fresh child,
9147                    // while a disable or drain moved the snapshot out of the
9148                    // state the respawn was counting down from.
9149                    if child.is_some() || !respawn_still_pending(&snapshot) {
9150                        pending_respawn = None;
9151                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = false);
9152                    }
9153                }
9154            }
9155        } else {
9156            let slow_retry = lock_snapshot(&snapshot).ok().and_then(|state| {
9157                (state.enabled && state.state == ModuleState::Failed)
9158                    .then_some(state.failed_retry.pending)
9159                    .flatten()
9160            });
9161            let command = if lock_snapshot(&snapshot)
9162                .is_ok_and(|state| state.waiting_for_previous_pid.is_some())
9163            {
9164                tokio::select! {
9165                    command = commands.recv() => command,
9166                    _ = previous_instance_recheck.tick() => {
9167                        if runtime.child_roster.previous_instance_pid(&spec.module_id).is_none() {
9168                            let enabled = lock_snapshot(&snapshot).is_ok_and(|state| state.enabled);
9169                            if enabled && !runtime.child_roster.is_closed() {
9170                                process_liveness.track(spec.module_id.clone(), Arc::clone(&snapshot));
9171                                match spawn_and_mark_running_async(&spec, &runtime, &snapshot).await {
9172                                    Ok(next_child) => child = Some(next_child),
9173                                    Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9174                                        let _ = defer_config_spawn(&spec, &runtime, &snapshot, RespawnKind::Spawn, &runtime.failure_context(true));
9175                                    }
9176                                    Err(SuperviseError::ConfigHeld { .. }) => {
9177                                        let _ = hold_config_spawn(&spec, &runtime, &snapshot, &runtime.failure_context(true));
9178                                    }
9179                                    Err(error) => {
9180                                        fail_snapshot(&snapshot, Some(&spec.module_id), None, &runtime.failure_context(true));
9181                                        error!(module_id = %spec.module_id, %error, "failed to start module after its previous instance exited");
9182                                    }
9183                                }
9184                            } else {
9185                                let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9186                                    state.waiting_for_previous_pid = None;
9187                                    state.waiting_for_previous_detail = None;
9188                                });
9189                            }
9190                        }
9191                        continue;
9192                    }
9193                }
9194            } else {
9195                tokio::select! {
9196                    biased;
9197                    command = commands.recv() => command,
9198                    _ = async {
9199                        match slow_retry {
9200                            Some(retry) => sleep_until(retry.deadline).await,
9201                            None => std::future::pending().await,
9202                        }
9203                    } => {
9204                        let retry = slow_retry.expect("only a scheduled slow retry can wake");
9205                        let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9206                            state.failed_retry.pending = None;
9207                        });
9208                        if runtime.child_roster.is_closed() {
9209                            continue;
9210                        }
9211                        info!(module_id = %spec.module_id, attempt = retry.attempt,
9212                            delay_secs = retry.delay.as_secs(), "starting failed module retry");
9213                        if let Err(error) = set_child_enabled(
9214                            &spec, &runtime, &registry, &process_liveness, &snapshot, &mut child, true,
9215                            &runtime.failure_context(true),
9216                        ).await {
9217                            error!(module_id = %spec.module_id, %error, "failed module retry could not start");
9218                        }
9219                        continue;
9220                    }
9221                }
9222            };
9223            let Some(command) = command else {
9224                containment::terminate(&runtime.child_roster.containment).await;
9225                return;
9226            };
9227            if !handle_supervisor_command(
9228                command,
9229                &mut spec,
9230                &mut runtime,
9231                &registry,
9232                &process_liveness,
9233                &snapshot,
9234                &mut child,
9235                &mut commands,
9236                &mut requeued,
9237            )
9238            .await
9239            {
9240                containment::terminate(&runtime.child_roster.containment).await;
9241                return;
9242            }
9243        }
9244    }
9245}
9246
9247// Preserve the deadline until the future is polled. Starting a relative sleep
9248// after the executor yields would restart part of the countdown.
9249async fn supervisor_sleep(wake_at: Option<Instant>) {
9250    match wake_at {
9251        Some(deadline) => sleep_until(deadline).await,
9252        None => std::future::pending().await,
9253    }
9254}
9255
9256fn log_crash_respawn(module_id: &str, schedule: CrashRestartSchedule) {
9257    info!(
9258        module_id,
9259        restart_in_window = schedule.restart_in_window,
9260        delay_ms = schedule.delay.as_millis() as u64,
9261        "respawning after crash"
9262    );
9263}
9264
9265/// Whether the respawn a backoff was counting down to is still wanted. A
9266/// disable or drain handled while the backoff elapsed moves the snapshot out
9267/// of `Restarting`, and the operator's stop must win over the pending respawn,
9268/// so every sleep-then-spawn path re-validates against the live snapshot
9269/// instead of assuming the state it left behind still holds.
9270fn respawn_still_pending(snapshot: &SharedSnapshot) -> bool {
9271    matches!(
9272        lock_snapshot(snapshot),
9273        Ok(state) if state.enabled && state.state == ModuleState::Restarting
9274    )
9275}
9276
9277enum NextAction {
9278    Stop {
9279        registration_released: bool,
9280    },
9281    Restart {
9282        schedule: Option<CrashRestartSchedule>,
9283    },
9284}
9285
9286#[allow(clippy::too_many_arguments)]
9287async fn handle_supervisor_command(
9288    command: SupervisorCommand,
9289    spec: &mut ModuleSpec,
9290    runtime: &mut SupervisorRuntimeConfig,
9291    registry: &Arc<Registry>,
9292    process_liveness: &SupervisorProcessLiveness,
9293    snapshot: &SharedSnapshot,
9294    child: &mut Option<SupervisedChild>,
9295    commands: &mut mpsc::Receiver<SupervisorCommand>,
9296    requeued: &mut VecDeque<SupervisorCommand>,
9297) -> bool {
9298    if let SupervisorCommand::SetEnabled {
9299        enabled: true,
9300        reset_budget: false,
9301        reply,
9302        ..
9303    } = command
9304    {
9305        let parked = lock_snapshot(snapshot).ok().and_then(|state| {
9306            (state.config_hold_parked
9307                && state.enabled
9308                && !state.process_alive
9309                && child.is_none()
9310                && state.state == ModuleState::Stopped)
9311                .then(|| {
9312                    (
9313                        state.config_hold_daemon_initiated,
9314                        state.config_hold_approval.clone(),
9315                    )
9316                })
9317        });
9318        // Clearing a configuration-delivery block must not restart a child that
9319        // exited on its own or exhausted its crash budget. Resume only an actor
9320        // stopped by a configuration hold; otherwise leave its slow retry alone.
9321        let result = if let Some((daemon_initiated, approval)) = parked {
9322            runtime.recovery_is_daemon = daemon_initiated;
9323            let failure = FailureContext {
9324                approval,
9325                ..runtime.failure_context(daemon_initiated)
9326            };
9327            let result = set_child_enabled_with_budget_policy(
9328                spec,
9329                runtime,
9330                registry,
9331                process_liveness,
9332                snapshot,
9333                child,
9334                true,
9335                &failure,
9336                false,
9337            )
9338            .await;
9339            if let Err(error) = &result {
9340                record_approved_attempt_failure(spec, snapshot, &failure, error);
9341            }
9342            result
9343        } else {
9344            Ok(false)
9345        };
9346        let _ = reply.send(result);
9347        return true;
9348    }
9349    let blocked = runtime
9350        .config_delivery
9351        .as_ref()
9352        .and_then(|delivery| delivery.0.check_module_hold(&spec.module_id).err())
9353        .filter(|error| error.code != "config_delivery_deferred")
9354        .map(|error| {
9355            config_delivery::gate_hold_error(spec, error, runtime.config_delivery.as_ref())
9356        })
9357        .or_else(|| recovery_block_error(spec, &runtime.child_roster))
9358        .or_else(|| {
9359            runtime
9360                .child_roster
9361                .previous_instance(&spec.module_id)
9362                .map(|(pid, reason)| previous_instance_error(spec, pid, reason))
9363        });
9364    let command = if let Some(error) = blocked {
9365        match command {
9366            SupervisorCommand::Restart { reply, .. } | SupervisorCommand::Reload { reply, .. } => {
9367                let _ = reply.send(Err(error));
9368                return true;
9369            }
9370            SupervisorCommand::Swap { reply, .. } => {
9371                let _ = reply.send(Err(error));
9372                return true;
9373            }
9374            SupervisorCommand::ConfigApplyRestart { .. } => return true,
9375            SupervisorCommand::SetEnabled {
9376                enabled: true,
9377                requester,
9378                reply,
9379                ..
9380            } => {
9381                if matches!(error, SuperviseError::ConfigHeld { .. })
9382                    && lock_snapshot(snapshot).is_ok_and(|state| !state.enabled)
9383                    && runtime
9384                        .config_delivery
9385                        .as_ref()
9386                        .is_some_and(|delivery| delivery.0.can_stage_unstamp_enable())
9387                {
9388                    // Stage only the pending unstamp's desired state. A stamped
9389                    // unapproved actor stays refused; admission release starts
9390                    // an unstamped actor only after reconciliation completes.
9391                    let mut changed = false;
9392                    let result = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9393                        changed = !state.enabled;
9394                        state.enabled = true;
9395                        if child.is_none() && state.waiting_for_previous_pid.is_none() {
9396                            state.state = ModuleState::Starting;
9397                            state.failed_retry.cancel();
9398                        }
9399                    })
9400                    .and_then(|_| {
9401                        if child.is_none()
9402                            && lock_snapshot(snapshot)?.waiting_for_previous_pid.is_none()
9403                        {
9404                            hold_config_spawn(
9405                                spec,
9406                                runtime,
9407                                snapshot,
9408                                &runtime.failure_context(false),
9409                            )?;
9410                        }
9411                        Ok(changed)
9412                    });
9413                    if result.is_ok() && changed {
9414                        runtime.start_requester = requester;
9415                    }
9416                    let _ = reply.send(result);
9417                    return true;
9418                }
9419                let _ = reply.send(Err(error));
9420                return true;
9421            }
9422            other => other,
9423        }
9424    } else {
9425        command
9426    };
9427    // A refused start or restart leaves the Failed actor's existing recovery
9428    // deadline intact. Cancel only after the command passes admission.
9429    if matches!(
9430        command,
9431        SupervisorCommand::Drain { .. }
9432            | SupervisorCommand::Retire { .. }
9433            | SupervisorCommand::SetEnabled { .. }
9434            | SupervisorCommand::Restart { .. }
9435    ) {
9436        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9437            state.failed_retry.cancel();
9438        });
9439    }
9440    match command {
9441        SupervisorCommand::ApprovedConfiguration { approved, reply } => {
9442            let result = async {
9443                let next = approved.module_entry(&spec.module_id).map_err(|error| {
9444                    SuperviseError::InvalidSpec { reason: error.to_string() }
9445                })?;
9446                let retry_approved_failure = {
9447                    let mut state = lock_snapshot(snapshot)?;
9448                    if let Some((generation, detail)) = &state.approved_start_failure {
9449                        if *generation == approved.identity() && next.enabled {
9450                            return Err(SuperviseError::Spawn {
9451                                program: spec.program.clone(),
9452                                source: std::io::Error::other(detail.clone()),
9453                                cgroup_path: None,
9454                            });
9455                        }
9456                    }
9457                    let retry = state.approved_start_failure.is_some();
9458                    state.approved_start_failure = None;
9459                    retry
9460                };
9461                stage_supervisor_configuration(
9462                    spec, runtime, snapshot, next.module_spec(), next.health,
9463                    next.drain_timeout_ms,
9464                );
9465                runtime.restart_policy = next.restart;
9466                runtime.register_timeout = next.register_timeout;
9467                if let Some(active) = child.as_mut()
9468                    .filter(|child| child.registration_deadline.is_some())
9469                {
9470                    active.registration_deadline = Some(active.spawned_at + next.register_timeout);
9471                }
9472                let enabled = lock_snapshot(snapshot)?.enabled;
9473                // An approval retries a changed failed entry or its own earlier
9474                // failed start, not an unrelated crash-budget failure. For an
9475                // unchanged entry, reconciled means the approved configuration
9476                // is effective; it does not claim the process has recovered.
9477                // A terminal gate stop is different: a new approval owns its
9478                // recovery even when the daemon entry itself did not change.
9479                let retry_gate_stopped = lock_snapshot(snapshot)?
9480                    .needs_approved_gate_restart(&approved.identity());
9481                let retry_failed = enabled && child.is_none()
9482                    && ((lock_snapshot(snapshot)?.state == ModuleState::Failed
9483                        && (retry_approved_failure || approved.changes_entry(&spec.module_id)))
9484                        || retry_gate_stopped);
9485                if retry_failed {
9486                    // This approval owns a new start, so the failed attempt's
9487                    // daemon retry must not survive either result of that start.
9488                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
9489                        state.failed_retry.cancel();
9490                        if retry_gate_stopped {
9491                            state.stop_reason = None;
9492                            state.config_exit_failed_approval = None;
9493                        }
9494                    })?;
9495                }
9496                if enabled != next.enabled || retry_failed {
9497                    let failure = FailureContext {
9498                        approval: next.enabled.then(|| approved.identity()),
9499                        ..runtime.failure_context(false)
9500                    };
9501                    let held = next.enabled && runtime.config_delivery.as_ref()
9502                        .is_some_and(|delivery| delivery.0.has_recorded_admission_hold(&spec.module_id)
9503                            || delivery.0.check_module_hold(&spec.module_id).is_err_and(|error| error.code == "config_delivery_deferred"));
9504                    if held {
9505                        // Preserve module-delivery failure/recovery holds. The
9506                        // admission release starts the actor when its own hold ends.
9507                        reset_restart_count(snapshot, &spec.module_id)?;
9508                        update_snapshot(snapshot, Some(&spec.module_id), |state| {
9509                            state.enabled = true;
9510                            if child.is_none() && state.waiting_for_previous_pid.is_none() {
9511                                state.state = ModuleState::Starting;
9512                            }
9513                        })?;
9514                        if child.is_none() && lock_snapshot(snapshot)?.waiting_for_previous_pid.is_none() {
9515                            hold_config_spawn(spec, runtime, snapshot, &failure)?;
9516                        }
9517                    } else {
9518                        match set_child_enabled_with_budget_policy(
9519                            spec, runtime, registry, process_liveness, snapshot, child,
9520                            next.enabled, &failure, true,
9521                        ).await {
9522                            Ok(_) => {},
9523                            Err(SuperviseError::ConfigHeld { .. }) if next.enabled => {},
9524                            Err(error) => return Err(error),
9525                        }
9526                        if !next.enabled {
9527                            containment::terminate(&runtime.child_roster.containment).await;
9528                        }
9529                    }
9530                }
9531                if (child.as_ref().is_some_and(|child| child.registration_spawn.is_some() && child.admission_base.is_none())
9532                        || (child.is_none() && lock_snapshot(snapshot)?.state == ModuleState::Restarting
9533                            && runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.stamp_channel_cutover_pending())))
9534                    && runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.module_is_gated(&spec.module_id))
9535                {
9536                    let failure = FailureContext {
9537                        approval: Some(approved.identity()),
9538                        ..runtime.failure_context(false)
9539                    };
9540                    // A stamp cannot adopt an unverified legacy process, even
9541                    // when its approved replacement no longer speaks subc.
9542                    // Stopping that process spends no crash restart budget.
9543                    if child.is_some() {
9544                        restart_child_with_budget_policy(spec, runtime, registry,
9545                            process_liveness, snapshot, child, runtime.drain_timeout, false).await?;
9546                    }
9547                    // The stamp is already committed. A deferred or held launch
9548                    // belongs to the normal retry/hold loop, not a failed apply.
9549                    update_snapshot(snapshot, Some(&spec.module_id), |state| state.respawn_pending = false)?;
9550                    match spawn_and_mark_running_async(spec, runtime, snapshot).await {
9551                        Ok(replacement) => *child = Some(replacement),
9552                        Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9553                            defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, &failure)?;
9554                        }
9555                        Err(SuperviseError::ConfigHeld { .. }) => hold_config_spawn(spec, runtime, snapshot, &failure)?,
9556                        Err(error) => {
9557                            fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
9558                            return Err(error);
9559                        }
9560                    }
9561                }
9562                info!(module_id=%spec.module_id, config_generation=approved.generation(), "approved daemon entry reconciled");
9563                Ok(())
9564            }
9565            .await;
9566            if let Err(error) = &result {
9567                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9568                    if state.enabled
9569                        && state.state == ModuleState::Failed
9570                        && state
9571                            .approved_start_failure
9572                            .as_ref()
9573                            .is_none_or(|(generation, _)| *generation != approved.identity())
9574                    {
9575                        state.approved_start_failure =
9576                            Some((approved.identity(), error.to_string()));
9577                    }
9578                });
9579            }
9580            let _ = reply.send(result);
9581            true
9582        }
9583        SupervisorCommand::ConfigPolicyProbe {
9584            connection,
9585            generation,
9586            attempt,
9587        } => {
9588            let Some(delivery) = &runtime.config_delivery else {
9589                return true;
9590            };
9591            let Ok(gate) = delivery.0.module_gate(&spec.module_id) else {
9592                return true;
9593            };
9594            let guard = gate.lock().await;
9595            let pending = delivery
9596                .0
9597                .on_blocking(move |owner| {
9598                    owner.policy_probe_pending(connection, generation, attempt)
9599                })
9600                .await
9601                .unwrap_or(false)
9602                && child.is_some()
9603                && registry
9604                    .get_module(&spec.module_id)
9605                    .ok()
9606                    .flatten()
9607                    .is_some_and(|registration| registration.connection_id == connection);
9608            drop(guard);
9609            if pending {
9610                run_health_probe_cycle(spec, runtime, registry, process_liveness, snapshot, child)
9611                    .await;
9612            }
9613            true
9614        }
9615        SupervisorCommand::ConfigApplyRestart {
9616            generation,
9617            supersedes_swap,
9618        } => {
9619            let Some(owner) = runtime
9620                .config_delivery
9621                .as_ref()
9622                .map(|delivery| delivery.0.clone())
9623            else {
9624                return true;
9625            };
9626            let Ok(gate) = owner.module_gate(&spec.module_id) else {
9627                return true;
9628            };
9629            let _guard = gate.lock().await;
9630            let spawn = child
9631                .as_ref()
9632                .and_then(|child| child.config_delivery.clone());
9633            let module = spec.module_id.clone();
9634            let current = owner
9635                .on_blocking(move |owner| {
9636                    Ok((supersedes_swap
9637                        || owner
9638                            .pending_config_restarts()?
9639                            .contains(&(module.clone(), generation)))
9640                        && owner.requires_fresher_spawn(&module, spawn.as_ref())?
9641                            == Some(generation))
9642                })
9643                .await
9644                .unwrap_or(false);
9645            if !current
9646                || !lock_snapshot(snapshot).is_ok_and(|state| {
9647                    state.enabled && !state.respawn_pending && state.process_alive
9648                })
9649            {
9650                return true;
9651            }
9652            drop(_guard);
9653            info!(module_id=%spec.module_id, config_generation=generation, "approved configuration restart preserves the crash budget");
9654            if let Err(error) = restart_child_with_budget_policy(
9655                spec,
9656                runtime,
9657                registry,
9658                process_liveness,
9659                snapshot,
9660                child,
9661                runtime.drain_timeout,
9662                false,
9663            )
9664            .await
9665            {
9666                warn!(module_id=%spec.module_id, %error, "approved configuration restart could not be scheduled");
9667            }
9668            true
9669        }
9670        SupervisorCommand::ConfigExitHold { reply } => {
9671            // A notification owns no start, backoff, reload reply or previous-
9672            // instance wait. Only an idle, registered initial start has no work
9673            // to preserve; its initialized startup context can be parked here.
9674            let idle_start = child.is_none()
9675                && lock_snapshot(snapshot).is_ok_and(|state| {
9676                    state.enabled
9677                        && state.state == ModuleState::Starting
9678                        && !state.process_alive
9679                        && !state.respawn_pending
9680                        && state.waiting_for_previous_pid.is_none()
9681                        && state.waiting_for_previous_detail.is_none()
9682                        && state.failed_retry.pending.is_none()
9683                })
9684                && runtime
9685                    .scheduled_respawn
9686                    .lock()
9687                    .unwrap_or_else(|p| p.into_inner())
9688                    .is_none()
9689                && runtime
9690                    .deferred_reload_reply
9691                    .lock()
9692                    .unwrap_or_else(|p| p.into_inner())
9693                    .is_none();
9694            let result = if idle_start {
9695                try_park_config_attempt(
9696                    spec,
9697                    runtime,
9698                    snapshot,
9699                    &runtime.failure_context(runtime.recovery_is_daemon),
9700                    None,
9701                )
9702                .map(|_| ())
9703            } else {
9704                Ok(())
9705            };
9706            let _ = reply.send(result);
9707            true
9708        }
9709        SupervisorCommand::ConfigDeliveryFailed { connection, hold } => {
9710            if registry
9711                .get_module(&spec.module_id)
9712                .ok()
9713                .flatten()
9714                .is_none_or(|registration| registration.connection_id != connection)
9715            {
9716                return true;
9717            }
9718            runtime.recovery_is_daemon = true;
9719            // With a recoverable generation, delivery-failure recovery spends
9720            // one crash-budget entry: the module rejected its configuration.
9721            // Approved configuration restarts spend none.
9722            if hold {
9723                let notice = begin_forwarding_drain_if_configured(
9724                    spec,
9725                    runtime,
9726                    registry,
9727                    snapshot,
9728                    Some(true),
9729                    RouteCloseReason::Disable,
9730                )
9731                .await;
9732                if let Ok(notice) = notice {
9733                    let drained = drain_optional_child(
9734                        &spec.module_id,
9735                        spec.protocol,
9736                        notice,
9737                        registry,
9738                        runtime.forwarding.as_deref(),
9739                        snapshot,
9740                        &runtime.terminal_ring,
9741                        &runtime.spawn_events,
9742                        child,
9743                        runtime.drain_timeout,
9744                        ModuleState::Failed,
9745                        Some(true),
9746                        &runtime.failure_context(true),
9747                    )
9748                    .await;
9749                    if drained.is_ok() {
9750                        match try_park_config_attempt(
9751                            spec,
9752                            runtime,
9753                            snapshot,
9754                            &runtime.failure_context(true),
9755                            None,
9756                        ) {
9757                            Ok(true) => {}
9758                            Ok(false) => {
9759                                if let Err(error) = budgeted_restart_child(
9760                                    spec,
9761                                    runtime,
9762                                    registry,
9763                                    process_liveness,
9764                                    snapshot,
9765                                    child,
9766                                    SupervisorHealthStatus::Unknown,
9767                                    Some("configuration delivery failed after its hold ended"),
9768                                    unix_ms_now(),
9769                                    false,
9770                                )
9771                                .await
9772                                {
9773                                    warn!(module_id=%spec.module_id, %error, "configuration failure restart could not be scheduled");
9774                                }
9775                            }
9776                            Err(error) => {
9777                                warn!(module_id=%spec.module_id, %error, "configuration failure could not be parked")
9778                            }
9779                        }
9780                    }
9781                }
9782            } else if let Err(error) = budgeted_restart_child(
9783                spec,
9784                runtime,
9785                registry,
9786                process_liveness,
9787                snapshot,
9788                child,
9789                SupervisorHealthStatus::Unknown,
9790                Some("configuration delivery failed"),
9791                unix_ms_now(),
9792                false,
9793            )
9794            .await
9795            {
9796                warn!(module_id=%spec.module_id, %error, "configuration failure restart could not be scheduled");
9797            }
9798            true
9799        }
9800        SupervisorCommand::Drain { requester, reply } => {
9801            // A plain stop runs no forwarding drain, so nothing reaches the
9802            // module over its connection before the wait: ask by signal.
9803            let result = drain_optional_child(
9804                &spec.module_id,
9805                spec.protocol,
9806                StopNotice::NotSent,
9807                registry,
9808                runtime.forwarding.as_deref(),
9809                snapshot,
9810                &runtime.terminal_ring,
9811                &runtime.spawn_events,
9812                child,
9813                runtime.drain_timeout,
9814                ModuleState::Stopped,
9815                None,
9816                &FailureContext::operator(),
9817            )
9818            .await;
9819            containment::terminate(&runtime.child_roster.containment).await;
9820            let registration_released = result.is_ok();
9821            if registration_released {
9822                runtime.record_activity_transition(
9823                    "subc.module_stopped",
9824                    &spec.module_id,
9825                    requester,
9826                );
9827            }
9828            let _ = reply.send(result);
9829            if registration_released {
9830                process_liveness.untrack_if_current(&spec.module_id, snapshot);
9831            }
9832            false
9833        }
9834        SupervisorCommand::Retire { requester, reply } => {
9835            let result = async {
9836                let stop_notice = begin_forwarding_drain_if_configured(
9837                    spec,
9838                    runtime,
9839                    registry,
9840                    snapshot,
9841                    None,
9842                    RouteCloseReason::Disable,
9843                )
9844                .await?;
9845                drain_optional_child(
9846                    &spec.module_id,
9847                    spec.protocol,
9848                    stop_notice,
9849                    registry,
9850                    runtime.forwarding.as_deref(),
9851                    snapshot,
9852                    &runtime.terminal_ring,
9853                    &runtime.spawn_events,
9854                    child,
9855                    runtime.drain_timeout,
9856                    ModuleState::Stopped,
9857                    None,
9858                    &FailureContext::operator(),
9859                )
9860                .await
9861            }
9862            .await;
9863            containment::terminate(&runtime.child_roster.containment).await;
9864            let registration_released = result.is_ok();
9865            if registration_released {
9866                runtime.record_activity_transition(
9867                    "subc.module_stopped",
9868                    &spec.module_id,
9869                    requester,
9870                );
9871            }
9872            let _ = reply.send(result);
9873            if registration_released {
9874                process_liveness.untrack_if_current(&spec.module_id, snapshot);
9875            }
9876            false
9877        }
9878        SupervisorCommand::Restart {
9879            requester,
9880            drain_timeout_ms,
9881            received_at_generation,
9882            queued_at,
9883            reply,
9884        } => {
9885            // Without this line a restart that waited in the queue (behind a
9886            // health probe cycle or another command) was invisible: the log
9887            // showed only the drain timing out, minutes after the operator's call.
9888            info!(
9889                module_id = %spec.module_id,
9890                queued_ms = u64::try_from(queued_at.elapsed().as_millis()).unwrap_or(u64::MAX),
9891                "restart command dequeued"
9892            );
9893            // ACK AT INITIATION, not completion. The blocking form deadlocked any
9894            // caller whose own request lane rides the module being restarted: the
9895            // caller's in-flight request keeps the drain from quiescing, the drain
9896            // keeps the restart from completing, and the completion keeps the reply
9897            // from releasing the caller — so the drain always timed out and cut the
9898            // initiator with a GOODBYE, even on a healthy module. Replying once the
9899            // restart is validated lets a self-lane caller settle, which is exactly
9900            // what makes the drain succeed. Completion is observable via
9901            // supervisor.list / module status; a post-ack failure lands the module
9902            // in a visible terminal state below rather than in a reply nobody can
9903            // receive.
9904            let validation = match lock_snapshot(snapshot) {
9905                Ok(state) if !state.enabled => Err(SuperviseError::Disabled {
9906                    module_id: spec.module_id.clone(),
9907                }),
9908                Ok(_) => Ok(()),
9909                Err(err) => Err(err),
9910            };
9911            let initiated = validation.is_ok();
9912            let _ = reply.send(validation);
9913            // A restart asks for a fresh process. Commands run one at a time,
9914            // so a restart queued behind another restart (two operator calls
9915            // in quick succession) is dequeued the moment the first one has
9916            // spawned its replacement -- before that process has sent HELLO.
9917            // Running it would drain and kill the process the first restart
9918            // just produced, which is the opposite of what both callers asked
9919            // for. If a process spawned after this request was received is
9920            // still supervised, the request is already satisfied. Not when the
9921            // configuration changed since that spawn: then the newer process
9922            // predates the spec this restart may exist to apply.
9923            // Generation publication can lag a child that is already serving
9924            // while its identity is recorded. Only process creation after request
9925            // receipt satisfies a restart, not publication after receipt.
9926            let satisfied_by_generation = if initiated
9927                && child
9928                    .as_ref()
9929                    .is_some_and(|child| child.spawned_at > queued_at)
9930            {
9931                lock_snapshot(snapshot).ok().and_then(|state| {
9932                    (!state.configuration_updated_since_spawn).then_some(state.spawn_generation)
9933                })
9934            } else {
9935                None
9936            };
9937            let satisfied_by_pending = initiated
9938                && child.is_none()
9939                && lock_snapshot(snapshot).ok().is_some_and(|mut state| {
9940                    // No child exists yet, so this replacement will necessarily
9941                    // be created after the queued request, unlike a published
9942                    // generation whose process may already have been serving.
9943                    let pending = state.respawn_pending && !state.configuration_updated_since_spawn;
9944                    if pending {
9945                        state.coalesced_restart_pending = true;
9946                    }
9947                    pending
9948                });
9949            if satisfied_by_pending {
9950                debug!(module_id = %spec.module_id, "restart coalesced into the pending replacement");
9951            } else if let Some(generation) = satisfied_by_generation {
9952                info!(
9953                    module_id = %spec.module_id,
9954                    received_at_generation,
9955                    "restart already satisfied by generation {generation}; not restarting again"
9956                );
9957            } else if initiated {
9958                // Precedence: this restart's operator override, else the module's
9959                // configured budget (already resolved into the runtime).
9960                let drain_timeout = drain_timeout_ms
9961                    .map(Duration::from_millis)
9962                    .unwrap_or(runtime.drain_timeout);
9963                if let Err(err) = restart_child(
9964                    spec,
9965                    runtime,
9966                    registry,
9967                    process_liveness,
9968                    snapshot,
9969                    child,
9970                    drain_timeout,
9971                )
9972                .await
9973                {
9974                    warn!(
9975                        module_id = %spec.module_id,
9976                        error = %err,
9977                        "operator restart failed after initiation ack; module state carries the outcome"
9978                    );
9979                    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9980                        state.state = ModuleState::Failed;
9981                        clear_current_process_facts(state);
9982                    });
9983                } else {
9984                    runtime.start_requester = requester;
9985                    runtime.pending_activity_restart = true;
9986                }
9987            }
9988            true
9989        }
9990        SupervisorCommand::Reload { requester, reply } => {
9991            let result =
9992                reload_child(spec, runtime, registry, process_liveness, snapshot, child).await;
9993            if result.is_ok() {
9994                runtime.start_requester = requester;
9995                runtime.pending_activity_restart = true;
9996            }
9997            if result.is_ok()
9998                && runtime
9999                    .scheduled_respawn
10000                    .lock()
10001                    .unwrap_or_else(|p| p.into_inner())
10002                    .as_ref()
10003                    .is_some_and(|pending| matches!(pending.kind, RespawnKind::Reload))
10004            {
10005                *runtime
10006                    .deferred_reload_reply
10007                    .lock()
10008                    .unwrap_or_else(|p| p.into_inner()) = Some(reply);
10009            } else {
10010                let _ = reply.send(result);
10011            }
10012            true
10013        }
10014        SupervisorCommand::SetEnabled {
10015            enabled,
10016            requester,
10017            reply,
10018            reset_budget,
10019        } => {
10020            let previous_requester = runtime.start_requester.clone();
10021            if enabled {
10022                runtime.start_requester = requester.clone();
10023            }
10024            let result = set_child_enabled_with_budget_policy(
10025                spec,
10026                runtime,
10027                registry,
10028                process_liveness,
10029                snapshot,
10030                child,
10031                enabled,
10032                &runtime.failure_context(false),
10033                reset_budget,
10034            )
10035            .await;
10036            if !enabled {
10037                containment::terminate(&runtime.child_roster.containment).await;
10038            }
10039            if matches!(result, Ok(true)) {
10040                runtime.pending_activity_restart = false;
10041                if enabled {
10042                    runtime.start_requester = requester;
10043                } else {
10044                    runtime.start_requester = None;
10045                    runtime.record_activity_transition(
10046                        "subc.module_disabled",
10047                        &spec.module_id,
10048                        requester,
10049                    );
10050                }
10051            } else {
10052                runtime.start_requester = previous_requester;
10053            }
10054            let _ = reply.send(result);
10055            true
10056        }
10057        SupervisorCommand::UpdateConfiguration {
10058            spec: next_spec,
10059            health,
10060            drain_timeout_ms,
10061            reply,
10062        } => {
10063            if runtime
10064                .config_delivery
10065                .as_ref()
10066                .is_some_and(|delivery| delivery.0.file_configuration_is_gated(&spec.module_id))
10067            {
10068                let _ = reply.send(Err(SuperviseError::ConfigHeld {
10069                    module_id: spec.module_id.clone(),
10070                    code: "config_gated".into(),
10071                    detail: "live file reconfiguration cannot replace stamped authority".into(),
10072                }));
10073                return true;
10074            }
10075            stage_supervisor_configuration(
10076                spec,
10077                runtime,
10078                snapshot,
10079                next_spec,
10080                health,
10081                drain_timeout_ms,
10082            );
10083            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10084                state.configuration_updated_since_spawn = true;
10085            });
10086            let _ = reply.send(Ok(()));
10087            true
10088        }
10089        SupervisorCommand::Swap {
10090            requester,
10091            ready_timeout,
10092            reply,
10093        } => {
10094            if spec.carry_containment
10095                || containment::current(&runtime.child_roster.containment).is_some()
10096            {
10097                let _ = reply.send(Err(SuperviseError::InvalidSpec {
10098                    reason: "a carried container cannot overlap a swap candidate".to_owned(),
10099                }));
10100                return true;
10101            }
10102            let mut swap_runtime = runtime.clone();
10103            swap_runtime.start_requester = requester;
10104            let before = lock_snapshot(snapshot)
10105                .ok()
10106                .map(|state| state.spawn_generation);
10107            let end = swap::run_swap(
10108                spec,
10109                &swap_runtime,
10110                registry,
10111                process_liveness,
10112                snapshot,
10113                child,
10114                commands,
10115                ready_timeout.unwrap_or(DEFAULT_SWAP_READY_TIMEOUT),
10116                reply,
10117            )
10118            .await;
10119            if before
10120                != lock_snapshot(snapshot)
10121                    .ok()
10122                    .map(|state| state.spawn_generation)
10123            {
10124                runtime.start_requester = swap_runtime.start_requester;
10125            }
10126            requeued.extend(end.requeue);
10127            true
10128        }
10129    }
10130}
10131
10132fn stage_supervisor_configuration(
10133    spec: &mut ModuleSpec,
10134    runtime: &mut SupervisorRuntimeConfig,
10135    snapshot: &SharedSnapshot,
10136    next_spec: ModuleSpec,
10137    health: HealthConfig,
10138    drain_timeout_ms: Option<u64>,
10139) {
10140    if let Some(handle) = &runtime.supervisor_handle {
10141        handle.apply_identity_configuration(&next_spec);
10142    }
10143    let launch_changed = *spec != next_spec;
10144    *spec = next_spec;
10145    if launch_changed {
10146        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10147            state.configuration_updated_since_spawn = true
10148        });
10149    }
10150    let health_changed = runtime.health != health;
10151    runtime.health = health;
10152    // Reset the cadence and old endpoint's failure streak on a live
10153    // health-policy change rather than waiting for its old deadline.
10154    if health_changed {
10155        let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10156            state.health = ModuleHealthStatus::default();
10157            state.last_probe_evidence = None;
10158        });
10159    }
10160    runtime.drain_timeout = drain_timeout_ms
10161        .map(Duration::from_millis)
10162        .unwrap_or(runtime.default_drain_timeout);
10163    *runtime
10164        .effective_drain_timeout
10165        .lock()
10166        .unwrap_or_else(|p| p.into_inner()) = runtime.drain_timeout;
10167}
10168
10169async fn restart_child(
10170    spec: &ModuleSpec,
10171    runtime: &SupervisorRuntimeConfig,
10172    registry: &Registry,
10173    process_liveness: &SupervisorProcessLiveness,
10174    snapshot: &SharedSnapshot,
10175    child: &mut Option<SupervisedChild>,
10176    drain_timeout: Duration,
10177) -> Result<(), SuperviseError> {
10178    restart_child_with_budget_policy(
10179        spec,
10180        runtime,
10181        registry,
10182        process_liveness,
10183        snapshot,
10184        child,
10185        drain_timeout,
10186        true,
10187    )
10188    .await
10189}
10190
10191#[allow(clippy::too_many_arguments)]
10192async fn restart_child_with_budget_policy(
10193    spec: &ModuleSpec,
10194    runtime: &SupervisorRuntimeConfig,
10195    registry: &Registry,
10196    process_liveness: &SupervisorProcessLiveness,
10197    snapshot: &SharedSnapshot,
10198    child: &mut Option<SupervisedChild>,
10199    drain_timeout: Duration,
10200    reset_budget: bool,
10201) -> Result<(), SuperviseError> {
10202    // Restart cycles a running module; it must not silently start a disabled one.
10203    if !lock_snapshot(snapshot)?.enabled {
10204        return Err(SuperviseError::Disabled {
10205            module_id: spec.module_id.clone(),
10206        });
10207    }
10208    let stop_notice = begin_forwarding_drain_with_timeout(
10209        spec,
10210        runtime,
10211        registry,
10212        snapshot,
10213        None,
10214        RouteCloseReason::Restart,
10215        drain_timeout,
10216    )
10217    .await?;
10218
10219    if child.is_some() {
10220        drain_optional_child(
10221            &spec.module_id,
10222            spec.protocol,
10223            stop_notice,
10224            registry,
10225            runtime.forwarding.as_deref(),
10226            snapshot,
10227            &runtime.terminal_ring,
10228            &runtime.spawn_events,
10229            child,
10230            drain_timeout,
10231            ModuleState::Restarting,
10232            Some(true),
10233            &FailureContext::operator(),
10234        )
10235        .await?;
10236    } else {
10237        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10238            state.enabled = true;
10239            state.state = ModuleState::Restarting;
10240            clear_current_process_facts(state);
10241        })?;
10242        release_dead_registration(
10243            registry,
10244            runtime.forwarding.as_deref(),
10245            snapshot,
10246            &spec.module_id,
10247            &runtime.failure_context(false),
10248        )
10249        .await?;
10250    }
10251
10252    if reset_budget {
10253        reset_restart_count(snapshot, &spec.module_id)?;
10254    }
10255    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10256    schedule_respawn(
10257        runtime,
10258        snapshot,
10259        &spec.module_id,
10260        runtime.restart_policy.backoff,
10261        RespawnKind::Spawn,
10262        false,
10263    )
10264}
10265
10266async fn reload_child(
10267    spec: &ModuleSpec,
10268    runtime: &SupervisorRuntimeConfig,
10269    registry: &Registry,
10270    process_liveness: &SupervisorProcessLiveness,
10271    snapshot: &SharedSnapshot,
10272    child: &mut Option<SupervisedChild>,
10273) -> Result<(), SuperviseError> {
10274    // Reload cycles a running module; it must not silently start a disabled one.
10275    if !lock_snapshot(snapshot)?.enabled {
10276        return Err(SuperviseError::Disabled {
10277            module_id: spec.module_id.clone(),
10278        });
10279    }
10280    let stop_notice = begin_forwarding_drain(
10281        spec,
10282        runtime,
10283        registry,
10284        snapshot,
10285        Some(true),
10286        RouteCloseReason::Reload,
10287    )
10288    .await?;
10289
10290    if child.is_some() {
10291        drain_optional_child(
10292            &spec.module_id,
10293            spec.protocol,
10294            stop_notice,
10295            registry,
10296            runtime.forwarding.as_deref(),
10297            snapshot,
10298            &runtime.terminal_ring,
10299            &runtime.spawn_events,
10300            child,
10301            runtime.drain_timeout,
10302            ModuleState::Restarting,
10303            Some(true),
10304            &FailureContext::operator(),
10305        )
10306        .await?;
10307    } else {
10308        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10309            state.enabled = true;
10310            state.state = ModuleState::Restarting;
10311            clear_current_process_facts(state);
10312        })?;
10313        release_dead_registration(
10314            registry,
10315            runtime.forwarding.as_deref(),
10316            snapshot,
10317            &spec.module_id,
10318            &runtime.failure_context(false),
10319        )
10320        .await?;
10321    }
10322
10323    reset_restart_count(snapshot, &spec.module_id)?;
10324    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10325    schedule_respawn(
10326        runtime,
10327        snapshot,
10328        &spec.module_id,
10329        runtime.restart_policy.backoff,
10330        RespawnKind::Reload,
10331        false,
10332    )
10333}
10334
10335async fn finish_reload_child(
10336    spec: &ModuleSpec,
10337    runtime: &SupervisorRuntimeConfig,
10338    registry: &Registry,
10339    process_liveness: &SupervisorProcessLiveness,
10340    snapshot: &SharedSnapshot,
10341    child: &mut Option<SupervisedChild>,
10342) -> Result<(), SuperviseError> {
10343    process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10344    let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
10345        Ok(next_child) => next_child,
10346        Err(error @ SuperviseError::ConfigDeliveryDeferred { .. }) => {
10347            defer_config_spawn(
10348                spec,
10349                runtime,
10350                snapshot,
10351                RespawnKind::Reload,
10352                &runtime.failure_context(runtime.recovery_is_daemon),
10353            )?;
10354            return Err(error);
10355        }
10356        Err(error @ SuperviseError::ConfigHeld { .. }) => {
10357            let failure = runtime.failure_context(runtime.recovery_is_daemon);
10358            if try_park_config_attempt(spec, runtime, snapshot, &failure, None)? {
10359                return Err(error);
10360            }
10361            defer_config_spawn(spec, runtime, snapshot, RespawnKind::Reload, &failure)?;
10362            return Err(SuperviseError::ConfigDeliveryDeferred {
10363                module_id: spec.module_id.clone(),
10364            });
10365        }
10366        Err(err) => {
10367            return handle_reload_spawn_failure(
10368                spec,
10369                runtime,
10370                process_liveness,
10371                snapshot,
10372                child,
10373                format!("new child failed to spawn: {err}"),
10374            )
10375            .await;
10376        }
10377    };
10378    *child = Some(next_child);
10379
10380    let wait_outcome = {
10381        let active_child = child.as_mut().expect("new reload child was just stored");
10382        wait_for_registration_after_reload(
10383            registry,
10384            &spec.module_id,
10385            snapshot,
10386            active_child,
10387            REGISTRY_RELEASE_TIMEOUT,
10388        )
10389        .await?
10390    };
10391
10392    match wait_outcome {
10393        RegistrationWaitOutcome::Registered => {
10394            child
10395                .as_mut()
10396                .expect("registered reload child")
10397                .registration_deadline = None;
10398            debug!(module_id = %spec.module_id, "supervised module reloaded and registered");
10399            Ok(())
10400        }
10401        RegistrationWaitOutcome::Exited(exit_report) => {
10402            if let Some(active_child) = child.as_mut() {
10403                active_child.drain_stderr(&spec.module_id).await;
10404            }
10405            // Keep the exited child's roster guard until its terminal is written.
10406            // Shutdown waits on that guard, not on the child Option used for respawn.
10407            let mut exited_child = child.take().expect("exited reload child is still stored");
10408            #[cfg(test)]
10409            if let Some(gate) = &runtime.test_reload_exit_record_gate {
10410                gate.reached.notify_one();
10411                gate.resume.notified().await;
10412            }
10413            let result = handle_reload_child_registration_failure(
10414                spec,
10415                runtime,
10416                registry,
10417                process_liveness,
10418                snapshot,
10419                child,
10420                ReloadRegistrationFailure {
10421                    exit_report: registration_failure_exit_report(exit_report),
10422                    reason: exited_child
10423                        .spawn_failure
10424                        .clone()
10425                        .unwrap_or_else(|| "new child exited before registering".to_string()),
10426                },
10427            )
10428            .await;
10429            exited_child
10430                .finish_exit(false)
10431                .await
10432                .map_err(|source| SuperviseError::Wait {
10433                    module_id: spec.module_id.clone(),
10434                    source,
10435                })?;
10436            result
10437        }
10438        RegistrationWaitOutcome::TimedOut => {
10439            let mut timed_out_child = child
10440                .take()
10441                .expect("timed-out reload child is still running");
10442            timed_out_child
10443                .start_kill()
10444                .map_err(|source| SuperviseError::Kill {
10445                    module_id: spec.module_id.clone(),
10446                    source,
10447                })?;
10448            let status = timed_out_child
10449                .wait()
10450                .await
10451                .map_err(|source| SuperviseError::Wait {
10452                    module_id: spec.module_id.clone(),
10453                    source,
10454                })?;
10455            timed_out_child.drain_stderr(&spec.module_id).await;
10456            let result = handle_reload_child_registration_failure(
10457                spec,
10458                runtime,
10459                registry,
10460                process_liveness,
10461                snapshot,
10462                child,
10463                ReloadRegistrationFailure {
10464                    exit_report: registration_failure_exit_report(classify_reaped_child_exit(
10465                        snapshot,
10466                        &timed_out_child,
10467                        &status,
10468                    )),
10469                    reason: format!(
10470                        "new child did not register within {:?}",
10471                        REGISTRY_RELEASE_TIMEOUT
10472                    ),
10473                },
10474            )
10475            .await;
10476            timed_out_child
10477                .finish_exit(false)
10478                .await
10479                .map_err(|source| SuperviseError::Wait {
10480                    module_id: spec.module_id.clone(),
10481                    source,
10482                })?;
10483            result
10484        }
10485    }
10486}
10487
10488#[allow(clippy::too_many_arguments)]
10489async fn set_child_enabled(
10490    spec: &ModuleSpec,
10491    runtime: &SupervisorRuntimeConfig,
10492    registry: &Registry,
10493    process_liveness: &SupervisorProcessLiveness,
10494    snapshot: &SharedSnapshot,
10495    child: &mut Option<SupervisedChild>,
10496    enabled: bool,
10497    failure: &FailureContext,
10498) -> Result<bool, SuperviseError> {
10499    set_child_enabled_with_budget_policy(
10500        spec,
10501        runtime,
10502        registry,
10503        process_liveness,
10504        snapshot,
10505        child,
10506        enabled,
10507        failure,
10508        true,
10509    )
10510    .await
10511}
10512
10513#[allow(clippy::too_many_arguments)]
10514async fn set_child_enabled_with_budget_policy(
10515    spec: &ModuleSpec,
10516    runtime: &SupervisorRuntimeConfig,
10517    registry: &Registry,
10518    process_liveness: &SupervisorProcessLiveness,
10519    snapshot: &SharedSnapshot,
10520    child: &mut Option<SupervisedChild>,
10521    enabled: bool,
10522    failure: &FailureContext,
10523    reset_budget: bool,
10524) -> Result<bool, SuperviseError> {
10525    let (current_enabled, current_state, respawn_pending) = {
10526        let state = lock_snapshot(snapshot)?;
10527        (state.enabled, state.state, state.respawn_pending)
10528    };
10529    // `start` (enable on an already-enabled module) heals TERMINAL states instead
10530    // of no-op'ing: a module whose restart budget exhausted (Failed) or that exited
10531    // clean (Stopped) has no live process and no other in-band recovery — the
10532    // operator's start is the explicit recovery act and resets the budget. Without
10533    // this arm the only revival was subc-probe --supervisor-restart in a terminal,
10534    // which the 2026-07-14 aft outage proved is a trap when the failed module is
10535    // the one providing every agent's shell.
10536    let revive_terminal = enabled
10537        && current_enabled
10538        && child.is_none()
10539        && (matches!(current_state, ModuleState::Failed | ModuleState::Stopped)
10540            || (current_state == ModuleState::Restarting && !respawn_pending));
10541    if current_enabled == enabled && !revive_terminal {
10542        return Ok(false);
10543    }
10544
10545    if enabled {
10546        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10547            state.enabled = true;
10548            state.state = ModuleState::Starting;
10549            clear_current_process_facts(state);
10550        })?;
10551        #[cfg(test)]
10552        if runtime.test_seed_stale_facts_before_enable_spawn {
10553            update_snapshot(snapshot, Some(&spec.module_id), |state| {
10554                state.process_alive = true;
10555                state.pid = Some(41);
10556                state.spawned_at_ms = Some(42);
10557                state.spawned_from = Some(PathBuf::from("/spawned/module"));
10558                state.spawned_file_identity = Some(SpawnedFileIdentity {
10559                    device: 43,
10560                    inode: 44,
10561                    #[cfg(windows)]
10562                    windows_image: None,
10563                });
10564            })?;
10565        }
10566        release_dead_registration(
10567            registry,
10568            runtime.forwarding.as_deref(),
10569            snapshot,
10570            &spec.module_id,
10571            failure,
10572        )
10573        .await?;
10574        if reset_budget {
10575            reset_restart_count(snapshot, &spec.module_id)?;
10576        }
10577        process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10578        let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
10579            Ok(next_child) => next_child,
10580            Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
10581                defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
10582                return Ok(true);
10583            }
10584            Err(error @ SuperviseError::ConfigHeld { .. }) => {
10585                if let Err(parking_error) = hold_config_spawn(spec, runtime, snapshot, failure) {
10586                    process_liveness.untrack_if_current(&spec.module_id, snapshot);
10587                    return Err(parking_error);
10588                }
10589                return Err(error);
10590            }
10591            Err(err) => {
10592                fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
10593                process_liveness.untrack_if_current(&spec.module_id, snapshot);
10594                return Err(err);
10595            }
10596        };
10597        *child = Some(next_child);
10598        debug!(module_id = %spec.module_id, "supervised module enabled");
10599        Ok(true)
10600    } else {
10601        update_snapshot(snapshot, Some(&spec.module_id), |state| {
10602            state.config_hold_parked = false;
10603            state.config_hold_daemon_initiated = false;
10604            state.config_hold_approval = None;
10605        })?;
10606        let stop_notice = begin_forwarding_drain_if_configured(
10607            spec,
10608            runtime,
10609            registry,
10610            snapshot,
10611            Some(false),
10612            RouteCloseReason::Disable,
10613        )
10614        .await?;
10615        drain_optional_child(
10616            &spec.module_id,
10617            spec.protocol,
10618            stop_notice,
10619            registry,
10620            runtime.forwarding.as_deref(),
10621            snapshot,
10622            &runtime.terminal_ring,
10623            &runtime.spawn_events,
10624            child,
10625            runtime.drain_timeout,
10626            ModuleState::Disabled,
10627            Some(false),
10628            failure,
10629        )
10630        .await?;
10631        debug!(module_id = %spec.module_id, "supervised module disabled");
10632        Ok(true)
10633    }
10634}
10635
10636#[allow(clippy::too_many_arguments)]
10637async fn on_child_exit(
10638    spec: &ModuleSpec,
10639    policy: RestartPolicy,
10640    registry: &Registry,
10641    snapshot: &SharedSnapshot,
10642    terminal_ring: &Arc<Mutex<TerminalRing>>,
10643    spawn_events: &SpawnEventFeed,
10644    roster: &ChildRoster,
10645    exit_report: ExitReport,
10646    daemon_initiated: bool,
10647) -> NextAction {
10648    // Once the daemon has begun shutting down, no exit is a crash to recover
10649    // from: the module is exiting because the daemon is going away (EOF on its
10650    // connection, or a service manager signalling the whole cgroup). Record it
10651    // as such and never schedule a respawn, which would only start a process
10652    // for the shutdown to end again.
10653    if roster.is_closed() {
10654        return on_child_exit_during_daemon_shutdown(
10655            spec,
10656            registry,
10657            snapshot,
10658            terminal_ring,
10659            spawn_events,
10660            exit_report,
10661        )
10662        .await;
10663    }
10664    // Deliberate stops the supervisor asks for (operator stop, disable,
10665    // restart, reload, swap, a health restart, a drain that runs out of budget)
10666    // takes the child out of the supervise loop and reaps it in
10667    // `drain_child_to_state`, and daemon shutdown is handled above. So an exit
10668    // that reaches this point is either unrequested or a first-HELLO timeout,
10669    // which is deliberately classified as a crash even after a clean TERM exit.
10670    //
10671    // For a subc-wire module a clean exit is still a stop: those modules are
10672    // written to re-raise SIGTERM, so a stray outside signal already reads as a
10673    // crash, and exiting 0 is a deliberate choice the module made. A
10674    // `protocol: "none"` module is a stock program we cannot change, and many
10675    // of them (nats-server among them) exit 0 on SIGTERM. Treating that as a
10676    // stop would leave the module down for good after any stray signal, so it
10677    // goes through the crash path instead: it spends restart budget, respawns
10678    // with the crash backoff, and ends `failed` when the budget runs out.
10679    let unrequested_clean_exit_of_protocol_none = exit_report.kind == ExitKind::Clean
10680        && running_protocol(spec, snapshot) == ModuleProtocol::None;
10681    match exit_report.kind {
10682        ExitKind::Clean if !unrequested_clean_exit_of_protocol_none => {
10683            info!(
10684                module_id = %spec.module_id,
10685                exit_code = ?exit_report.code,
10686                exit_signal = ?exit_report.signal,
10687                "supervised module exited cleanly"
10688            );
10689            if let Err(err) = publish_after_terminal_record(
10690                &spec.module_id,
10691                || {
10692                    record_terminal(
10693                        &spec.module_id,
10694                        terminal_ring,
10695                        spawn_events,
10696                        &exit_report,
10697                        TerminalDisposition::Stopped,
10698                    )
10699                },
10700                || {
10701                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10702                        state.state = ModuleState::Stopped;
10703                        clear_current_process_facts(state);
10704                        state.last_exit = Some(exit_report.clone());
10705                    })
10706                },
10707            ) {
10708                error!(module_id = %spec.module_id, error = %err, "failed to publish clean module exit");
10709            }
10710            let registration_released = match wait_for_registration_release(
10711                registry,
10712                &spec.module_id,
10713                REGISTRY_RELEASE_TIMEOUT,
10714            )
10715            .await
10716            {
10717                Ok(()) => true,
10718                Err(err) => {
10719                    warn!(module_id = %spec.module_id, error = %err, "registration still active after clean exit");
10720                    false
10721                }
10722            };
10723            NextAction::Stop {
10724                registration_released,
10725            }
10726        }
10727        ExitKind::Clean | ExitKind::Crash => {
10728            if unrequested_clean_exit_of_protocol_none {
10729                warn!(
10730                    module_id = %spec.module_id,
10731                    exit_code = ?exit_report.code,
10732                    exit_signal = ?exit_report.signal,
10733                    "protocol-none module exited cleanly without a stop request; handling it as a crash"
10734                );
10735            } else {
10736                warn!(
10737                    module_id = %spec.module_id,
10738                    exit_code = ?exit_report.code,
10739                    exit_signal = ?exit_report.signal,
10740                    "supervised module exited abnormally (crash)"
10741                );
10742            }
10743            let mut restart_schedule = None;
10744            let mut disposition = TerminalDisposition::Disabled;
10745            let mut final_state = ModuleState::Disabled;
10746            // Set only when the budget is what stopped the module, so the
10747            // terminal record says which limit was hit rather than leaving
10748            // `failed` to be read as "crashed once, badly".
10749            let mut disposition_detail = lock_snapshot(snapshot)
10750                .ok()
10751                .and_then(|mut state| state.spawn_failure.take());
10752            let now = Instant::now();
10753            if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10754                if state.enabled {
10755                    if let Some(schedule) = state.next_crash_restart(&policy, now) {
10756                        // Reserving the last slot exhausts the budget for the
10757                        // replacement, not for this exit. Publish its scheduled
10758                        // recovery atomically with the reservation so connection
10759                        // cleanup sees it while terminal recording still holds
10760                        // the visible state at Running.
10761                        state.respawn_pending = true;
10762                        final_state = ModuleState::Restarting;
10763                        restart_schedule = Some(schedule);
10764                        disposition = TerminalDisposition::Restarting;
10765                    } else {
10766                        final_state = ModuleState::Failed;
10767                        disposition = TerminalDisposition::Failed;
10768                        let budget = policy.budget_exhausted_detail();
10769                        disposition_detail =
10770                            Some(disposition_detail.take().map_or_else(
10771                                || budget.clone(),
10772                                |cause| format!("{cause}; {budget}"),
10773                            ));
10774                    }
10775                } else {
10776                    disposition = TerminalDisposition::Disabled;
10777                }
10778            }) {
10779                error!(module_id = %spec.module_id, error = %err, "failed to record crashed module exit");
10780                return NextAction::Stop {
10781                    registration_released: false,
10782                };
10783            }
10784            if disposition == TerminalDisposition::Failed {
10785                // The window is in the message, not only in the fields: this line
10786                // is read in a scrollback where a bare `max_restarts=3` reads as a
10787                // lifetime cap and sends the operator looking for three crashes
10788                // that never happened together.
10789                error!(
10790                    module_id = %spec.module_id,
10791                    max_restarts = policy.max_restarts,
10792                    window_secs = policy.window.as_secs(),
10793                    "module stopped: {}",
10794                    policy.budget_exhausted_detail()
10795                );
10796            }
10797            if let Err(err) = publish_after_terminal_record(
10798                &spec.module_id,
10799                || {
10800                    record_terminal_with_detail(
10801                        &spec.module_id,
10802                        terminal_ring,
10803                        spawn_events,
10804                        &exit_report,
10805                        disposition,
10806                        disposition_detail,
10807                    )
10808                },
10809                || {
10810                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10811                        state.state = final_state;
10812                        clear_current_process_facts(state);
10813                        if final_state == ModuleState::Failed
10814                            && daemon_initiated
10815                            && !roster.is_closed()
10816                        {
10817                            state.failed_retry.schedule(&spec.module_id);
10818                        }
10819                        state.last_exit = Some(exit_report.clone());
10820                    })
10821                },
10822            ) {
10823                error!(module_id = %spec.module_id, error = %err, "failed to publish crashed module exit");
10824            }
10825
10826            if let Some(schedule) = restart_schedule {
10827                NextAction::Restart {
10828                    schedule: Some(schedule),
10829                }
10830            } else {
10831                let registration_released = match wait_for_registration_release(
10832                    registry,
10833                    &spec.module_id,
10834                    REGISTRY_RELEASE_TIMEOUT,
10835                )
10836                .await
10837                {
10838                    Ok(()) => true,
10839                    Err(err) => {
10840                        warn!(module_id = %spec.module_id, error = %err, "registration still active after failed module");
10841                        false
10842                    }
10843                };
10844                NextAction::Stop {
10845                    registration_released,
10846                }
10847            }
10848        }
10849        ExitKind::DeliberateSeverance => {
10850            warn!(
10851                module_id = %spec.module_id,
10852                exit_code = ?exit_report.code,
10853                exit_signal = ?exit_report.signal,
10854                "supervised module exited after deliberate connection severance"
10855            );
10856            let should_restart = match lock_snapshot(snapshot) {
10857                Ok(state) => state.enabled,
10858                Err(err) => {
10859                    error!(module_id = %spec.module_id, error = %err, "failed to read deliberately severed module state");
10860                    return NextAction::Stop {
10861                        registration_released: false,
10862                    };
10863                }
10864            };
10865            let final_state = if should_restart {
10866                ModuleState::Restarting
10867            } else {
10868                ModuleState::Disabled
10869            };
10870            if let Err(err) = publish_after_terminal_record(
10871                &spec.module_id,
10872                || {
10873                    record_terminal(
10874                        &spec.module_id,
10875                        terminal_ring,
10876                        spawn_events,
10877                        &exit_report,
10878                        terminal_disposition(final_state),
10879                    )
10880                },
10881                || {
10882                    update_snapshot(snapshot, Some(&spec.module_id), |state| {
10883                        state.state = final_state;
10884                        clear_current_process_facts(state);
10885                        state.last_exit = Some(exit_report.clone());
10886                        state.lifetime_restarts += 1;
10887                    })
10888                },
10889            ) {
10890                error!(module_id = %spec.module_id, error = %err, "failed to publish deliberately severed module exit");
10891                return NextAction::Stop {
10892                    registration_released: false,
10893                };
10894            }
10895
10896            if should_restart {
10897                NextAction::Restart { schedule: None }
10898            } else {
10899                let registration_released = match wait_for_registration_release(
10900                    registry,
10901                    &spec.module_id,
10902                    REGISTRY_RELEASE_TIMEOUT,
10903                )
10904                .await
10905                {
10906                    Ok(()) => true,
10907                    Err(err) => {
10908                        warn!(module_id = %spec.module_id, error = %err, "registration still active after deliberately severed module exit");
10909                        false
10910                    }
10911                };
10912                NextAction::Stop {
10913                    registration_released,
10914                }
10915            }
10916        }
10917    }
10918}
10919
10920async fn on_child_exit_during_daemon_shutdown(
10921    spec: &ModuleSpec,
10922    registry: &Registry,
10923    snapshot: &SharedSnapshot,
10924    terminal_ring: &Arc<Mutex<TerminalRing>>,
10925    spawn_events: &SpawnEventFeed,
10926    exit_report: ExitReport,
10927) -> NextAction {
10928    info!(
10929        module_id = %spec.module_id,
10930        exit_code = ?exit_report.code,
10931        exit_signal = ?exit_report.signal,
10932        exit_kind = ?exit_report.kind,
10933        "supervised module exited during daemon shutdown; not restarting it"
10934    );
10935    if let Err(err) = publish_after_terminal_record(
10936        &spec.module_id,
10937        || {
10938            record_terminal(
10939                &spec.module_id,
10940                terminal_ring,
10941                spawn_events,
10942                &exit_report,
10943                TerminalDisposition::DaemonShutdown,
10944            )
10945        },
10946        || {
10947            update_snapshot(snapshot, Some(&spec.module_id), |state| {
10948                state.state = ModuleState::Stopped;
10949                clear_current_process_facts(state);
10950                state.last_exit = Some(exit_report.clone());
10951            })
10952        },
10953    ) {
10954        error!(module_id = %spec.module_id, error = %err, "failed to publish module exit during daemon shutdown");
10955    }
10956    let registration_released =
10957        wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT)
10958            .await
10959            .is_ok();
10960    NextAction::Stop {
10961        registration_released,
10962    }
10963}
10964
10965// Keep the status lock out of terminal I/O. Readers may observe the previous
10966// state while recording is in progress, but never a completed exit without its
10967// history. Journal errors are logged by the journal and retained in the ring;
10968// a recording panic still publishes the final state before resuming the unwind.
10969fn publish_after_terminal_record<T>(
10970    module_id: &str,
10971    record: impl FnOnce(),
10972    publish: impl FnOnce() -> T,
10973) -> T {
10974    let recorded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(record));
10975    let published = publish();
10976    if let Err(panic) = recorded {
10977        error!(
10978            module_id,
10979            "terminal recording panicked; published final state before resuming unwind"
10980        );
10981        std::panic::resume_unwind(panic);
10982    }
10983    published
10984}
10985
10986fn fail_after_wait_error(
10987    module_id: &str,
10988    snapshot: &SharedSnapshot,
10989    terminal_ring: &Arc<Mutex<TerminalRing>>,
10990    spawn_events: &SpawnEventFeed,
10991    detail: String,
10992    failure: &FailureContext,
10993) {
10994    let report = wait_error_exit_report();
10995    publish_after_terminal_record(
10996        module_id,
10997        || {
10998            record_terminal_with_detail(
10999                module_id,
11000                terminal_ring,
11001                spawn_events,
11002                &report,
11003                TerminalDisposition::Failed,
11004                Some(detail),
11005            )
11006        },
11007        || fail_snapshot(snapshot, Some(module_id), Some(report.clone()), failure),
11008    );
11009}
11010
11011#[cfg(test)]
11012fn record_wait_error_terminal(
11013    module_id: &str,
11014    terminal_ring: &Arc<Mutex<TerminalRing>>,
11015    spawn_events: &SpawnEventFeed,
11016) {
11017    record_terminal(
11018        module_id,
11019        terminal_ring,
11020        spawn_events,
11021        &wait_error_exit_report(),
11022        TerminalDisposition::Failed,
11023    );
11024}
11025
11026fn record_terminal(
11027    module_id: &str,
11028    terminal_ring: &Arc<Mutex<TerminalRing>>,
11029    spawn_events: &SpawnEventFeed,
11030    exit_report: &ExitReport,
11031    disposition: TerminalDisposition,
11032) {
11033    record_terminal_with_detail(
11034        module_id,
11035        terminal_ring,
11036        spawn_events,
11037        exit_report,
11038        disposition,
11039        None,
11040    );
11041}
11042
11043/// The ring lock is held only to capture the read (see
11044/// `TerminalJournal::capture_read`), so this module's exits keep recording
11045/// while the journal files are read. Blocking: it reads files.
11046fn durable_terminal_history_of(
11047    terminal_ring: &Mutex<TerminalRing>,
11048    module_id: &str,
11049) -> subc_control::TerminalHistory {
11050    let read = terminal_ring
11051        .lock()
11052        .unwrap_or_else(|p| p.into_inner())
11053        .capture_durable_history();
11054    read.read(module_id)
11055}
11056
11057fn record_terminal_with_detail(
11058    module_id: &str,
11059    terminal_ring: &Arc<Mutex<TerminalRing>>,
11060    spawn_events: &SpawnEventFeed,
11061    exit_report: &ExitReport,
11062    disposition: TerminalDisposition,
11063    disposition_detail: Option<String>,
11064) {
11065    #[cfg(test)]
11066    terminal_history_tests::before_terminal_record(spawn_events);
11067    spawn_events.emit_exited(module_id, exit_report.code, exit_report.signal);
11068    let record = TerminalRecord {
11069        exit_code: exit_report.code,
11070        exit_signal: exit_report.signal,
11071        at_ms: exit_report.at_ms,
11072        disposition,
11073        exit_kind: exit_report.kind.into(),
11074        disposition_detail,
11075    };
11076    terminal_ring
11077        .lock()
11078        .unwrap_or_else(|poisoned| poisoned.into_inner())
11079        .record_exit(module_id, record);
11080}
11081
11082fn untrack_if_registration_released(
11083    process_liveness: &SupervisorProcessLiveness,
11084    registry: &Registry,
11085    module_id: &str,
11086    snapshot: &SharedSnapshot,
11087) {
11088    match registry.get_module(module_id) {
11089        Ok(None) => process_liveness.untrack_if_current(module_id, snapshot),
11090        Ok(Some(_)) => {}
11091        Err(err) => {
11092            warn!(module_id, error = %err, "could not determine whether supervisor liveness can be untracked");
11093        }
11094    }
11095}
11096
11097/// The child's environment plan: inherit the parent's, drop ambient `CK_LOG`,
11098/// then apply the module's configured entries minus daemon-private capture keys.
11099///
11100/// Separated from `spawn_child` only so it can be asserted without spawning a
11101/// process — a duplicate of this logic in a test would pass while the real one
11102/// drifted, which is the defect class this function exists to avoid.
11103/// The subc-wire half of a spawn: `--subc <connection file>` and the launch
11104/// nonce. A `protocol: "none"` module gets neither, because it cannot use
11105/// either and the argument would stop a stock binary from starting at all.
11106/// `SUBC_MODULE_ID` is set on every path since an unread variable is inert.
11107///
11108/// The plain-spawn form, kept for the tests that assert its plan; spawns go
11109/// through [`apply_wire_spawn_args_for_admission`].
11110#[cfg(test)]
11111fn apply_wire_spawn_args(
11112    command: &mut Command,
11113    spec: &ModuleSpec,
11114    connection_file_path: Option<&std::path::Path>,
11115    handle: Option<&SupervisorHandle>,
11116) -> Result<Option<NonceHandoff>, SuperviseError> {
11117    apply_wire_spawn_args_for_role(
11118        command,
11119        spec,
11120        connection_file_path,
11121        handle,
11122        SpawnRole::Plain,
11123    )
11124}
11125
11126/// The read end of a spawn's launch-nonce pipe, prepared by
11127/// [`apply_wire_spawn_args_for_admission`] and installed as the child's descriptor 3
11128/// by the last pre-exec step, just before `spawn()`. Windows prepares a named
11129/// server before spawn and authenticates its client after the child exists.
11130#[cfg(unix)]
11131type NonceHandoff = subc_os::LaunchNonceHandoff;
11132#[cfg(windows)]
11133type NonceHandoff = subc_os::LaunchNoncePipeHandoff;
11134#[cfg(not(any(unix, windows)))]
11135type NonceHandoff = std::convert::Infallible;
11136
11137/// Create the launch nonce that a new module process must present when it
11138/// registers or opens a consumer connection, including a replacement process
11139/// started alongside a still-serving module.
11140///
11141/// A plain spawn replaces the module's recorded nonce. A swap candidate records
11142/// a separate candidate token so the still-serving incumbent and its consumers
11143/// keep their nonce. Both records are installed before the process exists, so
11144/// the child's initial HELLO registration cannot arrive ahead of its nonce.
11145///
11146/// On Unix the nonce is delivered only through a pipe. It is written into
11147/// a pipe whose read end the child gets as descriptor 3, named by
11148/// `SUBC_LAUNCH_NONCE_FD=3:<pipe inode>`: unlike the environment, another
11149/// process of the same user cannot read it with `ps eww`. That handoff is
11150/// returned rather than installed here. The combined descriptor placement runs
11151/// after the cgroup callback and placement barrier, so replacing slots 3-5
11152/// cannot close a descriptor either callback still needs.
11153/// Windows keeps SUBC_LAUNCH_NONCE as well until every module reads the named pipe.
11154#[cfg(test)]
11155fn apply_wire_spawn_args_for_role(
11156    command: &mut Command,
11157    spec: &ModuleSpec,
11158    connection_file_path: Option<&std::path::Path>,
11159    handle: Option<&SupervisorHandle>,
11160    role: SpawnRole,
11161) -> Result<Option<NonceHandoff>, SuperviseError> {
11162    apply_wire_spawn_args_for_admission(command, spec, connection_file_path, handle, role, None)
11163}
11164
11165fn apply_wire_spawn_args_for_admission(
11166    command: &mut Command,
11167    spec: &ModuleSpec,
11168    connection_file_path: Option<&std::path::Path>,
11169    handle: Option<&SupervisorHandle>,
11170    role: SpawnRole,
11171    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
11172) -> Result<Option<NonceHandoff>, SuperviseError> {
11173    command.env(SUBC_MODULE_ID_ENV, &spec.module_id);
11174    // SUBC_LAUNCH_NONCE_FD is removed for every child, `protocol: "none"`
11175    // included: a daemon started from a module's process tree inherits it,
11176    // and passing it on would point the child at a descriptor it does not
11177    // have.
11178    command.env_remove(subc_os::LAUNCH_NONCE_FD_ENV);
11179    #[cfg(windows)]
11180    {
11181        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_ENV);
11182        command.env_remove(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV);
11183    }
11184    // Remove inherited or configured copies too: withholding must mean absent.
11185    command.env_remove(SUBC_LAUNCH_NONCE_ENV);
11186    command.env_remove(subc_os::registration_channel::REGISTRATION_FD_ENV);
11187    command.env_remove(subc_os::registration_channel::REGISTRATION_PIPE_ENV);
11188    command.env_remove(subc_os::registration_channel::DAEMON_PID_ENV);
11189    if role == SpawnRole::Plain {
11190        if let Some(handle) = handle {
11191            #[cfg(all(test, unix))]
11192            {
11193                let pause = {
11194                    let mut slot = handle.plain_identity_policy_pause.lock().unwrap();
11195                    if slot
11196                        .as_ref()
11197                        .is_some_and(|(module, _)| module == &spec.module_id)
11198                    {
11199                        slot.take().map(|(_, pause)| pause)
11200                    } else {
11201                        None
11202                    }
11203                };
11204                if let Some(pause) = pause {
11205                    pause.reached.send(()).unwrap();
11206                    pause.release.recv().unwrap();
11207                }
11208            }
11209            // A rescan preserves the running child's nonce and reservation.
11210            // Replacement spawn preparation applies the new protocol now,
11211            // before protocol:none can return without minting a nonce.
11212            handle.apply_identity_policy(spec, spec.protocol);
11213        }
11214    }
11215    if spec.protocol == ModuleProtocol::None {
11216        return Ok(None);
11217    }
11218    if let Some(connection_file_path) = connection_file_path {
11219        command.arg(SUBC_ARG).arg(connection_file_path);
11220    }
11221
11222    if admission.is_some_and(|admission| admission.launch.is_some()) {
11223        if let Some(handle) = handle {
11224            match role {
11225                SpawnRole::Plain => {
11226                    handle
11227                        .spawn_nonces
11228                        .lock()
11229                        .unwrap_or_else(|p| p.into_inner())
11230                        .remove(&spec.module_id);
11231                    if spec.reserved {
11232                        handle
11233                            .reserved_nonces
11234                            .lock()
11235                            .unwrap_or_else(|p| p.into_inner())
11236                            .insert(spec.module_id.clone(), None);
11237                    }
11238                }
11239                // Swaps still need their lifecycle record, but the empty value
11240                // is not a bearer token and is never accepted by nonce HELLO.
11241                SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, String::new()),
11242            }
11243        }
11244        return Ok(None);
11245    }
11246    // Every subc-wire spawn receives a fresh one-time launch nonce for consumer
11247    // route.open attestation. Reserved modules additionally use the same nonce
11248    // for HELLO id-squatting protection. A respawn rotates both records.
11249    let nonce = generate_launch_nonce()?;
11250    if let Some(handle) = handle {
11251        match role {
11252            SpawnRole::Plain => {
11253                handle.set_spawn_nonce(&spec.module_id, nonce.clone());
11254                if spec.reserved {
11255                    handle.set_reserved_nonce(&spec.module_id, nonce.clone());
11256                }
11257            }
11258            SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, nonce.clone()),
11259        }
11260    }
11261    #[cfg(unix)]
11262    let handoff = {
11263        let handoff =
11264            subc_os::LaunchNonceHandoff::new(&nonce).map_err(|source| SuperviseError::Spawn {
11265                program: spec.program.clone(),
11266                source,
11267                cgroup_path: None,
11268            })?;
11269        command.env(subc_os::LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
11270        Some(handoff)
11271    };
11272    #[cfg(windows)]
11273    let handoff = prepare_windows_nonce_pipe(command, spec, &nonce);
11274    #[cfg(not(any(unix, windows)))]
11275    let handoff = None;
11276    // Older modules still read SUBC_LAUNCH_NONCE to register. Keep that copy
11277    // until the daemon's per-spawn delivery records show that every running
11278    // Windows module has read its secret from the named pipe.
11279    #[cfg(not(unix))]
11280    command.env(SUBC_LAUNCH_NONCE_ENV, nonce);
11281    Ok(handoff)
11282}
11283
11284pub(crate) fn apply_child_env(command: &mut Command, spec: &ModuleSpec) {
11285    command.env_remove(CK_LOG_ENV);
11286    // The spawn role is the supervisor's to set, and only on a swap candidate
11287    // (see `apply_spawn_role`). Removing it here, rather than just not setting
11288    // it, is what makes it absent on a plain spawn: the daemon's own
11289    // environment could carry it, and so could a spec built outside daemon
11290    // config (config refuses it as an `env` key). A module reading it on a
11291    // plain restart would pick the long swap budget and leave callers waiting.
11292    command.env_remove(SUBC_SPAWN_ROLE_ENV);
11293    for (key, value) in &spec.env {
11294        // cortexkit-log currently exposes retention only as a Rust struct, not
11295        // environment names. These values are daemon-private sink metadata and
11296        // must never become a public child-process contract by being inherited.
11297        if matches!(
11298            key.as_str(),
11299            CAPTURE_MAX_FILE_MB_ENV | CAPTURE_KEEP_ENV | CAPTURE_MAX_AGE_DAYS_ENV
11300        ) || key == SUBC_SPAWN_ROLE_ENV
11301        {
11302            continue;
11303        }
11304        command.env(key, value);
11305    }
11306}
11307
11308#[cfg(windows)]
11309fn prepare_windows_registration_pipe(
11310    command: &mut Command,
11311    spec: &ModuleSpec,
11312) -> Result<Option<SpawnRegistrationChannel>, SuperviseError> {
11313    if spec.protocol == ModuleProtocol::None {
11314        return Ok(None);
11315    }
11316    let pipe = subc_os::registration_channel::RegistrationPipe::new().map_err(|source| {
11317        SuperviseError::Spawn {
11318            program: spec.program.clone(),
11319            source,
11320            cgroup_path: None,
11321        }
11322    })?;
11323    command
11324        .env(
11325            subc_os::registration_channel::REGISTRATION_PIPE_ENV,
11326            pipe.name(),
11327        )
11328        .env(
11329            subc_os::registration_channel::DAEMON_PID_ENV,
11330            std::process::id().to_string(),
11331        );
11332    Ok(Some(pipe))
11333}
11334
11335#[cfg(windows)]
11336fn prepare_windows_nonce_pipe(
11337    command: &mut Command,
11338    spec: &ModuleSpec,
11339    nonce: &str,
11340) -> Option<NonceHandoff> {
11341    match subc_os::LaunchNoncePipeHandoff::new(nonce) {
11342        Ok(handoff) => {
11343            command.env(subc_os::LAUNCH_NONCE_PIPE_ENV, handoff.name());
11344            // Let a failed pipe read use SUBC_LAUNCH_NONCE so the process can
11345            // still register until every module reads the pipe. A reader without
11346            // this variable set to env returns the pipe error instead of using
11347            // an inherited or configured environment copy.
11348            command.env(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV, "env");
11349            Some(handoff)
11350        }
11351        Err(error) => {
11352            warn!(module_id = %spec.module_id, %error, "could not prepare launch nonce pipe; retaining the environment handoff");
11353            None
11354        }
11355    }
11356}
11357
11358#[cfg(windows)]
11359fn start_windows_nonce_pipe(
11360    handoff: Option<NonceHandoff>,
11361    pid: u32,
11362    spec: &ModuleSpec,
11363) -> Option<subc_os::LaunchNoncePipeDelivery> {
11364    // Close an unread pipe after REGISTRY_RELEASE_TIMEOUT (one second), the
11365    // same maximum wait used for registration during a reload. Older modules
11366    // may register using SUBC_LAUNCH_NONCE without ever connecting to the pipe.
11367    handoff.and_then(|handoff| match handoff.serve(pid, REGISTRY_RELEASE_TIMEOUT) {
11368        Ok(delivery) => Some(delivery),
11369        Err(error) => {
11370            warn!(module_id = %spec.module_id, %error, "could not serve launch nonce pipe; retaining the environment handoff");
11371            None
11372        }
11373    })
11374}
11375
11376fn observed_launch_nonce_source(snapshot: &SupervisorSnapshot) -> Option<String> {
11377    #[cfg(windows)]
11378    if snapshot.process_alive && snapshot.spawned_protocol == Some(ModuleProtocol::Subc) {
11379        return Some(
11380            if snapshot
11381                .pipe_consumed
11382                .as_ref()
11383                .is_some_and(|consumed| consumed.get().is_some())
11384            {
11385                "pipe"
11386            } else {
11387                "env"
11388            }
11389            .to_owned(),
11390        );
11391    }
11392    let _ = snapshot;
11393    None
11394}
11395
11396/// Which slot a spawn fills: the module's ordinary one, or the candidate slot
11397/// of a blue/green swap.
11398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11399enum SpawnRole {
11400    Plain,
11401    SwapCandidate,
11402}
11403
11404/// Set the spawn role for a swap candidate. A plain spawn gets nothing here;
11405/// `apply_child_env` has already removed the variable for every spawn.
11406fn apply_spawn_role(command: &mut Command, role: SpawnRole) {
11407    if role == SpawnRole::SwapCandidate {
11408        command.env(SUBC_SPAWN_ROLE_ENV, SPAWN_ROLE_SWAP_CANDIDATE);
11409    }
11410}
11411
11412fn previous_instance_error(
11413    spec: &ModuleSpec,
11414    pid: u32,
11415    reason: crate::live_children::RetainedReason,
11416) -> SuperviseError {
11417    SuperviseError::Spawn {
11418        program: spec.program.clone(),
11419        source: io::Error::new(io::ErrorKind::WouldBlock, reason.waiting_message(pid)),
11420        cgroup_path: None,
11421    }
11422}
11423
11424fn carries_containment(configured: bool, has_container: bool) -> bool {
11425    configured || has_container
11426}
11427
11428fn recovery_block_error(spec: &ModuleSpec, roster: &ChildRoster) -> Option<SuperviseError> {
11429    if !carries_containment(
11430        spec.carry_containment,
11431        containment::current(&roster.containment).is_some(),
11432    ) {
11433        return None;
11434    }
11435    Some(SuperviseError::Spawn {
11436        program: spec.program.clone(),
11437        source: io::Error::new(io::ErrorKind::WouldBlock, roster.recovery_block()?),
11438        cgroup_path: None,
11439    })
11440}
11441
11442#[allow(clippy::too_many_arguments)]
11443fn spawn_child(
11444    spec: &ModuleSpec,
11445    connection_file_path: Option<&std::path::Path>,
11446    handle: Option<&SupervisorHandle>,
11447    ring: &Arc<Mutex<StderrRing>>,
11448    capture_logs_dir: Option<&std::path::Path>,
11449    roster: &ChildRoster,
11450    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11451    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11452    register_timeout: Duration,
11453) -> Result<SupervisedChild, SuperviseError> {
11454    #[cfg(all(test, unix))]
11455    if let Some(source) = containment_tests::join_failure(spec, roster) {
11456        containment::terminate_blocking(&roster.containment);
11457        return Err(SuperviseError::Spawn {
11458            program: spec.program.clone(),
11459            source,
11460            cgroup_path: None,
11461        });
11462    }
11463    let result = spawn_child_in_slot(
11464        spec,
11465        connection_file_path,
11466        handle,
11467        ring,
11468        capture_logs_dir,
11469        roster,
11470        config_delivery,
11471        #[cfg(target_os = "linux")]
11472        cgroup_placement,
11473        SpawnRole::Plain,
11474        false,
11475        register_timeout,
11476    );
11477    if result
11478        .as_ref()
11479        .is_err_and(|error| !is_launch_deferral(error))
11480    {
11481        if roster.admission_pending(&spec.module_id) {
11482            containment::terminate_deferred(&roster.containment);
11483        } else {
11484            containment::terminate_blocking(&roster.containment);
11485        }
11486    }
11487    result
11488}
11489
11490/// A configuration deferral means the launch never started: the module gate
11491/// or the configuration owner was briefly busy, and every caller schedules
11492/// the same launch again shortly. A carried container stays for that retry,
11493/// as it does across a restart backoff; ending it here would kill the
11494/// module's helpers and give up the group the retry is meant to join.
11495fn is_launch_deferral(error: &SuperviseError) -> bool {
11496    matches!(error, SuperviseError::ConfigDeliveryDeferred { .. })
11497}
11498
11499/// Spawn one process of `spec` into a slot.
11500///
11501/// `alternate_slot` picks the process's cgroup label on Linux (see `swap::cgroup_name`).
11502/// A swap candidate needs a different cgroup from the process it is replacing,
11503/// which is still alive: in the same cgroup the two would be one kill domain,
11504/// and killing a failed candidate could take the incumbent with it.
11505///
11506/// The stderr capture file is `<module_id>.stderr.log` for every process of
11507/// the module, whichever slot it is in, because that is the one file
11508/// `ck module logs` reads. During a swap's overlap both processes append to it;
11509/// the daemon writes whole lines, so the two interleave by line, which is also
11510/// the merged view an operator wants while a swap runs.
11511#[allow(clippy::too_many_arguments)]
11512fn spawn_child_in_slot(
11513    spec: &ModuleSpec,
11514    connection_file_path: Option<&std::path::Path>,
11515    handle: Option<&SupervisorHandle>,
11516    ring: &Arc<Mutex<StderrRing>>,
11517    capture_logs_dir: Option<&std::path::Path>,
11518    roster: &ChildRoster,
11519    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11520    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11521    role: SpawnRole,
11522    alternate_slot: bool,
11523    register_timeout: Duration,
11524) -> Result<SupervisedChild, SuperviseError> {
11525    let prepared = prepare_child_in_slot(
11526        spec,
11527        connection_file_path,
11528        handle,
11529        capture_logs_dir,
11530        roster,
11531        config_delivery,
11532        #[cfg(target_os = "linux")]
11533        cgroup_placement,
11534        role,
11535        alternate_slot,
11536        false,
11537    )?;
11538    let gate = config_delivery
11539        .map(|delivery| delivery.module_gate(spec))
11540        .transpose()?;
11541    let _gate = gate
11542        .as_ref()
11543        .map(|gate| {
11544            gate.try_lock()
11545                .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
11546                    module_id: spec.module_id.clone(),
11547                })
11548        })
11549        .transpose()?;
11550    if let (Some(delivery), Some(admission)) = (config_delivery, &prepared.spawn_admission) {
11551        delivery.check(spec, admission)?;
11552    }
11553    let checked_base = prepared
11554        .spawn_admission
11555        .as_ref()
11556        .and_then(|admission| admission.approved_base())
11557        .cloned();
11558    let mut result = launch_child_in_slot(spec, ring, roster, prepared, register_timeout);
11559    drop(_gate);
11560    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
11561        (config_delivery, &result)
11562    {
11563        if let Some(base) = checked_base.as_ref().filter(|_| code == "program_refused") {
11564            if !delivery.record_refusal(spec, base, detail)? {
11565                result = Err(spawn_plan_stale(spec));
11566            }
11567        }
11568    }
11569    result
11570}
11571
11572struct AsyncInitialIdentity<'a> {
11573    supervisor: &'a Supervisor,
11574    module: String,
11575    committed: bool,
11576}
11577impl Drop for AsyncInitialIdentity<'_> {
11578    fn drop(&mut self) {
11579        if !self.committed {
11580            self.supervisor.abandon_unrostered(&self.module);
11581        }
11582    }
11583}
11584
11585/// Child-free preparation can be abandoned without orphaning a process. After
11586/// this value returns, the async caller validates its launch witness and creates
11587/// and publishes the child without another await.
11588struct PreparedChild {
11589    script_delivery: Option<script::Delivery>,
11590    registration_spawn: Option<Arc<RegistrationSpawn>>,
11591    registration_handle: Option<SupervisorHandle>,
11592    #[cfg(any(unix, windows))]
11593    registration_channel: Option<SpawnRegistrationChannel>,
11594    config_context: Option<config_delivery::ConfigDelivery>,
11595    binding_publication: Option<ProgramBindingPublication>,
11596    launch_spec: ModuleSpec,
11597    spawn_admission: Option<crate::config_gate::runtime::SpawnAdmission>,
11598    command: Command,
11599    carrying: bool,
11600    carried: Option<Arc<containment::CarriedContainment>>,
11601    #[cfg(unix)]
11602    launch_identity: Option<containment::LaunchIdentity>,
11603    #[cfg(unix)]
11604    group_target: containment::GroupTarget,
11605    #[cfg(target_os = "linux")]
11606    cgroup_placement: Option<subc_cgroup::Placement>,
11607    #[cfg(target_os = "linux")]
11608    cgroup_name: String,
11609    #[cfg(target_os = "linux")]
11610    cgroup_cleanup: PreparedCgroup,
11611    cgroup_path: Option<PathBuf>,
11612    #[cfg(unix)]
11613    admission_gate: Option<admission::Gate>,
11614    output_sink: ChildOutputSink,
11615    #[cfg(target_os = "macos")]
11616    privacy_exec: Option<PrivacyExec>,
11617    #[cfg(windows)]
11618    image_capture: subc_os::ExecutableCapture,
11619    #[cfg(windows)]
11620    nonce_handoff: Option<NonceHandoff>,
11621    spawned_at: Instant,
11622    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
11623    delivery_registration: Option<config_delivery::RegistrationGuard>,
11624    program_binding: Option<SpawnProgramBinding>,
11625}
11626
11627#[cfg(target_os = "linux")]
11628struct PreparedCgroup(Option<(subc_cgroup::Placement, String)>);
11629#[cfg(target_os = "linux")]
11630impl Drop for PreparedCgroup {
11631    fn drop(&mut self) {
11632        if let Some((placement, name)) = &self.0 {
11633            remove_module_cgroup(placement, name);
11634        }
11635    }
11636}
11637
11638pub(crate) struct SpawnProgramBinding {
11639    pub(crate) path: PathBuf,
11640    // Keep the inode alive if the configured name is replaced while preparation
11641    // is suspended, so replacement cannot pass through inode reuse.
11642    _file: std::fs::File,
11643    pub(crate) identity: subc_os::RetainedFileIdentity,
11644}
11645
11646impl SpawnProgramBinding {
11647    pub(crate) fn capture(spec: &ModuleSpec) -> Result<Self, SuperviseError> {
11648        Self::capture_after_resolution(spec, |_| {})
11649    }
11650
11651    fn capture_after_resolution(
11652        spec: &ModuleSpec,
11653        before_open: impl FnOnce(&std::path::Path),
11654    ) -> Result<Self, SuperviseError> {
11655        require_program_search_path(spec)?;
11656        #[cfg(windows)]
11657        let windows_capture =
11658            windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
11659                program: spec.program.clone(),
11660                source,
11661                cgroup_path: None,
11662            })?;
11663        #[cfg(windows)]
11664        let path = windows_capture.path().to_path_buf();
11665        #[cfg(not(windows))]
11666        let path = if spec.program.is_absolute() || spec.program.components().count() > 1 {
11667            spec.program.clone()
11668        } else {
11669            let path = spec
11670                .env
11671                .iter()
11672                .rev()
11673                .find(|(key, _)| key == "PATH")
11674                .map(|(_, path)| std::ffi::OsString::from(path))
11675                .or_else(|| std::env::var_os("PATH"))
11676                .unwrap_or_else(|| {
11677                    if cfg!(target_os = "macos") {
11678                        // Match Darwin's spawn search when PATH is absent, not
11679                        // the current-directory search of an explicitly empty PATH.
11680                        "/usr/bin:/bin".into()
11681                    } else {
11682                        Default::default()
11683                    }
11684                });
11685            std::env::split_paths(&path)
11686                .map(|dir| dir.join(&spec.program))
11687                .find(|path| {
11688                    if !path.is_file() {
11689                        return false;
11690                    }
11691                    #[cfg(unix)]
11692                    {
11693                        rustix::fs::accessat(
11694                            rustix::fs::CWD,
11695                            path,
11696                            rustix::fs::Access::EXEC_OK,
11697                            rustix::fs::AtFlags::EACCESS,
11698                        )
11699                        .is_ok()
11700                    }
11701                    #[cfg(not(unix))]
11702                    {
11703                        true
11704                    }
11705                })
11706                .ok_or_else(|| SuperviseError::Spawn {
11707                    program: spec.program.clone(),
11708                    source: io::Error::new(io::ErrorKind::NotFound, "executable not found in PATH"),
11709                    cgroup_path: None,
11710                })?
11711        };
11712        let resolved = std::fs::canonicalize(&path).map_err(|source| SuperviseError::Spawn {
11713            program: spec.program.clone(),
11714            source,
11715            cgroup_path: None,
11716        })?;
11717        before_open(&resolved);
11718        // Resolving links does not open their target. The descriptor open must
11719        // remain nonblocking and no-follow if that resolved name is substituted.
11720        let file =
11721            subc_os::open_regular_nofollow(&resolved).map_err(|source| SuperviseError::Spawn {
11722                program: spec.program.clone(),
11723                source: io::Error::other(source),
11724                cgroup_path: None,
11725            })?;
11726        let identity =
11727            subc_os::retained_file_identity(&file).map_err(|source| SuperviseError::Spawn {
11728                program: spec.program.clone(),
11729                source,
11730                cgroup_path: None,
11731            })?;
11732        Ok(Self {
11733            path,
11734            _file: file,
11735            identity,
11736        })
11737    }
11738    fn current(&self) -> bool {
11739        #[cfg(unix)]
11740        {
11741            subc_os::file_identity(&self.path) == Some(self.identity)
11742        }
11743        #[cfg(windows)]
11744        {
11745            std::fs::canonicalize(&self.path)
11746                .ok()
11747                .and_then(|path| subc_os::open_regular_nofollow(&path).ok())
11748                .and_then(|file| subc_os::retained_file_identity(&file).ok())
11749                == Some(self.identity)
11750        }
11751    }
11752}
11753
11754fn spawn_plan_stale(spec: &ModuleSpec) -> SuperviseError {
11755    SuperviseError::ConfigDeliveryDeferred {
11756        module_id: spec.module_id.clone(),
11757    }
11758}
11759
11760fn require_program_search_path(spec: &ModuleSpec) -> Result<(), SuperviseError> {
11761    if !cfg!(target_os = "macos")
11762        && !spec.program.is_absolute()
11763        && spec.program.components().count() == 1
11764        && !spec.env.iter().any(|(key, _)| {
11765            if cfg!(windows) {
11766                key.eq_ignore_ascii_case("PATH")
11767            } else {
11768                key == "PATH"
11769            }
11770        })
11771        && std::env::var_os("PATH").is_none()
11772    {
11773        // The OS default search is not a current-directory search. Refusing an
11774        // unspecified search path prevents approving a decoy in the current directory.
11775        return Err(SuperviseError::Spawn {
11776            program: spec.program.clone(),
11777            source: io::Error::new(io::ErrorKind::InvalidInput, "bare program requires PATH"),
11778            cgroup_path: None,
11779        });
11780    }
11781    Ok(())
11782}
11783
11784async fn spawn_child_async(
11785    spec: &ModuleSpec,
11786    runtime: &SupervisorRuntimeConfig,
11787) -> Result<SupervisedChild, SuperviseError> {
11788    #[cfg(all(test, unix))]
11789    if let Some(source) = containment_tests::join_failure(spec, &runtime.child_roster) {
11790        containment::terminate_blocking(&runtime.child_roster.containment);
11791        return Err(SuperviseError::Spawn {
11792            program: spec.program.clone(),
11793            source,
11794            cgroup_path: None,
11795        });
11796    }
11797    let result = spawn_child_in_slot_async(spec, runtime, SpawnRole::Plain, false).await;
11798    if result
11799        .as_ref()
11800        .is_err_and(|error| !is_launch_deferral(error))
11801    {
11802        if runtime.child_roster.admission_pending(&spec.module_id) {
11803            containment::terminate_deferred(&runtime.child_roster.containment);
11804        } else {
11805            containment::terminate_blocking(&runtime.child_roster.containment);
11806        }
11807    }
11808    result
11809}
11810
11811async fn spawn_child_in_slot_async(
11812    spec: &ModuleSpec,
11813    runtime: &SupervisorRuntimeConfig,
11814    role: SpawnRole,
11815    alternate_slot: bool,
11816) -> Result<SupervisedChild, SuperviseError> {
11817    let gate = runtime
11818        .config_delivery
11819        .as_ref()
11820        .map(|delivery| delivery.0.module_gate(&spec.module_id))
11821        .transpose()
11822        .map_err(|error| SuperviseError::InvalidSpec {
11823            reason: error.to_string(),
11824        })?;
11825    if gate.as_ref().is_some_and(|gate| gate.try_lock().is_err()) {
11826        return Err(SuperviseError::ConfigDeliveryDeferred {
11827            module_id: spec.module_id.clone(),
11828        });
11829    }
11830    let prepared_spec = spec.clone();
11831    let prepared_runtime = runtime.clone();
11832    let prepared = tokio::task::spawn_blocking(move || {
11833        let prepared = prepare_child_in_slot(
11834            &prepared_spec,
11835            prepared_runtime.connection_file_path.as_deref(),
11836            prepared_runtime.supervisor_handle.as_ref(),
11837            prepared_runtime.capture_logs_dir.as_deref(),
11838            &prepared_runtime.child_roster,
11839            prepared_runtime.spawn_delivery(),
11840            #[cfg(target_os = "linux")]
11841            prepared_runtime.cgroup_placement.as_ref(),
11842            role,
11843            alternate_slot,
11844            true,
11845        );
11846        prepared
11847    })
11848    .await
11849    .map_err(|_| SuperviseError::InvalidSpec {
11850        reason: "configuration launch preparation stopped".into(),
11851    })??;
11852    if let Some(registration) = &prepared.delivery_registration {
11853        if !registration.launch_current()? {
11854            return Err(spawn_plan_stale(spec));
11855        }
11856    }
11857    let _gate = match gate {
11858        Some(gate) => {
11859            Some(
11860                gate.try_lock_owned()
11861                    .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
11862                        module_id: spec.module_id.clone(),
11863                    })?,
11864            )
11865        }
11866        None => None,
11867    };
11868    if let (Some(delivery), Some(admission)) = (runtime.spawn_delivery(), &prepared.spawn_admission)
11869    {
11870        delivery.check(spec, admission)?;
11871    }
11872    if prepared
11873        .spawn_admission
11874        .as_ref()
11875        .is_none_or(|admission| admission.launch.is_none())
11876        && prepared
11877            .program_binding
11878            .as_ref()
11879            .is_some_and(|binding| !binding.current())
11880    {
11881        return Err(spawn_plan_stale(spec));
11882    }
11883    // No await may separate this last identity check from ownership publication.
11884    let checked_base = prepared
11885        .spawn_admission
11886        .as_ref()
11887        .and_then(|admission| admission.approved_base())
11888        .cloned();
11889    let mut result = launch_child_in_slot(
11890        spec,
11891        &runtime.stderr_ring,
11892        &runtime.child_roster,
11893        prepared,
11894        runtime.register_timeout,
11895    );
11896    drop(_gate);
11897    if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
11898        (runtime.config_delivery.as_ref(), &result)
11899    {
11900        if let Some(base) = checked_base.filter(|_| code == "program_refused") {
11901            let module = spec.module_id.clone();
11902            let identity = subc_config::raw_digest(detail.as_bytes());
11903            let recorded = delivery
11904                .0
11905                .on_blocking(move |owner| owner.record_program_refusal(&module, &base, identity))
11906                .await;
11907            match recorded {
11908                Ok(true) => {}
11909                Ok(false) => result = Err(spawn_plan_stale(spec)),
11910                Err(error) => {
11911                    result = Err(config_delivery::gate_hold_error(
11912                        spec,
11913                        error,
11914                        Some(delivery),
11915                    ))
11916                }
11917            }
11918        }
11919    }
11920    result
11921}
11922
11923fn validate_spawn_program(
11924    spec: &ModuleSpec,
11925    admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
11926    delivery: Option<config_delivery::SpawnDelivery<'_>>,
11927) -> Result<(), SuperviseError> {
11928    if let Some(admission) = admission {
11929        if let Some(program) = &admission.launch {
11930            if let Err(error) = program.validate_for_spawn() {
11931                // A captured unsigned image is a definite refusal. Uncertain
11932                // reads are deferred by validate_for_spawn, not attributed to
11933                // the operator as a changed or unapprovable program.
11934                if let (Some(context), Some(base)) = (delivery, admission.approved_base()) {
11935                    if error.code == "program_refused"
11936                        && !context.record_refusal(spec, base, &error.detail)?
11937                    {
11938                        return Err(spawn_plan_stale(spec));
11939                    }
11940                }
11941                return Err(config_delivery::gate_hold_error(
11942                    spec,
11943                    error,
11944                    delivery.map(|context| context.runtime()).as_ref(),
11945                ));
11946            }
11947        }
11948    }
11949    Ok(())
11950}
11951
11952#[allow(clippy::too_many_arguments)]
11953fn prepare_child_in_slot(
11954    spec: &ModuleSpec,
11955    connection_file_path: Option<&std::path::Path>,
11956    handle: Option<&SupervisorHandle>,
11957    capture_logs_dir: Option<&std::path::Path>,
11958    roster: &ChildRoster,
11959    config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11960    #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11961    role: SpawnRole,
11962    alternate_slot: bool,
11963    asynchronous: bool,
11964) -> Result<PreparedChild, SuperviseError> {
11965    require_program_search_path(spec)?;
11966    let spawn_admission = config_delivery
11967        .map(|delivery| delivery.prepare(spec))
11968        .transpose()?;
11969    #[cfg(target_os = "macos")]
11970    let gated = spawn_admission
11971        .as_ref()
11972        .is_some_and(|admission| admission.approved_base().is_some());
11973    let mut launch_spec = spawn_admission
11974        .as_ref()
11975        .and_then(|admission| admission.launch.as_ref())
11976        .map(|launch| launch.spec.clone())
11977        .unwrap_or_else(|| spec.clone());
11978    if let Some(script) = &launch_spec.script {
11979        launch_spec.program =
11980            script::runner_path(script.runtime).map_err(|source| SuperviseError::Spawn {
11981                program: launch_spec.program.clone(),
11982                source,
11983                cgroup_path: None,
11984            })?;
11985    }
11986    let script_content = if let Some(entry) = &launch_spec.script {
11987        Some(
11988            spawn_admission
11989                .as_ref()
11990                .and_then(|admission| admission.launch.as_ref())
11991                .and_then(|launch| launch.script.clone())
11992                .map_or_else(|| script::ScriptBytes::read(&entry.path), Ok)
11993                .map_err(|error| config_delivery::gate_hold_error(&launch_spec, error, None))?,
11994        )
11995    } else {
11996        None
11997    };
11998    let spec = &launch_spec;
11999    if let Some(error) = recovery_block_error(spec, roster) {
12000        return Err(error);
12001    }
12002    if let Some((pid, reason)) = roster.previous_instance(&spec.module_id) {
12003        return Err(previous_instance_error(spec, pid, reason));
12004    }
12005    if roster.is_closed() {
12006        return Err(SuperviseError::Spawn {
12007            program: spec.program.clone(),
12008            source: io::Error::other("the daemon is shutting down; not starting a new process"),
12009            cgroup_path: None,
12010        });
12011    }
12012    let carried = containment::current(&roster.containment);
12013    let carrying = carries_containment(spec.carry_containment, carried.is_some());
12014    if role != SpawnRole::Plain && carrying {
12015        return Err(SuperviseError::InvalidSpec {
12016            reason: "a carried container cannot overlap a swap candidate".to_owned(),
12017        });
12018    }
12019    #[cfg(unix)]
12020    let launch_identity = if carrying && carried.is_none() {
12021        Some(
12022            containment::LaunchIdentity::capture().map_err(|source| SuperviseError::Spawn {
12023                program: spec.program.clone(),
12024                source,
12025                cgroup_path: None,
12026            })?,
12027        )
12028    } else {
12029        None
12030    };
12031    #[cfg(target_os = "linux")]
12032    let cgroup_placement = match &carried {
12033        Some(container) => container.cgroup().map(|(placement, _)| placement),
12034        None => cgroup_placement,
12035    };
12036    #[cfg(unix)]
12037    let group_target = if let Some(container) = carried
12038        .as_ref()
12039        .filter(|container| container.group().is_some())
12040    {
12041        containment::GroupTarget::Pinned(Arc::clone(container))
12042    } else {
12043        #[cfg(target_os = "linux")]
12044        let cgroup_container = carrying && cgroup_placement.is_some();
12045        #[cfg(not(target_os = "linux"))]
12046        let cgroup_container = false;
12047        if cgroup_container {
12048            containment::GroupTarget::NoGroup
12049        } else {
12050            containment::GroupTarget::OwnLeader
12051        }
12052    };
12053    #[cfg(target_os = "linux")]
12054    let cgroup_name = {
12055        // Slot names alone are not kill domains: a retired incumbent may still
12056        // be draining when a later enable/restart spawns into the same slot.
12057        // Decimal entropy keeps the suffix unambiguous; Placement performs
12058        // the module-id escaping and constructs the filesystem path.
12059        if let Some((_, name)) = carried.as_ref().and_then(|container| container.cgroup()) {
12060            name.to_owned()
12061        } else if cgroup_placement.is_none() {
12062            swap::cgroup_name(&spec.module_id, alternate_slot)
12063        } else {
12064            let nonce = generate_launch_nonce()?;
12065            let suffix = u128::from_str_radix(&nonce[..32], 16).expect("hex launch nonce");
12066            // Leave room for byte escaping and the suffix under NAME_MAX. The
12067            // label is only for humans; the nonce identifies the kill domain.
12068            let mut end = spec.module_id.len().min(64);
12069            while !spec.module_id.is_char_boundary(end) {
12070                end -= 1;
12071            }
12072            format!(
12073                "{}_{suffix}",
12074                swap::cgroup_name(&spec.module_id[..end], alternate_slot)
12075            )
12076        }
12077    };
12078    #[cfg(not(target_os = "linux"))]
12079    let _ = alternate_slot;
12080    #[cfg(windows)]
12081    let image_capture = windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
12082        program: spec.program.clone(),
12083        source,
12084        cgroup_path: None,
12085    })?;
12086    #[cfg(windows)]
12087    let program_binding = if asynchronous {
12088        let mut resolved = spec.clone();
12089        resolved.program = image_capture.path().to_path_buf();
12090        Some(SpawnProgramBinding::capture(&resolved)?)
12091    } else {
12092        None
12093    };
12094    #[cfg(not(windows))]
12095    let program_binding = (asynchronous || cfg!(target_os = "macos"))
12096        .then(|| SpawnProgramBinding::capture(spec))
12097        .transpose()?;
12098    #[cfg(target_os = "macos")]
12099    validate_spawn_program(spec, spawn_admission.as_ref(), config_delivery)?;
12100    #[cfg(target_os = "macos")]
12101    let (mut command, privacy_exec, exec_ack) = privacy_command(
12102        spec,
12103        program_binding
12104            .as_ref()
12105            .expect("macOS captures every launch"),
12106        roster,
12107        // Ungated launches retain legacy unsuspended exec, including scripts. Suspended
12108        // verification admits approved programs only. prepare() above fails
12109        // closed if the gate cannot decide; an image sample is not authority.
12110        gated,
12111    )?;
12112    #[cfg(windows)]
12113    let mut command = Command::new(image_capture.path());
12114    #[cfg(not(any(target_os = "macos", windows)))]
12115    let mut command = Command::new(
12116        program_binding
12117            .as_ref()
12118            .map_or(spec.program.as_path(), |binding| binding.path.as_path()),
12119    );
12120    command.args(&spec.args);
12121    // AMBIENT `CK_LOG` MUST NOT LEAK INTO AN OTHERWISE UNCONFIGURED MODULE — but
12122    // that is the whole of the intent, so remove that one key rather than the
12123    // environment.
12124    //
12125    // This was `env_clear()` from 0.17.41 until 0.18.3, which achieved the goal
12126    // and took the POSIX environment with it. Modules spawned that way had no
12127    // HOME, XDG_RUNTIME_DIR, TMPDIR or USER, and the consequences ran past
12128    // logging:
12129    //
12130    //   * `connection_file::discover` reads XDG_RUNTIME_DIR and HOME, so with
12131    //     both unset it fell back to the temp dir alone and `ck` could not find
12132    //     a daemon running on the same machine from inside any module's process
12133    //     tree — reporting a path the file has never lived at, which reads as
12134    //     "the daemon did not write its file".
12135    //   * `default_data_home()` with HOME and XDG_DATA_HOME both unset returns
12136    //     the RELATIVE `.local/share`, so a module deriving its own store path
12137    //     resolved it against its own CWD. That is the store-fragmentation
12138    //     defect the daemon already refuses in config (`parse_doc` rejects a
12139    //     relative `storage.data_home`) arriving by derivation instead.
12140    //   * anything a module spawns inherited it: git without ~/.gitconfig,
12141    //     cargo without CARGO_HOME, ssh, python user dirs — all degrading
12142    //     quietly rather than erroring.
12143    //
12144    // Reported by iceteaSA as #104 after deploying 0.18.2, where `ck daemon`
12145    // offered one candidate under /tmp while the file sat in /run/user/1000.
12146    //
12147    // A configured module is unaffected either way: `module_spec()` puts the
12148    // resolved CK_LOG into `spec.env`, which is applied below and therefore
12149    // wins over anything ambient.
12150    apply_child_env(&mut command, spec);
12151    if spec.script.is_some() {
12152        script::remove_runtime_env(&mut command, spec);
12153    }
12154    let origin_witness = crate::program_origin::LaunchWitness::capture_command(spec, &command)
12155        .map_err(|source| SuperviseError::Spawn {
12156            program: spec.program.clone(),
12157            source,
12158            cgroup_path: None,
12159        })?;
12160    command.current_dir(&origin_witness.working_directory);
12161    apply_spawn_role(&mut command, role);
12162    let nonce_handoff = apply_wire_spawn_args_for_admission(
12163        &mut command,
12164        spec,
12165        connection_file_path,
12166        handle,
12167        role,
12168        spawn_admission.as_ref(),
12169    )?;
12170    #[cfg(unix)]
12171    let mut slots = subc_os::registration_channel::ChildDescriptorSlots::default();
12172    command.env_remove(subc_os::script_pipe::SCRIPT_FD_ENV);
12173    let script_delivery = script_content
12174        .map(|content| {
12175            script::Delivery::prepare(
12176                content,
12177                &mut command,
12178                #[cfg(unix)]
12179                &mut slots,
12180            )
12181        })
12182        .transpose()
12183        .map_err(|source| SuperviseError::Spawn {
12184            program: spec.program.clone(),
12185            source,
12186            cgroup_path: None,
12187        })?;
12188    #[cfg(unix)]
12189    let registration_channel = if spec.protocol == ModuleProtocol::Subc {
12190        let (parent, child, metadata) = subc_os::registration_channel::registration_socketpair()
12191            .map_err(|source| SuperviseError::Spawn {
12192                program: spec.program.clone(),
12193                source,
12194                cgroup_path: None,
12195            })?;
12196        slots
12197            .channel(child)
12198            .map_err(|source| SuperviseError::Spawn {
12199                program: spec.program.clone(),
12200                source,
12201                cgroup_path: None,
12202            })?;
12203        command
12204            .env(subc_os::registration_channel::REGISTRATION_FD_ENV, metadata)
12205            .env(
12206                subc_os::registration_channel::DAEMON_PID_ENV,
12207                std::process::id().to_string(),
12208            );
12209        Some(parent)
12210    } else {
12211        None
12212    };
12213    #[cfg(windows)]
12214    let registration_channel = prepare_windows_registration_pipe(&mut command, spec)?;
12215    let binding_publication = if spawn_admission
12216        .as_ref()
12217        .is_some_and(|admission| admission.launch.is_some())
12218    {
12219        handle.and_then(|handle| handle.begin_program_binding(&spec.module_id, role))
12220    } else {
12221        None
12222    };
12223    let registration_spawn = (spec.protocol == ModuleProtocol::Subc)
12224        .then(|| {
12225            handle.map(|handle| {
12226                let spawn = RegistrationSpawn::new_with_binding_requirement(
12227                    handle,
12228                    &spec.module_id,
12229                    role,
12230                    binding_publication.clone(),
12231                    spawn_admission
12232                        .as_ref()
12233                        .is_some_and(|admission| admission.launch.is_some()),
12234                );
12235                if let Some(admission) = &spawn_admission {
12236                    admission.initialize_origin(&spawn.authority, &origin_witness);
12237                }
12238                handle.record_nonce_launch(&spawn);
12239                spawn
12240            })
12241        })
12242        .flatten();
12243
12244    #[cfg(target_os = "linux")]
12245    let cgroup_path = cgroup_placement
12246        .map(|placement| {
12247            if let Some(container) = &carried {
12248                let path = container
12249                    .cgroup_path()
12250                    .ok_or_else(|| io::Error::other("carried container has no cgroup path"))?;
12251                placement.existing_module_path(path)?.ok_or_else(|| {
12252                    io::Error::new(
12253                        io::ErrorKind::NotFound,
12254                        "carried cgroup disappeared before replacement",
12255                    )
12256                })
12257            } else {
12258                if carrying {
12259                    containment::prepare_cgroup_path(placement, &cgroup_name)
12260                } else {
12261                    placement.module_path(&cgroup_name)
12262                }
12263            }
12264        })
12265        .transpose()
12266        .map_err(|source| SuperviseError::Cgroup {
12267            module_id: spec.module_id.clone(),
12268            source,
12269        })?;
12270    #[cfg(not(target_os = "linux"))]
12271    let cgroup_path: Option<PathBuf> = None;
12272    // Own a newly created directory before any fallible admission or command
12273    // preparation. Existing carried containment must never be removed here.
12274    #[cfg(target_os = "linux")]
12275    let cgroup_cleanup = PreparedCgroup(
12276        cgroup_placement
12277            .filter(|_| carried.is_none())
12278            .map(|placement| (placement.clone(), cgroup_name.clone())),
12279    );
12280    #[cfg(unix)]
12281    let mut admission_gate = if carrying {
12282        Some(
12283            admission::Gate::install(&mut command, spec, roster).map_err(|source| {
12284                SuperviseError::Spawn {
12285                    program: spec.program.clone(),
12286                    source,
12287                    cgroup_path: cgroup_path.clone(),
12288                }
12289            })?,
12290        )
12291    } else {
12292        None
12293    };
12294    #[cfg(target_os = "linux")]
12295    if let Some(path) = &cgroup_path {
12296        apply_cgroup_placement(&mut command, spec, path)?;
12297    }
12298
12299    let output_sink = if let Some(logs_dir) = capture_logs_dir {
12300        let path = logs_dir.join(format!("{}.stderr.log", spec.module_id));
12301        match ChildOutputSink::open(&path, capture_retention(spec)) {
12302            Ok(sink) => sink,
12303            Err(error) => {
12304                warn!(
12305                    module_id = %spec.module_id,
12306                    path = %path.display(),
12307                    error = %error,
12308                    "could not open child output capture file; forwarding to stderr"
12309                );
12310                ChildOutputSink::Stderr
12311            }
12312        }
12313    } else {
12314        ChildOutputSink::Stderr
12315    };
12316
12317    command.stdout(Stdio::piped());
12318    command.stderr(Stdio::piped());
12319    command.kill_on_drop(!carrying);
12320    // EACH MODULE LEADS ITS OWN PROCESS GROUP (the child calls setpgid(0, 0)
12321    // before exec). In the daemon's group, a service manager that kills the
12322    // job's process group when the daemon exits (launchd's default) killed
12323    // every module at the same moment its control connection closed, so no
12324    // module ever ran its EOF teardown on a daemon stop. Outside that group a
12325    // module is reached only by the daemon: the EOF it sees when its
12326    // connection closes, and the bounded stop in `child_roster` for anything
12327    // still running after that. On Linux this composes with the cgroup
12328    // placement above: that is a pre_exec write to cgroup.procs, std performs
12329    // setpgid in the child before running pre_exec callbacks, and the two
12330    // change independent process attributes.
12331    //
12332    // stdin is /dev/null because a process outside the terminal's foreground
12333    // group is stopped (SIGTTIN) if it reads the terminal, which a daemon run
12334    // by hand would otherwise hand down. Under a service manager stdin is
12335    // already /dev/null.
12336    #[cfg(unix)]
12337    command.process_group(
12338        carried
12339            .as_ref()
12340            .map(|container| container.verified_join_group())
12341            .transpose()
12342            .map_err(|source| SuperviseError::Spawn {
12343                program: spec.program.clone(),
12344                source,
12345                cgroup_path: cgroup_path.clone(),
12346            })?
12347            .flatten()
12348            .unwrap_or(0) as i32,
12349    );
12350    command.stdin(Stdio::null());
12351    #[cfg(unix)]
12352    if let Some(gate) = &mut admission_gate {
12353        gate.install_placement(&mut command);
12354    }
12355    // Fill all reserved slots in one allocation-free step, after placement has
12356    // stopped using descriptors that the fixed slots may replace.
12357    #[cfg(unix)]
12358    {
12359        if let Some(handoff) = nonce_handoff {
12360            slots.nonce(handoff);
12361        }
12362        #[cfg(target_os = "macos")]
12363        slots
12364            .acknowledgement(exec_ack.into_descriptor())
12365            .map_err(|source| SuperviseError::Spawn {
12366                program: spec.program.clone(),
12367                source,
12368                cgroup_path: cgroup_path.clone(),
12369            })?;
12370        slots.install(command.as_std_mut());
12371    }
12372    #[cfg(not(any(unix, windows)))]
12373    let _ = nonce_handoff;
12374
12375    // Containment, step 1 of 3 (issue #109): create the child suspended so it
12376    // cannot run a single instruction -- and therefore cannot spawn a
12377    // grandchild -- before it is in the job. See `contain_spawned_child` for the
12378    // other two steps and why the window matters.
12379    #[cfg(windows)]
12380    {
12381        subc_jobobject::ensure_root_job().map_err(|source| SuperviseError::Spawn {
12382            program: spec.program.clone(),
12383            source,
12384            cgroup_path: None,
12385        })?;
12386        subc_jobobject::suspend_on_create_async(&mut command);
12387    }
12388    // Timestamp before the spawn call: on Unix the child can serve before that
12389    // call even returns. This conservative bound never labels an older child
12390    // as a replacement for a request received during process creation.
12391    let spawned_at = Instant::now();
12392    let delivery_context = config_delivery;
12393    let config_delivery = config_delivery
12394        .map(|delivery| {
12395            delivery.spawned(
12396                spec,
12397                spawn_admission
12398                    .as_ref()
12399                    .expect("delivery prepares spawn admission"),
12400                spawned_at,
12401                role,
12402                registration_spawn
12403                    .as_ref()
12404                    .map(|spawn| spawn.authority.clone()),
12405            )
12406        })
12407        .transpose()?
12408        .flatten();
12409    let mut delivery_registration =
12410        delivery_context.map(|context| context.registration_guard(config_delivery.as_ref(), role));
12411    if let Some(registration) = &mut delivery_registration {
12412        registration.defer_cleanup();
12413    }
12414    if asynchronous {
12415        #[cfg(test)]
12416        if let Some(context) = delivery_context {
12417            context.pause_preflight_for_test();
12418        }
12419    }
12420    validate_spawn_program(spec, spawn_admission.as_ref(), delivery_context)?;
12421    Ok(PreparedChild {
12422        script_delivery,
12423        registration_spawn,
12424        registration_handle: handle.cloned(),
12425        #[cfg(any(unix, windows))]
12426        registration_channel,
12427        config_context: delivery_context.map(|delivery| delivery.runtime()),
12428        binding_publication,
12429        launch_spec,
12430        spawn_admission,
12431        command,
12432        carrying,
12433        carried: carried.clone(),
12434        #[cfg(unix)]
12435        launch_identity,
12436        #[cfg(unix)]
12437        group_target,
12438        #[cfg(target_os = "linux")]
12439        cgroup_placement: cgroup_placement.cloned(),
12440        #[cfg(target_os = "linux")]
12441        cgroup_cleanup,
12442        #[cfg(target_os = "linux")]
12443        cgroup_name,
12444        cgroup_path,
12445        #[cfg(unix)]
12446        admission_gate,
12447        output_sink,
12448        #[cfg(target_os = "macos")]
12449        privacy_exec,
12450        #[cfg(windows)]
12451        image_capture,
12452        #[cfg(windows)]
12453        nonce_handoff,
12454        spawned_at,
12455        config_delivery,
12456        delivery_registration,
12457        program_binding,
12458    })
12459}
12460
12461fn launch_child_in_slot(
12462    _spec: &ModuleSpec,
12463    ring: &Arc<Mutex<StderrRing>>,
12464    roster: &ChildRoster,
12465    prepared: PreparedChild,
12466    register_timeout: Duration,
12467) -> Result<SupervisedChild, SuperviseError> {
12468    let launch_spec = prepared.launch_spec.clone();
12469    let registration_declaration = prepared
12470        .spawn_admission
12471        .as_ref()
12472        .and_then(|admission| admission.registration_declaration(&launch_spec.module_id));
12473    let admission_base = prepared
12474        .spawn_admission
12475        .as_ref()
12476        .and_then(|admission| admission.approved_base())
12477        .cloned();
12478    let spec = &launch_spec;
12479    let expected_image = prepared
12480        .spawn_admission
12481        .as_ref()
12482        .and_then(|admission| admission.launch.as_ref())
12483        .map(|launch| launch.image);
12484    let program_launch = prepared
12485        .spawn_admission
12486        .and_then(|admission| admission.launch);
12487    let config_owner = prepared
12488        .config_context
12489        .as_ref()
12490        .map(|context| context.0.clone());
12491    let binding_publication = prepared.binding_publication;
12492    #[cfg(test)]
12493    if let Some(context) = &prepared.config_context {
12494        context.0.before_spawn_exec_for_test();
12495    }
12496    #[cfg(feature = "test-support")]
12497    if let Some(context) = &prepared.config_context {
12498        context
12499            .0
12500            .pause_spawn_before_exec()
12501            .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(context)))?;
12502    }
12503    let mut command = prepared.command;
12504    let carrying = prepared.carrying;
12505    let carried = prepared.carried;
12506    #[cfg(unix)]
12507    let launch_identity = prepared.launch_identity;
12508    #[cfg(unix)]
12509    let group_target = prepared.group_target;
12510    #[cfg(target_os = "linux")]
12511    let cgroup_placement = prepared.cgroup_placement.as_ref();
12512    #[cfg(target_os = "linux")]
12513    let cgroup_name = prepared.cgroup_name;
12514    #[cfg(target_os = "linux")]
12515    let mut cgroup_cleanup = prepared.cgroup_cleanup;
12516    #[cfg(target_os = "linux")]
12517    let _ = cgroup_cleanup.0.take();
12518    let cgroup_path = prepared.cgroup_path;
12519    #[cfg(unix)]
12520    let admission_gate = prepared.admission_gate;
12521    let output_sink = prepared.output_sink;
12522    #[cfg(target_os = "macos")]
12523    let mut privacy_exec = prepared.privacy_exec;
12524    #[cfg(target_os = "macos")]
12525    if let Some(pending) = &mut privacy_exec {
12526        pending.admission_binding = binding_publication.clone();
12527        if expected_image.is_some() {
12528            pending.expected = expected_image;
12529        }
12530    }
12531    #[cfg(any(unix, windows))]
12532    let registration_channel = prepared.registration_channel;
12533    let registration_spawn = prepared.registration_spawn;
12534    let registration_handle = prepared.registration_handle;
12535    #[cfg(windows)]
12536    let image_capture = prepared.image_capture;
12537    #[cfg(windows)]
12538    let nonce_handoff = prepared.nonce_handoff;
12539    let spawned_at = prepared.spawned_at;
12540    let config_delivery = prepared.config_delivery;
12541    let delivery_registration = prepared.delivery_registration;
12542    let _program_binding = prepared.program_binding;
12543    #[cfg(all(test, unix))]
12544    containment_tests::record_spawn_attempt(spec, &mut command);
12545    #[cfg(unix)]
12546    let spawned = match admission_gate {
12547        Some(gate) => gate
12548            .spawn(
12549                command,
12550                spec,
12551                roster,
12552                launch_identity,
12553                #[cfg(target_os = "linux")]
12554                cgroup_placement
12555                    .zip(cgroup_path.as_ref())
12556                    .map(|(placement, path)| {
12557                        (placement.clone(), cgroup_name.clone(), path.clone())
12558                    }),
12559            )
12560            .map(|(child, admitted)| (child, Some(admitted))),
12561        None => {
12562            let spawned =
12563                subc_os::child_spawn::tokio_spawn(&mut command).map(|child| (child, None));
12564            // The callback owns all child-only sources. Closing them here is
12565            // necessary for channel EOF and macOS exec acknowledgement EOF.
12566            drop(command);
12567            spawned
12568        }
12569    };
12570    #[cfg(not(unix))]
12571    let spawned = subc_os::child_spawn::tokio_spawn(&mut command);
12572    let spawned = match spawned {
12573        Ok(child) => child,
12574        Err(source) => {
12575            if carried
12576                .as_ref()
12577                .and_then(|container| container.group())
12578                .is_some()
12579            {
12580                containment::terminate_blocking(&roster.containment);
12581            }
12582            #[cfg(target_os = "linux")]
12583            if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12584                remove_module_cgroup(placement, &cgroup_name);
12585            }
12586            return Err(SuperviseError::Spawn {
12587                program: spec.program.clone(),
12588                source,
12589                cgroup_path,
12590            });
12591        }
12592    };
12593    #[cfg(unix)]
12594    let (mut child, mut admitted) = spawned;
12595    #[cfg(unix)]
12596    let group_target = admitted
12597        .as_ref()
12598        .map(|attempt| attempt.group_target())
12599        .unwrap_or(group_target);
12600    #[cfg(not(unix))]
12601    let mut child = spawned;
12602    if let Some(delivery) = prepared.script_delivery {
12603        delivery.start(child.id().expect("spawned child has a pid"));
12604    }
12605    #[cfg(test)]
12606    spawn_record_tests::after_create(&child, spec);
12607
12608    // Bind while the child is still suspended, before job assignment resumes it.
12609    // Keeping the executable handle open across CreateProcessW denies rename
12610    // and deletion, so the file cannot be exchanged during spawn. Bind that
12611    // file ID to the process handle returned by spawn, never a reopened PID.
12612    #[cfg(windows)]
12613    let windows_image = match image_capture.bind_tokio(&child) {
12614        Ok(image) => Arc::new(image),
12615        Err(source) => {
12616            kill_and_reap_rejected_child(&mut child);
12617            return Err(SuperviseError::Spawn {
12618                program: spec.program.clone(),
12619                source,
12620                cgroup_path: None,
12621            });
12622        }
12623    };
12624    // Assign the suspended child to its module job; resume only after its
12625    // process identity has been durably recorded for orphan recovery.
12626    #[cfg(windows)]
12627    let job = contain_spawned_child(&mut child, spec, carried.as_ref())?;
12628    let spawned_at_ms = unix_ms_now();
12629    #[cfg(not(windows))]
12630    let spawned_from = spec.program.clone();
12631    #[cfg(windows)]
12632    let spawned_from = windows_image.path().to_path_buf();
12633    #[cfg(not(windows))]
12634    let spawned_file_identity = spawned_file_identity(&spawned_from);
12635    #[cfg(windows)]
12636    let spawned_file_identity = Some(SpawnedFileIdentity {
12637        device: 0,
12638        inode: 0,
12639        windows_image: Some(Arc::clone(&windows_image)),
12640    });
12641    let pid = child.id().ok_or_else(|| SuperviseError::Spawn {
12642        program: spec.program.clone(),
12643        source: io::Error::other("spawned child exposed no live pid"),
12644        cgroup_path: cgroup_path.clone(),
12645    })?;
12646    #[cfg(windows)]
12647    let nonce_delivery = start_windows_nonce_pipe(nonce_handoff, pid, spec);
12648    #[cfg(not(windows))]
12649    let process_start_time = admitted
12650        .as_ref()
12651        .map(|admitted| admitted.birth)
12652        .or_else(|| crate::provenance::process_start_time(pid));
12653    #[cfg(windows)]
12654    let process_start_time = Some(windows_image.start_time());
12655    let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
12656    #[cfg(all(test, target_os = "macos"))]
12657    privacy_exec_boundary_tests::before_image_sample(spec, pid);
12658    #[cfg(all(test, target_os = "linux"))]
12659    assert!(roster.admission_event_for_test(&spec.module_id, "before_image_binding", Some(pid)));
12660    // Record the committed kernel image, not the configured pathname: PATH
12661    // lookup and shebang interpretation can select a different executable.
12662    // Linux's posix_spawn can return before that image is installed, so the
12663    // observer also waits for the kernel's first-exec flag to clear.
12664    #[cfg(not(windows))]
12665    let recorded_image = observe_spawned_image(pid);
12666    #[cfg(all(test, target_os = "linux"))]
12667    let recorded_image = if roster.admission_event_for_test(
12668        &spec.module_id,
12669        "after_spawn_image_sample",
12670        Some(pid),
12671    ) {
12672        recorded_image
12673    } else {
12674        None
12675    };
12676    #[cfg(target_os = "linux")]
12677    // An exited child cannot receive HELLO service and has no readable /proc/exe.
12678    // Keep its real exit for the supervisor instead of turning a crash into a hold.
12679    let exited_before_binding = expected_image.is_some()
12680        && recorded_image.and_then(|image| image.executable) != expected_image
12681        && child.try_wait().ok().flatten().is_some();
12682    #[cfg(target_os = "linux")]
12683    let unavailable_initial_image = expected_image.is_some()
12684        && recorded_image.and_then(|image| image.executable).is_none()
12685        && !exited_before_binding;
12686    #[cfg(not(target_os = "linux"))]
12687    let unavailable_initial_image = false;
12688    #[cfg(target_os = "linux")]
12689    if expected_image
12690        .is_some_and(|expected| recorded_image.and_then(|image| image.executable) != Some(expected))
12691        && !exited_before_binding
12692        && !unavailable_initial_image
12693    {
12694        kill_module_cgroup(cgroup_placement, &cgroup_name);
12695        kill_and_reap_rejected_child(&mut child, group_target.clone());
12696        return Err(SuperviseError::ConfigHeld {
12697            module_id: spec.module_id.clone(),
12698            code: "program_refused".into(),
12699            detail: format!(
12700                "spawned executable {:?} does not match hashed program {:?}",
12701                recorded_image.and_then(|image| image.executable),
12702                expected_image
12703            ),
12704        });
12705    }
12706    #[cfg(not(target_os = "linux"))]
12707    let _ = expected_image;
12708    #[cfg(target_os = "macos")]
12709    let binding_ready = privacy_exec.is_none();
12710    #[cfg(target_os = "linux")]
12711    let binding_ready = !exited_before_binding;
12712    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
12713    let binding_ready = cfg!(windows);
12714    // spawn() confirms only the first exec, into the trampoline. Never persist
12715    // the trampoline image; the asynchronous acknowledgement publishes the
12716    // module image once the trampoline has replaced itself with the module.
12717    #[cfg(target_os = "macos")]
12718    let recorded_image = if privacy_exec.is_some() {
12719        None
12720    } else {
12721        recorded_image
12722    };
12723    #[cfg(target_os = "linux")]
12724    let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
12725    #[cfg(not(target_os = "linux"))]
12726    let recorded_cgroup_name = None;
12727    #[cfg(unix)]
12728    let preadmitted = admitted
12729        .as_mut()
12730        .and_then(|admitted| admitted.leader.take());
12731    #[cfg(not(unix))]
12732    let preadmitted: Option<crate::child_roster::RosterGuard> = None;
12733    let roster_guard = if let Some(guard) = preadmitted {
12734        Ok(guard)
12735    } else {
12736        roster.admit(
12737            spec.module_id.clone(),
12738            pid,
12739            spec.protocol,
12740            process_start_time,
12741            crate::child_roster::RecordedIdentity {
12742                container: None,
12743                #[cfg(unix)]
12744                carried: None,
12745                #[cfg(not(windows))]
12746                start_time: recorded_image.map(|image| image.start_time),
12747                #[cfg(windows)]
12748                start_time: process_start_time,
12749                #[cfg(not(windows))]
12750                executable: recorded_image
12751                    .and_then(|image| image.executable)
12752                    .map(crate::live_children::ExecutableIdentity::from),
12753                #[cfg(windows)]
12754                executable: Some(crate::live_children::ExecutableIdentity::from(
12755                    windows_image.identity(),
12756                )),
12757                cgroup_name: recorded_cgroup_name,
12758                #[cfg(target_os = "linux")]
12759                cgroup_placement: cgroup_placement.cloned(),
12760            },
12761        )
12762    };
12763    let roster_guard = match roster_guard {
12764        Ok(guard) => guard,
12765        Err(failure) => {
12766            return failure.with_cleanup(|source| {
12767                #[cfg(windows)]
12768                if let Some(job) = &job {
12769                    let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
12770                }
12771                #[cfg(target_os = "linux")]
12772                kill_module_cgroup(cgroup_placement, &cgroup_name);
12773                #[cfg(unix)]
12774                let rejected_group = group_target.clone();
12775                kill_and_reap_rejected_child(
12776                    &mut child,
12777                    #[cfg(unix)]
12778                    rejected_group,
12779                );
12780                #[cfg(target_os = "linux")]
12781                if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12782                    remove_module_cgroup(placement, &cgroup_name);
12783                }
12784                Err(SuperviseError::Spawn {
12785                    program: spec.program.clone(),
12786                    source: io::Error::other(format!(
12787                        "could not durably record module child: {source}"
12788                    )),
12789                    cgroup_path,
12790                })
12791            });
12792        }
12793    };
12794    #[cfg(unix)]
12795    if admitted.is_some() {
12796        if let Some(image) = recorded_image {
12797            if let Err(source) = roster_guard.confirm_executable(image) {
12798                kill_and_reap_rejected_child(&mut child, group_target.clone());
12799                return Err(SuperviseError::Spawn {
12800                    program: spec.program.clone(),
12801                    source,
12802                    cgroup_path,
12803                });
12804            }
12805        }
12806    }
12807    // The pre-spawn check can pass just before shutdown begins. Ownership is
12808    // published at the start of admission, even while a record write is queued.
12809    // If shutdown already saw an empty roster before that publication, this
12810    // check sees the roster closed and ends the child before starting a module.
12811    if roster.is_closed() {
12812        if carrying {
12813            #[cfg(unix)]
12814            let rejected_group = admitted
12815                .as_ref()
12816                .map(|admitted| admitted.rejection_target())
12817                .unwrap_or_else(|| group_target.clone());
12818            #[cfg(windows)]
12819            if let Some(job) = &job {
12820                let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
12821            }
12822            kill_and_reap_rejected_child(
12823                &mut child,
12824                #[cfg(unix)]
12825                rejected_group,
12826            );
12827            #[cfg(all(test, unix))]
12828            let _ =
12829                roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
12830            drop(roster_guard);
12831            return Err(SuperviseError::Spawn {
12832                program: spec.program.clone(),
12833                source: io::Error::other(
12834                    "the daemon began shutting down during carried admission; ended the container",
12835                ),
12836                cgroup_path,
12837            });
12838        }
12839        // This child was never admitted, so there is no module protocol shutdown to wait for.
12840        #[cfg(target_os = "linux")]
12841        kill_module_cgroup(cgroup_placement, &cgroup_name);
12842        if let Err(error) = child.start_kill() {
12843            debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
12844        }
12845        #[cfg(target_os = "linux")]
12846        if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12847            // This spawn was never admitted, so shutdown has no roster entry
12848            // to await. Do not detach its cleanup: the runtime could exit
12849            // before that task reaps the rejected child and removes its group.
12850            while matches!(child.try_wait(), Ok(None)) {
12851                std::thread::yield_now();
12852            }
12853            if matches!(
12854                subc_cgroup::kill_module(Some(placement), &cgroup_name),
12855                subc_cgroup::KillOutcome::Killed
12856            ) {
12857                if let Ok(path) = placement.module_path(&cgroup_name) {
12858                    while std::fs::read_to_string(path.join("cgroup.events"))
12859                        .ok()
12860                        .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
12861                    {
12862                        std::thread::yield_now();
12863                    }
12864                }
12865            }
12866            remove_module_cgroup(placement, &cgroup_name);
12867        }
12868        drop(roster_guard);
12869        return Err(SuperviseError::Spawn {
12870            program: spec.program.clone(),
12871            source: io::Error::other(
12872                "the daemon began shutting down while this process was starting; ended it",
12873            ),
12874            cgroup_path,
12875        });
12876    }
12877
12878    let (stdout_pump, stderr_pump) =
12879        crate::child_output::start(&mut child, output_sink, ring, &spec.module_id);
12880
12881    let exec = Arc::new(crate::activity::ExecOutcome::new());
12882    #[cfg(target_os = "macos")]
12883    let pending_exec = privacy_exec.is_some();
12884    #[cfg(not(target_os = "macos"))]
12885    let pending_exec = false;
12886    if !pending_exec {
12887        exec.finish(crate::activity::ExecState::CommittedExec);
12888    }
12889    #[cfg(windows)]
12890    let subtree_target = job
12891        .as_ref()
12892        .map(|job| crate::subtree_resources::Target::Job(Arc::downgrade(job)))
12893        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_job"));
12894    #[cfg(target_os = "linux")]
12895    let subtree_target = cgroup_path
12896        .map(crate::subtree_resources::Target::Cgroup)
12897        .unwrap_or(crate::subtree_resources::Target::Unavailable("no_cgroup"));
12898    #[cfg(not(any(target_os = "linux", windows)))]
12899    let subtree_target = crate::subtree_resources::Target::Unavailable("unsupported_platform");
12900    let mut supervised = SupervisedChild {
12901        registration_spawn,
12902        #[cfg(any(unix, windows))]
12903        registration_channel,
12904        live_program_binding: None,
12905        registered_config_connection: None,
12906        admission_base,
12907        registration_declaration,
12908        _program_binding: binding_publication,
12909        subtree_target,
12910        child: containment::ProcessChild::plain(child, pid),
12911        exec: crate::activity::ExecOwner(exec),
12912        #[cfg(windows)]
12913        nonce_delivery,
12914        protocol: spec.protocol,
12915        #[cfg(target_os = "linux")]
12916        module_id: cgroup_name,
12917        #[cfg(target_os = "linux")]
12918        cgroup_placement: cgroup_placement.cloned(),
12919        #[cfg(windows)]
12920        job,
12921        stdout_pump,
12922        stderr_pump,
12923        stderr_ring: Arc::clone(ring),
12924        spawned_at,
12925        config_delivery,
12926        registration_deadline: None,
12927        registration_watch: None,
12928        spawned_at_ms,
12929        spawned_from,
12930        launch_spec_digest: LaunchSpecDigest::from_spec(spec),
12931        spawned_file_identity,
12932        process_start_time,
12933        process_identity,
12934        pid,
12935        roster_guard: Some(roster_guard),
12936        #[cfg(target_os = "macos")]
12937        privacy_exec,
12938        #[cfg(target_os = "macos")]
12939        report_ready: Arc::new(OnceLock::new()),
12940        spawn_failure: None,
12941        admission_kill_sent: false,
12942    };
12943    if let Err(error) = containment::adopt(&mut supervised, spec, roster) {
12944        supervised.child.reject(
12945            #[cfg(unix)]
12946            group_target,
12947        );
12948        #[cfg(all(test, unix))]
12949        let _ = roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
12950        return Err(error);
12951    }
12952    if let (Some(launch), Some(owner), Some(base)) = (
12953        program_launch,
12954        config_owner,
12955        supervised.admission_base.clone(),
12956    ) {
12957        supervised.live_program_binding =
12958            content_binding::LiveProgramBinding::new(launch, &supervised, owner, base);
12959        if let (Some(publication), Some(live)) = (
12960            &supervised._program_binding,
12961            &supervised.live_program_binding,
12962        ) {
12963            publication.attach(live);
12964        }
12965    }
12966    #[cfg(unix)]
12967    if let Some(admitted) = admitted.take() {
12968        admitted.disarm();
12969    }
12970    #[cfg(windows)]
12971    if let Err(error) = resume_suspended_child(pid, spec) {
12972        containment::terminate_blocking(&roster.containment);
12973        let _ = supervised.child.start_kill();
12974        return Err(error);
12975    }
12976    if binding_ready {
12977        // An unreadable initial image is not a definite mismatch. Keep the
12978        // owned child and delivery registration until its reaped status decides
12979        // whether it crashed on its own or was stopped by admission's kill.
12980        let checked = if unavailable_initial_image {
12981            Err(crate::config_gate::GateError::new(
12982                "config_delivery_deferred",
12983                "initial process image is unavailable",
12984            ))
12985        } else {
12986            match (
12987                &supervised._program_binding,
12988                &supervised.live_program_binding,
12989            ) {
12990                (Some(binding), _) => binding.verify(),
12991                (None, Some(live)) => live.check(),
12992                _ if supervised.admission_base.is_some() => {
12993                    Err(crate::config_gate::GateError::new(
12994                        "config_delivery_deferred",
12995                        "live program witness is unavailable",
12996                    ))
12997                }
12998                _ => Ok(()),
12999            }
13000        };
13001        #[cfg(all(test, target_os = "linux"))]
13002        let checked = if roster.admission_event_for_test(
13003            &spec.module_id,
13004            "after_content_witness_check",
13005            Some(pid),
13006        ) {
13007            checked
13008        } else {
13009            Err(crate::config_gate::GateError::new(
13010                "config_delivery_deferred",
13011                "current process image is unavailable",
13012            ))
13013        };
13014        if let Err(error) = checked {
13015            if let Some(binding) = &mut supervised._program_binding {
13016                binding.reject();
13017            }
13018            // Reap through the normal child-reaping path, retaining the real exit record and
13019            // its roster ownership. A refusal must also end any helpers.
13020            if error.code == "program_refused" || supervised.try_wait().ok().flatten().is_none() {
13021                supervised.spawn_failure = Some(format!("{}: {}", error.code, error.detail));
13022                #[cfg(all(test, target_os = "linux"))]
13023                assert!(roster.admission_event_for_test(
13024                    &spec.module_id,
13025                    if unavailable_initial_image {
13026                        "before_initial_image_kill"
13027                    } else {
13028                        "before_content_witness_kill"
13029                    },
13030                    Some(pid),
13031                ));
13032                let _ = supervised.start_admission_kill();
13033                #[cfg(all(test, target_os = "linux"))]
13034                if supervised.admission_kill_sent {
13035                    assert!(roster.admission_event_for_test(
13036                        &spec.module_id,
13037                        "after_admission_kill_sent",
13038                        Some(pid),
13039                    ));
13040                }
13041            }
13042        }
13043    }
13044    if let Some(registration) = delivery_registration {
13045        registration.commit();
13046    }
13047    if let Some(spawn) = &supervised.registration_spawn {
13048        if let Some(identity) = supervised.process_identity {
13049            let _ = spawn.identity.set(identity);
13050        }
13051        if supervised.spawn_failure.is_some() {
13052            spawn.refuse();
13053        } else if binding_ready {
13054            spawn.ready();
13055        }
13056        #[cfg(any(unix, windows))]
13057        if let (Some(handle), Some(channel)) =
13058            (registration_handle, supervised.registration_channel.take())
13059        {
13060            handle.serve_registration(channel, spawn.clone(), pid, spawned_at + register_timeout);
13061        }
13062    }
13063    Ok(supervised)
13064}
13065
13066#[cfg(test)]
13067mod spawn_record_tests {
13068    use super::*;
13069
13070    thread_local! {
13071        static LAST_PID: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
13072    }
13073
13074    pub(super) fn after_create(child: &Child, _spec: &ModuleSpec) {
13075        LAST_PID.set(child.id());
13076        #[cfg(windows)]
13077        if let Some((_, address)) = _spec
13078            .env
13079            .iter()
13080            .find(|(key, _)| key == "SUBC_TEST_AFTER_CREATE")
13081        {
13082            use std::io::{Read, Write};
13083            let mut stream = std::net::TcpStream::connect(address).unwrap();
13084            stream
13085                .write_all(&child.id().unwrap().to_ne_bytes())
13086                .unwrap();
13087            let mut release = [0];
13088            stream.read_exact(&mut release).unwrap();
13089        }
13090    }
13091
13092    #[cfg(windows)]
13093    pub(super) fn assignment_failpoint(spec: &ModuleSpec) -> io::Result<()> {
13094        if spec
13095            .env
13096            .iter()
13097            .any(|(key, _)| key == "SUBC_TEST_ASSIGNMENT_FAILURE")
13098        {
13099            Err(io::Error::other("injected module job assignment failure"))
13100        } else {
13101            Ok(())
13102        }
13103    }
13104
13105    fn spec() -> ModuleSpec {
13106        ModuleSpec {
13107            script: None,
13108            module_id: "spawn-record-worker".into(),
13109            #[cfg(unix)]
13110            program: "/bin/sleep".into(),
13111            #[cfg(windows)]
13112            program: std::env::current_exe().unwrap(),
13113            #[cfg(unix)]
13114            args: vec!["60".into()],
13115            #[cfg(windows)]
13116            args: vec![
13117                "--exact".into(),
13118                "supervise::spawn_record_tests::windows_store_touch_fixture".into(),
13119                "--nocapture".into(),
13120            ],
13121            env: vec![],
13122            reserved: false,
13123            reserved_prefixes: vec![],
13124            protocol: ModuleProtocol::None,
13125            overlap: Default::default(),
13126            carry_containment: false,
13127        }
13128    }
13129
13130    #[tokio::test]
13131    async fn record_sync_failure_fails_spawn_and_reaps_child() {
13132        let home = cortexkit_test_support::ScratchDir::new("record-sync-failure");
13133        let supervisor =
13134            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
13135                .with_live_children_record(home.join("live-children.json"));
13136        crate::live_children::fail_next_file_sync();
13137        let result = supervisor.spawn(spec());
13138        let failed = result.is_err();
13139        if let Ok(module) = result {
13140            module.stop().await.unwrap();
13141        }
13142        assert!(failed, "record failure must fail spawn");
13143        let pid = LAST_PID.get().expect("the real OS child was created");
13144        assert!(
13145            subc_os::Process::open(pid).unwrap().is_none(),
13146            "child {pid} survived rejected admission or was not reaped"
13147        );
13148    }
13149
13150    #[cfg(target_os = "macos")]
13151    #[test]
13152    #[ignore = "manual on-device latency measurement"]
13153    fn durable_record_write_latency_50() {
13154        let home = cortexkit_test_support::ScratchDir::new("record-latency");
13155        let path = home.join("live-children.json");
13156        let children = vec![crate::live_children::LiveChild {
13157            module_id: "latency-worker".into(),
13158            pid: std::process::id(),
13159            protocol: ModuleProtocol::None,
13160            start_time: Some(1),
13161            executable: None,
13162            cgroup_name: None,
13163            container: None,
13164        }];
13165        let mut samples = Vec::new();
13166        for _ in 0..50 {
13167            let start = std::time::Instant::now();
13168            crate::live_children::write_record(&path, &children).unwrap();
13169            samples.push(start.elapsed());
13170        }
13171        samples.sort();
13172        eprintln!(
13173            "durable_record_write_latency_50: n=50 median={:?} p95={:?}",
13174            (samples[24] + samples[25]) / 2,
13175            samples[47]
13176        );
13177    }
13178
13179    #[cfg(windows)]
13180    #[test]
13181    fn windows_store_touch_fixture() {
13182        if let Some(path) = std::env::var_os("SUBC_TEST_STORE_TOUCH") {
13183            std::fs::write(path, b"module ran").unwrap();
13184        }
13185    }
13186
13187    #[cfg(windows)]
13188    #[tokio::test]
13189    async fn windows_daemon_fixture() {
13190        let Ok(address) = std::env::var("SUBC_TEST_DAEMON_BARRIER") else {
13191            return;
13192        };
13193        let mut spec = spec();
13194        spec.env.push(("SUBC_TEST_AFTER_CREATE".into(), address));
13195        let supervisor =
13196            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13197        let _module = supervisor.spawn(spec).unwrap();
13198    }
13199
13200    #[cfg(windows)]
13201    #[test]
13202    fn windows_daemon_death_before_module_job_assignment_leaves_no_child() {
13203        use std::io::Read;
13204        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
13205        // An outer job models a scheduler/service host. The daemon's root and
13206        // root job must nest without requiring breakaway from this job.
13207        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
13208        command
13209            .args([
13210                "--exact",
13211                "supervise::spawn_record_tests::windows_daemon_fixture",
13212                "--nocapture",
13213            ])
13214            .env(
13215                "SUBC_TEST_DAEMON_BARRIER",
13216                listener.local_addr().unwrap().to_string(),
13217            );
13218        let mut daemon = subc_jobobject::spawn_contained(&mut command).unwrap();
13219        listener.set_nonblocking(true).unwrap();
13220        let deadline = std::time::Instant::now() + Duration::from_secs(30);
13221        let mut stream = loop {
13222            if let Ok((stream, _)) = listener.accept() {
13223                break stream;
13224            }
13225            assert!(
13226                daemon.child.try_wait().unwrap().is_none(),
13227                "daemon failed before rendezvous"
13228            );
13229            assert!(
13230                std::time::Instant::now() < deadline,
13231                "daemon did not reach CreateProcess failpoint"
13232            );
13233            std::thread::yield_now();
13234        };
13235        stream
13236            .set_read_timeout(Some(Duration::from_secs(30)))
13237            .unwrap();
13238        let mut pid = [0; 4];
13239        stream.read_exact(&mut pid).unwrap();
13240        let pid = u32::from_ne_bytes(pid);
13241        assert!(subc_jobobject::process_exists(pid));
13242        // Terminate only the daemon, not its outer job: otherwise the host job
13243        // would also kill a child whose daemon never joined its root job.
13244        daemon.child.kill().unwrap();
13245        daemon.child.wait().unwrap();
13246        let exited = subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10));
13247        if !exited {
13248            daemon.job.terminate().unwrap();
13249        }
13250        assert!(exited, "suspended child {pid} outlived hard-killed daemon");
13251    }
13252
13253    #[cfg(windows)]
13254    #[tokio::test]
13255    async fn windows_containment_failure_never_resumes() {
13256        let home = cortexkit_test_support::ScratchDir::new("assignment-refusal");
13257        let sentinel = home.join("store-touched");
13258        let mut spec = spec();
13259        spec.env
13260            .push(("SUBC_TEST_ASSIGNMENT_FAILURE".into(), "1".into()));
13261        spec.env.push((
13262            "SUBC_TEST_STORE_TOUCH".into(),
13263            sentinel.display().to_string(),
13264        ));
13265        let supervisor =
13266            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13267        let result = supervisor.spawn(spec);
13268        // A version that resumes despite assignment failure must have time to
13269        // execute its sentinel before dropping the returned module kills it.
13270        if let Ok(module) = result {
13271            let _ = tokio::time::timeout(Duration::from_secs(10), async {
13272                while !sentinel.exists() && module.state().unwrap() == ModuleState::Running {
13273                    tokio::task::yield_now().await;
13274                }
13275            })
13276            .await;
13277            let _ = module.stop().await;
13278            panic!(
13279                "assignment failure resumed a module; store touched={}",
13280                sentinel.exists()
13281            );
13282        }
13283        assert!(
13284            !sentinel.exists(),
13285            "refused module executed store-touch sentinel"
13286        );
13287        assert!(!subc_jobobject::process_exists(LAST_PID.get().unwrap()));
13288    }
13289
13290    #[cfg(windows)]
13291    #[tokio::test]
13292    async fn windows_nested_daemon_fixture() {
13293        let Some(sentinel) = std::env::var_os("SUBC_TEST_NESTED_STORE") else {
13294            return;
13295        };
13296        let mut spec = spec();
13297        spec.env.push((
13298            "SUBC_TEST_STORE_TOUCH".into(),
13299            sentinel.to_str().unwrap().into(),
13300        ));
13301        let supervisor =
13302            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13303        let module = supervisor
13304            .spawn(spec)
13305            .expect("per-module job must nest below daemon and host jobs");
13306        tokio::time::timeout(Duration::from_secs(10), async {
13307            while !PathBuf::from(&sentinel).exists() {
13308                tokio::task::yield_now().await;
13309            }
13310        })
13311        .await
13312        .unwrap();
13313        module.stop().await.unwrap();
13314    }
13315
13316    #[cfg(windows)]
13317    #[test]
13318    fn windows_module_job_nests_under_host_job() {
13319        let home = cortexkit_test_support::ScratchDir::new("nested-jobs");
13320        let sentinel = home.join("nested-store-touched");
13321        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
13322        command
13323            .args([
13324                "--exact",
13325                "supervise::spawn_record_tests::windows_nested_daemon_fixture",
13326                "--nocapture",
13327            ])
13328            .env("SUBC_TEST_NESTED_STORE", &sentinel);
13329        let mut daemon = subc_jobobject::spawn_contained(&mut command).unwrap();
13330        assert!(daemon.child.wait().unwrap().success());
13331        assert!(sentinel.exists(), "nested protocol:none module never ran");
13332    }
13333}
13334
13335#[cfg(target_os = "linux")]
13336pub(crate) fn kill_module_cgroup(placement: Option<&subc_cgroup::Placement>, module_id: &str) {
13337    use subc_cgroup::KillOutcome;
13338    match subc_cgroup::kill_module(placement, module_id) {
13339        KillOutcome::Killed => {}
13340        KillOutcome::NotPlaced | KillOutcome::Unsupported => {
13341            debug!(
13342                module_id,
13343                "cgroup tree kill unavailable; using direct-child kill"
13344            );
13345        }
13346        KillOutcome::IoError { path, error } => {
13347            warn!(module_id, path = %path.display(), %error, "cgroup tree kill failed; using direct-child kill");
13348        }
13349    }
13350}
13351
13352/// Assign a freshly spawned Windows child without ever resuming on failure.
13353///
13354/// Steps 2 and 3 of the suspended-create contract: the job is created and the
13355/// child assigned **while it is still suspended** (step 1 is
13356/// `suspend_on_create_async` at the spawn site). The caller resumes only after
13357/// the child's roster admission is durable. Failed containment kills and reaps
13358/// the suspended child instead of running an unprotected module.
13359#[cfg(windows)]
13360fn contain_spawned_child(
13361    child: &mut Child,
13362    spec: &ModuleSpec,
13363    carried: Option<&Arc<containment::CarriedContainment>>,
13364) -> Result<Option<Arc<Mutex<subc_jobobject::JobObject>>>, SuperviseError> {
13365    let assignment = || {
13366        let job = match carried {
13367            Some(container) => container.job(),
13368            None => Arc::new(Mutex::new(subc_jobobject::JobObject::new()?)),
13369        };
13370        #[cfg(test)]
13371        spawn_record_tests::assignment_failpoint(spec)?;
13372        job.lock()
13373            .unwrap_or_else(|p| p.into_inner())
13374            .assign(child)?;
13375        Ok::<_, io::Error>(job)
13376    };
13377    match assignment() {
13378        Ok(job) => Ok(Some(job)),
13379        Err(source) => {
13380            kill_and_reap_rejected_child(child);
13381            Err(SuperviseError::Spawn {
13382                program: spec.program.clone(),
13383                source: io::Error::other(format!(
13384                    "Windows module job containment failed: {source}"
13385                )),
13386                cgroup_path: None,
13387            })
13388        }
13389    }
13390}
13391
13392/// Rejection is synchronous: do not return a spawn error while the child can
13393/// still run, or rely on kill-on-drop to reap it at some later runtime turn.
13394fn kill_and_reap_rejected_child(child: &mut Child, #[cfg(unix)] group: containment::GroupTarget) {
13395    #[cfg(unix)]
13396    group.signal_rejected(child);
13397    let _ = child.start_kill();
13398    while matches!(child.try_wait(), Ok(None)) {
13399        std::thread::yield_now();
13400    }
13401}
13402
13403/// Resume a suspended child, killing it if it cannot be started.
13404///
13405/// A suspended process holds a pid and does nothing, so there is no useful
13406/// state to return: the caller gets an error and the spawn fails.
13407#[cfg(windows)]
13408fn resume_suspended_child(pid: u32, spec: &ModuleSpec) -> Result<(), SuperviseError> {
13409    if let Err(source) = subc_jobobject::resume_main_thread(pid) {
13410        // Kill it here rather than leaving a suspended process for the caller
13411        // to notice; `kill_on_drop` would eventually do this, but the module
13412        // would have been reported as running in between.
13413        let _ = subc_os::child_spawn::status(
13414            std::process::Command::new("taskkill.exe")
13415                .args(["/PID", &pid.to_string(), "/T", "/F"])
13416                .stdin(Stdio::null())
13417                .stdout(Stdio::null())
13418                .stderr(Stdio::null()),
13419        );
13420        return Err(SuperviseError::Spawn {
13421            program: spec.program.clone(),
13422            source,
13423            cgroup_path: None,
13424        });
13425    }
13426    Ok(())
13427}
13428
13429#[cfg(target_os = "linux")]
13430fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
13431    match placement.remove_module(module_id) {
13432        Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
13433        Err(error) => warn!(
13434            module_id,
13435            error = %error,
13436            "could not remove module cgroup after process exit; continuing teardown"
13437        ),
13438    }
13439}
13440
13441#[cfg(target_os = "linux")]
13442const REAPED_CGROUP_TERM_GRACE: Duration = Duration::from_secs(2);
13443#[cfg(target_os = "linux")]
13444const REAPED_CGROUP_FREEZE_TIMEOUT: Duration = Duration::from_millis(100);
13445
13446#[cfg(target_os = "linux")]
13447async fn cleanup_reaped_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
13448    let path = placement.module_path(module_id).ok();
13449    if path.as_ref().is_some_and(|path| {
13450        std::fs::read_to_string(path.join("cgroup.events"))
13451            .ok()
13452            .is_some_and(|events| events.lines().any(|line| line == "populated 0"))
13453    }) {
13454        remove_module_cgroup(placement, module_id);
13455        return;
13456    }
13457
13458    // Freeze before enumerating: a frozen task cannot exit and release its PID
13459    // for reuse by a process outside this module while SIGTERM is being sent.
13460    if terminate_reaped_cgroup(placement, module_id).await {
13461        if let Some(path) = &path {
13462            let deadline = Instant::now() + REAPED_CGROUP_TERM_GRACE;
13463            while cgroup_is_populated(path) && Instant::now() < deadline {
13464                sleep_until((Instant::now() + Duration::from_millis(1)).min(deadline)).await;
13465            }
13466        }
13467    }
13468
13469    // Reaping the direct child is not proof its descendants exited. Kill any
13470    // survivors; when `cgroup.kill` succeeds, wait for the kernel to report the
13471    // cgroup empty before rmdir.
13472    if matches!(
13473        subc_cgroup::kill_module(Some(placement), module_id),
13474        subc_cgroup::KillOutcome::Killed
13475    ) {
13476        if let Some(path) = &path {
13477            while cgroup_is_populated(path) {
13478                sleep(Duration::from_millis(1)).await;
13479            }
13480        }
13481    }
13482    remove_module_cgroup(placement, module_id);
13483}
13484
13485#[cfg(target_os = "linux")]
13486fn cgroup_is_populated(path: &std::path::Path) -> bool {
13487    std::fs::read_to_string(path.join("cgroup.events"))
13488        .ok()
13489        .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
13490}
13491
13492#[cfg(target_os = "linux")]
13493async fn terminate_reaped_cgroup(placement: &subc_cgroup::Placement, module_id: &str) -> bool {
13494    let frozen =
13495        match subc_cgroup::freeze_module(Some(placement), module_id, REAPED_CGROUP_FREEZE_TIMEOUT)
13496            .await
13497        {
13498            subc_cgroup::FreezeOutcome::Frozen(frozen) => frozen,
13499            outcome => {
13500                tracing::debug!(
13501                    module_id,
13502                    ?outcome,
13503                    "cgroup freeze failed; skipping SIGTERM grace"
13504                );
13505                return false;
13506            }
13507        };
13508    let listed = match frozen.processes() {
13509        subc_cgroup::ProcsOutcome::Listed(pids) => {
13510            for pid in pids.into_iter().filter(|pid| *pid > 1) {
13511                if let Some(pid) = rustix::process::Pid::from_raw(pid) {
13512                    if let Err(error) =
13513                        rustix::process::kill_process(pid, rustix::process::Signal::TERM)
13514                    {
13515                        tracing::debug!(module_id, %pid, %error, "leftover cgroup SIGTERM failed");
13516                    }
13517                }
13518            }
13519            true
13520        }
13521        outcome => {
13522            tracing::debug!(
13523                module_id,
13524                ?outcome,
13525                "cgroup process listing failed; skipping SIGTERM grace"
13526            );
13527            false
13528        }
13529    };
13530    match frozen.thaw() {
13531        subc_cgroup::ThawOutcome::Thawed => listed,
13532        outcome => {
13533            tracing::debug!(
13534                module_id,
13535                ?outcome,
13536                "cgroup thaw failed; proceeding to cgroup.kill"
13537            );
13538            false
13539        }
13540    }
13541}
13542
13543#[cfg(target_os = "linux")]
13544fn apply_cgroup_placement(
13545    command: &mut Command,
13546    spec: &ModuleSpec,
13547    path: &std::path::Path,
13548) -> Result<(), SuperviseError> {
13549    subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
13550        module_id: spec.module_id.clone(),
13551        source,
13552    })
13553}
13554
13555fn capture_retention(spec: &ModuleSpec) -> Retention {
13556    let defaults = Retention::default();
13557    let value = |name: &str| {
13558        spec.env
13559            .iter()
13560            .rev()
13561            .find_map(|(key, value)| (key == name).then_some(value.as_str()))
13562    };
13563    Retention {
13564        max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
13565            .and_then(|value| value.parse().ok())
13566            .unwrap_or(defaults.max_file_mb),
13567        keep: value(CAPTURE_KEEP_ENV)
13568            .and_then(|value| value.parse().ok())
13569            .unwrap_or(defaults.keep),
13570        max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
13571            .and_then(|value| value.parse().ok())
13572            .unwrap_or(defaults.max_age_days),
13573    }
13574}
13575
13576/// A fresh 256-bit CSPRNG launch nonce, lowercase hex. Used to bind a reserved
13577/// module's registration to the exact process the supervisor spawned.
13578fn generate_launch_nonce() -> Result<String, SuperviseError> {
13579    let mut bytes = [0u8; 32];
13580    getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
13581        reason: source.to_string(),
13582    })?;
13583    let mut hex = String::with_capacity(64);
13584    for b in bytes {
13585        use std::fmt::Write;
13586        let _ = write!(hex, "{b:02x}");
13587    }
13588    Ok(hex)
13589}
13590
13591/// Constant-time byte comparison so a reserved-nonce mismatch leaks no timing
13592/// signal about how many leading bytes matched.
13593fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
13594    if a.len() != b.len() {
13595        return false;
13596    }
13597    let mut diff = 0u8;
13598    for (x, y) in a.iter().zip(b.iter()) {
13599        diff |= x ^ y;
13600    }
13601    diff == 0
13602}
13603
13604/// The kernel's image after an acknowledged exec, shared by ordinary launches
13605/// and privacy trampolines. PATH and shebang interpretation are kernel facts,
13606/// not identities inferred from a configured pathname.
13607#[cfg(not(windows))]
13608fn observe_spawned_image(pid: u32) -> Option<subc_os::Observation> {
13609    let process = subc_os::Process::open(pid).ok().flatten()?;
13610    #[cfg(target_os = "linux")]
13611    return sample_after_linux_exec(
13612        || {
13613            let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
13614            let committed = linux_exec_committed(&stat);
13615            #[cfg(test)]
13616            spawn_image_tests::report_exec_state(committed);
13617            committed
13618        },
13619        || process.observe(),
13620    );
13621    #[cfg(not(target_os = "linux"))]
13622    process.observe()
13623}
13624
13625/// glibc's posix_spawn parent can wake in exec_mmap before the child's new mm
13626/// is installed. PF_FORKNOEXEC is cleared later in begin_new_exec, after that
13627/// installation. Until it clears, /proc/pid/exe can still name the daemon.
13628#[cfg(target_os = "linux")]
13629fn linux_exec_committed(stat: &str) -> Option<bool> {
13630    const PF_FORKNOEXEC: u64 = 0x40;
13631    let flags = stat.rsplit_once(')')?.1.split_whitespace().nth(6)?;
13632    Some(flags.parse::<u64>().ok()? & PF_FORKNOEXEC == 0)
13633}
13634
13635#[cfg(target_os = "linux")]
13636fn sample_after_linux_exec(
13637    mut exec_committed: impl FnMut() -> Option<bool>,
13638    observe: impl FnOnce() -> Option<subc_os::Observation>,
13639) -> Option<subc_os::Observation> {
13640    let deadline = std::time::Instant::now() + Duration::from_secs(1);
13641    while !exec_committed()? {
13642        // A failed or indefinitely stalled exec must not publish the inherited
13643        // image as authority to signal a future orphan. Missing identity keeps
13644        // the existing conservative orphan-sweep behavior.
13645        if std::time::Instant::now() >= deadline {
13646            return None;
13647        }
13648        std::thread::sleep(Duration::from_micros(50));
13649    }
13650    observe()
13651}
13652
13653#[cfg(all(test, target_os = "linux"))]
13654mod spawn_image_tests {
13655    use super::*;
13656    use std::cell::{Cell, RefCell};
13657
13658    enum ExecEvent {
13659        Uncommitted,
13660        Image(Option<subc_os::Observation>),
13661    }
13662
13663    thread_local! {
13664        static EXEC_EVENTS: RefCell<Option<std::sync::mpsc::Sender<ExecEvent>>> = const { RefCell::new(None) };
13665    }
13666
13667    pub(super) fn report_exec_state(committed: Option<bool>) {
13668        if committed == Some(false) {
13669            EXEC_EVENTS.with(|events| {
13670                if let Some(events) = events.borrow_mut().take() {
13671                    let _ = events.send(ExecEvent::Uncommitted);
13672                }
13673            });
13674        }
13675    }
13676
13677    #[test]
13678    fn linux_spawn_observation_waits_for_a_paused_fork_to_exec() {
13679        use std::io::{Read, Write};
13680        use std::os::fd::AsRawFd;
13681
13682        let descriptor = std::fs::File::open("/dev/null").unwrap();
13683        let mut command = std::process::Command::new("/bin/sleep");
13684        command.arg("30");
13685        let (mut ready, mut release) =
13686            subc_os::fork_exec_test::pause_before_exec(&mut command, descriptor.as_raw_fd())
13687                .unwrap();
13688        let spawn = std::thread::spawn(move || command.spawn());
13689        let mut message = [0u8; 8];
13690        ready.read_exact(&mut message).unwrap();
13691        let pid = i32::from_ne_bytes(message[..4].try_into().unwrap()) as u32;
13692        let before = std::fs::read_to_string(format!("/proc/{pid}/stat"));
13693        let inherited = subc_os::Process::open(pid).unwrap().unwrap().observe();
13694        let (events, received) = std::sync::mpsc::channel();
13695        let observer = std::thread::spawn(move || {
13696            EXEC_EVENTS.with(|slot| *slot.borrow_mut() = Some(events.clone()));
13697            let image = observe_spawned_image(pid);
13698            let _ = events.send(ExecEvent::Image(image));
13699        });
13700        // Release only once the production observer has seen the uncommitted
13701        // exec, or has incorrectly returned the inherited image. Either way,
13702        // release and reap before asserting so a regression cannot leak a child.
13703        let first = received.recv_timeout(Duration::from_secs(5));
13704        release.write_all(&[1]).unwrap();
13705        let mut child = spawn.join().unwrap().unwrap();
13706        let after = match first {
13707            Ok(ExecEvent::Uncommitted) => match received.recv_timeout(Duration::from_secs(5)) {
13708                Ok(ExecEvent::Image(image)) => image,
13709                _ => None,
13710            },
13711            Ok(ExecEvent::Image(image)) => image,
13712            Err(_) => None,
13713        };
13714        observer.join().unwrap();
13715        child.kill().unwrap();
13716        child.wait().unwrap();
13717
13718        assert_eq!(linux_exec_committed(&before.unwrap()), Some(false));
13719        assert_eq!(
13720            inherited.unwrap().executable,
13721            subc_os::file_identity(&std::env::current_exe().unwrap())
13722        );
13723        assert_eq!(
13724            after.unwrap().executable,
13725            subc_os::file_identity(std::path::Path::new("/bin/sleep"))
13726        );
13727    }
13728
13729    #[test]
13730    fn spawned_image_is_not_sampled_until_linux_exec_commits() {
13731        let committed = Cell::new(false);
13732        let inherited = subc_os::Observation {
13733            start_time: 23,
13734            executable: Some(subc_os::FileIdentity {
13735                device: 29,
13736                inode: 31,
13737            }),
13738        };
13739        let module = subc_os::Observation {
13740            start_time: 23,
13741            executable: Some(subc_os::FileIdentity {
13742                device: 29,
13743                inode: 37,
13744            }),
13745        };
13746        let polls = Cell::new(0);
13747        let image = sample_after_linux_exec(
13748            || {
13749                polls.set(polls.get() + 1);
13750                // Hold the inherited image through the first poll, as in the
13751                // posix_spawn parent-wake window, then commit the module image.
13752                committed.set(polls.get() == 2);
13753                Some(committed.get())
13754            },
13755            || Some(if committed.get() { module } else { inherited }),
13756        );
13757        assert_eq!(image, Some(module));
13758        assert_eq!(polls.get(), 2);
13759    }
13760
13761    #[test]
13762    fn linux_exec_flag_is_read_from_flags_after_the_last_parenthesis() {
13763        assert_eq!(
13764            linux_exec_committed("17 (a ) b) R 1 2 3 4 5 4194368"),
13765            Some(false)
13766        );
13767        assert_eq!(
13768            linux_exec_committed("17 (a ) b) R 1 2 3 4 5 4194304"),
13769            Some(true)
13770        );
13771        assert_eq!(linux_exec_committed("17 (a) R 1 2 3 4 5 invalid"), None);
13772        assert_eq!(linux_exec_committed("17 (a) R"), None);
13773    }
13774
13775    #[test]
13776    fn unreadable_exec_state_never_samples_an_inherited_image() {
13777        assert_eq!(
13778            sample_after_linux_exec(
13779                || None,
13780                || panic!("must not sample before exec confirmation")
13781            ),
13782            None
13783        );
13784    }
13785
13786    #[test]
13787    fn uncommitted_exec_times_out_without_sampling_an_inherited_image() {
13788        assert_eq!(
13789            sample_after_linux_exec(
13790                || Some(false),
13791                || panic!("must not sample after an exec timeout")
13792            ),
13793            None
13794        );
13795    }
13796}
13797
13798/// Resolve once and spawn that exact path, so PATH lookup cannot choose a
13799/// different executable after the no-delete capture was taken.
13800#[cfg(windows)]
13801pub(crate) fn windows_spawn_capture(spec: &ModuleSpec) -> io::Result<subc_os::ExecutableCapture> {
13802    if let Err(error) = require_program_search_path(spec) {
13803        return Err(match error {
13804            SuperviseError::Spawn { source, .. } => source,
13805            error => io::Error::other(error),
13806        });
13807    }
13808    let mut program = spec.program.clone();
13809    if program.is_absolute() || program.components().count() > 1 {
13810        // An explicit path can name a PE image with no extension. Try that
13811        // exact file first, as Command does, before falling back to .exe.
13812        match subc_os::ExecutableCapture::open(&program) {
13813            Ok(capture) => return Ok(capture),
13814            Err(error)
13815                if error.kind() == io::ErrorKind::NotFound && program.extension().is_none() => {}
13816            Err(error) => return Err(error),
13817        }
13818        program.set_extension("exe");
13819        return subc_os::ExecutableCapture::open(&program);
13820    }
13821    if program.extension().is_none() {
13822        program.set_extension("exe");
13823    }
13824    let custom_path = spec
13825        .env
13826        .iter()
13827        .rev()
13828        .find(|(key, _)| key.eq_ignore_ascii_case("PATH"));
13829    let mut directories = Vec::new();
13830    // These are Windows' default executable search locations. A configured
13831    // PATH still overrides the inherited PATH, not the system directories.
13832    if let Some(parent) = std::env::current_exe()?.parent() {
13833        directories.push(parent.to_path_buf());
13834    }
13835    directories.push(std::env::current_dir()?);
13836    if let Some(windows) = std::env::var_os("SystemRoot") {
13837        let windows = PathBuf::from(windows);
13838        directories.push(windows.join("System32"));
13839        directories.push(windows.clone());
13840    }
13841    let path = custom_path
13842        .map(|(_, value)| std::ffi::OsString::from(value))
13843        .or_else(|| std::env::var_os("PATH"));
13844    if let Some(path) = path {
13845        directories.extend(std::env::split_paths(&path));
13846    }
13847    for directory in directories {
13848        match subc_os::ExecutableCapture::open(&directory.join(&program)) {
13849            Ok(capture) => return Ok(capture),
13850            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
13851            Err(error) => return Err(error),
13852        }
13853    }
13854    Err(io::Error::new(
13855        io::ErrorKind::NotFound,
13856        "resolved executable not found",
13857    ))
13858}
13859
13860async fn spawn_and_mark_running_async(
13861    spec: &ModuleSpec,
13862    runtime: &SupervisorRuntimeConfig,
13863    snapshot: &SharedSnapshot,
13864) -> Result<SupervisedChild, SuperviseError> {
13865    let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
13866    let registration_watch = watch_registration(&runtime.registry, spec);
13867    #[cfg(unix)]
13868    let joining_group = containment::current(&runtime.child_roster.containment)
13869        .is_some_and(|container| container.group().is_some());
13870    let result = spawn_child_async(spec, runtime).await;
13871    #[cfg(unix)]
13872    let result = match result {
13873        Err(error)
13874            if joining_group
13875                && !is_launch_deferral(&error)
13876                && !runtime.child_roster.is_closed()
13877                && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
13878                && runtime
13879                    .child_roster
13880                    .previous_instance(&spec.module_id)
13881                    .is_none() =>
13882        {
13883            // A failed group join has already ended the old container. Its single
13884            // fresh-container retry belongs to the same restart budget entry.
13885            warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
13886            spawn_child_async(spec, runtime).await
13887        }
13888        other => other,
13889    };
13890    let mut child = result?;
13891    arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
13892    if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
13893        containment::terminate_blocking(&runtime.child_roster.containment);
13894        return Err(error);
13895    }
13896    if let Some(spawn) = activity_spawn {
13897        spawn.complete(snapshot);
13898    }
13899    Ok(child)
13900}
13901
13902#[cfg(test)]
13903fn spawn_and_mark_running(
13904    spec: &ModuleSpec,
13905    runtime: &SupervisorRuntimeConfig,
13906    snapshot: &SharedSnapshot,
13907) -> Result<SupervisedChild, SuperviseError> {
13908    let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
13909    let registration_watch = watch_registration(&runtime.registry, spec);
13910    #[cfg(unix)]
13911    let joining_group = containment::current(&runtime.child_roster.containment)
13912        .is_some_and(|container| container.group().is_some());
13913    let spawn = || {
13914        spawn_child(
13915            spec,
13916            runtime.connection_file_path.as_deref(),
13917            runtime.supervisor_handle.as_ref(),
13918            &runtime.stderr_ring,
13919            runtime.capture_logs_dir.as_deref(),
13920            &runtime.child_roster,
13921            runtime.spawn_delivery(),
13922            #[cfg(target_os = "linux")]
13923            runtime.cgroup_placement.as_ref(),
13924            runtime.register_timeout,
13925        )
13926    };
13927    let result = spawn();
13928    #[cfg(unix)]
13929    let result = match result {
13930        Err(error)
13931            if joining_group
13932                && !is_launch_deferral(&error)
13933                && !runtime.child_roster.is_closed()
13934                && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
13935                && runtime
13936                    .child_roster
13937                    .previous_instance(&spec.module_id)
13938                    .is_none() =>
13939        {
13940            // The failed join already destroyed and verified the old container.
13941            // Try one fresh group as part of this same restart, without spending
13942            // another crash-budget entry. Cgroups and Windows jobs do not retry.
13943            warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
13944            spawn()
13945        }
13946        other => other,
13947    };
13948    let child = result?;
13949    let mut child = child;
13950    arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
13951    if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
13952        containment::terminate_blocking(&runtime.child_roster.containment);
13953        return Err(error);
13954    }
13955    if let Some(spawn) = activity_spawn {
13956        spawn.complete(snapshot);
13957    }
13958    Ok(child)
13959}
13960
13961struct RegistrationWatch {
13962    changes: watch::Receiver<u64>,
13963    baseline: u64,
13964}
13965
13966// Capture before spawning: a fast child's accepted HELLO can disappear from the
13967// active registry before the monitor first runs. A pre-existing registration
13968// must not satisfy a new process's deadline either.
13969fn watch_registration(registry: &Registry, spec: &ModuleSpec) -> Option<RegistrationWatch> {
13970    if spec.protocol != ModuleProtocol::Subc {
13971        return None;
13972    }
13973    let changes = registry.subscribe_module_changes(&spec.module_id).ok()?;
13974    let baseline = *changes.borrow();
13975    Some(RegistrationWatch { changes, baseline })
13976}
13977
13978fn arm_registration_deadline(
13979    child: &mut SupervisedChild,
13980    budget: Duration,
13981    registration_watch: Option<RegistrationWatch>,
13982) {
13983    child.registration_watch = registration_watch;
13984    child.registration_deadline = (child.protocol == ModuleProtocol::Subc
13985        && child.awaiting_registration())
13986    .then_some(child.spawned_at + budget);
13987}
13988
13989async fn stop_unregistered_child(child: &mut SupervisedChild) -> io::Result<()> {
13990    child.retire_registration();
13991    if let Some(container) = child.child.container() {
13992        container.stop_members().await;
13993        child.kill_leader()?;
13994        child.wait().await?;
13995        return Ok(());
13996    }
13997    #[cfg(unix)]
13998    {
13999        // Children lead their own process groups. Signal the whole group so a
14000        // helper stuck before HELLO cannot survive its supervised parent.
14001        let group = unreaped_registration_group(child)?;
14002        let _ = rustix::process::kill_process_group(group, rustix::process::Signal::TERM);
14003        // Process-group safety rule: only signal a group while its leader is
14004        // our unreaped child. Even a zombie leader reserves its pid/group id;
14005        // reaping it before KILL would let that id name an unrelated group.
14006        // Sleep without waiting so TERM-ignoring helpers get the full grace.
14007        sleep(crate::child_roster::TERM_TO_KILL).await;
14008        let group = unreaped_registration_group(child)?;
14009        let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
14010    }
14011    // Windows terminates the containing Job Object as well as the direct
14012    // child. Linux also kills the child's cgroup when placement is enabled.
14013    child.start_kill()?;
14014    child.wait().await?;
14015    Ok(())
14016}
14017
14018#[cfg(unix)]
14019fn unreaped_registration_group(child: &SupervisedChild) -> io::Result<rustix::process::Pid> {
14020    if let Some(container) = child.child.container() {
14021        return container
14022            .group()
14023            .and_then(|pid| rustix::process::Pid::from_raw(pid as i32))
14024            .ok_or_else(|| io::Error::other("a carried cgroup has no signalable process group"));
14025    }
14026    // The group id comes only from the pid recorded at spawn, when the child
14027    // created its own group. Never admit init's group or a negative group id.
14028    let group = i32::try_from(child.pid)
14029        .ok()
14030        .filter(|pid| *pid > 1)
14031        .and_then(rustix::process::Pid::from_raw)
14032        .ok_or_else(|| {
14033            io::Error::new(
14034                io::ErrorKind::InvalidInput,
14035                "invalid supervised process group",
14036            )
14037        })?;
14038    if child.child.id() != Some(child.pid) {
14039        return Err(io::Error::new(
14040            io::ErrorKind::InvalidInput,
14041            "refusing process-group signal after supervised child was reaped",
14042        ));
14043    }
14044    Ok(group)
14045}
14046
14047enum RegistrationWaitOutcome {
14048    Registered,
14049    Exited(ExitReport),
14050    TimedOut,
14051}
14052
14053struct ReloadRegistrationFailure {
14054    exit_report: ExitReport,
14055    reason: String,
14056}
14057
14058#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14059enum BusyGaugeObservation {
14060    Quiescent,
14061    Busy,
14062    Omitted,
14063}
14064
14065/// What one health answer said about one declared busy gauge.
14066#[derive(Debug, Clone, PartialEq, Eq)]
14067enum GaugeVerdict {
14068    /// The gauge read 0: this gauge is not what holds the drain.
14069    Zero,
14070    /// The gauge read a positive count.
14071    NonZero(u64),
14072    /// The gauge was present but not a non-negative integer (`0.0`, a string,
14073    /// a negative number). It counts as busy, because the daemon cannot tell
14074    /// it is idle. Carries the value as JSON text, cut to a short prefix.
14075    NotACount(String),
14076    /// The health answer had no metrics object, or one without this gauge.
14077    Missing,
14078    /// The probe produced no health answer to read; carries the probe error's
14079    /// evidence label (`no-answer` for a probe that timed out).
14080    ProbeFailed(&'static str),
14081}
14082
14083impl GaugeVerdict {
14084    fn reads_quiet(&self) -> bool {
14085        matches!(self, Self::Zero)
14086    }
14087}
14088
14089impl fmt::Display for GaugeVerdict {
14090    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14091        match self {
14092            Self::Zero => f.write_str("zero"),
14093            Self::NonZero(value) => write!(f, "non_zero({value})"),
14094            Self::NotACount(value) => write!(f, "not_a_count({value})"),
14095            Self::Missing => f.write_str("missing_from_health_body"),
14096            Self::ProbeFailed(kind) => write!(f, "probe_failed({kind})"),
14097        }
14098    }
14099}
14100
14101/// The longest JSON text kept for a gauge value that is not a count, so a
14102/// module reporting a large object as a gauge cannot flood the drain log.
14103const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
14104
14105/// Read each declared gauge out of one health answer's metrics.
14106fn gauge_verdicts(metrics: Option<&Value>, gauges: &[String]) -> Vec<GaugeVerdict> {
14107    let metrics = metrics.and_then(Value::as_object);
14108    gauges
14109        .iter()
14110        .map(
14111            |gauge| match metrics.and_then(|metrics| metrics.get(gauge)) {
14112                None => GaugeVerdict::Missing,
14113                Some(value) => match value.as_u64() {
14114                    Some(0) => GaugeVerdict::Zero,
14115                    Some(count) => GaugeVerdict::NonZero(count),
14116                    None => {
14117                        let mut text = value.to_string();
14118                        if text.len() > GAUGE_VALUE_TEXT_LIMIT {
14119                            let mut end = GAUGE_VALUE_TEXT_LIMIT;
14120                            while !text.is_char_boundary(end) {
14121                                end -= 1;
14122                            }
14123                            text.truncate(end);
14124                            text.push_str("...");
14125                        }
14126                        GaugeVerdict::NotACount(text)
14127                    }
14128                },
14129            },
14130        )
14131        .collect()
14132}
14133
14134/// The drain's overall reading of one health answer: omitted when any
14135/// declared gauge is missing, quiescent only when every gauge reads 0.
14136fn busy_gauge_observation(verdicts: &[GaugeVerdict]) -> BusyGaugeObservation {
14137    if verdicts
14138        .iter()
14139        .any(|verdict| matches!(verdict, GaugeVerdict::Missing))
14140    {
14141        BusyGaugeObservation::Omitted
14142    } else if verdicts.iter().all(GaugeVerdict::reads_quiet) {
14143        BusyGaugeObservation::Quiescent
14144    } else {
14145        BusyGaugeObservation::Busy
14146    }
14147}
14148
14149/// One declared gauge's history over a drain: the latest verdict on it, and
14150/// the latest value actually read for it (which a later failed probe or
14151/// missing gauge does not erase). Times are offsets from the start of the
14152/// drain's wait.
14153#[derive(Debug, Clone, Default, PartialEq, Eq)]
14154struct GaugeTrace {
14155    latest: Option<(GaugeVerdict, Duration)>,
14156    last_value: Option<(GaugeVerdict, Duration)>,
14157}
14158
14159/// What a drain's busy-gauge probes saw, kept so that a drain which runs to
14160/// its ceiling can say in its timeout line which declared gauge held it and
14161/// why. Without it, a gauge that read busy, a gauge the module never
14162/// reported, and a probe that never got an answer all looked the same: a
14163/// drain that ended at its ceiling with nothing in flight.
14164#[derive(Debug, Clone, Default, PartialEq, Eq)]
14165struct DrainGaugeTrace {
14166    /// Health probes the drain sent.
14167    probes: u32,
14168    /// Each declared gauge, in declaration order.
14169    gauges: Vec<(String, GaugeTrace)>,
14170}
14171
14172impl DrainGaugeTrace {
14173    fn new(gauges: &[String]) -> Self {
14174        Self {
14175            probes: 0,
14176            gauges: gauges
14177                .iter()
14178                .map(|gauge| (gauge.clone(), GaugeTrace::default()))
14179                .collect(),
14180        }
14181    }
14182
14183    /// Record one probe's verdicts, one per declared gauge, `at` into the drain.
14184    fn record(&mut self, verdicts: &[GaugeVerdict], at: Duration) {
14185        self.probes = self.probes.saturating_add(1);
14186        for ((_, trace), verdict) in self.gauges.iter_mut().zip(verdicts) {
14187            trace.latest = Some((verdict.clone(), at));
14188            if matches!(
14189                verdict,
14190                GaugeVerdict::Zero | GaugeVerdict::NonZero(_) | GaugeVerdict::NotACount(_)
14191            ) {
14192                trace.last_value = Some((verdict.clone(), at));
14193            }
14194        }
14195    }
14196}
14197
14198/// Renders as `gauge: latest verdict @ offset; last value @ offset` for each
14199/// declared gauge, separated by ` | `. A value is shown as its verdict
14200/// (`zero`, `non_zero(n)`, `not_a_count(json)`), so it says both what was read
14201/// and whether that counted as busy.
14202impl fmt::Display for DrainGaugeTrace {
14203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14204        if self.gauges.is_empty() {
14205            return f.write_str("none declared");
14206        }
14207        for (index, (name, trace)) in self.gauges.iter().enumerate() {
14208            if index > 0 {
14209                f.write_str(" | ")?;
14210            }
14211            write!(f, "{name}: ")?;
14212            match &trace.latest {
14213                Some((verdict, at)) => write!(f, "{verdict} @{}ms", at.as_millis())?,
14214                None => f.write_str("never probed")?,
14215            }
14216            match &trace.last_value {
14217                Some((value, at)) => write!(f, "; last value {value} @{}ms", at.as_millis())?,
14218                None => f.write_str("; no value ever read")?,
14219            }
14220        }
14221        Ok(())
14222    }
14223}
14224
14225pub(crate) fn declared_busy_gauges(
14226    registry: &Registry,
14227    module_id: &str,
14228) -> Result<Vec<String>, SuperviseError> {
14229    busy_gauges_of(
14230        registry
14231            .get_module(module_id)
14232            .map_err(SuperviseError::Registry)?,
14233    )
14234}
14235
14236/// [`declared_busy_gauges`] for the registration a connection holds, in any
14237/// slot: after cutover the incumbent is no longer the id's active
14238/// registration, and its own manifest is the one that names its gauges.
14239fn declared_busy_gauges_for_connection(
14240    registry: &Registry,
14241    connection_id: ConnectionId,
14242) -> Result<Vec<String>, SuperviseError> {
14243    busy_gauges_of(
14244        registry
14245            .get_module_by_connection(connection_id)
14246            .map_err(SuperviseError::Registry)?,
14247    )
14248}
14249
14250fn busy_gauges_of(
14251    registration: Option<crate::registry::ModuleRegistration>,
14252) -> Result<Vec<String>, SuperviseError> {
14253    let Some(registration) = registration else {
14254        return Ok(Vec::new());
14255    };
14256    let Some(self_signals) = registration.manifest.self_signals else {
14257        return Ok(Vec::new());
14258    };
14259
14260    let mut gauges = Vec::new();
14261    for declaration in self_signals {
14262        if declaration.kind != SelfSignalKind::Busy {
14263            continue;
14264        }
14265        match declaration.anchored_to {
14266            SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
14267                gauges.extend(declared)
14268            }
14269            _ => {
14270                // An invalid Busy anchor is fail-safe: the empty name cannot be
14271                // present in a conforming health report, so this drain stays busy.
14272                gauges.push(String::new());
14273            }
14274        }
14275    }
14276    Ok(gauges)
14277}
14278
14279/// Wait for `endpoint` to have nothing in flight and, when the module declares
14280/// busy gauges, for a health probe to report them quiet. The probe is addressed
14281/// by `scope`: a swap's superseded incumbent must be asked about its own
14282/// gauges, and by module id the probe would reach the promoted candidate.
14283/// While the gauges read busy, the probe repeats every
14284/// [`DRAIN_BUSY_REPROBE_INTERVAL`] until they read quiet or `deadline` passes.
14285/// Every probe's reading of each gauge is recorded in `trace`, for the caller's
14286/// timeout line.
14287#[allow(clippy::too_many_arguments)]
14288async fn wait_for_forwarding_quiescence(
14289    forwarding: &ForwardingTable,
14290    module_id: &str,
14291    runtime: &SupervisorRuntimeConfig,
14292    endpoint: crate::ModuleEndpointId,
14293    deadline: Instant,
14294    busy_gauges: &[String],
14295    scope: DrainScope,
14296    trace: &mut DrainGaugeTrace,
14297) -> Result<bool, SuperviseError> {
14298    let wait_started = Instant::now();
14299    let mut gauges_quiescent = busy_gauges.is_empty();
14300    let mut next_probe_at = wait_started;
14301    let mut omission_reported = false;
14302
14303    loop {
14304        let now = Instant::now();
14305        if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
14306            let report = match scope {
14307                DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
14308                DrainScope::Endpoint(endpoint) => {
14309                    probe_endpoint_health(endpoint, runtime, Some(deadline)).await
14310                }
14311            };
14312            let verdicts = match &report {
14313                Ok(report) => gauge_verdicts(report.metrics.as_ref(), busy_gauges),
14314                Err(err) => vec![GaugeVerdict::ProbeFailed(err.label()); busy_gauges.len()],
14315            };
14316            trace.record(&verdicts, wait_started.elapsed());
14317            gauges_quiescent = match report {
14318                Ok(_) => match busy_gauge_observation(&verdicts) {
14319                    BusyGaugeObservation::Quiescent => true,
14320                    BusyGaugeObservation::Busy => false,
14321                    BusyGaugeObservation::Omitted => {
14322                        // Once per drain: a module that never reports a gauge
14323                        // it declared would otherwise say so on every probe.
14324                        if !omission_reported {
14325                            forwarding
14326                                .counters()
14327                                .increment_drains_with_undeclared_gauge();
14328                            let missing = busy_gauges
14329                                .iter()
14330                                .zip(&verdicts)
14331                                .filter(|(_, verdict)| matches!(verdict, GaugeVerdict::Missing))
14332                                .map(|(gauge, _)| gauge.as_str())
14333                                .collect::<Vec<_>>()
14334                                .join(",");
14335                            warn!(
14336                                module_id,
14337                                missing_gauges = %missing,
14338                                "drain health.check answer lacks a declared busy gauge; the drain treats the module as busy until it reports it"
14339                            );
14340                            omission_reported = true;
14341                        }
14342                        false
14343                    }
14344                },
14345                Err(err) => {
14346                    warn!(
14347                        module_id,
14348                        error = %err,
14349                        "drain health.check did not produce declared busy gauges; treating module as busy"
14350                    );
14351                    false
14352                }
14353            };
14354            // Counted from the probe's completion: the probe above was awaited,
14355            // so no second probe can start while one is still outstanding.
14356            next_probe_at = Instant::now() + drain_busy_reprobe_interval();
14357        }
14358
14359        let in_flight = forwarding
14360            .endpoint_in_flight_count(endpoint)
14361            .map_err(SuperviseError::Forwarding)?;
14362        if in_flight == 0 && gauges_quiescent {
14363            return Ok(true);
14364        }
14365
14366        let now = Instant::now();
14367        if now >= deadline {
14368            return Ok(false);
14369        }
14370        let mut wait = deadline
14371            .saturating_duration_since(now)
14372            .min(REGISTRY_RELEASE_POLL);
14373        if !busy_gauges.is_empty() {
14374            wait = wait.min(next_probe_at.saturating_duration_since(now));
14375        }
14376        sleep(wait).await;
14377    }
14378}
14379
14380/// The wait between drain busy-gauge probes: the larger of
14381/// [`DRAIN_BUSY_REPROBE_INTERVAL`] and [`REGISTRY_RELEASE_POLL`], the
14382/// drain's own in-flight poll interval.
14383fn drain_busy_reprobe_interval() -> Duration {
14384    DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
14385}
14386
14387/// Logs why a drain gave up: the drain waited its full timeout without the
14388/// module going quiet, and teardown is being forced.
14389///
14390/// The line names two kinds of evidence, because a bare "timed out" hides
14391/// causes that need different fixes:
14392/// - `holdouts`: the requests and routes still open when the timeout hit,
14393///   and on which connections. One stuck call is a module bug; a held stream
14394///   on every session is a module that should end its streams when it
14395///   receives `module.draining`.
14396/// - `gauges`: for each busy gauge the module declares, its latest reading
14397///   and how many probes ran. This separates a module that kept reporting
14398///   itself busy, one whose health answer never contained the gauge, and one
14399///   that never answered the probes, which otherwise all look like a timeout
14400///   with nothing in flight.
14401fn warn_drain_timed_out(
14402    module_id: &str,
14403    drain_timeout: Duration,
14404    reason: RouteCloseReason,
14405    holdouts: &crate::forwarding::DrainHoldouts,
14406    gauges: &DrainGaugeTrace,
14407) {
14408    warn!(
14409        module_id = %module_id,
14410        waited = ?drain_timeout,
14411        ?reason,
14412        held_requests = holdouts.requests,
14413        held_routes = holdouts.routes,
14414        total_routes = holdouts.total_routes,
14415        top_connections = ?holdouts.top_connections,
14416        // `module_channel:corr`, so the module can find each held request
14417        // in its own log; capped, so `held_requests` is the full count.
14418        held = %holdouts
14419            .held
14420            .iter()
14421            .map(|(channel, corr)| format!("{channel}:{corr}"))
14422            .collect::<Vec<_>>()
14423            .join(","),
14424        gauge_probes = gauges.probes,
14425        busy_gauges = %gauges,
14426        "route drain timed out before request quiescence; forcing teardown"
14427    );
14428}
14429
14430/// The `route.closed` `drained` value implied by a quiescence-wait outcome.
14431///
14432/// `Ok` is always honest and passed straight through -- the wait actually measured
14433/// in-flight state. `Err` means the wait produced no measurement at all (the
14434/// forwarding table's lock was poisoned), so `false` is reported as the one honest
14435/// constant: the drain did not complete. Never recomputed from route state, never a
14436/// third "unknown" value -- the caller must still send a well-formed `route.closed`.
14437fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
14438    match wait_result {
14439        Ok(drained) => *drained,
14440        Err(_) => false,
14441    }
14442}
14443
14444fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
14445    for released in released_routes {
14446        let frame = match Frame::build_with_version(
14447            released.negotiated_ver,
14448            FrameType::Goodbye,
14449            control_flags(),
14450            released.channel,
14451            released.epoch,
14452            0,
14453            Vec::new(),
14454        ) {
14455            Ok(frame) => frame,
14456            Err(err) => {
14457                warn!(
14458                    route_channel = released.channel,
14459                    error = %err,
14460                    "failed to build supervisor drain route GOODBYE frame"
14461                );
14462                continue;
14463            }
14464        };
14465        if !released.close_on_delivery_failure() {
14466            crate::forwarding::send_module_route_goodbye(
14467                &forwarding.counters(),
14468                &released.sink,
14469                frame,
14470                released.module_id.as_deref(),
14471                "supervisor drain",
14472            );
14473            continue;
14474        }
14475        if let Err(err) = released.sink.try_send(frame) {
14476            warn!(
14477                target_connection_id = released.connection_id.get(),
14478                route_channel = released.channel,
14479                error = %err,
14480                "supervisor drain route GOODBYE was not delivered to client; closing target connection"
14481            );
14482            let _ = forwarding.escalate_client_delivery_failure(
14483                released.connection_id,
14484                released.channel,
14485                released.epoch,
14486                CloseReason::new(
14487                    "route_goodbye_delivery_failed",
14488                    format!(
14489                        "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
14490                        released.channel
14491                    ),
14492                ),
14493                crate::forwarding::UndeliveredFrame {
14494                    module_id: released.module_id.as_deref(),
14495                    sink: &released.sink,
14496                },
14497            );
14498        }
14499    }
14500}
14501
14502async fn send_module_draining(
14503    module_id: &str,
14504    reason: RouteCloseReason,
14505    deadline_ms: u64,
14506    target: &ModuleDrainTarget,
14507    _wait_for_flush: bool,
14508) -> bool {
14509    let body = match serde_json::to_vec(&ModuleControlCommand::Draining {
14510        reason,
14511        deadline_ms,
14512    }) {
14513        Ok(body) => body,
14514        Err(err) => {
14515            warn!(
14516                module_id,
14517                error = %err,
14518                "failed to encode module draining command"
14519            );
14520            return false;
14521        }
14522    };
14523    let frame = match Frame::build_with_version(
14524        target.negotiated_ver,
14525        FrameType::Push,
14526        control_flags(),
14527        0,
14528        0,
14529        0,
14530        body,
14531    ) {
14532        Ok(frame) => frame,
14533        Err(err) => {
14534            warn!(
14535                module_id,
14536                error = %err,
14537                "failed to build module draining command frame"
14538            );
14539            return false;
14540        }
14541    };
14542    #[cfg(unix)]
14543    if _wait_for_flush {
14544        return target.sink.send_flushed(frame).await.is_ok();
14545    }
14546    if let Err(err) = target.sink.try_send(frame) {
14547        warn!(
14548            module_id,
14549            target_connection_id = target.endpoint.connection_id.get(),
14550            error = %err,
14551            "module draining command was not delivered to peer"
14552        );
14553        return false;
14554    }
14555    true
14556}
14557
14558/// The channel-0 GOODBYE that tells a module its stop is planned.
14559fn module_goodbye_frame(module_id: &str, negotiated_ver: u8) -> Option<Frame> {
14560    match Frame::build_with_version(
14561        negotiated_ver,
14562        FrameType::Goodbye,
14563        control_flags(),
14564        0,
14565        0,
14566        0,
14567        Vec::new(),
14568    ) {
14569        Ok(frame) => Some(frame),
14570        Err(err) => {
14571            warn!(
14572                module_id,
14573                error = %err,
14574                "failed to build module GOODBYE frame"
14575            );
14576            None
14577        }
14578    }
14579}
14580
14581/// Send every registered module connection its module GOODBYE at daemon
14582/// shutdown, then request that connection's close.
14583///
14584/// A module tells a planned stop from a lost daemon by whether a GOODBYE came
14585/// before EOF, so the GOODBYE must reach the socket before the close. A close
14586/// request does not wait for the connection's queued frames: its writer gets a
14587/// bounded grace after the close, is aborted if it overruns it, and the daemon
14588/// process may exit before that grace ends. So with `wait_for_flush`, each
14589/// connection is closed only after its writer has acknowledged writing the
14590/// GOODBYE, or once a short shared budget runs out, so one module that is not
14591/// reading cannot hold up the others or the shutdown. Without it the GOODBYEs
14592/// are only queued, for a shutdown the operator has told to stop waiting.
14593/// A connection that is already gone is skipped.
14594#[cfg(unix)]
14595async fn send_module_goodbyes_for_daemon_shutdown(
14596    forwarding: &Arc<ForwardingTable>,
14597    reason: &CloseReason,
14598    wait_for_flush: bool,
14599) {
14600    const GOODBYE_BUDGET: Duration = Duration::from_millis(500);
14601    let targets = match forwarding.module_connections() {
14602        Ok(targets) => targets,
14603        Err(err) => {
14604            warn!(error = %err, "could not list module connections for shutdown GOODBYE");
14605            return;
14606        }
14607    };
14608    let deadline = Instant::now() + GOODBYE_BUDGET;
14609    let mut sends = tokio::task::JoinSet::new();
14610    for target in targets {
14611        let Some(frame) = module_goodbye_frame(&target.module_id, target.negotiated_ver) else {
14612            continue;
14613        };
14614        if !wait_for_flush {
14615            if let Err(err) = target.sink.try_send(frame) {
14616                debug!(
14617                    module_id = %target.module_id,
14618                    error = %err,
14619                    "shutdown module GOODBYE was not queued"
14620                );
14621            }
14622            continue;
14623        }
14624        let forwarding = Arc::clone(forwarding);
14625        let reason = reason.clone();
14626        sends.spawn(async move {
14627            match timeout_at(deadline, target.sink.send_flushed(frame)).await {
14628                Ok(Ok(())) => {}
14629                Ok(Err(err)) => debug!(
14630                    module_id = %target.module_id,
14631                    error = %err,
14632                    "module connection closed before its shutdown GOODBYE was written"
14633                ),
14634                Err(_) => warn!(
14635                    module_id = %target.module_id,
14636                    budget = ?GOODBYE_BUDGET,
14637                    "shutdown module GOODBYE was not written within its budget; closing anyway"
14638                ),
14639            }
14640            forwarding.request_connection_close(target.endpoint.connection_id, reason);
14641        });
14642    }
14643    // Every task ends by the shared deadline, so this wait is bounded too.
14644    while sends.join_next().await.is_some() {}
14645}
14646
14647async fn send_module_goodbye(
14648    module_id: &str,
14649    forwarding: &ForwardingTable,
14650    target: &ModuleDrainTarget,
14651    wait_for_flush: bool,
14652) {
14653    let Some(frame) = module_goodbye_frame(module_id, target.negotiated_ver) else {
14654        return;
14655    };
14656    // A channel is shut down synchronously after its drain. Its final frame
14657    // must reach the socket writer first; queue admission alone can lose it.
14658    let sent = if wait_for_flush {
14659        timeout(Duration::from_millis(500), target.sink.send_flushed(frame))
14660            .await
14661            .map_err(|_| "module GOODBYE flush exceeded 500ms".to_owned())
14662            .and_then(|result| result.map_err(|err| err.to_string()))
14663    } else {
14664        target.sink.try_send(frame).map_err(|err| err.to_string())
14665    };
14666    if let Err(err) = sent {
14667        warn!(
14668            module_id,
14669            target_connection_id = target.endpoint.connection_id.get(),
14670            error = %err,
14671            "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
14672        );
14673        forwarding.request_connection_close(
14674            target.endpoint.connection_id,
14675            CloseReason::new(
14676                "module_goodbye_delivery_failed",
14677                format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
14678            ),
14679        );
14680    }
14681}
14682
14683#[derive(Clone, Copy)]
14684struct ForwardingDrainContext<'a> {
14685    spec: &'a ModuleSpec,
14686    runtime: &'a SupervisorRuntimeConfig,
14687    registry: &'a Registry,
14688    scope: DrainScope,
14689}
14690
14691/// Which process a forwarding drain addresses.
14692#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14693enum DrainScope {
14694    /// Whatever endpoint is active for the module id: every plain stop,
14695    /// restart and reload. Also moves the module's state to `Draining`.
14696    Active,
14697    /// One specific endpoint: a swap's incumbent after cutover. Draining it by
14698    /// module id would resolve to the promoted candidate and leave neither
14699    /// process routable. The module's state is left alone, since the promoted
14700    /// candidate is what it describes and that process is running.
14701    Endpoint(crate::ModuleEndpointId),
14702}
14703
14704/// Whether a child being drained has already been asked to stop by the time
14705/// its drain wait starts.
14706///
14707/// The drain wait is the same budget whatever this says. What it decides is
14708/// whether the supervisor must ask by signal before that wait begins: a child
14709/// that nobody asked will sit out the whole budget and then be SIGKILLed,
14710/// healthy or not.
14711#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14712enum StopNotice {
14713    /// The module was sent `module.draining` and a module GOODBYE over its own
14714    /// registered connection, and stops itself.
14715    SentOverConnection,
14716    /// The forwarding drain found no registered connection for the module: a
14717    /// subc child spawned moments ago that has not sent HELLO yet, or a
14718    /// `protocol: "none"` child, which never registers.
14719    NoConnection,
14720    /// This path sends nothing over the module's connection: the supervisor has
14721    /// no forwarding table, or the caller stops the child without a forwarding
14722    /// drain.
14723    NotSent,
14724}
14725
14726async fn begin_forwarding_drain(
14727    spec: &ModuleSpec,
14728    runtime: &SupervisorRuntimeConfig,
14729    registry: &Registry,
14730    snapshot: &SharedSnapshot,
14731    enabled: Option<bool>,
14732    reason: RouteCloseReason,
14733) -> Result<StopNotice, SuperviseError> {
14734    let Some(forwarding) = runtime.forwarding.as_ref() else {
14735        return Err(SuperviseError::ReloadUnavailable {
14736            module_id: spec.module_id.clone(),
14737            reason: "supervisor was not configured with a forwarding table".to_string(),
14738        });
14739    };
14740
14741    begin_forwarding_drain_with(
14742        forwarding,
14743        ForwardingDrainContext {
14744            spec,
14745            runtime,
14746            registry,
14747            scope: DrainScope::Active,
14748        },
14749        snapshot,
14750        enabled,
14751        reason,
14752        runtime.drain_timeout,
14753    )
14754    .await
14755}
14756
14757async fn begin_forwarding_drain_if_configured(
14758    spec: &ModuleSpec,
14759    runtime: &SupervisorRuntimeConfig,
14760    registry: &Registry,
14761    snapshot: &SharedSnapshot,
14762    enabled: Option<bool>,
14763    reason: RouteCloseReason,
14764) -> Result<StopNotice, SuperviseError> {
14765    begin_forwarding_drain_with_timeout(
14766        spec,
14767        runtime,
14768        registry,
14769        snapshot,
14770        enabled,
14771        reason,
14772        runtime.drain_timeout,
14773    )
14774    .await
14775}
14776
14777/// Like [`begin_forwarding_drain_if_configured`] but with an explicit drain
14778/// budget, for paths where the operator overrides the module's configured one
14779/// (`supervisor.restart{drain_timeout_ms}`).
14780async fn begin_forwarding_drain_with_timeout(
14781    spec: &ModuleSpec,
14782    runtime: &SupervisorRuntimeConfig,
14783    registry: &Registry,
14784    snapshot: &SharedSnapshot,
14785    enabled: Option<bool>,
14786    reason: RouteCloseReason,
14787    drain_timeout: Duration,
14788) -> Result<StopNotice, SuperviseError> {
14789    let Some(forwarding) = runtime.forwarding.as_ref() else {
14790        return Ok(StopNotice::NotSent);
14791    };
14792
14793    begin_forwarding_drain_with(
14794        forwarding,
14795        ForwardingDrainContext {
14796            spec,
14797            runtime,
14798            registry,
14799            scope: DrainScope::Active,
14800        },
14801        snapshot,
14802        enabled,
14803        reason,
14804        drain_timeout,
14805    )
14806    .await
14807}
14808
14809async fn begin_forwarding_drain_with(
14810    forwarding: &ForwardingTable,
14811    context: ForwardingDrainContext<'_>,
14812    snapshot: &SharedSnapshot,
14813    enabled: Option<bool>,
14814    reason: RouteCloseReason,
14815    drain_timeout: Duration,
14816) -> Result<StopNotice, SuperviseError> {
14817    let ForwardingDrainContext {
14818        spec,
14819        runtime,
14820        registry,
14821        scope,
14822    } = context;
14823    debug_assert_ne!(reason, RouteCloseReason::Crash);
14824    let terminal = matches!(reason, RouteCloseReason::Disable);
14825    let drain_started_at = Instant::now();
14826    let drain_deadline = drain_started_at + drain_timeout;
14827    let deadline_ms =
14828        unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
14829    let busy_gauges = match scope {
14830        DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
14831        DrainScope::Endpoint(endpoint) => {
14832            declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
14833        }
14834    };
14835
14836    // Admission gate first: route.open/commit and route REQUEST admission are closed
14837    // before the first quiescence check, so the outstanding count can only fall.
14838    let gate_started = Instant::now();
14839    let drain_target = match scope {
14840        DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
14841        DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
14842    }
14843    .map_err(SuperviseError::Forwarding)?;
14844    // The instant admission closed, and how long taking the forwarding write
14845    // lock to close it took. The timeout line reports only the quiescence
14846    // wait, so without this a drain that started late looked like one that
14847    // started on time.
14848    info!(
14849        module_id = %spec.module_id,
14850        ?reason,
14851        gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
14852        connected = drain_target.is_some(),
14853        "module drain began; route admission closed"
14854    );
14855    if scope == DrainScope::Active {
14856        update_snapshot(snapshot, Some(&spec.module_id), |state| {
14857            state.state = ModuleState::Draining;
14858            state.draining_to_replace =
14859                matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
14860            if let Some(enabled) = enabled {
14861                state.enabled = enabled;
14862            }
14863        })?;
14864    }
14865
14866    let Some(target) = drain_target.as_ref() else {
14867        // Nothing was sent: the module has no registered connection to carry
14868        // `module.draining` or a GOODBYE. The caller must not assume the child
14869        // was asked to stop.
14870        return Ok(StopNotice::NoConnection);
14871    };
14872    let flush_goodbye = runtime.supervisor_handle.as_ref().is_some_and(|handle| {
14873        handle
14874            .registration_spawn(target.endpoint.connection_id)
14875            .is_some()
14876    });
14877    {
14878        send_module_draining(&spec.module_id, reason, deadline_ms, target, false).await;
14879        #[cfg(feature = "test-support")]
14880        forwarding.wait_before_route_closing_for_test().await;
14881        let routes = forwarding
14882            .endpoint_routes(target.endpoint)
14883            .map_err(SuperviseError::Forwarding)?;
14884        let routes_notified = routes.len();
14885        crate::control::send_route_control_pushes(
14886            forwarding,
14887            routes.clone(),
14888            ClientControlPush::RouteClosing {
14889                module_id: spec.module_id.clone(),
14890                channels: Vec::new(),
14891                reason,
14892            },
14893        );
14894        send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
14895
14896        // `route.closing` was just sent above: from here on every return path,
14897        // including an early one, MUST send `route.closed` before propagating
14898        // anything else. A client holds `closing` as a promise that a verdict is
14899        // coming; leaving early without `closed` strands it waiting forever, since
14900        // `closing` carries no timeout of its own.
14901        let mut gauge_trace = DrainGaugeTrace::new(&busy_gauges);
14902        let wait_result = wait_for_forwarding_quiescence(
14903            forwarding,
14904            &spec.module_id,
14905            runtime,
14906            target.endpoint,
14907            drain_deadline,
14908            &busy_gauges,
14909            scope,
14910            &mut gauge_trace,
14911        )
14912        .await;
14913        let drained = drained_after_quiescence_wait(&wait_result);
14914        if let Err(err) = &wait_result {
14915            error!(
14916                module_id = %spec.module_id,
14917                ?reason,
14918                error = %err,
14919                "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
14920            );
14921        } else if !drained {
14922            // Read before teardown releases the routes.
14923            let holdouts = forwarding
14924                .endpoint_drain_holdouts(target.endpoint)
14925                .unwrap_or_default();
14926            warn_drain_timed_out(
14927                &spec.module_id,
14928                drain_timeout,
14929                reason,
14930                &holdouts,
14931                &gauge_trace,
14932            );
14933        }
14934        crate::control::send_route_control_pushes(
14935            forwarding,
14936            routes,
14937            ClientControlPush::RouteClosed {
14938                module_id: spec.module_id.clone(),
14939                channels: Vec::new(),
14940                reason,
14941                drained,
14942                abandoned: target.abandoned_bindings.len() as u32,
14943                excluded_subscriptions: target.excluded_subscriptions,
14944                terminal: Some(terminal),
14945            },
14946        );
14947        wait_result?;
14948
14949        // `route.closed` has now been sent unconditionally above. From here the
14950        // remaining steps are cleanup (route + module GOODBYE) rather than a
14951        // promise the client is waiting on, but a lock-poisoned
14952        // `release_module_endpoint_routes` would otherwise skip the module
14953        // GOODBYE silently too -- send it before propagating the error.
14954        let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
14955            Ok(routes) => routes,
14956            Err(err) => {
14957                warn!(
14958                    module_id = %spec.module_id,
14959                    ?reason,
14960                    error = %err,
14961                    "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
14962                );
14963                send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
14964                return Err(SuperviseError::Forwarding(err));
14965            }
14966        };
14967        let route_goodbye_count = released_routes.len();
14968        send_route_goodbyes(forwarding, released_routes);
14969        send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
14970
14971        // The drain's happy path was previously silent: every emission above is
14972        // best-effort with only its failure arm logged, so "were consumers told"
14973        // was unprovable from the daemon log (surfaced by a 30-minute consumer
14974        // hang where the open question was exactly whether teardown notice went
14975        // out). One summary line makes that class decidable in one grep.
14976        info!(
14977            module_id = %spec.module_id,
14978            ?reason,
14979            routes_notified,
14980            route_goodbyes = route_goodbye_count,
14981            abandoned_reservations = target.abandoned_bindings.len(),
14982            excluded_subscriptions = target.excluded_subscriptions,
14983            drained,
14984            "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
14985        );
14986    }
14987
14988    Ok(StopNotice::SentOverConnection)
14989}
14990
14991/// Wait for the freshly spawned child to take the ACTIVE slot for `module_id`,
14992/// the only slot a plain (non-swap) spawn can register into.
14993async fn wait_for_registration_after_reload(
14994    registry: &Registry,
14995    module_id: &str,
14996    snapshot: &SharedSnapshot,
14997    child: &mut SupervisedChild,
14998    wait: Duration,
14999) -> Result<RegistrationWaitOutcome, SuperviseError> {
15000    wait_for_slot_registration(
15001        registry,
15002        crate::registry::RegistrationSlot::Active(module_id),
15003        module_id,
15004        snapshot,
15005        child,
15006        wait,
15007    )
15008    .await
15009}
15010
15011/// Wait for `child` to register into `slot`, or to exit, or for `wait` to pass.
15012///
15013/// Keyed on the slot rather than the bare module id because during a swap the
15014/// id's active slot is already held by the incumbent: an id-keyed wait would
15015/// report the incumbent's registration as the candidate's and a candidate that
15016/// never registers would look registered. A swap candidate waits on
15017/// `crate::registry::RegistrationSlot::Candidate`.
15018async fn wait_for_slot_registration(
15019    registry: &Registry,
15020    slot: crate::registry::RegistrationSlot<'_>,
15021    module_id: &str,
15022    snapshot: &SharedSnapshot,
15023    child: &mut SupervisedChild,
15024    wait: Duration,
15025) -> Result<RegistrationWaitOutcome, SuperviseError> {
15026    let deadline = Instant::now() + wait;
15027    loop {
15028        if registry
15029            .registration(slot)
15030            .map_err(SuperviseError::Registry)?
15031            .is_some()
15032        {
15033            return Ok(RegistrationWaitOutcome::Registered);
15034        }
15035
15036        let now = Instant::now();
15037        if now >= deadline {
15038            return Ok(RegistrationWaitOutcome::TimedOut);
15039        }
15040        let remaining = deadline.saturating_duration_since(now);
15041        let poll = remaining.min(REGISTRY_RELEASE_POLL);
15042
15043        tokio::select! {
15044            wait_result = child.wait() => {
15045                let status = wait_result.map_err(|source| SuperviseError::Wait {
15046                    module_id: module_id.to_string(),
15047                    source,
15048                })?;
15049                return Ok(RegistrationWaitOutcome::Exited(classify_reaped_child_exit(
15050                    snapshot,
15051                    child,
15052                    &status,
15053                )));
15054            }
15055            _ = sleep(poll) => {}
15056        }
15057    }
15058}
15059
15060fn registration_failure_exit_report(mut exit_report: ExitReport) -> ExitReport {
15061    // A process stopped for missing its first HELLO did not provide service,
15062    // even if its TERM handler exits zero. Reload also uses this classification
15063    // when a replacement exits before registering.
15064    if exit_report.kind != ExitKind::DeliberateSeverance {
15065        exit_report.kind = ExitKind::Crash;
15066    }
15067    exit_report
15068}
15069
15070async fn handle_reload_child_registration_failure(
15071    spec: &ModuleSpec,
15072    runtime: &SupervisorRuntimeConfig,
15073    registry: &Registry,
15074    process_liveness: &SupervisorProcessLiveness,
15075    snapshot: &SharedSnapshot,
15076    _child: &mut Option<SupervisedChild>,
15077    failure: ReloadRegistrationFailure,
15078) -> Result<(), SuperviseError> {
15079    let ReloadRegistrationFailure {
15080        exit_report,
15081        reason,
15082    } = failure;
15083    match on_child_exit(
15084        spec,
15085        runtime.restart_policy,
15086        registry,
15087        snapshot,
15088        &runtime.terminal_ring,
15089        &runtime.spawn_events,
15090        &runtime.child_roster,
15091        exit_report,
15092        runtime.recovery_is_daemon,
15093    )
15094    .await
15095    {
15096        NextAction::Stop {
15097            registration_released,
15098        } => {
15099            if registration_released {
15100                process_liveness.untrack_if_current(&spec.module_id, snapshot);
15101            }
15102        }
15103        NextAction::Restart { schedule } => {
15104            let delay = schedule.map_or(runtime.restart_policy.delay_for_restart(0), |schedule| {
15105                schedule.delay
15106            });
15107            if let Some(schedule) = schedule {
15108                log_crash_respawn(&spec.module_id, schedule);
15109            }
15110            schedule_respawn(
15111                runtime,
15112                snapshot,
15113                &spec.module_id,
15114                delay,
15115                RespawnKind::Spawn,
15116                true,
15117            )?;
15118        }
15119    }
15120    Err(SuperviseError::ReloadFailed {
15121        module_id: spec.module_id.clone(),
15122        reason,
15123    })
15124}
15125
15126async fn handle_reload_spawn_failure(
15127    spec: &ModuleSpec,
15128    runtime: &SupervisorRuntimeConfig,
15129    process_liveness: &SupervisorProcessLiveness,
15130    snapshot: &SharedSnapshot,
15131    _child: &mut Option<SupervisedChild>,
15132    reason: String,
15133) -> Result<(), SuperviseError> {
15134    let now = Instant::now();
15135    let mut schedule = None;
15136    update_snapshot(snapshot, Some(&spec.module_id), |state| {
15137        clear_current_process_facts(state);
15138        if state.enabled {
15139            schedule = state.next_crash_restart(&runtime.restart_policy, now);
15140            state.state = if schedule.is_some() {
15141                ModuleState::Restarting
15142            } else {
15143                if runtime
15144                    .failure_context(runtime.recovery_is_daemon)
15145                    .may_retry()
15146                {
15147                    state.failed_retry.schedule(&spec.module_id);
15148                }
15149                ModuleState::Failed
15150            };
15151        } else {
15152            state.state = ModuleState::Disabled;
15153        }
15154    })?;
15155    if let Some(schedule) = schedule {
15156        schedule_respawn(
15157            runtime,
15158            snapshot,
15159            &spec.module_id,
15160            schedule.delay,
15161            RespawnKind::Spawn,
15162            true,
15163        )?;
15164    } else {
15165        process_liveness.untrack_if_current(&spec.module_id, snapshot);
15166    }
15167    Err(SuperviseError::ReloadFailed {
15168        module_id: spec.module_id.clone(),
15169        reason,
15170    })
15171}
15172
15173fn control_flags() -> Flags {
15174    Flags::new(false, Priority::Passive, false)
15175}
15176
15177#[allow(clippy::too_many_arguments)]
15178async fn drain_optional_child(
15179    module_id: &str,
15180    protocol: ModuleProtocol,
15181    stop_notice: StopNotice,
15182    registry: &Registry,
15183    forwarding: Option<&ForwardingTable>,
15184    snapshot: &SharedSnapshot,
15185    terminal_ring: &Arc<Mutex<TerminalRing>>,
15186    spawn_events: &SpawnEventFeed,
15187    child: &mut Option<SupervisedChild>,
15188    drain_timeout: Duration,
15189    final_state: ModuleState,
15190    enabled: Option<bool>,
15191    failure: &FailureContext,
15192) -> Result<(), SuperviseError> {
15193    if let Some(child) = child.take() {
15194        drain_child_to_state(
15195            module_id,
15196            protocol,
15197            stop_notice,
15198            registry,
15199            forwarding,
15200            snapshot,
15201            terminal_ring,
15202            spawn_events,
15203            child,
15204            drain_timeout,
15205            final_state,
15206            enabled,
15207            failure,
15208        )
15209        .await
15210    } else {
15211        update_snapshot(snapshot, Some(module_id), |state| {
15212            state.state = final_state;
15213            if final_state == ModuleState::Failed {
15214                state.failed_retry.failed_at = Some(Instant::now());
15215            }
15216            if let Some(enabled) = enabled {
15217                state.enabled = enabled;
15218            }
15219            clear_current_process_facts(state);
15220        })?;
15221        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await
15222    }
15223}
15224
15225#[allow(clippy::too_many_arguments)]
15226async fn drain_child_to_state(
15227    module_id: &str,
15228    _protocol: ModuleProtocol,
15229    stop_notice: StopNotice,
15230    registry: &Registry,
15231    forwarding: Option<&ForwardingTable>,
15232    snapshot: &SharedSnapshot,
15233    terminal_ring: &Arc<Mutex<TerminalRing>>,
15234    spawn_events: &SpawnEventFeed,
15235    mut child: SupervisedChild,
15236    drain_timeout: Duration,
15237    final_state: ModuleState,
15238    enabled: Option<bool>,
15239    failure: &FailureContext,
15240) -> Result<(), SuperviseError> {
15241    let protocol = child.protocol;
15242    child.retire_registration();
15243    update_snapshot(snapshot, Some(module_id), |state| {
15244        state.state = ModuleState::Draining;
15245        state.draining_to_replace = final_state == ModuleState::Restarting;
15246        if let Some(enabled) = enabled {
15247            state.enabled = enabled;
15248        }
15249    })?;
15250
15251    // The wait below is the same budget in every case; what differs is
15252    // whether anything has ASKED the child to stop before it starts. Only a
15253    // forwarding drain that reached the module's registered connection has
15254    // (`module.draining`, then a module GOODBYE). Every other child was told
15255    // nothing: a `protocol: "none"` module, which never registers; a subc
15256    // module spawned moments ago that has not sent HELLO yet; or a stop that
15257    // runs no forwarding drain. Without a signal the budget is only a delay
15258    // in front of SIGKILL -- and the not-yet-registered child is the worst
15259    // case, because it registers into a module that is already draining,
15260    // is never told, and is killed while healthy.
15261    if stop_notice != StopNotice::SentOverConnection {
15262        if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
15263            info!(
15264                module_id,
15265                pid = child.pid,
15266                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
15267                "module has no connection yet; requesting stop by signal"
15268            );
15269        }
15270        request_graceful_stop(module_id, &child);
15271    }
15272
15273    let exit_report = match timeout(drain_timeout, child.wait()).await {
15274        Ok(Ok(status)) => classify_reaped_child_exit(snapshot, &child, &status),
15275        Ok(Err(source)) => {
15276            fail_after_wait_error(
15277                module_id,
15278                snapshot,
15279                terminal_ring,
15280                spawn_events,
15281                format!("failed to wait during drain: {source}"),
15282                failure,
15283            );
15284            return Err(SuperviseError::Wait {
15285                module_id: module_id.to_string(),
15286                source,
15287            });
15288        }
15289        Err(_) => {
15290            // Mirror the sibling arm above: state is already `Draining`, and an
15291            // error propagated from here would strand it there -- a state
15292            // `set_enabled(true)` cannot heal (`revive_terminal` matches only
15293            // `Failed | Stopped`), leaving an operator Restart as the only exit.
15294            // `Failed` before `?` keeps the module operator-visible and
15295            // revivable. Trigger is an ESRCH race (process exits between the
15296            // drain timeout firing and the kill) or a post-kill wait failure
15297            // (issue #34).
15298            //
15299            // Logged because the kill is otherwise visible only as signal 9 in
15300            // the terminal ring, and the budget it follows can be long enough
15301            // that consumers see a stretch of refusals with no stated cause.
15302            warn!(
15303                module_id,
15304                pid = child.pid,
15305                budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
15306                reason = ?final_state,
15307                ?stop_notice,
15308                "drain budget expired before the module exited; killing it"
15309            );
15310            let kill =
15311                if final_state == ModuleState::Restarting && child.child.container().is_some() {
15312                    child.kill_leader()
15313                } else {
15314                    child.start_kill()
15315                };
15316            kill.map_err(|source| {
15317                fail_after_wait_error(
15318                    module_id,
15319                    snapshot,
15320                    terminal_ring,
15321                    spawn_events,
15322                    format!("failed to kill during drain: {source}"),
15323                    failure,
15324                );
15325                SuperviseError::Kill {
15326                    module_id: module_id.to_string(),
15327                    source,
15328                }
15329            })?;
15330            let status = child.wait().await.map_err(|source| {
15331                fail_after_wait_error(
15332                    module_id,
15333                    snapshot,
15334                    terminal_ring,
15335                    spawn_events,
15336                    format!("failed to wait after drain kill: {source}"),
15337                    failure,
15338                );
15339                SuperviseError::Wait {
15340                    module_id: module_id.to_string(),
15341                    source,
15342                }
15343            })?;
15344            classify_reaped_child_exit(snapshot, &child, &status)
15345        }
15346    };
15347
15348    let detail = lock_snapshot(snapshot)?.drain_disposition_detail.take();
15349    publish_after_terminal_record(
15350        module_id,
15351        || {
15352            record_terminal_with_detail(
15353                module_id,
15354                terminal_ring,
15355                spawn_events,
15356                &exit_report,
15357                terminal_disposition(final_state),
15358                detail,
15359            )
15360        },
15361        || {
15362            update_snapshot(snapshot, Some(module_id), |state| {
15363                state.state = final_state;
15364                if final_state == ModuleState::Failed {
15365                    state.failed_retry.failed_at = Some(Instant::now());
15366                }
15367                if let Some(enabled) = enabled {
15368                    state.enabled = enabled;
15369                }
15370                clear_current_process_facts(state);
15371                state.last_exit = Some(exit_report.clone());
15372                if exit_report.kind == ExitKind::DeliberateSeverance {
15373                    state.lifetime_restarts += 1;
15374                }
15375            })
15376        },
15377    )?;
15378    child.drain_stderr(module_id).await;
15379
15380    let released =
15381        release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
15382    child
15383        .finish_exit(
15384            released.is_ok()
15385                && final_state == ModuleState::Restarting
15386                && child.spawn_failure.is_none(),
15387        )
15388        .await
15389        .map_err(|source| SuperviseError::Wait {
15390            module_id: module_id.to_owned(),
15391            source,
15392        })?;
15393    released
15394}
15395
15396/// Ask a child that nothing else has asked to stop, by signal.
15397///
15398/// A registered subc module is asked over its own connection: the drain sends
15399/// `route.closing`/`route.closed` to its consumers, a GOODBYE per route, then a
15400/// module GOODBYE, and the module stops itself. A module that speaks no subc
15401/// wire receives none of that, and neither does a subc module that has not
15402/// registered yet, so for them the drain budget would be pure delay in front of
15403/// a SIGKILL -- and for a process with a store to flush (JetStream is the
15404/// reason `protocol: "none"` exists) a SIGKILL turns every ordinary teardown
15405/// into a recovery on the next start.
15406///
15407/// NEVER CALLED FOR A MODULE THAT WAS TOLD OVER ITS CONNECTION, and that is a
15408/// rule rather than an optimisation: that module's graceful stop is already
15409/// running by the time its child is drained, and a signal would race it.
15410///
15411/// Best-effort by construction. A child that has already exited is the ordinary
15412/// case rather than an error (the kill lands on a reaped or exiting pid), so a
15413/// failure is logged at debug and the wait-then-kill below still decides the
15414/// outcome.
15415#[cfg(unix)]
15416fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
15417    let Some(pid) = child
15418        .id()
15419        .and_then(|pid| i32::try_from(pid).ok())
15420        .and_then(rustix::process::Pid::from_raw)
15421    else {
15422        debug!(
15423            module_id,
15424            "no pid to signal for teardown; falling through to the drain wait"
15425        );
15426        return;
15427    };
15428    match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
15429        Ok(()) => debug!(
15430            module_id,
15431            "sent SIGTERM to a module nothing else asked to stop"
15432        ),
15433        Err(err) => debug!(
15434            module_id,
15435            error = %err,
15436            "SIGTERM to module failed; the drain wait and kill still apply"
15437        ),
15438    }
15439}
15440
15441/// Windows has no SIGTERM and no portable stand-in for one. The graceful stops
15442/// Windows does offer need cooperation this supervisor cannot assume: a console
15443/// control event requires sharing a console with the child, and `WM_CLOSE`
15444/// requires the child to pump a message loop. A supervised server process does
15445/// neither, so there is nothing to send and teardown is the wait followed by the
15446/// kill. Emulating a signal here would mean inventing a stop protocol, which is
15447/// the thing `protocol: "none"` exists to avoid.
15448#[cfg(not(unix))]
15449fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
15450    debug!(
15451        module_id,
15452        "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
15453    );
15454}
15455
15456fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
15457    match final_state {
15458        ModuleState::Stopped => TerminalDisposition::Stopped,
15459        ModuleState::Disabled => TerminalDisposition::Disabled,
15460        ModuleState::Restarting => TerminalDisposition::Restarting,
15461        ModuleState::Failed => TerminalDisposition::Failed,
15462        ModuleState::Starting
15463        | ModuleState::Running
15464        | ModuleState::Unresponsive
15465        | ModuleState::Draining => {
15466            unreachable!("terminal exits only finish in terminal or restarting states")
15467        }
15468    }
15469}
15470
15471/// Release a reaped child's registration before allowing another spawn.
15472///
15473/// EOF is not a process-lifetime signal: an inherited socket can stay open
15474/// indefinitely, and serial frame dispatch can be waiting on egress instead of
15475/// reading EOF. After the normal release grace, request connection close (which
15476/// cancels both reads and dispatch), then allow one more release grace for the
15477/// connection guard's forwarding cleanup. Never evict a different connection.
15478async fn release_dead_registration(
15479    registry: &Registry,
15480    forwarding: Option<&ForwardingTable>,
15481    snapshot: &SharedSnapshot,
15482    module_id: &str,
15483    failure: &FailureContext,
15484) -> Result<(), SuperviseError> {
15485    let result = async {
15486        let registration = registry
15487            .get_module(module_id)
15488            .map_err(SuperviseError::Registry)?;
15489        match wait_for_registration_release(registry, module_id, REGISTRY_RELEASE_TIMEOUT).await {
15490            Ok(()) => return Ok(()),
15491            Err(SuperviseError::RegistrationStillActive { .. }) => {}
15492            Err(err) => return Err(err),
15493        }
15494        let pid = lock_snapshot(snapshot)?.reaped_pid;
15495        if let (Some(registration), Some(forwarding), Some(pid)) = (registration, forwarding, pid) {
15496            warn!(
15497                module_id,
15498                pid,
15499                connection_id = registration.connection_id.get(),
15500                "reaped module registration outlived release grace; closing dead connection"
15501            );
15502            forwarding.request_connection_close(
15503                registration.connection_id,
15504                CloseReason::new(
15505                    "supervised_process_reaped",
15506                    format!("module '{module_id}' pid {pid} exited"),
15507                ),
15508            );
15509            wait_for_slot_registration_release(
15510                registry,
15511                crate::registry::RegistrationSlot::Connection(registration.connection_id),
15512                REGISTRY_RELEASE_TIMEOUT,
15513            )
15514            .await?;
15515        }
15516        wait_for_registration_release(registry, module_id, Duration::ZERO).await
15517    }
15518    .await;
15519    if let Err(err) = &result {
15520        fail_snapshot(snapshot, Some(module_id), None, failure);
15521        error!(module_id, error = %err, "registration release failed after child exit; module is failed and start can retry");
15522    }
15523    result
15524}
15525
15526/// Wait for the ACTIVE registration of `module_id` to go away, which is what a
15527/// plain stop or restart waits for before it spawns a replacement.
15528async fn wait_for_registration_release(
15529    registry: &Registry,
15530    module_id: &str,
15531    wait: Duration,
15532) -> Result<(), SuperviseError> {
15533    wait_for_slot_registration_release(
15534        registry,
15535        crate::registry::RegistrationSlot::Active(module_id),
15536        wait,
15537    )
15538    .await
15539}
15540
15541/// Wait for the registration in `slot` to go away.
15542///
15543/// Keyed on the slot rather than the bare module id because a successful swap
15544/// never empties the id's active slot (the promoted candidate is in it), so an
15545/// id-keyed wait for the incumbent's release would always time out. Draining a
15546/// swap's incumbent waits on `crate::registry::RegistrationSlot::Connection` with the
15547/// incumbent's connection instead.
15548async fn wait_for_slot_registration_release(
15549    registry: &Registry,
15550    slot: crate::registry::RegistrationSlot<'_>,
15551    wait: Duration,
15552) -> Result<(), SuperviseError> {
15553    let deadline = Instant::now() + wait;
15554    let mut release_events = registration_release_events().subscribe();
15555    let still_active = |registration: &crate::registry::ModuleRegistration| {
15556        SuperviseError::RegistrationStillActive {
15557            module_id: registration.manifest.module_id.clone(),
15558            waited: wait,
15559        }
15560    };
15561    loop {
15562        let _observed_generation = *release_events.borrow_and_update();
15563        let Some(registration) = registry
15564            .registration(slot)
15565            .map_err(SuperviseError::Registry)?
15566        else {
15567            return Ok(());
15568        };
15569
15570        let now = Instant::now();
15571        if now >= deadline {
15572            return Err(still_active(&registration));
15573        }
15574
15575        let remaining = deadline.saturating_duration_since(now);
15576        match timeout(remaining, release_events.changed()).await {
15577            Ok(Ok(())) | Ok(Err(_)) => {}
15578            Err(_) => return Err(still_active(&registration)),
15579        }
15580    }
15581}
15582
15583#[cfg(test)]
15584mod slot_registration_wait_tests {
15585    use super::*;
15586    use crate::registry::{ConnectionId, RegistrationSlot};
15587    use subc_protocol::manifest::ModuleManifest;
15588
15589    #[tokio::test]
15590    async fn enable_release_failure_is_failed_and_a_second_enable_retries() {
15591        let registry = Arc::new(Registry::default());
15592        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default());
15593        let runtime = supervisor.runtime_config();
15594        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::disabled()));
15595        let spec = ModuleSpec {
15596            script: None,
15597            module_id: "enable-stale-registration".to_string(),
15598            program: PathBuf::from("/missing/enable-retry-test"),
15599            args: Vec::new(),
15600            env: Vec::new(),
15601            reserved: false,
15602            reserved_prefixes: Vec::new(),
15603            protocol: ModuleProtocol::Subc,
15604            overlap: Default::default(),
15605            carry_containment: false,
15606        };
15607        let connection = ConnectionId::new(90);
15608        registry
15609            .register_with_control_ops(
15610                ModuleManifest::builder(&spec.module_id, "0.1.0").build(),
15611                1,
15612                connection,
15613                Vec::new(),
15614            )
15615            .unwrap();
15616        let mut child = None;
15617        let err = set_child_enabled(
15618            &spec,
15619            &runtime,
15620            &registry,
15621            &supervisor.process_liveness,
15622            &snapshot,
15623            &mut child,
15624            true,
15625            &runtime.failure_context(false),
15626        )
15627        .await
15628        .unwrap_err();
15629        assert!(matches!(
15630            err,
15631            SuperviseError::RegistrationStillActive { .. }
15632        ));
15633        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
15634        assert!(child.is_none());
15635        registry.deregister_connection(connection).unwrap();
15636        let err = set_child_enabled(
15637            &spec,
15638            &runtime,
15639            &registry,
15640            &supervisor.process_liveness,
15641            &snapshot,
15642            &mut child,
15643            true,
15644            &runtime.failure_context(false),
15645        )
15646        .await
15647        .unwrap_err();
15648        assert!(
15649            matches!(err, SuperviseError::Spawn { .. }),
15650            "second enable must attempt a spawn: {err}"
15651        );
15652        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
15653    }
15654
15655    const INCUMBENT: u64 = 1;
15656    const CANDIDATE: u64 = 2;
15657
15658    fn swapped_registry() -> Arc<Registry> {
15659        let registry = Arc::new(Registry::default());
15660        let manifest = ModuleManifest::builder("m", "0.1.0").build();
15661        registry
15662            .register_with_control_ops(
15663                manifest.clone(),
15664                1,
15665                ConnectionId::new(INCUMBENT),
15666                Vec::new(),
15667            )
15668            .unwrap();
15669        registry
15670            .register_candidate_with_control_ops(
15671                manifest,
15672                1,
15673                ConnectionId::new(CANDIDATE),
15674                Vec::new(),
15675            )
15676            .unwrap();
15677        registry
15678    }
15679
15680    /// After a promotion the id's active slot is held by the new process, so an
15681    /// id-keyed wait for the incumbent's release can never succeed; the
15682    /// connection-keyed wait completes as soon as the incumbent deregisters.
15683    #[tokio::test]
15684    async fn incumbent_release_is_awaited_by_connection_not_by_module_id() {
15685        let registry = swapped_registry();
15686        registry.promote_candidate("m").unwrap().unwrap();
15687
15688        assert!(matches!(
15689            wait_for_registration_release(&registry, "m", Duration::from_millis(50)).await,
15690            Err(SuperviseError::RegistrationStillActive { .. })
15691        ));
15692
15693        // Still held while the incumbent's connection has not deregistered.
15694        assert!(matches!(
15695            wait_for_slot_registration_release(
15696                &registry,
15697                RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
15698                Duration::from_millis(50),
15699            )
15700            .await,
15701            Err(SuperviseError::RegistrationStillActive { .. })
15702        ));
15703
15704        let releaser = Arc::clone(&registry);
15705        let release = tokio::spawn(async move {
15706            sleep(Duration::from_millis(20)).await;
15707            releaser
15708                .deregister_connection(ConnectionId::new(INCUMBENT))
15709                .unwrap();
15710            notify_registration_release();
15711        });
15712        wait_for_slot_registration_release(
15713            &registry,
15714            RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
15715            Duration::from_secs(5),
15716        )
15717        .await
15718        .expect("the incumbent's own registration is released");
15719        release.await.unwrap();
15720        assert!(registry.get_module("m").unwrap().is_some());
15721    }
15722
15723    /// The candidate slot is waited on separately from the active slot: the
15724    /// incumbent's registration neither holds up nor stands in for it.
15725    #[tokio::test]
15726    async fn candidate_slot_wait_ignores_the_incumbents_registration() {
15727        let registry = swapped_registry();
15728        assert!(matches!(
15729            wait_for_slot_registration_release(
15730                &registry,
15731                RegistrationSlot::Candidate("m"),
15732                Duration::from_millis(50),
15733            )
15734            .await,
15735            Err(SuperviseError::RegistrationStillActive { .. })
15736        ));
15737        registry
15738            .deregister_connection(ConnectionId::new(CANDIDATE))
15739            .unwrap();
15740        wait_for_slot_registration_release(
15741            &registry,
15742            RegistrationSlot::Candidate("m"),
15743            Duration::from_millis(50),
15744        )
15745        .await
15746        .expect("a candidate slot with no candidate is released");
15747        assert!(registry
15748            .registration(RegistrationSlot::Active("m"))
15749            .unwrap()
15750            .is_some());
15751    }
15752}
15753
15754fn classify_exit(status: &ExitStatus) -> ExitReport {
15755    ExitReport {
15756        kind: if status.success() {
15757            ExitKind::Clean
15758        } else {
15759            ExitKind::Crash
15760        },
15761        code: status.code(),
15762        signal: exit_signal(status),
15763        at_ms: unix_ms_now(),
15764    }
15765}
15766
15767/// The terminal record for a module whose `wait()` call itself errored (e.g. the
15768/// child was already reaped out-of-band). There is no `ExitStatus` to read a code
15769/// or signal from -- `None`/`None` is the honest shape, not a guess -- but the
15770/// disposition still must be `Failed` so the terminal ring is not silently missing
15771/// an entry, matching what `fail_snapshot` records for this same arm.
15772fn wait_error_exit_report() -> ExitReport {
15773    ExitReport {
15774        kind: ExitKind::Crash,
15775        code: None,
15776        signal: None,
15777        at_ms: unix_ms_now(),
15778    }
15779}
15780
15781#[cfg(unix)]
15782fn exit_signal(status: &ExitStatus) -> Option<i32> {
15783    use std::os::unix::process::ExitStatusExt;
15784
15785    status.signal()
15786}
15787
15788#[cfg(not(unix))]
15789fn exit_signal(_status: &ExitStatus) -> Option<i32> {
15790    None
15791}
15792
15793/// Give an operator-touched module its full crash budget back.
15794///
15795/// Named for the counter it used to zero; it now empties the in-window ring,
15796/// which is the same act. `lifetime_restarts` is untouched on purpose -- the
15797/// ledger of what happened survives every operator action.
15798fn reset_restart_count(snapshot: &SharedSnapshot, module_id: &str) -> Result<(), SuperviseError> {
15799    update_snapshot(snapshot, Some(module_id), |state| {
15800        state.clear_crash_restarts();
15801    })
15802}
15803
15804fn set_running(
15805    snapshot: &SharedSnapshot,
15806    child: &SupervisedChild,
15807    module_id: &str,
15808    spawn_events: &SpawnEventFeed,
15809) -> Result<(), SuperviseError> {
15810    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
15811        module_id: Some(module_id.to_string()),
15812    })?;
15813    state.spawn_generation = spawn_events.emit_spawned(
15814        module_id,
15815        child
15816            .registration_spawn
15817            .as_ref()
15818            .map(|spawn| spawn.authority.spawn_number()),
15819        child.pid,
15820        child.spawned_at_ms,
15821    );
15822    if std::mem::take(&mut state.coalesced_restart_pending) {
15823        let generation = state.spawn_generation;
15824        info!(module_id, "restart already satisfied by generation {generation}; coalesced pending request completed");
15825    }
15826    state.drain_disposition_detail = None;
15827    state.spawn_failure = None;
15828    state.admission_refused = None;
15829    state.config_hold_parked = false;
15830    state.config_hold_daemon_initiated = false;
15831    state.config_hold_approval = None;
15832    state.legacy_registration_spawn =
15833        child.registration_spawn.is_some() && child.admission_base.is_none();
15834    state.registration_declaration = child.registration_declaration.clone();
15835    state.stop_reason = None;
15836    state.config_exit_failed_approval = None;
15837    state.waiting_for_previous_pid = None;
15838    state.waiting_for_previous_detail = None;
15839    // Every caller of this is a plain spawn, which always uses the primary key;
15840    // a promoted swap candidate sets the flag itself after this returns.
15841    state.in_alternate_slot = false;
15842    state.configuration_updated_since_spawn = false;
15843    state.spawned_protocol = Some(child.protocol);
15844    state.state = ModuleState::Running;
15845    state.approved_start_failure = None;
15846    state.enabled = true;
15847    state.process_alive = true;
15848    state.pid = child.id();
15849    state.subtree_target = child.subtree_target.clone();
15850    // Probe samples belong to one process. Keep module-level escalation and
15851    // late-answer history, but never charge a new child for its predecessor's misses.
15852    state.health.status = SupervisorHealthStatus::Unknown;
15853    state.last_probe_evidence = None;
15854    state.health.consecutive_failures = 0;
15855    state.health.detail = None;
15856    state.health.metrics = None;
15857    state.health.last_probe_ms = None;
15858    state.failed_retry.healthy_since = None;
15859    state.failed_retry.failed_at = None;
15860    state.failed_retry.running_since = Some(child.spawned_at);
15861    #[cfg(windows)]
15862    {
15863        state.pipe_consumed = child
15864            .nonce_delivery
15865            .as_ref()
15866            .map(|delivery| delivery.consumed());
15867    }
15868    #[cfg(target_os = "macos")]
15869    {
15870        state.report_ready = Some(Arc::clone(&child.report_ready));
15871    }
15872    state.spawned_at_ms = Some(child.spawned_at_ms);
15873    state.exec_outcome = Some(Arc::clone(&child.exec.0));
15874    state.spawned_from = Some(child.spawned_from.clone());
15875    state.launch_spec_digest = Some(child.launch_spec_digest.clone());
15876    state.spawned_file_identity = child.spawned_file_identity.clone();
15877    state.process_start_time = child.process_start_time;
15878    Ok(())
15879}
15880
15881fn clear_current_process_facts(state: &mut SupervisorSnapshot) {
15882    state.legacy_registration_spawn = false;
15883    state.registration_declaration = None;
15884    state.subtree_target = crate::subtree_resources::Target::Unavailable("not_running");
15885    state.failed_retry.healthy_since = None;
15886    state.failed_retry.running_since = None;
15887    state.waiting_for_previous_pid = None;
15888    state.waiting_for_previous_detail = None;
15889    state.process_alive = false;
15890    state.spawned_protocol = None;
15891    state.pid = None;
15892    #[cfg(windows)]
15893    {
15894        state.pipe_consumed = None;
15895    }
15896    #[cfg(target_os = "macos")]
15897    {
15898        state.report_ready = None;
15899    }
15900    state.spawned_at_ms = None;
15901    state.exec_outcome = None;
15902    state.spawned_from = None;
15903    state.launch_spec_digest = None;
15904    state.spawned_file_identity = None;
15905    state.process_start_time = None;
15906    state.deliberate_severance = None;
15907}
15908
15909#[cfg(test)]
15910fn record_deliberate_severance(
15911    snapshot: &SharedSnapshot,
15912    identity: ProcessIdentity,
15913) -> Result<(), SuperviseError> {
15914    update_snapshot(snapshot, None, |state| {
15915        state.deliberate_severance = Some(identity);
15916    })
15917}
15918
15919fn apply_deliberate_severance_marker(
15920    snapshot: &SharedSnapshot,
15921    exited_identity: Option<ProcessIdentity>,
15922    mut exit_report: ExitReport,
15923) -> ExitReport {
15924    let marker = lock_snapshot(snapshot)
15925        .ok()
15926        .and_then(|mut state| state.deliberate_severance.take());
15927    if marker.is_some() && marker == exited_identity {
15928        exit_report.kind = ExitKind::DeliberateSeverance;
15929    }
15930    exit_report
15931}
15932
15933fn classify_reaped_child_exit(
15934    snapshot: &SharedSnapshot,
15935    child: &SupervisedChild,
15936    status: &ExitStatus,
15937) -> ExitReport {
15938    let _ = update_snapshot(snapshot, None, |state| {
15939        state.reaped_pid = Some(child.pid);
15940        state.spawn_failure = child.spawn_failure.clone();
15941    });
15942    if matches!(
15943        child.spawn_failure.as_deref(),
15944        Some("registration_timeout" | "registration_channel_closed")
15945    ) {
15946        registration_failure_exit_report(classify_exit(status))
15947    } else {
15948        apply_deliberate_severance_marker(snapshot, child.process_identity(), classify_exit(status))
15949    }
15950}
15951
15952fn fail_snapshot(
15953    snapshot: &SharedSnapshot,
15954    module_id: Option<&str>,
15955    last_exit: Option<ExitReport>,
15956    failure: &FailureContext,
15957) {
15958    if let Err(err) = update_snapshot(snapshot, module_id, |state| {
15959        state.state = ModuleState::Failed;
15960        state.config_hold_parked = false;
15961        state.config_hold_daemon_initiated = false;
15962        state.config_hold_approval = None;
15963        clear_current_process_facts(state);
15964        if failure.may_retry() && state.enabled {
15965            state.failed_retry.schedule(module_id.unwrap_or("unknown"));
15966        } else if failure.shutdown.is_set() {
15967            state.failed_retry.cancel();
15968        }
15969        if let Some(last_exit) = last_exit {
15970            state.last_exit = Some(last_exit);
15971        }
15972    }) {
15973        error!(error = %err, "failed to mark supervisor state failed");
15974    }
15975}
15976
15977fn update_snapshot(
15978    snapshot: &SharedSnapshot,
15979    module_id: Option<&str>,
15980    update: impl FnOnce(&mut SupervisorSnapshot),
15981) -> Result<(), SuperviseError> {
15982    let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
15983        module_id: module_id.map(ToOwned::to_owned),
15984    })?;
15985    update(&mut state);
15986    Ok(())
15987}
15988
15989const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
15990
15991fn lock_snapshot_for_control<'a>(
15992    snapshot: &'a SharedSnapshot,
15993    module_id: &str,
15994    caller: &'static str,
15995) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
15996    let started_at = Instant::now();
15997    let guard = lock_snapshot(snapshot)?;
15998    let waited = started_at.elapsed();
15999    if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
16000        warn!(
16001            module_id = %module_id,
16002            waited_ms = waited.as_millis() as u64,
16003            caller = %caller,
16004            "slow snapshot lock"
16005        );
16006    }
16007    Ok(guard)
16008}
16009
16010fn lock_snapshot(
16011    snapshot: &SharedSnapshot,
16012) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
16013    snapshot
16014        .lock()
16015        .map_err(|_| SuperviseError::StatePoisoned { module_id: None })
16016}
16017
16018#[cfg(test)]
16019mod terminal_history_tests {
16020    include!("supervise_route_open_recovery_tests.rs");
16021    use std::{
16022        path::PathBuf,
16023        sync::Arc,
16024        time::{Duration, Instant},
16025    };
16026
16027    use tokio::{sync::mpsc, time::sleep};
16028
16029    use super::{
16030        apply_deliberate_severance_marker, daemon_will_restart, drain_child_to_state,
16031        drained_after_quiescence_wait, handle_reload_spawn_failure, health_restart_child,
16032        lock_snapshot, on_child_exit, record_deliberate_severance, record_wait_error_terminal,
16033        reset_restart_count, spawn_and_mark_running, update_snapshot, wait_error_exit_report,
16034        ExitKind, ExitReport, ModuleProtocol, ModuleSpec, ModuleState, NextAction, ProcessIdentity,
16035        RestartPolicy, SpawnEventKind, StopNotice, SuperviseError, SupervisedConfiguration,
16036        SupervisedModule, SupervisedModuleInner, Supervisor, SupervisorHandle,
16037        SupervisorHealthStatus, SupervisorSnapshot,
16038    };
16039    // The supervisor's clock, distinct from the `std::time::Instant` these tests
16040    // use for their own wall-clock deadlines: crash-restart instants must be on
16041    // the same clock the production code stamps them with, which is tokio's (and
16042    // is what `start_paused` tests can move).
16043    use super::Instant as ClockInstant;
16044    use crate::{
16045        registry::Registry,
16046        terminal_ring::{TerminalRing, TerminalRingConfig},
16047    };
16048    use std::sync::Mutex;
16049    use subc_control::TerminalDisposition;
16050
16051    /// See the twin in `control.rs` for why this derives the path from
16052    /// `current_exe()` and why the existence check is here: `--lib` alone does
16053    /// not build `[[bin]]` targets, and a bare spawn then fails with a raw
16054    /// `NotFound` that reads as a broken test rather than an unbuilt dependency.
16055    pub(super) fn fake_aft_stub_path() -> PathBuf {
16056        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
16057        assert!(
16058            path.exists(),
16059            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
16060             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
16061            path.display()
16062        );
16063        path
16064    }
16065
16066    #[test]
16067    fn reserved_never_spawned_refuses_every_hello() {
16068        // The canary hole: a reserved id whose module has never spawned had NO
16069        // gate entry and admitted anyone -- the reservation protected the nonce
16070        // holder, not the NAME. Now the entry is present with no legitimate
16071        // holder and refuses all comers.
16072        let supervisor = SupervisorHandle::default();
16073        supervisor.apply_identity_configuration(&ModuleSpec {
16074            script: None,
16075            module_id: "never-spawned".to_string(),
16076            program: PathBuf::from("/usr/bin/false"),
16077            args: Vec::new(),
16078            env: Vec::new(),
16079            reserved: true,
16080            reserved_prefixes: Vec::new(),
16081            protocol: ModuleProtocol::Subc,
16082            overlap: Default::default(),
16083            carry_containment: false,
16084        });
16085        assert!(
16086            supervisor
16087                .reserved_hello_verification("never-spawned", Some("any-forged-nonce"))
16088                .is_err(),
16089            "forged nonce must refuse on a reserved never-spawned id"
16090        );
16091        assert!(
16092            supervisor
16093                .reserved_hello_verification("never-spawned", None)
16094                .is_err(),
16095            "absent nonce must refuse on a reserved never-spawned id"
16096        );
16097        // And a real spawn nonce minted later admits exactly that nonce.
16098        supervisor.set_spawn_nonce("never-spawned", "minted".to_string());
16099        supervisor.apply_identity_configuration(&ModuleSpec {
16100            script: None,
16101            module_id: "never-spawned".to_string(),
16102            program: PathBuf::from("/usr/bin/false"),
16103            args: Vec::new(),
16104            env: Vec::new(),
16105            reserved: true,
16106            reserved_prefixes: Vec::new(),
16107            protocol: ModuleProtocol::Subc,
16108            overlap: Default::default(),
16109            carry_containment: false,
16110        });
16111        assert!(supervisor
16112            .reserved_hello_verification("never-spawned", Some("minted"))
16113            .is_ok());
16114        assert!(supervisor
16115            .reserved_hello_verification("never-spawned", Some("forged"))
16116            .is_err());
16117    }
16118
16119    /// Put `count` crash restarts on a snapshot's ring as if they had all just
16120    /// happened, which is what "spent budget" looks like to every reader.
16121    fn seed_crash_restarts(state: &mut SupervisorSnapshot, count: u32) {
16122        let now = ClockInstant::now();
16123        for _ in 0..count {
16124            state.crash_restarts.push_back(now);
16125        }
16126    }
16127
16128    /// Age the oldest recorded restart out of `window`, standing in for the hours
16129    /// that would otherwise have to pass. Injecting the instant is the point: a
16130    /// test that slept a real window would take ten minutes and still prove less.
16131    fn age_oldest_crash_restart_out_of_window(state: &mut SupervisorSnapshot, window: Duration) {
16132        let aged = state
16133            .crash_restarts
16134            .front()
16135            .expect("a crash restart must be recorded before it can be aged")
16136            .checked_sub(window + Duration::from_secs(1))
16137            .expect("the test clock is far enough from its origin to age an instant");
16138        state.crash_restarts[0] = aged;
16139    }
16140
16141    fn snapshot_with_restarts(enabled: bool, count: u32) -> SupervisorSnapshot {
16142        let mut state = SupervisorSnapshot::new(ModuleState::Running, enabled);
16143        seed_crash_restarts(&mut state, count);
16144        state
16145    }
16146
16147    #[test]
16148    fn daemon_owned_recovery_predicate_uses_the_pre_increment_budget() {
16149        let policy = RestartPolicy::new(3, Duration::ZERO);
16150        let now = ClockInstant::now();
16151        assert!(daemon_will_restart(
16152            &mut snapshot_with_restarts(true, 2),
16153            &policy,
16154            now
16155        ));
16156        assert!(!daemon_will_restart(
16157            &mut snapshot_with_restarts(true, 3),
16158            &policy,
16159            now
16160        ));
16161        assert!(!daemon_will_restart(
16162            &mut snapshot_with_restarts(false, 0),
16163            &policy,
16164            now
16165        ));
16166    }
16167
16168    #[test]
16169    fn crash_restart_backoff_escalates_with_in_window_count() {
16170        let policy = RestartPolicy::new(4, Duration::from_millis(100))
16171            .with_max_backoff(Duration::from_secs(30));
16172        let now = ClockInstant::now();
16173        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16174        let schedules = (0..4)
16175            .map(|_| {
16176                state
16177                    .next_crash_restart(&policy, now)
16178                    .expect("the test policy allows four crash restarts")
16179            })
16180            .collect::<Vec<_>>();
16181
16182        assert_eq!(
16183            schedules
16184                .iter()
16185                .map(|schedule| schedule.restart_in_window)
16186                .collect::<Vec<_>>(),
16187            vec![0, 1, 2, 3]
16188        );
16189        assert_eq!(
16190            schedules
16191                .iter()
16192                .map(|schedule| schedule.delay)
16193                .collect::<Vec<_>>(),
16194            vec![
16195                Duration::from_millis(100),
16196                Duration::from_secs(1),
16197                Duration::from_secs(10),
16198                Duration::from_secs(30),
16199            ]
16200        );
16201    }
16202
16203    #[test]
16204    fn crash_restart_backoff_resets_after_ring_clear() {
16205        let policy = RestartPolicy::new(3, Duration::from_millis(100));
16206        let now = ClockInstant::now();
16207        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16208        assert_eq!(
16209            state.next_crash_restart(&policy, now).unwrap().delay,
16210            Duration::from_millis(100)
16211        );
16212        assert_eq!(
16213            state.next_crash_restart(&policy, now).unwrap().delay,
16214            Duration::from_secs(1)
16215        );
16216
16217        state.clear_crash_restarts();
16218        let schedule = state
16219            .next_crash_restart(&policy, now)
16220            .expect("a cleared ring must allow another restart");
16221        assert_eq!(schedule.restart_in_window, 0);
16222        assert_eq!(schedule.delay, Duration::from_millis(100));
16223    }
16224
16225    #[test]
16226    fn crash_restart_backoff_ignores_aged_restarts() {
16227        let policy = RestartPolicy::new(3, Duration::from_millis(100));
16228        let now = ClockInstant::now();
16229        let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16230        state
16231            .next_crash_restart(&policy, now)
16232            .expect("the first restart is allowed");
16233        state
16234            .next_crash_restart(&policy, now)
16235            .expect("the second restart is allowed");
16236        state.crash_restarts[0] = now
16237            .checked_sub(policy.window + Duration::from_secs(1))
16238            .expect("the fake clock can age a restart past the window");
16239
16240        let schedule = state
16241            .next_crash_restart(&policy, now)
16242            .expect("an aged restart must release its slot");
16243        assert_eq!(schedule.restart_in_window, 1);
16244        assert_eq!(schedule.delay, Duration::from_secs(1));
16245        assert_eq!(state.crash_restarts.len(), 2);
16246    }
16247
16248    /// The budget is a rate: the same three spent restarts refuse a respawn
16249    /// while they are recent and allow one once they have aged past the window.
16250    /// Nothing about the module changed in between, which is the whole point.
16251    #[test]
16252    fn a_budget_spent_before_the_window_no_longer_refuses() {
16253        let policy = RestartPolicy::new(3, Duration::ZERO);
16254        let mut state = snapshot_with_restarts(true, 3);
16255        let now = ClockInstant::now();
16256        assert!(!daemon_will_restart(&mut state, &policy, now));
16257
16258        assert!(daemon_will_restart(
16259            &mut state,
16260            &policy,
16261            now + policy.window + Duration::from_secs(1)
16262        ));
16263        assert!(
16264            state.crash_restarts.is_empty(),
16265            "reading the budget must drop the instants that left the window"
16266        );
16267    }
16268
16269    fn module_with_recovery_snapshot(
16270        state: ModuleState,
16271        enabled: bool,
16272        restart_count: u32,
16273    ) -> SupervisedModule {
16274        let registry = Arc::new(Registry::default());
16275        let supervisor =
16276            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(3, Duration::ZERO));
16277        let runtime = supervisor.runtime_config();
16278        let spec = ModuleSpec {
16279            script: None,
16280            module_id: "recovery-snapshot".to_string(),
16281            program: fake_aft_stub_path(),
16282            args: Vec::new(),
16283            env: Vec::new(),
16284            reserved: false,
16285            reserved_prefixes: Vec::new(),
16286            protocol: ModuleProtocol::Subc,
16287            overlap: Default::default(),
16288            carry_containment: false,
16289        };
16290        let mut snapshot = SupervisorSnapshot::new(state, enabled);
16291        seed_crash_restarts(&mut snapshot, restart_count);
16292        // These tests read synthetic snapshots. A real child and monitor would
16293        // race those reads by replacing the requested state during startup.
16294        let (commands, _rx) = mpsc::channel(4);
16295        let configured_enabled = snapshot.enabled;
16296        SupervisedModule {
16297            inner: Arc::new(SupervisedModuleInner {
16298                module_id: spec.module_id.clone(),
16299                registry,
16300                snapshot: Arc::new(Mutex::new(snapshot)),
16301                configuration: Arc::new(Mutex::new(SupervisedConfiguration {
16302                    spec,
16303                    enabled: configured_enabled,
16304                    health: runtime.health,
16305                    register_timeout: runtime.register_timeout,
16306                    restart_policy: runtime.restart_policy,
16307                })),
16308                stderr_ring: runtime.stderr_ring,
16309                terminal_ring: runtime.terminal_ring,
16310                commands,
16311                monitor: Mutex::new(None),
16312                effective_drain_timeout: runtime.effective_drain_timeout,
16313                provenance_probe: supervisor.provenance_probe.clone(),
16314                retained: runtime.child_roster.retained_view(),
16315            }),
16316        }
16317    }
16318
16319    #[cfg(target_os = "linux")]
16320    #[tokio::test]
16321    async fn no_cgroup_placement_does_not_block_fake_aft_stub_spawn() {
16322        let supervisor =
16323            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
16324                .with_cgroup_placement(None);
16325        let result = supervisor.spawn(ModuleSpec {
16326            script: None,
16327            module_id: "no-cgroup-placement".to_string(),
16328            program: fake_aft_stub_path(),
16329            args: Vec::new(),
16330            env: Vec::new(),
16331            reserved: false,
16332            reserved_prefixes: Vec::new(),
16333            protocol: ModuleProtocol::Subc,
16334            overlap: Default::default(),
16335            carry_containment: false,
16336        });
16337
16338        assert!(
16339            result.is_ok(),
16340            "no delegation must not turn an otherwise valid spawn into a failure: {result:?}"
16341        );
16342    }
16343
16344    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16345    async fn undecided_snapshot_uses_shared_restart_predicate() {
16346        assert!(module_with_recovery_snapshot(ModuleState::Running, true, 2)
16347            .will_recover_after_connection_loss()
16348            .unwrap());
16349        assert!(
16350            !module_with_recovery_snapshot(ModuleState::Running, true, 3)
16351                .will_recover_after_connection_loss()
16352                .unwrap()
16353        );
16354    }
16355
16356    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16357    async fn restarting_snapshot_at_exhausted_budget_is_non_terminal() {
16358        assert!(
16359            module_with_recovery_snapshot(ModuleState::Restarting, true, 3)
16360                .will_recover_after_connection_loss()
16361                .unwrap()
16362        );
16363    }
16364
16365    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16366    async fn terminal_phase_snapshots_are_terminal_before_budget_exhaustion() {
16367        assert!(!module_with_recovery_snapshot(ModuleState::Failed, true, 0)
16368            .will_recover_after_connection_loss()
16369            .unwrap());
16370        assert!(
16371            !module_with_recovery_snapshot(ModuleState::Disabled, true, 0)
16372                .will_recover_after_connection_loss()
16373                .unwrap()
16374        );
16375    }
16376
16377    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16378    async fn warming_snapshot_is_limited_to_startup_phases() {
16379        for state in [
16380            ModuleState::Starting,
16381            ModuleState::Running,
16382            ModuleState::Restarting,
16383        ] {
16384            assert!(
16385                module_with_recovery_snapshot(state, true, 0)
16386                    .is_warming()
16387                    .unwrap(),
16388                "{state:?} should be warming"
16389            );
16390        }
16391        for state in [
16392            ModuleState::Unresponsive,
16393            ModuleState::Draining,
16394            ModuleState::Stopped,
16395            ModuleState::Failed,
16396            ModuleState::Disabled,
16397        ] {
16398            assert!(
16399                !module_with_recovery_snapshot(state, true, 0)
16400                    .is_warming()
16401                    .unwrap(),
16402                "{state:?} should not be warming"
16403            );
16404        }
16405    }
16406
16407    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16408    async fn terminal_history_survives_respawn_and_keeps_both_crashes_in_order() {
16409        let registry = Arc::new(Registry::default());
16410        let supervisor =
16411            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO));
16412        let module = supervisor
16413            .spawn(ModuleSpec {
16414                script: None,
16415                module_id: "terminal-history".to_string(),
16416                program: fake_aft_stub_path(),
16417                args: Vec::new(),
16418                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
16419                reserved: false,
16420                reserved_prefixes: Vec::new(),
16421                protocol: ModuleProtocol::Subc,
16422                overlap: Default::default(),
16423                carry_containment: false,
16424            })
16425            .unwrap();
16426
16427        let deadline = Instant::now() + Duration::from_secs(5);
16428        loop {
16429            let history = module.terminal_history();
16430            if history.entries.len() == 2 {
16431                assert_eq!(module.status().unwrap().state, ModuleState::Failed);
16432                assert_eq!(history.dropped, 0);
16433                assert_eq!(
16434                    history
16435                        .entries
16436                        .iter()
16437                        .map(|entry| entry.exit_code)
16438                        .collect::<Vec<_>>(),
16439                    vec![Some(23), Some(23)]
16440                );
16441                assert!(history.entries[0].at_ms <= history.entries[1].at_ms);
16442                return;
16443            }
16444            assert!(
16445                Instant::now() < deadline,
16446                "module did not retain two terminal exits: {history:?}"
16447            );
16448            sleep(Duration::from_millis(10)).await;
16449        }
16450    }
16451
16452    /// A disable issued while a crash respawn is still backing off must preempt
16453    /// that respawn: the operator's stop wins, the disable must not queue behind
16454    /// the backoff, and the module must never come back up afterwards.
16455    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16456    async fn disable_during_crash_backoff_cancels_pending_respawn() {
16457        let backoff = Duration::from_secs(2);
16458        let supervisor = Supervisor::new_for_test(
16459            Arc::new(Registry::default()),
16460            RestartPolicy::new(10, backoff),
16461        );
16462        let module = supervisor
16463            .spawn(ModuleSpec {
16464                script: None,
16465                module_id: "disable-during-backoff".to_string(),
16466                program: fake_aft_stub_path(),
16467                args: Vec::new(),
16468                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
16469                reserved: false,
16470                reserved_prefixes: Vec::new(),
16471                protocol: ModuleProtocol::Subc,
16472                overlap: Default::default(),
16473                carry_containment: false,
16474            })
16475            .unwrap();
16476
16477        // Wait for the first crash to put the module into its backoff window.
16478        let deadline = Instant::now() + Duration::from_secs(5);
16479        loop {
16480            if module.status().unwrap().state == ModuleState::Restarting {
16481                break;
16482            }
16483            assert!(
16484                Instant::now() < deadline,
16485                "module never entered the crash backoff"
16486            );
16487            sleep(Duration::from_millis(10)).await;
16488        }
16489
16490        let started = Instant::now();
16491        module.set_enabled(false).await.unwrap();
16492        let waited = started.elapsed();
16493
16494        assert!(
16495            waited < backoff / 2,
16496            "disable waited {waited:?} behind the {backoff:?} crash backoff; the operator command must preempt the pending respawn"
16497        );
16498        assert_eq!(module.status().unwrap().state, ModuleState::Disabled);
16499
16500        // Outlast the backoff: the respawn it was counting down to must never run.
16501        sleep(backoff + Duration::from_millis(500)).await;
16502        let status = module.status().unwrap();
16503        assert_eq!(status.state, ModuleState::Disabled);
16504        assert_eq!(
16505            status.spawn_generation, 1,
16506            "module respawned after the operator disabled it"
16507        );
16508    }
16509
16510    /// A `protocol: "none"` child that stays parked and exits 0 on SIGTERM:
16511    /// the shape of nats-server, the program this rule exists for.
16512    #[cfg(unix)]
16513    fn protocol_none_sigterm_exits_clean_spec(
16514        module_id: &str,
16515        dir: &std::path::Path,
16516    ) -> (ModuleSpec, PathBuf, PathBuf) {
16517        let ready = dir.join("ready");
16518        let marker = dir.join("sigterm");
16519        let spec = ModuleSpec {
16520            script: None,
16521            module_id: module_id.to_string(),
16522            program: fake_aft_stub_path(),
16523            args: Vec::new(),
16524            env: vec![
16525                ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
16526                (
16527                    "FAKE_AFT_SIGTERM_MARKER_PATH".to_string(),
16528                    marker.display().to_string(),
16529                ),
16530                (
16531                    "FAKE_AFT_NEVER_CONNECT_READY_PATH".to_string(),
16532                    ready.display().to_string(),
16533                ),
16534            ],
16535            reserved: false,
16536            reserved_prefixes: Vec::new(),
16537            protocol: ModuleProtocol::None,
16538            overlap: Default::default(),
16539            carry_containment: false,
16540        };
16541        (spec, ready, marker)
16542    }
16543
16544    /// Wait for a file the child writes, so a signal is never sent before the
16545    /// child's SIGTERM handler is installed (the default disposition would
16546    /// kill it by signal and the exit would not be clean).
16547    #[cfg(unix)]
16548    async fn wait_for_file(path: &std::path::Path) {
16549        let deadline = Instant::now() + Duration::from_secs(10);
16550        while !path.exists() {
16551            assert!(
16552                Instant::now() < deadline,
16553                "{} never appeared",
16554                path.display()
16555            );
16556            sleep(Duration::from_millis(10)).await;
16557        }
16558    }
16559
16560    /// A protocol-none module that exits 0 because something OUTSIDE the
16561    /// supervisor sent it SIGTERM is respawned, and the terminal record carries
16562    /// the crash-path disposition rather than `stopped`.
16563    #[cfg(unix)]
16564    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16565    async fn protocol_none_unrequested_clean_exit_restarts_as_a_crash() {
16566        let dir = cortexkit_test_support::ScratchDir::new("none-unrequested-clean-exit");
16567        let (spec, ready, marker) =
16568            protocol_none_sigterm_exits_clean_spec("none-unrequested-clean-exit", dir.path());
16569        let supervisor = Supervisor::new_for_test(
16570            Arc::new(Registry::default()),
16571            RestartPolicy::new(3, Duration::ZERO),
16572        );
16573        let module = supervisor.spawn(spec).unwrap();
16574        wait_for_file(&ready).await;
16575        // The ready file proves the child installed its SIGTERM handler, not
16576        // that the supervisor has processed the privacy trampoline's exec
16577        // acknowledgement. On macOS status withholds the pid until then.
16578        let deadline = Instant::now() + Duration::from_secs(10);
16579        let first_pid = loop {
16580            let status = module.status().unwrap();
16581            if status.state == ModuleState::Running {
16582                if let Some(pid) = status.pid {
16583                    break pid;
16584                }
16585            }
16586            assert!(
16587                Instant::now() < deadline,
16588                "a running module must report its pid after exec confirmation: {status:?}"
16589            );
16590            sleep(Duration::from_millis(10)).await;
16591        };
16592
16593        rustix::process::kill_process(
16594            rustix::process::Pid::from_raw(i32::try_from(first_pid).unwrap()).unwrap(),
16595            rustix::process::Signal::TERM,
16596        )
16597        .unwrap();
16598
16599        let deadline = Instant::now() + Duration::from_secs(10);
16600        let respawned = loop {
16601            let status = module.status().unwrap();
16602            if status.state == ModuleState::Running
16603                && status.pid.is_some_and(|pid| pid != first_pid)
16604            {
16605                break status;
16606            }
16607            assert!(
16608                Instant::now() < deadline,
16609                "protocol-none module was not respawned after an unrequested clean exit: {status:?}"
16610            );
16611            sleep(Duration::from_millis(10)).await;
16612        };
16613        assert_eq!(respawned.spawn_generation, 2);
16614        assert!(
16615            marker.exists(),
16616            "the child must have exited through its SIGTERM handler (exit 0), or this proves nothing about clean exits"
16617        );
16618
16619        let history = module.terminal_history();
16620        assert_eq!(history.entries.len(), 1, "{history:?}");
16621        let entry = &history.entries[0];
16622        assert_eq!(entry.exit_code, Some(0));
16623        assert_eq!(entry.exit_kind, subc_control::TerminalExitKind::Clean);
16624        assert_eq!(entry.disposition, TerminalDisposition::Restarting);
16625
16626        module.stop().await.unwrap();
16627    }
16628
16629    /// Repeated unrequested clean exits of a protocol-none module spend the
16630    /// restart budget exactly as crashes do, and the module ends `failed` with
16631    /// the budget named.
16632    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16633    async fn protocol_none_repeated_clean_exits_exhaust_the_restart_budget() {
16634        let supervisor = Supervisor::new_for_test(
16635            Arc::new(Registry::default()),
16636            RestartPolicy::new(1, Duration::ZERO),
16637        );
16638        let module = supervisor
16639            .spawn(ModuleSpec {
16640                script: None,
16641                module_id: "none-clean-exit-budget".to_string(),
16642                program: fake_aft_stub_path(),
16643                args: Vec::new(),
16644                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "0".to_string())],
16645                reserved: false,
16646                reserved_prefixes: Vec::new(),
16647                protocol: ModuleProtocol::None,
16648                overlap: Default::default(),
16649                carry_containment: false,
16650            })
16651            .unwrap();
16652
16653        // Failed follows the terminal write; this deadline only bounds a hang,
16654        // not an assumed duration for the two launches or their exit recording.
16655        let deadline = Instant::now() + Duration::from_secs(10);
16656        loop {
16657            let status = module.status().unwrap();
16658            if status.state == ModuleState::Failed {
16659                break;
16660            }
16661            assert!(
16662                Instant::now() < deadline,
16663                "module never exhausted its budget: {status:?} {:?}",
16664                module.terminal_history()
16665            );
16666            sleep(Duration::from_millis(10)).await;
16667        }
16668        let history = module.terminal_history();
16669        assert_eq!(
16670            history
16671                .entries
16672                .iter()
16673                .map(|entry| (entry.exit_code, entry.disposition.clone()))
16674                .collect::<Vec<_>>(),
16675            vec![
16676                (Some(0), TerminalDisposition::Restarting),
16677                (Some(0), TerminalDisposition::Failed),
16678            ]
16679        );
16680        let detail = history.entries[1]
16681            .disposition_detail
16682            .as_deref()
16683            .expect("a budget failure names the budget");
16684        assert!(detail.contains("max_restarts=1"), "{detail}");
16685        assert_eq!(module.status().unwrap().spawn_generation, 2);
16686    }
16687
16688    #[test]
16689    fn restart_budget_failure_is_published_after_its_terminal_record() {
16690        use std::io::{Read, Write};
16691        let supervisor = Supervisor::new_for_test(
16692            Arc::new(Registry::default()),
16693            RestartPolicy::new(0, Duration::ZERO),
16694        );
16695        let runtime = supervisor.runtime_config();
16696        let spec = ModuleSpec {
16697            script: None,
16698            protocol: ModuleProtocol::None,
16699            ..windowed_crash_spec("budget-publication-order")
16700        };
16701        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
16702            ModuleState::Running,
16703            true,
16704        )));
16705        lock_snapshot(&snapshot).unwrap().process_alive = true;
16706        let reaped_snapshot = snapshot.clone();
16707        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16708        let history = runtime.terminal_ring.clone();
16709        let reap = std::thread::spawn(move || {
16710            tokio::runtime::Builder::new_current_thread()
16711                .enable_all()
16712                .build()
16713                .unwrap()
16714                .block_on(on_child_exit(
16715                    &spec,
16716                    runtime.restart_policy,
16717                    &supervisor.registry,
16718                    &reaped_snapshot,
16719                    &runtime.terminal_ring,
16720                    &runtime.spawn_events,
16721                    &runtime.child_roster,
16722                    ExitReport {
16723                        kind: ExitKind::Clean,
16724                        code: Some(0),
16725                        signal: None,
16726                        at_ms: 1,
16727                    },
16728                    true,
16729                ))
16730        });
16731        let mut reached = [0];
16732        barrier.read_exact(&mut reached).unwrap();
16733        assert_eq!(&reached, b"R");
16734        let (before_state, before_alive) = {
16735            let state = lock_snapshot(&snapshot).unwrap();
16736            (state.state, state.process_alive)
16737        };
16738        let before_history = history.lock().unwrap().snapshot();
16739        barrier.write_all(b"X").unwrap();
16740        assert!(matches!(reap.join().unwrap(), NextAction::Stop { .. }));
16741        assert!(before_history.entries.is_empty());
16742        assert_ne!(
16743            before_state,
16744            ModuleState::Failed,
16745            "Failed was visible before its terminal record could be written"
16746        );
16747        assert!(before_alive);
16748        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
16749        let history = history.lock().unwrap().snapshot();
16750        assert_eq!(history.entries.len(), 1);
16751        assert_eq!(history.entries[0].exit_code, Some(0));
16752        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16753    }
16754
16755    #[test]
16756    fn crash_restart_at_budget_limit_remains_recoverable_while_recording() {
16757        use std::io::{Read, Write};
16758
16759        let supervisor = Supervisor::new_for_test(
16760            Arc::new(Registry::default()),
16761            RestartPolicy::new(3, Duration::ZERO),
16762        );
16763        let mut runtime = supervisor.runtime_config();
16764        let module = module_with_recovery_snapshot(ModuleState::Running, true, 2);
16765        let snapshot = module.inner.snapshot.clone();
16766        lock_snapshot(&snapshot).unwrap().process_alive = true;
16767        runtime.terminal_ring = module.inner.terminal_ring.clone();
16768        let spec = windowed_crash_spec(module.module_id());
16769        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16770        let reaped_snapshot = snapshot.clone();
16771        let reap = std::thread::spawn(move || {
16772            tokio::runtime::Builder::new_current_thread()
16773                .enable_all()
16774                .build()
16775                .unwrap()
16776                .block_on(on_child_exit(
16777                    &spec,
16778                    runtime.restart_policy,
16779                    &supervisor.registry,
16780                    &reaped_snapshot,
16781                    &runtime.terminal_ring,
16782                    &runtime.spawn_events,
16783                    &runtime.child_roster,
16784                    ExitReport {
16785                        kind: ExitKind::Crash,
16786                        code: Some(2),
16787                        signal: None,
16788                        at_ms: 1,
16789                    },
16790                    true,
16791                ))
16792        });
16793
16794        // Hold the crash handler between its budget decision and publication.
16795        // Connection cleanup must still see the recovery that this crash chose,
16796        // even when that recovery consumes the last available restart slot.
16797        let mut reached = [0];
16798        barrier.read_exact(&mut reached).unwrap();
16799        assert_eq!(&reached, b"R");
16800        let before_status = module.status().unwrap();
16801        let before_history = module.terminal_history();
16802        let before_recovers = module.will_recover_after_connection_loss().unwrap();
16803        barrier.write_all(b"X").unwrap();
16804        assert!(matches!(reap.join().unwrap(), NextAction::Restart { .. }));
16805
16806        assert_eq!(before_status.state, ModuleState::Running);
16807        assert!(before_status.process_alive);
16808        assert_eq!(before_status.restart_count, 3);
16809        assert!(before_history.entries.is_empty());
16810        assert!(
16811            before_recovers,
16812            "connection cleanup would report a terminal close for a scheduled crash restart"
16813        );
16814        let restarting = module.status().unwrap();
16815        assert_eq!(restarting.state, ModuleState::Restarting);
16816        assert_eq!(restarting.restart_count, 3);
16817        assert!(module.will_recover_after_connection_loss().unwrap());
16818        let history = module.terminal_history();
16819        assert_eq!(history.entries.len(), 1);
16820        assert_eq!(
16821            history.entries[0].disposition,
16822            TerminalDisposition::Restarting
16823        );
16824
16825        // Once the replacement is running, its next crash must be judged
16826        // against the exhausted budget rather than the previous recovery.
16827        update_snapshot(&snapshot, Some(module.module_id()), |state| {
16828            state.state = ModuleState::Running;
16829            state.respawn_pending = false;
16830        })
16831        .unwrap();
16832        assert!(!module.will_recover_after_connection_loss().unwrap());
16833        update_snapshot(&snapshot, Some(module.module_id()), |state| {
16834            state.enabled = false;
16835            state.respawn_pending = true;
16836        })
16837        .unwrap();
16838        assert!(!module.will_recover_after_connection_loss().unwrap());
16839    }
16840
16841    fn terminal_record_barrier(events: &super::SpawnEventFeed) -> std::net::TcpStream {
16842        use std::net::{TcpListener, TcpStream};
16843        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
16844        let writer = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
16845        let (barrier, _) = listener.accept().unwrap();
16846        for stream in [&writer, &barrier] {
16847            stream
16848                .set_read_timeout(Some(Duration::from_secs(10)))
16849                .unwrap();
16850            stream
16851                .set_write_timeout(Some(Duration::from_secs(10)))
16852                .unwrap();
16853        }
16854        *events.1.lock().unwrap() = Some(writer);
16855        barrier
16856    }
16857
16858    pub(super) fn before_terminal_record(events: &super::SpawnEventFeed) {
16859        use std::io::{Read, Write};
16860        let barrier = events.1.lock().unwrap().take();
16861        if let Some(mut barrier) = barrier {
16862            barrier.write_all(b"R").unwrap();
16863            let mut release = [0];
16864            barrier.read_exact(&mut release).unwrap();
16865            assert_eq!(&release, b"X");
16866        }
16867    }
16868
16869    #[test]
16870    fn health_restart_budget_failure_is_published_after_its_terminal_record() {
16871        use std::io::{Read, Write};
16872
16873        let supervisor = Supervisor::new_for_test(
16874            Arc::new(Registry::default()),
16875            RestartPolicy::new(0, Duration::ZERO),
16876        );
16877        let mut runtime = supervisor.runtime_config();
16878        let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
16879        let snapshot = module.inner.snapshot.clone();
16880        runtime.terminal_ring = module.inner.terminal_ring.clone();
16881        let spec = ModuleSpec {
16882            script: None,
16883            module_id: module.module_id().into(),
16884            program: fake_aft_stub_path(),
16885            protocol: ModuleProtocol::None,
16886            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
16887            ..windowed_crash_spec(module.module_id())
16888        };
16889        let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16890        let reap = std::thread::spawn(move || {
16891            tokio::runtime::Builder::new_current_thread()
16892                .enable_all()
16893                .build()
16894                .unwrap()
16895                .block_on(async {
16896                    let mut child =
16897                        Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
16898                    health_restart_child(
16899                        &spec,
16900                        &runtime,
16901                        &supervisor.registry,
16902                        &supervisor.process_liveness,
16903                        &snapshot,
16904                        &mut child,
16905                        SupervisorHealthStatus::Failing,
16906                        Some("health probe did not answer"),
16907                        1,
16908                    )
16909                    .await
16910                    .unwrap();
16911                    assert!(child.is_none());
16912                });
16913        });
16914        // The loopback barrier acknowledges entry into terminal recording by
16915        // health_restart_child's drain, then waits for the test's release byte.
16916        // Status and history are observed while that writer is held, not after
16917        // an elapsed-time guess about when the health action has completed.
16918        let mut reached = [0];
16919        barrier.read_exact(&mut reached).unwrap();
16920        assert_eq!(&reached, b"R");
16921        let before_status = module.status().unwrap();
16922        let before_history = module.terminal_history();
16923        barrier.write_all(b"X").unwrap();
16924        reap.join().unwrap();
16925        assert!(before_history.entries.is_empty());
16926        assert_ne!(
16927            before_status.state,
16928            ModuleState::Failed,
16929            "Failed was visible before its terminal record could be written"
16930        );
16931        assert!(
16932            before_status.process_alive,
16933            "process death was visible before its terminal record could be written"
16934        );
16935        let failed = module.status().unwrap();
16936        assert_eq!(failed.state, ModuleState::Failed);
16937        assert!(!failed.process_alive);
16938        let history = module.terminal_history();
16939        assert_eq!(history.entries.len(), 1);
16940        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16941        assert_eq!(
16942            history.entries[0].disposition_detail.as_deref(),
16943            Some("crash budget exhausted: max_restarts=0 within window_secs=600")
16944        );
16945    }
16946
16947    #[test]
16948    fn observed_exits_publish_process_death_after_terminal_history() {
16949        use std::io::{Read, Write};
16950        for (kind, enabled, shutdown, wait_error, expected_state) in [
16951            (ExitKind::Clean, true, false, false, ModuleState::Stopped),
16952            (ExitKind::Crash, true, false, false, ModuleState::Restarting),
16953            (ExitKind::Crash, false, false, false, ModuleState::Disabled),
16954            (
16955                ExitKind::DeliberateSeverance,
16956                true,
16957                false,
16958                false,
16959                ModuleState::Restarting,
16960            ),
16961            #[cfg(unix)]
16962            (ExitKind::Crash, true, true, false, ModuleState::Stopped),
16963            (ExitKind::Crash, true, false, true, ModuleState::Failed),
16964        ] {
16965            let supervisor = Supervisor::new_for_test(
16966                Arc::new(Registry::default()),
16967                RestartPolicy::new(1, Duration::ZERO),
16968            );
16969            let runtime = supervisor.runtime_config();
16970            #[cfg(unix)]
16971            if shutdown {
16972                runtime.child_roster.close();
16973            }
16974            #[cfg(not(unix))]
16975            let _ = shutdown;
16976            let spec = windowed_crash_spec("exit-publication-order");
16977            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
16978                ModuleState::Running,
16979                enabled,
16980            )));
16981            lock_snapshot(&snapshot).unwrap().process_alive = true;
16982            let reaped_snapshot = snapshot.clone();
16983            let history = runtime.terminal_ring.clone();
16984            let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16985            let reap = std::thread::spawn(move || {
16986                if wait_error {
16987                    super::fail_after_wait_error(
16988                        &spec.module_id,
16989                        &reaped_snapshot,
16990                        &runtime.terminal_ring,
16991                        &runtime.spawn_events,
16992                        "wait failed".into(),
16993                        &runtime.failure_context(true),
16994                    );
16995                } else {
16996                    tokio::runtime::Builder::new_current_thread()
16997                        .enable_all()
16998                        .build()
16999                        .unwrap()
17000                        .block_on(on_child_exit(
17001                            &spec,
17002                            runtime.restart_policy,
17003                            &supervisor.registry,
17004                            &reaped_snapshot,
17005                            &runtime.terminal_ring,
17006                            &runtime.spawn_events,
17007                            &runtime.child_roster,
17008                            ExitReport {
17009                                kind,
17010                                code: Some(0),
17011                                signal: None,
17012                                at_ms: 1,
17013                            },
17014                            true,
17015                        ));
17016                }
17017            });
17018            let mut reached = [0];
17019            barrier.read_exact(&mut reached).unwrap();
17020            assert_eq!(&reached, b"R");
17021            let before_alive = lock_snapshot(&snapshot).unwrap().process_alive;
17022            let before_history = history.lock().unwrap().snapshot();
17023            barrier.write_all(b"X").unwrap();
17024            reap.join().unwrap();
17025            assert!(
17026                before_alive,
17027                "{kind:?}: death was published before recording"
17028            );
17029            assert!(before_history.entries.is_empty());
17030            assert_eq!(lock_snapshot(&snapshot).unwrap().state, expected_state);
17031            assert!(!lock_snapshot(&snapshot).unwrap().process_alive);
17032            assert_eq!(history.lock().unwrap().snapshot().entries.len(), 1);
17033        }
17034    }
17035
17036    #[tokio::test]
17037    async fn health_restart_budget_failure_remains_failed_when_journal_append_fails() {
17038        let dir = cortexkit_test_support::ScratchDir::new("health-budget-journal-failure");
17039        let path = dir.join("terminals.jsonl");
17040        std::fs::create_dir(&path).unwrap();
17041        let supervisor = Supervisor::new_for_test(
17042            Arc::new(Registry::default()),
17043            RestartPolicy::new(0, Duration::ZERO),
17044        )
17045        .with_terminal_journal(path, "health-budget-journal-failure".into());
17046        let runtime = supervisor.runtime_config();
17047        let spec = ModuleSpec {
17048            script: None,
17049            program: fake_aft_stub_path(),
17050            protocol: ModuleProtocol::None,
17051            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
17052            ..windowed_crash_spec("health-budget-journal-failure")
17053        };
17054        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17055        let mut child = Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
17056        health_restart_child(
17057            &spec,
17058            &runtime,
17059            &supervisor.registry,
17060            &supervisor.process_liveness,
17061            &snapshot,
17062            &mut child,
17063            SupervisorHealthStatus::Failing,
17064            None,
17065            1,
17066        )
17067        .await
17068        .unwrap();
17069        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17070        assert!(!lock_snapshot(&snapshot).unwrap().process_alive);
17071        let history = runtime
17072            .terminal_ring
17073            .lock()
17074            .unwrap()
17075            .durable_history(&spec.module_id);
17076        assert!(history.journal_write_failures > 0);
17077        assert_eq!(history.entries.len(), 1);
17078        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
17079    }
17080
17081    #[test]
17082    fn health_restart_budget_failure_remains_failed_when_exit_recording_panics() {
17083        let supervisor = Supervisor::new_for_test(
17084            Arc::new(Registry::default()),
17085            RestartPolicy::new(0, Duration::ZERO),
17086        );
17087        let runtime = supervisor.runtime_config();
17088        let spec = ModuleSpec {
17089            script: None,
17090            program: fake_aft_stub_path(),
17091            protocol: ModuleProtocol::None,
17092            env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
17093            ..windowed_crash_spec("health-budget-recording-panic")
17094        };
17095        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17096        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
17097            tokio::runtime::Builder::new_current_thread()
17098                .enable_all()
17099                .build()
17100                .unwrap()
17101                .block_on(async {
17102                    let mut child =
17103                        Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
17104                    runtime.spawn_events.0.lock().unwrap().seq = u64::MAX;
17105                    health_restart_child(
17106                        &spec,
17107                        &runtime,
17108                        &supervisor.registry,
17109                        &supervisor.process_liveness,
17110                        &snapshot,
17111                        &mut child,
17112                        SupervisorHealthStatus::Failing,
17113                        None,
17114                        1,
17115                    )
17116                    .await
17117                    .unwrap();
17118                });
17119        }));
17120        let panic = result.expect_err("recording must still unwind");
17121        assert_eq!(
17122            panic.downcast_ref::<String>().map(String::as_str),
17123            Some("spawn event sequence exhausted")
17124        );
17125        let state = lock_snapshot(&snapshot).unwrap();
17126        assert_eq!(state.state, ModuleState::Failed);
17127        assert!(!state.process_alive);
17128        assert!(state.last_exit.is_some());
17129    }
17130
17131    #[tokio::test]
17132    async fn restart_budget_failure_remains_failed_when_journal_append_fails() {
17133        let dir = cortexkit_test_support::ScratchDir::new("budget-journal-failure");
17134        let path = dir.join("terminals.jsonl");
17135        std::fs::create_dir(&path).unwrap();
17136        let supervisor = Supervisor::new_for_test(
17137            Arc::new(Registry::default()),
17138            RestartPolicy::new(0, Duration::ZERO),
17139        )
17140        .with_terminal_journal(path, "budget-journal-failure".into());
17141        let runtime = supervisor.runtime_config();
17142        let spec = windowed_crash_spec("budget-journal-failure");
17143        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17144        assert!(matches!(
17145            on_child_exit(
17146                &spec,
17147                runtime.restart_policy,
17148                &supervisor.registry,
17149                &snapshot,
17150                &runtime.terminal_ring,
17151                &runtime.spawn_events,
17152                &runtime.child_roster,
17153                crash_exit_report(1),
17154                true,
17155            )
17156            .await,
17157            NextAction::Stop { .. }
17158        ));
17159        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17160        let history = runtime
17161            .terminal_ring
17162            .lock()
17163            .unwrap()
17164            .durable_history(&spec.module_id);
17165        assert!(history.journal_write_failures > 0);
17166        assert_eq!(history.entries.len(), 1);
17167        assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
17168    }
17169
17170    #[test]
17171    fn restart_budget_failure_remains_failed_when_exit_recording_panics() {
17172        let supervisor = Supervisor::new_for_test(
17173            Arc::new(Registry::default()),
17174            RestartPolicy::new(0, Duration::ZERO),
17175        );
17176        let runtime = supervisor.runtime_config();
17177        let spec = windowed_crash_spec("budget-recording-panic");
17178        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17179        runtime
17180            .spawn_events
17181            .emit_spawned(&spec.module_id, None, 1, 1);
17182        // Exhausting the event sequence makes emit_exited panic before the
17183        // terminal write, exercising publication on the recording unwind.
17184        runtime.spawn_events.0.lock().unwrap().seq = u64::MAX;
17185        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
17186            tokio::runtime::Builder::new_current_thread()
17187                .enable_all()
17188                .build()
17189                .unwrap()
17190                .block_on(on_child_exit(
17191                    &spec,
17192                    runtime.restart_policy,
17193                    &supervisor.registry,
17194                    &snapshot,
17195                    &runtime.terminal_ring,
17196                    &runtime.spawn_events,
17197                    &runtime.child_roster,
17198                    crash_exit_report(1),
17199                    true,
17200                ))
17201        }));
17202        let panic = result.err().expect("recording must still unwind");
17203        assert_eq!(
17204            panic.downcast_ref::<String>().map(String::as_str),
17205            Some("spawn event sequence exhausted")
17206        );
17207        assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17208    }
17209
17210    /// A stop the supervisor itself requests still stops a protocol-none
17211    /// module, even though the child answers the SIGTERM with exit 0.
17212    #[cfg(unix)]
17213    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17214    async fn protocol_none_requested_stop_and_disable_do_not_respawn() {
17215        for disable in [false, true] {
17216            let label = if disable {
17217                "none-requested-disable"
17218            } else {
17219                "none-requested-stop"
17220            };
17221            let dir = cortexkit_test_support::ScratchDir::new(label);
17222            let (spec, ready, marker) = protocol_none_sigterm_exits_clean_spec(label, dir.path());
17223            let supervisor = Supervisor::new_for_test(
17224                Arc::new(Registry::default()),
17225                RestartPolicy::new(3, Duration::ZERO),
17226            );
17227            let module = supervisor.spawn(spec).unwrap();
17228            wait_for_file(&ready).await;
17229
17230            if disable {
17231                module.set_enabled(false).await.unwrap();
17232            } else {
17233                module.stop().await.unwrap();
17234            }
17235            assert!(
17236                marker.exists(),
17237                "{label}: the child must have left through its SIGTERM handler with exit 0"
17238            );
17239
17240            // Long enough for a zero-backoff respawn to have happened if the
17241            // exit had been treated as a crash.
17242            sleep(Duration::from_millis(500)).await;
17243            let status = module.status().unwrap();
17244            let expected = if disable {
17245                ModuleState::Disabled
17246            } else {
17247                ModuleState::Stopped
17248            };
17249            assert_eq!(status.state, expected, "{label}");
17250            assert_eq!(
17251                status.spawn_generation, 1,
17252                "{label}: respawned after a requested stop"
17253            );
17254            let history = module.terminal_history();
17255            assert_eq!(history.entries.len(), 1, "{label}: {history:?}");
17256            assert_eq!(history.entries[0].exit_code, Some(0), "{label}");
17257            assert_ne!(
17258                history.entries[0].disposition,
17259                TerminalDisposition::Restarting,
17260                "{label}"
17261            );
17262        }
17263    }
17264
17265    /// A subc-wire module that exits 0 on its own is still a stop: the
17266    /// protocol-none rule must not reach it.
17267    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17268    async fn subc_wire_clean_exit_is_still_a_stop() {
17269        let supervisor = Supervisor::new_for_test(
17270            Arc::new(Registry::default()),
17271            RestartPolicy::new(3, Duration::ZERO),
17272        );
17273        let module = supervisor
17274            .spawn(ModuleSpec {
17275                script: None,
17276                module_id: "wire-clean-exit".to_string(),
17277                program: fake_aft_stub_path(),
17278                args: Vec::new(),
17279                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "0".to_string())],
17280                reserved: false,
17281                reserved_prefixes: Vec::new(),
17282                protocol: ModuleProtocol::Subc,
17283                overlap: Default::default(),
17284                carry_containment: false,
17285            })
17286            .unwrap();
17287
17288        let deadline = Instant::now() + Duration::from_secs(10);
17289        while module.terminal_history().entries.is_empty() {
17290            assert!(Instant::now() < deadline, "module never exited");
17291            sleep(Duration::from_millis(10)).await;
17292        }
17293        // Long enough for a zero-backoff respawn to have happened.
17294        sleep(Duration::from_millis(500)).await;
17295        let status = module.status().unwrap();
17296        assert_eq!(status.state, ModuleState::Stopped);
17297        assert_eq!(status.spawn_generation, 1);
17298        let history = module.terminal_history();
17299        assert_eq!(history.entries.len(), 1, "{history:?}");
17300        assert_eq!(history.entries[0].exit_code, Some(0));
17301        assert_eq!(history.entries[0].disposition, TerminalDisposition::Stopped);
17302    }
17303
17304    #[cfg(unix)]
17305    #[tokio::test]
17306    async fn reload_exit_keeps_roster_until_terminal_is_recorded_during_shutdown() {
17307        let dir = cortexkit_test_support::ScratchDir::new("reload-roster-terminal-order");
17308        let record = dir.join("live-children.json");
17309        let supervisor = Supervisor::new_for_test(
17310            Arc::new(Registry::default()),
17311            RestartPolicy::new(0, Duration::ZERO),
17312        );
17313        let mut runtime = supervisor.runtime_config();
17314        runtime.child_roster.record_to(record.clone());
17315        let gate = Arc::new(super::ReloadExitRecordGate::default());
17316        runtime.test_reload_exit_record_gate = Some(Arc::clone(&gate));
17317        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17318        let spec = ModuleSpec {
17319            script: None,
17320            module_id: "reload-exit-roster".into(),
17321            program: fake_aft_stub_path(),
17322            args: Vec::new(),
17323            env: vec![("FAKE_AFT_EXIT_CODE".into(), "23".into())],
17324            reserved: false,
17325            reserved_prefixes: Vec::new(),
17326            protocol: ModuleProtocol::Subc,
17327            overlap: Default::default(),
17328            carry_containment: false,
17329        };
17330        let mut child = None;
17331        let reload = super::finish_reload_child(
17332            &spec,
17333            &runtime,
17334            &supervisor.registry,
17335            &supervisor.process_liveness,
17336            &snapshot,
17337            &mut child,
17338        );
17339        tokio::pin!(reload);
17340        tokio::select! {
17341            result = &mut reload => panic!("reload missed the before-record gate: {result:?}"),
17342            _ = gate.reached.notified() => {}
17343        }
17344        assert!(runtime
17345            .terminal_ring
17346            .lock()
17347            .unwrap()
17348            .snapshot()
17349            .entries
17350            .is_empty());
17351        assert_eq!(
17352            crate::live_children::read_record(&record).unwrap().len(),
17353            1,
17354            "shutdown must still wait for the reaped child until its terminal record exists"
17355        );
17356        runtime.child_roster.close();
17357        gate.resume.notify_one();
17358        assert!(reload.await.is_err());
17359        assert!(crate::live_children::read_record(&record)
17360            .unwrap()
17361            .is_empty());
17362        let history = runtime.terminal_ring.lock().unwrap().snapshot();
17363        assert_eq!(history.entries.len(), 1);
17364        assert_eq!(
17365            history.entries[0].disposition,
17366            TerminalDisposition::DaemonShutdown
17367        );
17368    }
17369
17370    /// Each restart-producing arm has its own state transition. Keeping their
17371    /// lifetime count assertions adjacent prevents a later new arm from silently
17372    /// spending budget without recording the historical restart.
17373    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17374    async fn every_restart_increment_path_advances_lifetime_count() {
17375        let supervisor = Supervisor::new_for_test(
17376            Arc::new(Registry::default()),
17377            RestartPolicy::new(1, Duration::ZERO),
17378        );
17379        let runtime = supervisor.runtime_config();
17380        let spec = ModuleSpec {
17381            script: None,
17382            module_id: "lifetime-increment-path".to_string(),
17383            program: PathBuf::from("/unused/lifetime-increment-path"),
17384            args: Vec::new(),
17385            env: Vec::new(),
17386            reserved: false,
17387            reserved_prefixes: Vec::new(),
17388            protocol: ModuleProtocol::Subc,
17389            overlap: Default::default(),
17390            carry_containment: false,
17391        };
17392
17393        let crash_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17394        assert!(matches!(
17395            on_child_exit(
17396                &spec,
17397                runtime.restart_policy,
17398                &supervisor.registry,
17399                &crash_snapshot,
17400                &runtime.terminal_ring,
17401                &runtime.spawn_events,
17402                &runtime.child_roster,
17403                ExitReport {
17404                    kind: ExitKind::Crash,
17405                    code: Some(1),
17406                    signal: None,
17407                    at_ms: 1,
17408                },
17409                true,
17410            )
17411            .await,
17412            NextAction::Restart { schedule: _ }
17413        ));
17414        let (crash_restarts, crash_lifetime) = {
17415            let state = lock_snapshot(&crash_snapshot).unwrap();
17416            (state.crash_restarts.len(), state.lifetime_restarts)
17417        };
17418        assert_eq!(crash_restarts, 1);
17419        assert_eq!(crash_lifetime, 1);
17420
17421        let health_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17422        let mut health_child = None;
17423        assert!(matches!(
17424            health_restart_child(
17425                &spec,
17426                &runtime,
17427                &supervisor.registry,
17428                &supervisor.process_liveness,
17429                &health_snapshot,
17430                &mut health_child,
17431                SupervisorHealthStatus::Failing,
17432                None,
17433                2,
17434            )
17435            .await,
17436            Ok(())
17437        ));
17438        assert!(health_child.is_none());
17439        assert!(lock_snapshot(&health_snapshot).unwrap().respawn_pending);
17440        assert!(runtime.scheduled_respawn.lock().unwrap().take().is_some());
17441        let (health_restarts, health_lifetime) = {
17442            let state = lock_snapshot(&health_snapshot).unwrap();
17443            (state.crash_restarts.len(), state.lifetime_restarts)
17444        };
17445        assert_eq!(health_restarts, 1);
17446        assert_eq!(health_lifetime, 1);
17447
17448        let reload_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17449        let mut reload_child = None;
17450        assert!(matches!(
17451            handle_reload_spawn_failure(
17452                &spec,
17453                &runtime,
17454                &supervisor.process_liveness,
17455                &reload_snapshot,
17456                &mut reload_child,
17457                "forced reload spawn failure".to_string(),
17458            )
17459            .await,
17460            Err(SuperviseError::ReloadFailed { .. })
17461        ));
17462        let (reload_restarts, reload_lifetime) = {
17463            let state = lock_snapshot(&reload_snapshot).unwrap();
17464            (state.crash_restarts.len(), state.lifetime_restarts)
17465        };
17466        assert_eq!(reload_restarts, 1);
17467        assert_eq!(reload_lifetime, 1);
17468    }
17469
17470    #[tokio::test]
17471    async fn deliberately_severed_live_child_records_lifetime_without_spending_restart_budget() {
17472        let supervisor = Supervisor::new_for_test(
17473            Arc::new(Registry::default()),
17474            RestartPolicy::new(3, Duration::ZERO),
17475        );
17476        let runtime = supervisor.runtime_config();
17477        let spec = ModuleSpec {
17478            script: None,
17479            module_id: "deliberately-severed".to_string(),
17480            program: PathBuf::from("/unused/deliberately-severed"),
17481            args: Vec::new(),
17482            env: Vec::new(),
17483            reserved: false,
17484            reserved_prefixes: Vec::new(),
17485            protocol: ModuleProtocol::Subc,
17486            overlap: Default::default(),
17487            carry_containment: false,
17488        };
17489        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17490        let process = ProcessIdentity {
17491            pid: 41,
17492            start_time: 101,
17493        };
17494        record_deliberate_severance(&snapshot, process).unwrap();
17495        let exit_report = apply_deliberate_severance_marker(
17496            &snapshot,
17497            Some(process),
17498            ExitReport {
17499                kind: ExitKind::Crash,
17500                code: Some(1),
17501                signal: None,
17502                at_ms: 1,
17503            },
17504        );
17505        assert_eq!(exit_report.kind, ExitKind::DeliberateSeverance);
17506
17507        assert!(matches!(
17508            on_child_exit(
17509                &spec,
17510                runtime.restart_policy,
17511                &supervisor.registry,
17512                &snapshot,
17513                &runtime.terminal_ring,
17514                &runtime.spawn_events,
17515                &runtime.child_roster,
17516                exit_report,
17517                true,
17518            )
17519            .await,
17520            NextAction::Restart { schedule: _ }
17521        ));
17522        let state = lock_snapshot(&snapshot).unwrap();
17523        assert_eq!(state.lifetime_restarts, 1);
17524        assert_eq!(state.crash_restarts.len(), 0);
17525    }
17526
17527    #[tokio::test]
17528    async fn genuine_crash_spends_restart_budget_and_records_lifetime() {
17529        let supervisor = Supervisor::new_for_test(
17530            Arc::new(Registry::default()),
17531            RestartPolicy::new(3, Duration::ZERO),
17532        );
17533        let runtime = supervisor.runtime_config();
17534        let spec = ModuleSpec {
17535            script: None,
17536            module_id: "genuine-crash".to_string(),
17537            program: PathBuf::from("/unused/genuine-crash"),
17538            args: Vec::new(),
17539            env: Vec::new(),
17540            reserved: false,
17541            reserved_prefixes: Vec::new(),
17542            protocol: ModuleProtocol::Subc,
17543            overlap: Default::default(),
17544            carry_containment: false,
17545        };
17546        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17547
17548        assert!(matches!(
17549            on_child_exit(
17550                &spec,
17551                runtime.restart_policy,
17552                &supervisor.registry,
17553                &snapshot,
17554                &runtime.terminal_ring,
17555                &runtime.spawn_events,
17556                &runtime.child_roster,
17557                ExitReport {
17558                    kind: ExitKind::Crash,
17559                    code: Some(1),
17560                    signal: None,
17561                    at_ms: 1,
17562                },
17563                true,
17564            )
17565            .await,
17566            NextAction::Restart { schedule: _ }
17567        ));
17568        let state = lock_snapshot(&snapshot).unwrap();
17569        assert_eq!(state.lifetime_restarts, 1);
17570        assert_eq!(state.crash_restarts.len(), 1);
17571    }
17572
17573    fn crash_exit_report(at_ms: u64) -> ExitReport {
17574        ExitReport {
17575            kind: ExitKind::Crash,
17576            code: Some(1),
17577            signal: None,
17578            at_ms,
17579        }
17580    }
17581
17582    fn windowed_crash_spec(module_id: &str) -> ModuleSpec {
17583        ModuleSpec {
17584            script: None,
17585            module_id: module_id.to_string(),
17586            program: PathBuf::from("/unused").join(module_id),
17587            args: Vec::new(),
17588            env: Vec::new(),
17589            reserved: false,
17590            reserved_prefixes: Vec::new(),
17591            protocol: ModuleProtocol::Subc,
17592            overlap: Default::default(),
17593            carry_containment: false,
17594        }
17595    }
17596
17597    /// A real crash loop still stops. Three crashes with nothing aging out spend
17598    /// a budget of two and the third respawn is refused, and both surfaces an
17599    /// operator has -- the log line and the retained terminal record -- name the
17600    /// window rather than only the cap, because `max_restarts=2` alone is what
17601    /// this budget used to mean.
17602    #[tokio::test]
17603    async fn three_crashes_inside_the_window_stop_the_module_and_name_the_window() {
17604        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::ERROR);
17605        let supervisor = Supervisor::new_for_test(
17606            Arc::new(Registry::default()),
17607            RestartPolicy::new(2, Duration::ZERO),
17608        );
17609        let runtime = supervisor.runtime_config();
17610        let spec = windowed_crash_spec("crash-loop-in-window");
17611        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17612
17613        for attempt in 1..=2 {
17614            assert!(
17615                matches!(
17616                    on_child_exit(
17617                        &spec,
17618                        runtime.restart_policy,
17619                        &supervisor.registry,
17620                        &snapshot,
17621                        &runtime.terminal_ring,
17622                        &runtime.spawn_events,
17623                        &runtime.child_roster,
17624                        crash_exit_report(attempt),
17625                        true,
17626                    )
17627                    .await,
17628                    NextAction::Restart { schedule: _ }
17629                ),
17630                "crash {attempt} is inside the budget and must respawn"
17631            );
17632        }
17633
17634        assert!(matches!(
17635            on_child_exit(
17636                &spec,
17637                runtime.restart_policy,
17638                &supervisor.registry,
17639                &snapshot,
17640                &runtime.terminal_ring,
17641                &runtime.spawn_events,
17642                &runtime.child_roster,
17643                crash_exit_report(3),
17644                true,
17645            )
17646            .await,
17647            NextAction::Stop { .. }
17648        ));
17649
17650        {
17651            let state = lock_snapshot(&snapshot).unwrap();
17652            assert_eq!(state.state, ModuleState::Failed);
17653            assert_eq!(state.crash_restarts.len(), 2);
17654            assert_eq!(state.lifetime_restarts, 2);
17655        }
17656
17657        let history = runtime
17658            .terminal_ring
17659            .lock()
17660            .expect("terminal ring is not poisoned")
17661            .snapshot();
17662        let last = history
17663            .entries
17664            .last()
17665            .expect("the refused crash is retained");
17666        assert_eq!(last.disposition, TerminalDisposition::Failed);
17667        assert_eq!(
17668            last.disposition_detail.as_deref(),
17669            Some("crash budget exhausted: max_restarts=2 within window_secs=600")
17670        );
17671
17672        let captured = crate::router::test_log::captured_logs(&logs);
17673        assert!(
17674            captured.contains("crash budget exhausted: max_restarts=2 within window_secs=600"),
17675            "the stop must be logged with its window: {captured}"
17676        );
17677    }
17678
17679    /// The rate, stated as a test: three crashes where the first has aged past
17680    /// the window are two crashes as far as the budget is concerned, so the
17681    /// third respawn is allowed and the ring holds only the two recent ones.
17682    ///
17683    /// This is the case a lifetime counter got wrong -- and the case the daemon
17684    /// now hits routinely, since a module exits non-zero every time its
17685    /// connection to the daemon drops.
17686    #[tokio::test]
17687    async fn a_crash_older_than_the_window_frees_its_slot_for_a_later_crash() {
17688        let supervisor = Supervisor::new_for_test(
17689            Arc::new(Registry::default()),
17690            RestartPolicy::new(2, Duration::ZERO),
17691        );
17692        let runtime = supervisor.runtime_config();
17693        let spec = windowed_crash_spec("crash-across-windows");
17694        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17695
17696        for attempt in 1..=2 {
17697            assert!(matches!(
17698                on_child_exit(
17699                    &spec,
17700                    runtime.restart_policy,
17701                    &supervisor.registry,
17702                    &snapshot,
17703                    &runtime.terminal_ring,
17704                    &runtime.spawn_events,
17705                    &runtime.child_roster,
17706                    crash_exit_report(attempt),
17707                    true,
17708                )
17709                .await,
17710                NextAction::Restart { schedule: _ }
17711            ));
17712        }
17713
17714        // The oldest crash moves out of the window; nothing else about the
17715        // module changes.
17716        update_snapshot(&snapshot, Some(&spec.module_id), |state| {
17717            age_oldest_crash_restart_out_of_window(state, runtime.restart_policy.window);
17718        })
17719        .unwrap();
17720
17721        assert!(
17722            matches!(
17723                on_child_exit(
17724                    &spec,
17725                    runtime.restart_policy,
17726                    &supervisor.registry,
17727                    &snapshot,
17728                    &runtime.terminal_ring,
17729                    &runtime.spawn_events,
17730                    &runtime.child_roster,
17731                    crash_exit_report(3),
17732                    true,
17733                )
17734                .await,
17735                NextAction::Restart { schedule: _ }
17736            ),
17737            "a crash older than the window must not hold a budget slot"
17738        );
17739
17740        let state = lock_snapshot(&snapshot).unwrap();
17741        assert_eq!(state.state, ModuleState::Restarting);
17742        assert_eq!(
17743            state.crash_restarts.len(),
17744            2,
17745            "the aged instant is dropped and the new one takes its place"
17746        );
17747        assert_eq!(
17748            state.lifetime_restarts, 3,
17749            "the ledger counts every restart, including the ones the window forgot"
17750        );
17751    }
17752
17753    /// An operator restart hands the budget back whole, and the ledger keeps
17754    /// counting. Those are different questions -- "how close is this module to
17755    /// being stopped" and "how many times has it been replaced" -- and the
17756    /// operator action answers only the first.
17757    #[tokio::test]
17758    async fn an_operator_restart_clears_the_ring_and_leaves_the_ledger_alone() {
17759        let supervisor = Supervisor::new_for_test(
17760            Arc::new(Registry::default()),
17761            RestartPolicy::new(2, Duration::ZERO),
17762        );
17763        let runtime = supervisor.runtime_config();
17764        let spec = windowed_crash_spec("operator-cleared-budget");
17765        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17766
17767        for attempt in 1..=2 {
17768            assert!(matches!(
17769                on_child_exit(
17770                    &spec,
17771                    runtime.restart_policy,
17772                    &supervisor.registry,
17773                    &snapshot,
17774                    &runtime.terminal_ring,
17775                    &runtime.spawn_events,
17776                    &runtime.child_roster,
17777                    crash_exit_report(attempt),
17778                    true,
17779                )
17780                .await,
17781                NextAction::Restart { schedule: _ }
17782            ));
17783        }
17784
17785        reset_restart_count(&snapshot, &spec.module_id).unwrap();
17786        {
17787            let state = lock_snapshot(&snapshot).unwrap();
17788            assert!(
17789                state.crash_restarts.is_empty(),
17790                "an operator restart returns the full budget"
17791            );
17792            assert_eq!(
17793                state.lifetime_restarts, 2,
17794                "clearing the budget must not unmake the crashes"
17795            );
17796        }
17797
17798        assert!(
17799            matches!(
17800                on_child_exit(
17801                    &spec,
17802                    runtime.restart_policy,
17803                    &supervisor.registry,
17804                    &snapshot,
17805                    &runtime.terminal_ring,
17806                    &runtime.spawn_events,
17807                    &runtime.child_roster,
17808                    crash_exit_report(3),
17809                    true,
17810                )
17811                .await,
17812                NextAction::Restart { schedule: _ }
17813            ),
17814            "the cleared budget must be spendable again"
17815        );
17816        let state = lock_snapshot(&snapshot).unwrap();
17817        assert_eq!(state.crash_restarts.len(), 1);
17818        assert_eq!(state.lifetime_restarts, 3);
17819    }
17820
17821    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17822    async fn severance_marker_for_a_dead_child_does_not_label_its_successor() {
17823        let severed = ProcessIdentity {
17824            pid: 41,
17825            start_time: 101,
17826        };
17827        let successor = ProcessIdentity {
17828            pid: 41,
17829            start_time: 202,
17830        };
17831        let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
17832        update_snapshot(&module.inner.snapshot, Some("recovery-snapshot"), |state| {
17833            state.pid = Some(successor.pid);
17834            state.process_start_time = Some(successor.start_time);
17835        })
17836        .unwrap();
17837        assert!(!module.record_deliberate_severance(severed).unwrap());
17838
17839        let exit_report = apply_deliberate_severance_marker(
17840            &module.inner.snapshot,
17841            Some(successor),
17842            ExitReport {
17843                kind: ExitKind::Crash,
17844                code: Some(1),
17845                signal: None,
17846                at_ms: 1,
17847            },
17848        );
17849
17850        assert_eq!(exit_report.kind, ExitKind::Crash);
17851    }
17852
17853    #[tokio::test]
17854    async fn drain_reap_marks_deliberate_severance_and_records_lifetime_without_budget() {
17855        let registry = Registry::default();
17856        let supervisor = Supervisor::new_for_test(
17857            Arc::new(Registry::default()),
17858            RestartPolicy::new(3, Duration::ZERO),
17859        );
17860        let runtime = supervisor.runtime_config();
17861        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17862        let spec = ModuleSpec {
17863            script: None,
17864            module_id: "drain-deliberate-severance".to_string(),
17865            program: fake_aft_stub_path(),
17866            args: Vec::new(),
17867            env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
17868            reserved: false,
17869            reserved_prefixes: Vec::new(),
17870            protocol: ModuleProtocol::Subc,
17871            overlap: Default::default(),
17872            carry_containment: false,
17873        };
17874        let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
17875        let process = ProcessIdentity {
17876            pid: 41,
17877            start_time: 101,
17878        };
17879        child.process_identity = Some(process);
17880        update_snapshot(&snapshot, Some(&spec.module_id), |state| {
17881            state.pid = Some(process.pid);
17882            state.process_start_time = Some(process.start_time);
17883        })
17884        .unwrap();
17885        record_deliberate_severance(&snapshot, process).unwrap();
17886
17887        drain_child_to_state(
17888            &spec.module_id,
17889            spec.protocol,
17890            // The child exits on its own; no signal may change the exit this
17891            // test classifies.
17892            StopNotice::SentOverConnection,
17893            &registry,
17894            None,
17895            &snapshot,
17896            &runtime.terminal_ring,
17897            &runtime.spawn_events,
17898            child,
17899            Duration::from_secs(1),
17900            ModuleState::Stopped,
17901            Some(false),
17902            &super::FailureContext::operator(),
17903        )
17904        .await
17905        .unwrap();
17906
17907        let state = lock_snapshot(&snapshot).unwrap();
17908        assert_eq!(
17909            state.last_exit.as_ref().map(|exit| exit.kind),
17910            Some(ExitKind::DeliberateSeverance)
17911        );
17912        assert_eq!(state.lifetime_restarts, 1);
17913        assert_eq!(state.crash_restarts.len(), 0);
17914        drop(state);
17915        let history = runtime.terminal_ring.lock().unwrap().snapshot();
17916        assert_eq!(
17917            history.entries[0].exit_kind,
17918            subc_control::TerminalExitKind::DeliberateSeverance
17919        );
17920    }
17921
17922    #[tokio::test]
17923    async fn ordinary_drain_reap_does_not_record_a_lifetime_restart() {
17924        let registry = Registry::default();
17925        let supervisor = Supervisor::new_for_test(
17926            Arc::new(Registry::default()),
17927            RestartPolicy::new(3, Duration::ZERO),
17928        );
17929        let runtime = supervisor.runtime_config();
17930        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17931        let spec = ModuleSpec {
17932            script: None,
17933            module_id: "ordinary-drain".to_string(),
17934            program: fake_aft_stub_path(),
17935            args: Vec::new(),
17936            env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
17937            reserved: false,
17938            reserved_prefixes: Vec::new(),
17939            protocol: ModuleProtocol::Subc,
17940            overlap: Default::default(),
17941            carry_containment: false,
17942        };
17943        let child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
17944
17945        drain_child_to_state(
17946            &spec.module_id,
17947            spec.protocol,
17948            // The child exits on its own; no signal may change the exit this
17949            // test classifies.
17950            StopNotice::SentOverConnection,
17951            &registry,
17952            None,
17953            &snapshot,
17954            &runtime.terminal_ring,
17955            &runtime.spawn_events,
17956            child,
17957            Duration::from_secs(1),
17958            ModuleState::Stopped,
17959            Some(false),
17960            &super::FailureContext::operator(),
17961        )
17962        .await
17963        .unwrap();
17964
17965        let state = lock_snapshot(&snapshot).unwrap();
17966        assert_eq!(
17967            state.last_exit.as_ref().map(|exit| exit.kind),
17968            Some(ExitKind::Crash)
17969        );
17970        assert_eq!(state.lifetime_restarts, 0);
17971        assert_eq!(state.crash_restarts.len(), 0);
17972    }
17973
17974    #[test]
17975    fn fatal_connection_teardown_cannot_arm_a_marker_for_a_surviving_process() {
17976        // The server's generic fatal-routing branch only knows that the
17977        // connection failed; it does not know that the daemon deliberately
17978        // initiated a process-killing severance. Keep this seam explicit so a
17979        // future connection error path cannot silently reintroduce the stale
17980        // exemption that mislabels a later genuine crash.
17981        assert!(!include_str!("server.rs")
17982            .contains("router.record_deliberate_connection_severance(ctx.connection_id)"));
17983    }
17984
17985    /// The `route.closed` `drained` value must be the quiescence wait's own
17986    /// measurement (`Ok`), never invented -- except on `Err`, where there is no
17987    /// measurement at all and `false` is the one honest constant. This is the exact
17988    /// logic `begin_forwarding_drain_with` now applies before sending `route.closed`
17989    /// on every return path, including the one that used to return early via `?`
17990    /// with `route.closing` already sent and no `route.closed` ever following.
17991    #[test]
17992    fn drained_after_quiescence_wait_passes_ok_through_and_forces_false_on_err() {
17993        assert!(drained_after_quiescence_wait(&Ok(true)));
17994        assert!(!drained_after_quiescence_wait(&Ok(false)));
17995        assert!(!drained_after_quiescence_wait(&Err(
17996            SuperviseError::StatePoisoned { module_id: None }
17997        )));
17998    }
17999
18000    /// `supervise_loop`'s `wait()`-error arm now calls `record_terminal` like every
18001    /// other exit path does, so a module whose child `wait()` itself errored (e.g.
18002    /// already reaped out-of-band) still leaves a terminal record rather than none
18003    /// at all. Triggering the real `wait()` I/O error from an integration test would
18004    /// need a genuine already-reaped-child race, which is OS-specific and not
18005    /// something this suite attempts elsewhere; this test instead verifies the
18006    /// record produced for that arm end-to-end through the real `TerminalRing`, and
18007    /// the call site itself is verified by inspection to sit in that exact arm.
18008    #[test]
18009    fn wait_error_exit_report_records_a_failed_terminal_with_no_code_or_signal() {
18010        let ring = Arc::new(Mutex::new(TerminalRing::new(
18011            TerminalRingConfig::default(),
18012            0,
18013        )));
18014        record_wait_error_terminal("wait-error", &ring, &super::SpawnEventFeed::default());
18015
18016        let snapshot = ring.lock().unwrap().snapshot();
18017        assert_eq!(snapshot.entries.len(), 1);
18018        let entry = &snapshot.entries[0];
18019        assert_eq!(entry.exit_code, None);
18020        assert_eq!(entry.exit_signal, None);
18021        assert_eq!(entry.disposition, TerminalDisposition::Failed);
18022    }
18023
18024    /// A launch is numbered before it starts. One that never runs keeps its
18025    /// number, and the next launch of the module is numbered after it.
18026    #[test]
18027    fn spawn_generation_of_a_failed_launch_is_never_reused() {
18028        let feed = super::SpawnEventFeed::default();
18029        feed.configure_incarnation("launch-numbering".to_string());
18030        let (incarnation, failed) = feed.allocate_generation("relaunched");
18031        assert_eq!(incarnation, "launch-numbering");
18032        let (_, next) = feed.allocate_generation("relaunched");
18033        assert!(next > failed);
18034        assert_eq!(feed.emit_spawned("relaunched", Some(next), 7, 1), next);
18035        // A process with no pre-allocated number is numbered after both.
18036        assert!(feed.emit_spawned("relaunched", None, 8, 2) > next);
18037        assert_eq!(
18038            feed.allocate_generation("other").1,
18039            1,
18040            "numbering is per module"
18041        );
18042    }
18043
18044    #[test]
18045    fn wait_error_exit_path_preserves_spawn_event_density() {
18046        let feed = super::SpawnEventFeed::default();
18047        feed.configure_incarnation("wait-error-density".to_string());
18048        feed.emit_spawned("wait-error", None, 41, 1);
18049        let ring = Arc::new(Mutex::new(TerminalRing::new(
18050            TerminalRingConfig::default(),
18051            0,
18052        )));
18053
18054        record_wait_error_terminal("wait-error", &ring, &feed);
18055        feed.emit_spawned("after-wait-error", None, 42, 2);
18056
18057        let state = feed.0.lock().unwrap();
18058        let sequences = state
18059            .events
18060            .iter()
18061            .map(|event| event.cursor.seq)
18062            .collect::<Vec<_>>();
18063        assert_eq!(sequences, vec![1, 2, 3]);
18064        assert_eq!(state.events[1].kind, SpawnEventKind::Exited);
18065        assert_eq!(state.events[1].exit_code, None);
18066        assert_eq!(state.events[1].exit_signal, None);
18067    }
18068
18069    /// Pins the report's `kind` too: the wait-error arm treats an unwaitable child
18070    /// as a crash (matching `fail_snapshot`'s `Failed` disposition for this arm),
18071    /// not a clean exit it never actually observed.
18072    #[test]
18073    fn wait_error_exit_report_is_classified_as_a_crash() {
18074        assert_eq!(wait_error_exit_report().kind, ExitKind::Crash);
18075    }
18076}
18077
18078#[cfg(all(test, unix))]
18079mod restart_ordering_tests {
18080    use super::*;
18081    use std::io::Write;
18082    use tokio::io::AsyncReadExt;
18083
18084    #[test]
18085    #[ignore = "child process fixture"]
18086    fn serving_child() {
18087        let Ok(address_file) = std::env::var("RESTART_TEST_ADDRESS_FILE") else {
18088            return;
18089        };
18090        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
18091        std::fs::write(address_file, listener.local_addr().unwrap().to_string()).unwrap();
18092        for stream in listener.incoming() {
18093            writeln!(stream.unwrap(), "{}", std::process::id()).unwrap();
18094        }
18095    }
18096
18097    async fn restart_before_publication(requests: usize) {
18098        let home = cortexkit_test_support::ScratchDir::new("restart-before-publication");
18099        let address_file = home.path().join("address");
18100        let spec = ModuleSpec {
18101            script: None,
18102            module_id: "restart-serving-child".into(),
18103            program: std::env::current_exe().unwrap(),
18104            args: vec![
18105                "--exact".into(),
18106                "supervise::restart_ordering_tests::serving_child".into(),
18107                "--ignored".into(),
18108                "--nocapture".into(),
18109            ],
18110            env: vec![(
18111                "RESTART_TEST_ADDRESS_FILE".into(),
18112                address_file.display().to_string(),
18113            )],
18114            reserved: false,
18115            reserved_prefixes: vec![],
18116            protocol: ModuleProtocol::None,
18117            overlap: Default::default(),
18118            carry_containment: false,
18119        };
18120        let mut supervisor =
18121            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
18122        let (spawned_tx, spawned_rx) = oneshot::channel();
18123        let spawned_tx = Mutex::new(Some(spawned_tx));
18124        let (release_tx, release_rx) = std::sync::mpsc::channel();
18125        let release_rx = Mutex::new(release_rx);
18126        // Hold publication, not the child: it must answer a real request before
18127        // the restart enters the queue, even though status still has generation 0.
18128        supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |_| {
18129            spawned_tx.lock().unwrap().take().unwrap().send(()).unwrap();
18130            release_rx
18131                .lock()
18132                .unwrap()
18133                .recv_timeout(Duration::from_secs(20))
18134                .unwrap();
18135        })));
18136        let registered = supervisor
18137            .register_configured_with_health(
18138                spec.clone(),
18139                true,
18140                HealthConfig::default(),
18141                None,
18142                RestartPolicy::new(3, Duration::ZERO),
18143                DEFAULT_REGISTER_TIMEOUT,
18144            )
18145            .unwrap();
18146        let module = registered.module.clone();
18147        let startup = tokio::task::spawn_blocking(move || {
18148            supervisor.start_registered_configured(registered, None, true)
18149        });
18150        spawned_rx.await.unwrap();
18151        let old_pid = tokio::time::timeout(Duration::from_secs(10), async {
18152            let address = loop {
18153                if let Ok(address) = std::fs::read_to_string(&address_file) {
18154                    if !address.is_empty() {
18155                        break address;
18156                    }
18157                }
18158                tokio::time::sleep(Duration::from_millis(1)).await;
18159            };
18160            let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();
18161            let mut reply = String::new();
18162            stream.read_to_string(&mut reply).await.unwrap();
18163            reply.trim().parse::<u32>().unwrap()
18164        })
18165        .await
18166        .expect("child must serve before generation publication");
18167        assert_eq!(
18168            lock_snapshot(&module.inner.snapshot)
18169                .unwrap()
18170                .spawn_generation,
18171            0
18172        );
18173        let mut replies = Vec::new();
18174        for _ in 0..requests {
18175            let mut restart = Box::pin(module.restart(Some(0)));
18176            // Poll the public API through queue admission, leaving only its ACK
18177            // pending. The monitor cannot consume the command until released.
18178            std::future::poll_fn(|cx| {
18179                assert!(std::future::Future::poll(restart.as_mut(), cx).is_pending());
18180                std::task::Poll::Ready(())
18181            })
18182            .await;
18183            replies.push(restart);
18184        }
18185        release_tx.send(()).unwrap();
18186        startup.await.unwrap().unwrap();
18187        for reply in replies {
18188            reply.await.unwrap();
18189        }
18190        // Restart schedules its replacement after completing the handler. Wait
18191        // for that separate actor turn before placing the command barrier.
18192        let replacement = tokio::time::timeout(Duration::from_secs(10), async {
18193            loop {
18194                if lock_snapshot(&module.inner.snapshot)
18195                    .unwrap()
18196                    .spawn_generation
18197                    > 1
18198                {
18199                    break;
18200                }
18201                tokio::time::sleep(Duration::from_millis(1)).await;
18202            }
18203        })
18204        .await;
18205        // Commands are handled serially. The update-spec reply proves every
18206        // restart handler has finished before we inspect the snapshot; restart's
18207        // own ACK only acknowledges initiation, not replacement completion.
18208        module.update_spec_for_test(spec).await.unwrap();
18209        let (generation, pid) = {
18210            let state = lock_snapshot(&module.inner.snapshot).unwrap();
18211            (state.spawn_generation, state.pid)
18212        };
18213        module.stop().await.unwrap();
18214        replacement.expect("restart must publish a replacement for the already-serving child");
18215        assert_ne!(
18216            pid,
18217            Some(old_pid),
18218            "a serving child predating the restart must be replaced"
18219        );
18220        assert_eq!(generation, 2, "queued restarts must share one replacement");
18221    }
18222
18223    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
18224    async fn restart_received_after_serving_before_generation_publication_replaces_child() {
18225        restart_before_publication(1).await;
18226    }
18227
18228    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
18229    async fn restart_queued_behind_restart_does_not_kill_its_replacement() {
18230        restart_before_publication(2).await;
18231    }
18232
18233    #[tokio::test]
18234    async fn restart_queued_before_replacement_spawn_keeps_the_new_child() {
18235        let supervisor =
18236            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
18237        let registered = supervisor
18238            .register_configured_with_health(
18239                ModuleSpec {
18240                    script: None,
18241                    module_id: "queued-before-replacement".into(),
18242                    // `/bin/sleep` itself, not `/bin/sh -c "exec sleep"`: on
18243                    // macOS a module whose running image is not the configured
18244                    // program is refused once its exec is confirmed (see
18245                    // `record_write_stall_tests::sleeping_spec`).
18246                    program: "/bin/sleep".into(),
18247                    args: vec!["600".into()],
18248                    env: vec![],
18249                    reserved: false,
18250                    reserved_prefixes: vec![],
18251                    protocol: ModuleProtocol::None,
18252                    overlap: Default::default(),
18253                    carry_containment: false,
18254                },
18255                true,
18256                HealthConfig::default(),
18257                None,
18258                RestartPolicy::default(),
18259                DEFAULT_REGISTER_TIMEOUT,
18260            )
18261            .unwrap();
18262        let RegisteredConfiguredModule {
18263            mut spec,
18264            mut runtime,
18265            module,
18266            mut commands,
18267        } = registered;
18268        let snapshot = &module.inner.snapshot;
18269        let mut restart = Box::pin(module.restart(Some(0)));
18270        std::future::poll_fn(|cx| {
18271            assert!(std::future::Future::poll(restart.as_mut(), cx).is_pending());
18272            std::task::Poll::Ready(())
18273        })
18274        .await;
18275        // Drive the actor explicitly so a replacement is definitely spawned
18276        // after receipt, but before this queued command is dequeued.
18277        let mut child = Some(spawn_and_mark_running(&spec, &runtime, snapshot).unwrap());
18278        let replacement_pid = child.as_ref().unwrap().id();
18279        let command = commands.recv().await.unwrap();
18280        assert!(
18281            handle_supervisor_command(
18282                command,
18283                &mut spec,
18284                &mut runtime,
18285                &supervisor.registry,
18286                &supervisor.process_liveness,
18287                snapshot,
18288                &mut child,
18289                &mut commands,
18290                &mut VecDeque::new(),
18291            )
18292            .await
18293        );
18294        restart.await.unwrap();
18295        let kept_pid = child.as_ref().and_then(SupervisedChild::id);
18296        let pending = lock_snapshot(snapshot).unwrap().respawn_pending;
18297        if let Some(mut child) = child {
18298            child.start_kill().unwrap();
18299            child.wait().await.unwrap();
18300        }
18301        assert_eq!(
18302            kept_pid, replacement_pid,
18303            "a newer replacement must survive"
18304        );
18305        assert!(
18306            !pending,
18307            "a satisfied restart must not schedule another spawn"
18308        );
18309    }
18310}
18311
18312#[cfg(all(test, unix))]
18313mod health_event_tests {
18314    use super::*;
18315    use cortexkit_test_support::ScratchDir;
18316    use subc_protocol::{manifest::Concurrency, session::ModuleControlResponse};
18317
18318    struct Actor {
18319        module: SupervisedModule,
18320        registry: Arc<Registry>,
18321        forwarding: Arc<ForwardingTable>,
18322        spec: ModuleSpec,
18323        health: HealthConfig,
18324        rx: mpsc::Receiver<crate::router::OutboundFrame>,
18325        roster: ChildRoster,
18326        _home: ScratchDir,
18327    }
18328
18329    async fn wait_for<T>(reason: &str, mut observe: impl FnMut() -> Option<T>) -> T {
18330        // OS exec and socket readiness are real I/O. Stay runnable while waiting
18331        // for an observed condition, rather than letting paused time auto-advance
18332        // deadlines or assuming a fixed number of yields finishes the work.
18333        let deadline = std::time::Instant::now() + Duration::from_secs(10);
18334        let tick = Instant::now();
18335        loop {
18336            if let Some(value) = observe() {
18337                assert_eq!(Instant::now(), tick, "{reason} must not wait for a timer");
18338                return value;
18339            }
18340            assert!(
18341                std::time::Instant::now() < deadline,
18342                "timed out waiting for {reason}"
18343            );
18344            tokio::task::yield_now().await;
18345        }
18346    }
18347
18348    impl Actor {
18349        async fn start(protocol: ModuleProtocol, cadence: Duration) -> Self {
18350            Self::start_with_policy(
18351                protocol,
18352                cadence,
18353                DEFAULT_REGISTER_TIMEOUT,
18354                RestartPolicy::new(3, Duration::ZERO),
18355            )
18356            .await
18357        }
18358
18359        async fn start_with_policy(
18360            protocol: ModuleProtocol,
18361            cadence: Duration,
18362            register_timeout: Duration,
18363            policy: RestartPolicy,
18364        ) -> Self {
18365            let home = ScratchDir::new("health-events");
18366            let registry = Arc::new(Registry::default());
18367            let forwarding = Arc::new(ForwardingTable::default());
18368            let health = HealthConfig {
18369                cadence,
18370                deadline: Duration::from_secs(3600),
18371                ..HealthConfig::default()
18372            };
18373            let supervisor = Supervisor::new_for_test(registry.clone(), policy)
18374                .with_forwarding(forwarding.clone())
18375                .with_health_config(health.clone());
18376            let spec = ModuleSpec {
18377                script: None,
18378                module_id: "event-health-child".into(),
18379                // `/bin/sleep` itself, not `/bin/sh -c "exec sleep"`: on macOS
18380                // the privacy trampoline refuses a module whose running image
18381                // is not the configured program, and `start` below waits for
18382                // the process to be confirmed (`reported_pid`). The shell form
18383                // passed only while the image check ran before the shell had
18384                // replaced itself with `sleep` (see
18385                // `record_write_stall_tests::sleeping_spec`).
18386                program: PathBuf::from("/bin/sleep"),
18387                // The process stays alive but has no real bus peer. Registrations
18388                // below exercise the same registry writes as accepted HELLOs.
18389                args: vec!["600".into()],
18390                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
18391                    .into_iter()
18392                    .map(|key| (key.into(), home.path().display().to_string()))
18393                    .collect(),
18394                reserved: false,
18395                reserved_prefixes: vec![],
18396                protocol,
18397                overlap: Default::default(),
18398                carry_containment: false,
18399            };
18400            let module = supervisor
18401                .supervise_configured_requested(
18402                    spec.clone(),
18403                    true,
18404                    health.clone(),
18405                    Some(0),
18406                    policy,
18407                    register_timeout,
18408                    None,
18409                )
18410                .unwrap();
18411            let (_, rx) = mpsc::channel(8);
18412            let actor = Self {
18413                module,
18414                registry,
18415                forwarding,
18416                spec,
18417                health,
18418                rx,
18419                roster: supervisor.child_roster.clone(),
18420                _home: home,
18421            };
18422            actor
18423                .wait_for_select(|checkpoint| checkpoint.generation > 0)
18424                .await;
18425            actor
18426        }
18427
18428        async fn expire_registration_wait(&self, remaining: Duration) {
18429            tokio::time::advance(remaining).await;
18430            wait_for("registration timeout TERM grace", || {
18431                lock_snapshot(&self.module.inner.snapshot)
18432                    .unwrap()
18433                    .actor_select
18434                    .is_none()
18435                    .then_some(())
18436            })
18437            .await;
18438            tokio::time::advance(crate::child_roster::TERM_TO_KILL).await;
18439        }
18440
18441        fn turns(&self) -> u64 {
18442            lock_snapshot(&self.module.inner.snapshot)
18443                .unwrap()
18444                .actor_turns
18445        }
18446
18447        async fn wait_for_select(
18448            &self,
18449            expected: impl Fn(&ActorSelectCheckpoint) -> bool,
18450        ) -> ActorSelectCheckpoint {
18451            wait_for("actor select checkpoint", || {
18452                let state = lock_snapshot(&self.module.inner.snapshot).unwrap();
18453                state.actor_select.filter(|checkpoint| {
18454                    checkpoint.generation == state.spawn_generation
18455                        && state.state == ModuleState::Running
18456                        && state.process_alive
18457                        && state.reported_pid().is_some()
18458                        && expected(checkpoint)
18459                })
18460            })
18461            .await
18462        }
18463
18464        fn hello(&mut self, connection: u64, health: bool) {
18465            let manifest =
18466                subc_protocol::manifest::ModuleManifest::builder(&self.spec.module_id, "1.0.0")
18467                    .protocol_ver(subc_protocol::PROTOCOL_VERSION)
18468                    .build();
18469            let connection = ConnectionId::new(connection);
18470            let (tx, rx) = mpsc::channel(8);
18471            self.rx = rx;
18472            self.forwarding
18473                .register_module_connection(
18474                    connection,
18475                    self.spec.module_id.clone(),
18476                    subc_protocol::PROTOCOL_VERSION,
18477                    Concurrency::ModuleManaged,
18478                    FrameSink::new(tx),
18479                )
18480                .unwrap();
18481            self.registry
18482                .register_with_control_ops(
18483                    manifest,
18484                    subc_protocol::PROTOCOL_VERSION,
18485                    connection,
18486                    if health {
18487                        vec![MODULE_CONTROL_OP_HEALTH_CHECK.into()]
18488                    } else {
18489                        vec![]
18490                    },
18491                )
18492                .unwrap();
18493        }
18494
18495        async fn probe(&mut self) -> crate::router::OutboundFrame {
18496            let frame = wait_for("outbound health probe", || match self.rx.try_recv() {
18497                Ok(frame) => Some(frame),
18498                Err(mpsc::error::TryRecvError::Empty) => None,
18499                Err(mpsc::error::TryRecvError::Disconnected) => panic!("health peer disconnected"),
18500            })
18501            .await;
18502            let body: Value = serde_json::from_slice(&frame.body).unwrap();
18503            assert_eq!(body["op"], MODULE_CONTROL_OP_HEALTH_CHECK);
18504            frame
18505        }
18506
18507        fn no_probe(&mut self) {
18508            assert!(matches!(
18509                self.rx.try_recv(),
18510                Err(mpsc::error::TryRecvError::Empty)
18511            ));
18512        }
18513
18514        fn answer(&self, connection: u64, frame: crate::router::OutboundFrame) {
18515            self.forwarding
18516                .complete_module_control_rpc(
18517                    ConnectionId::new(connection),
18518                    frame.header.corr,
18519                    Some(MODULE_CONTROL_OP_HEALTH_CHECK),
18520                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
18521                        status: HealthStatus::Ok,
18522                        detail: None,
18523                        metrics: None,
18524                    }),
18525                )
18526                .unwrap();
18527        }
18528    }
18529
18530    #[tokio::test(start_paused = true)]
18531    async fn registration_timeout_kills_at_120_seconds_and_respawns() {
18532        let actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18533        let initial = actor.module.status().unwrap();
18534        tokio::time::advance(Duration::from_secs(119)).await;
18535        tokio::task::yield_now().await;
18536        assert_eq!(actor.module.status().unwrap().pid, initial.pid);
18537        assert!(actor.module.terminal_history().entries.is_empty());
18538        actor.expire_registration_wait(Duration::from_secs(1)).await;
18539        actor
18540            .wait_for_select(|at| at.generation > initial.spawn_generation)
18541            .await;
18542        let status = actor.module.status().unwrap();
18543        assert_ne!(status.pid, initial.pid);
18544        assert!(!cortexkit_test_support::process_alive(
18545            initial.pid.unwrap() as i32
18546        ));
18547        assert_eq!(status.restart_count, 1);
18548        assert_eq!(status.last_exit.unwrap().kind, ExitKind::Crash);
18549        let entries = actor.module.terminal_history().entries;
18550        assert_eq!(entries.len(), 1);
18551        assert_eq!(
18552            entries[0].disposition_detail.as_deref(),
18553            Some("registration_timeout")
18554        );
18555        actor.module.stop().await.unwrap();
18556    }
18557
18558    #[tokio::test(start_paused = true)]
18559    async fn registration_timeout_is_cancelled_by_hello_at_119_seconds() {
18560        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18561        let pid = actor.module.status().unwrap().pid;
18562        tokio::time::advance(Duration::from_secs(119)).await;
18563        actor.hello(1, false);
18564        let registered = actor
18565            .wait_for_select(|at| at.registered_connection.is_some())
18566            .await;
18567        assert_eq!(
18568            registered.wake_after, None,
18569            "HELLO must cancel the deadline"
18570        );
18571        tokio::time::advance(Duration::from_secs(300)).await;
18572        tokio::task::yield_now().await;
18573        assert_eq!(actor.module.status().unwrap().pid, pid);
18574        assert!(actor.module.terminal_history().entries.is_empty());
18575        // A disconnect after the first HELLO must not re-arm a startup timer.
18576        actor
18577            .registry
18578            .deregister_connection(ConnectionId::new(1))
18579            .unwrap();
18580        actor
18581            .wait_for_select(|at| at.registered_connection.is_none())
18582            .await;
18583        tokio::time::advance(Duration::from_secs(300)).await;
18584        tokio::task::yield_now().await;
18585        assert_eq!(actor.module.status().unwrap().pid, pid);
18586        assert!(actor.module.terminal_history().entries.is_empty());
18587        actor.module.stop().await.unwrap();
18588
18589        let mut transient = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18590        let pid = transient.module.status().unwrap().pid;
18591        tokio::time::advance(Duration::from_secs(119)).await;
18592        let turns = transient.turns();
18593        // Both writes happen before the supervisor can refresh the registry.
18594        // An accepted HELLO must remain evidence after its connection is gone.
18595        transient.hello(1, false);
18596        transient
18597            .registry
18598            .deregister_connection(ConnectionId::new(1))
18599            .unwrap();
18600        let parked = transient.wait_for_select(|at| at.turn > turns).await;
18601        assert_eq!(
18602            parked.wake_after, None,
18603            "transient HELLO must cancel the deadline"
18604        );
18605        tokio::time::advance(Duration::from_secs(300)).await;
18606        tokio::task::yield_now().await;
18607        assert_eq!(transient.module.status().unwrap().pid, pid);
18608        assert!(transient.module.terminal_history().entries.is_empty());
18609        transient.module.stop().await.unwrap();
18610    }
18611
18612    #[tokio::test(start_paused = true)]
18613    async fn registration_timeouts_exhaust_budget_and_schedule_slow_retry() {
18614        let actor = Actor::start_with_policy(
18615            ModuleProtocol::Subc,
18616            Duration::from_secs(30),
18617            Duration::from_secs(10),
18618            RestartPolicy::new(1, Duration::ZERO),
18619        )
18620        .await;
18621        let generation = actor.module.status().unwrap().spawn_generation;
18622        actor
18623            .expire_registration_wait(Duration::from_secs(10))
18624            .await;
18625        actor.wait_for_select(|at| at.generation > generation).await;
18626        actor
18627            .expire_registration_wait(Duration::from_secs(10))
18628            .await;
18629        let retry = wait_for("failed retry schedule", || {
18630            let state = lock_snapshot(&actor.module.inner.snapshot).unwrap();
18631            (state.state == ModuleState::Failed)
18632                .then_some(state.failed_retry.pending)
18633                .flatten()
18634        })
18635        .await;
18636        assert_eq!(retry.delay, Duration::from_secs(600));
18637        assert_eq!(retry.attempt, 1);
18638        let entries = actor.module.terminal_history().entries;
18639        assert_eq!(entries.len(), 2);
18640        assert_eq!(entries[1].disposition, TerminalDisposition::Failed);
18641        assert!(entries[1]
18642            .disposition_detail
18643            .as_deref()
18644            .unwrap()
18645            .contains("registration_timeout"));
18646        tokio::time::advance(Duration::from_secs(599)).await;
18647        tokio::task::yield_now().await;
18648        assert_eq!(actor.module.state().unwrap(), ModuleState::Failed);
18649        tokio::time::advance(Duration::from_secs(1)).await;
18650        actor
18651            .wait_for_select(|at| at.generation > generation + 1)
18652            .await;
18653        // The slow retry is another ordinary spawn, with its own HELLO budget.
18654        actor
18655            .expire_registration_wait(Duration::from_secs(10))
18656            .await;
18657        wait_for("slow retry registration timeout", || {
18658            (actor.module.terminal_history().entries.len() == 3).then_some(())
18659        })
18660        .await;
18661        actor.module.stop().await.unwrap();
18662    }
18663
18664    #[tokio::test(start_paused = true)]
18665    async fn registration_timeout_honours_ten_second_override() {
18666        let actor = Actor::start_with_policy(
18667            ModuleProtocol::Subc,
18668            Duration::from_secs(30),
18669            Duration::from_secs(10),
18670            RestartPolicy::new(3, Duration::ZERO),
18671        )
18672        .await;
18673        let generation = actor.module.status().unwrap().spawn_generation;
18674        tokio::time::advance(Duration::from_secs(9)).await;
18675        tokio::task::yield_now().await;
18676        assert!(actor.module.terminal_history().entries.is_empty());
18677        actor.expire_registration_wait(Duration::from_secs(1)).await;
18678        actor.wait_for_select(|at| at.generation > generation).await;
18679        assert_eq!(actor.module.terminal_history().entries.len(), 1);
18680        actor.module.stop().await.unwrap();
18681    }
18682
18683    #[tokio::test]
18684    async fn registration_timeout_kills_term_ignoring_helper_before_reaping_leader() {
18685        use std::os::unix::process::{CommandExt, ExitStatusExt};
18686
18687        struct Helper(std::process::Child);
18688        impl Drop for Helper {
18689            fn drop(&mut self) {
18690                // This handle still owns the helper until wait returns. Never
18691                // clean up its old process group after the leader is reaped.
18692                if matches!(self.0.try_wait(), Ok(None)) {
18693                    let _ = self.0.kill();
18694                    let _ = self.0.wait();
18695                }
18696            }
18697        }
18698
18699        let home = ScratchDir::new("registration-timeout-helper");
18700        let supervisor = Supervisor::new_for_test(
18701            Arc::new(Registry::default()),
18702            RestartPolicy::new(0, Duration::ZERO),
18703        );
18704        let spec = ModuleSpec {
18705            script: None,
18706            module_id: "registration-timeout-group".into(),
18707            program: "/bin/sleep".into(),
18708            args: vec!["120".into()],
18709            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
18710                .into_iter()
18711                .map(|key| (key.into(), home.path().display().to_string()))
18712                .collect(),
18713            reserved: false,
18714            reserved_prefixes: vec![],
18715            protocol: ModuleProtocol::Subc,
18716            overlap: Default::default(),
18717            carry_containment: false,
18718        };
18719        let module = supervisor
18720            .supervise_configured_requested(
18721                spec,
18722                true,
18723                HealthConfig::default(),
18724                None,
18725                RestartPolicy::new(0, Duration::ZERO),
18726                Duration::from_secs(10),
18727                None,
18728            )
18729            .unwrap();
18730        let leader = timeout(Duration::from_secs(5), async {
18731            loop {
18732                if let Some(pid) = module.status().unwrap().pid {
18733                    break pid;
18734                }
18735                sleep(Duration::from_millis(5)).await;
18736            }
18737        })
18738        .await
18739        .expect("supervised group leader must be reported before the deadline");
18740        assert!(leader > 1);
18741        let ready = home.join("helper.ready");
18742        // Own the helper separately so even a broken group kill can be cleaned
18743        // up by its own unreaped child handle, without signalling a stale pgid.
18744        let mut helper = Helper(
18745            std::process::Command::new("/bin/sh")
18746                .args([
18747                    "-c",
18748                    "trap '' TERM; : > \"$1\"; exec /bin/sleep 120",
18749                    "helper",
18750                ])
18751                .arg(&ready)
18752                .process_group(i32::try_from(leader).unwrap())
18753                .stdout(std::process::Stdio::null())
18754                .stderr(std::process::Stdio::null())
18755                .spawn()
18756                .unwrap(),
18757        );
18758        timeout(Duration::from_secs(5), async {
18759            while !ready.exists() {
18760                assert!(helper.0.try_wait().unwrap().is_none());
18761                sleep(Duration::from_millis(5)).await;
18762            }
18763        })
18764        .await
18765        .expect("helper must install TERM ignore before the registration deadline");
18766        let helper_pid =
18767            rustix::process::Pid::from_raw(i32::try_from(helper.0.id()).unwrap()).unwrap();
18768        rustix::process::kill_process(helper_pid, rustix::process::Signal::TERM).unwrap();
18769        sleep(Duration::from_millis(20)).await;
18770        assert!(
18771            helper.0.try_wait().unwrap().is_none(),
18772            "helper must ignore TERM"
18773        );
18774
18775        timeout(Duration::from_secs(20), async {
18776            while module.state().unwrap() != ModuleState::Failed {
18777                sleep(Duration::from_millis(5)).await;
18778            }
18779        })
18780        .await
18781        .expect("registration timeout must stop and reap the group leader");
18782        let helper_exit = timeout(Duration::from_secs(3), async {
18783            loop {
18784                if let Some(status) = helper.0.try_wait().unwrap() {
18785                    break status;
18786                }
18787                sleep(Duration::from_millis(5)).await;
18788            }
18789        })
18790        .await
18791        .expect("TERM-ignoring helper survived the registration timeout's group KILL");
18792        assert_eq!(helper_exit.signal(), Some(9));
18793        assert!(!cortexkit_test_support::process_alive(
18794            i32::try_from(leader).unwrap()
18795        ));
18796        assert_eq!(
18797            module.status().unwrap().last_exit.unwrap().kind,
18798            ExitKind::Crash
18799        );
18800        assert!(module.terminal_history().entries[0]
18801            .disposition_detail
18802            .as_deref()
18803            .unwrap()
18804            .contains("registration_timeout"));
18805        module.stop().await.unwrap();
18806    }
18807
18808    #[tokio::test(start_paused = true)]
18809    async fn registration_timeout_does_not_count_an_earlier_exit() {
18810        let actor = Actor::start_with_policy(
18811            ModuleProtocol::Subc,
18812            Duration::from_secs(30),
18813            DEFAULT_REGISTER_TIMEOUT,
18814            RestartPolicy::new(0, Duration::ZERO),
18815        )
18816        .await;
18817        let pid = actor.module.status().unwrap().pid.unwrap();
18818        rustix::process::kill_process(
18819            rustix::process::Pid::from_raw(pid as i32).unwrap(),
18820            rustix::process::Signal::TERM,
18821        )
18822        .unwrap();
18823        wait_for("early exit", || {
18824            (actor.module.state().unwrap() == ModuleState::Failed).then_some(())
18825        })
18826        .await;
18827        tokio::time::advance(Duration::from_secs(121)).await;
18828        tokio::task::yield_now().await;
18829        let entries = actor.module.terminal_history().entries;
18830        assert_eq!(entries.len(), 1);
18831        assert!(!entries[0]
18832            .disposition_detail
18833            .as_deref()
18834            .unwrap()
18835            .contains("registration_timeout"));
18836        assert_eq!(actor.module.status().unwrap().lifetime_restarts, 0);
18837        actor.module.stop().await.unwrap();
18838    }
18839
18840    #[tokio::test(start_paused = true)]
18841    async fn registration_timeout_is_cancelled_by_daemon_shutdown() {
18842        let actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18843        let pid = actor.module.status().unwrap().pid;
18844        tokio::time::advance(Duration::from_secs(119)).await;
18845        actor.roster.close();
18846        let turns = actor.turns();
18847        tokio::time::advance(Duration::from_secs(300)).await;
18848        let parked = actor.wait_for_select(|at| at.turn > turns).await;
18849        assert_eq!(parked.wake_after, None);
18850        assert_eq!(actor.module.status().unwrap().pid, pid);
18851        assert!(actor.module.terminal_history().entries.is_empty());
18852        actor.module.stop().await.unwrap();
18853        let status = actor.module.status().unwrap();
18854        assert_eq!(status.restart_count, 0);
18855        assert_eq!(
18856            actor.module.terminal_history().entries[0].disposition,
18857            TerminalDisposition::DaemonShutdown
18858        );
18859    }
18860
18861    #[tokio::test(start_paused = true)]
18862    async fn no_health_children_park_for_sixty_seconds() {
18863        let none = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
18864        let unregistered = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18865        let mut unadvertised = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18866        unadvertised.hello(1, false);
18867        // Include any one-off registration wake in the budget; receiving a
18868        // no-health HELLO must not turn a parked child into a polling child.
18869        // Advance in 10 ms steps so the old poll really executes ~6,000 turns;
18870        // a single 60 s jump would only observe one expired timer.
18871        for _ in 0..6000 {
18872            tokio::time::advance(Duration::from_millis(10)).await;
18873            tokio::task::yield_now().await;
18874        }
18875        for actor in [&none, &unregistered, &unadvertised] {
18876            assert!(
18877                actor.turns() <= 5,
18878                "no-health actor woke {} times",
18879                actor.turns()
18880            );
18881            assert_eq!(actor.module.state().unwrap(), ModuleState::Running);
18882        }
18883    }
18884
18885    #[tokio::test(start_paused = true)]
18886    async fn late_hello_starts_a_due_probe_in_the_notification_tick() {
18887        // With a zero cadence the first probe is due at once, so this measures
18888        // only how fast the registration notification starts health probing,
18889        // not the normal 30-33 s wait before a first probe (checked below).
18890        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::ZERO).await;
18891        let tick = Instant::now();
18892        actor.hello(1, true);
18893        actor.probe().await;
18894        assert_eq!(Instant::now(), tick, "HELLO must not wait for a poll");
18895    }
18896
18897    #[tokio::test(start_paused = true)]
18898    async fn hello_keeps_the_jittered_cadence_and_catalog_updates_do_not_reset_it() {
18899        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18900        let hello_tick = Instant::now();
18901        actor.hello(1, true);
18902        let armed = actor
18903            .wait_for_select(|checkpoint| {
18904                checkpoint.registered_connection == Some(ConnectionId::new(1))
18905                    && checkpoint.next_probe_at.is_some()
18906            })
18907            .await;
18908        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18909        assert!((Duration::from_secs(30)..Duration::from_secs(33)).contains(&delay));
18910        let first_deadline = hello_tick + delay;
18911        assert_eq!(armed.next_probe_at, Some(first_deadline));
18912        tokio::time::advance(Duration::from_secs(29)).await;
18913        let turns = actor.turns();
18914        actor
18915            .registry
18916            .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
18917            .unwrap();
18918        let updated = actor
18919            .wait_for_select(|checkpoint| checkpoint.turn > turns)
18920            .await;
18921        assert_eq!(
18922            updated.next_probe_at,
18923            Some(first_deadline),
18924            "catalog update must not reset cadence"
18925        );
18926        actor.no_probe();
18927        tokio::time::advance(first_deadline - Instant::now()).await;
18928        let frame = actor.probe().await;
18929        actor.answer(1, frame);
18930        let next = jittered_health_delay(&actor.spec.module_id, 1, actor.health.cadence);
18931        let next_deadline = Instant::now() + next;
18932        let rearmed = actor
18933            .wait_for_select(|checkpoint| {
18934                checkpoint
18935                    .next_probe_at
18936                    .is_some_and(|deadline| deadline > first_deadline)
18937            })
18938            .await;
18939        assert_eq!(rearmed.next_probe_at, Some(next_deadline));
18940        tokio::time::advance(next - Duration::from_nanos(1)).await;
18941        actor.no_probe();
18942        tokio::time::advance(Duration::from_nanos(1)).await;
18943        actor.probe().await;
18944    }
18945
18946    #[tokio::test(start_paused = true)]
18947    async fn disconnect_disarms_and_reconnect_rearms_health() {
18948        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18949        actor.hello(1, true);
18950        actor
18951            .wait_for_select(|checkpoint| {
18952                checkpoint.registered_connection == Some(ConnectionId::new(1))
18953                    && checkpoint.next_probe_at.is_some()
18954            })
18955            .await;
18956        let turns = actor.turns();
18957        let tick = Instant::now();
18958        actor
18959            .registry
18960            .deregister_connection(ConnectionId::new(1))
18961            .unwrap();
18962        let disarmed = actor
18963            .wait_for_select(|checkpoint| {
18964                checkpoint.turn > turns && checkpoint.registered_connection.is_none()
18965            })
18966            .await;
18967        assert_eq!(disarmed.next_probe_at, None);
18968        assert_eq!(disarmed.wake_after, None);
18969        assert_eq!(
18970            Instant::now(),
18971            tick,
18972            "disconnect must disarm in the notification tick"
18973        );
18974        tokio::time::advance(Duration::from_secs(60)).await;
18975        actor.no_probe();
18976        let reconnect_tick = Instant::now();
18977        actor.hello(2, true);
18978        let rearmed = actor
18979            .wait_for_select(|checkpoint| {
18980                checkpoint.registered_connection == Some(ConnectionId::new(2))
18981                    && checkpoint.next_probe_at.is_some()
18982            })
18983            .await;
18984        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18985        assert_eq!(rearmed.next_probe_at, Some(reconnect_tick + delay));
18986        tokio::time::advance(delay).await;
18987        actor.probe().await;
18988    }
18989
18990    #[tokio::test(start_paused = true)]
18991    async fn reregistration_without_health_disarms_the_old_schedule() {
18992        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18993        actor.hello(1, true);
18994        actor
18995            .wait_for_select(|checkpoint| {
18996                checkpoint.registered_connection == Some(ConnectionId::new(1))
18997                    && checkpoint.next_probe_at.is_some()
18998            })
18999            .await;
19000        actor
19001            .registry
19002            .deregister_connection(ConnectionId::new(1))
19003            .unwrap();
19004        actor.hello(2, false);
19005        let disarmed = actor
19006            .wait_for_select(|checkpoint| {
19007                checkpoint.registered_connection == Some(ConnectionId::new(2))
19008            })
19009            .await;
19010        assert_eq!(disarmed.next_probe_at, None);
19011        assert_eq!(disarmed.wake_after, None);
19012        tokio::time::advance(Duration::from_secs(60)).await;
19013        actor.no_probe();
19014    }
19015
19016    #[tokio::test(start_paused = true)]
19017    async fn restart_waits_for_its_own_hello_before_rearming_health() {
19018        let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
19019        actor.hello(1, true);
19020        let armed = actor
19021            .wait_for_select(|checkpoint| {
19022                checkpoint.registered_connection == Some(ConnectionId::new(1))
19023                    && checkpoint.next_probe_at.is_some()
19024            })
19025            .await;
19026        // Simulate the old process's connection closing before the restart
19027        // tears the process down. The replacement process has started but has
19028        // not sent its HELLO, so it is not registered.
19029        actor
19030            .registry
19031            .deregister_connection(ConnectionId::new(1))
19032            .unwrap();
19033        actor.module.restart(Some(0)).await.unwrap();
19034        let parked = actor
19035            .wait_for_select(|checkpoint| {
19036                checkpoint.generation > armed.generation
19037                    && checkpoint.registered_connection.is_none()
19038                    && checkpoint.next_probe_at.is_none()
19039            })
19040            .await;
19041        assert_eq!(parked.wake_after, Some(DEFAULT_REGISTER_TIMEOUT));
19042        actor.rx.close();
19043        // Drain the stop notice the restart queued for the old process's connection,
19044        // so it isn't mistaken for traffic to the replacement.
19045        while actor.rx.try_recv().is_ok() {}
19046        let turns = actor.turns();
19047        tokio::time::advance(Duration::from_secs(60)).await;
19048        let after = actor.turns();
19049        eprintln!(
19050            "restart park turns: before={turns} after={after} delta={}",
19051            after - turns
19052        );
19053        assert_eq!(after, turns, "replacement must park before HELLO");
19054        let hello_tick = Instant::now();
19055        actor.hello(2, true);
19056        let rearmed = actor
19057            .wait_for_select(|checkpoint| {
19058                checkpoint.registered_connection == Some(ConnectionId::new(2))
19059                    && checkpoint.next_probe_at.is_some()
19060            })
19061            .await;
19062        let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
19063        assert_eq!(rearmed.next_probe_at, Some(hello_tick + delay));
19064        tokio::time::advance(delay).await;
19065        actor.probe().await;
19066    }
19067
19068    #[tokio::test(start_paused = true)]
19069    async fn http_probe_waits_a_full_cadence_for_each_spawn() {
19070        use tokio::{
19071            io::{AsyncReadExt, AsyncWriteExt},
19072            net::TcpListener,
19073        };
19074        let mut actor = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
19075        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
19076        actor.health.http = Some(format!("http://{}/healthz", listener.local_addr().unwrap()));
19077        let (started_tx, mut started_rx) = mpsc::channel(8);
19078        let peer = tokio::spawn(async move {
19079            loop {
19080                let (mut socket, _) = listener.accept().await.unwrap();
19081                let mut request = [0; 1024];
19082                assert!(socket.read(&mut request).await.unwrap() > 0);
19083                started_tx.send(Instant::now()).await.unwrap();
19084                socket
19085                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
19086                    .await
19087                    .unwrap();
19088            }
19089        });
19090        actor
19091            .module
19092            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
19093            .await
19094            .unwrap();
19095        let first_tick = Instant::now();
19096        let first = actor
19097            .wait_for_select(|checkpoint| checkpoint.next_probe_at.is_some())
19098            .await;
19099        assert!(first.next_probe_at.unwrap() >= first_tick + actor.health.cadence);
19100        assert!(started_rx.try_recv().is_err());
19101
19102        // Restart just before the old deadline: reusing it would give the new
19103        // process only one second to start, rather than a full cadence.
19104        tokio::time::advance(
19105            first.next_probe_at.unwrap() - Instant::now() - Duration::from_secs(1),
19106        )
19107        .await;
19108        actor.module.restart(Some(0)).await.unwrap();
19109        let spawn_tick = Instant::now();
19110        let replacement = actor
19111            .wait_for_select(|checkpoint| checkpoint.generation > first.generation)
19112            .await;
19113        let deadline = replacement.next_probe_at.unwrap();
19114        assert!(
19115            deadline >= spawn_tick + actor.health.cadence,
19116            "a replacement must not inherit its predecessor's probe deadline"
19117        );
19118        tokio::time::advance(actor.health.cadence - Duration::from_nanos(1)).await;
19119        assert!(
19120            started_rx.try_recv().is_err(),
19121            "no HTTP probe during startup grace"
19122        );
19123        tokio::time::advance(deadline - Instant::now()).await;
19124        let landed = wait_for("first replacement HTTP probe", || {
19125            started_rx.try_recv().ok()
19126        })
19127        .await;
19128        assert!(landed >= spawn_tick + actor.health.cadence);
19129        wait_for("healthy replacement", || {
19130            (actor.module.status().unwrap().health.status == SupervisorHealthStatus::Ok)
19131                .then_some(())
19132        })
19133        .await;
19134        peer.abort();
19135    }
19136
19137    #[tokio::test(start_paused = true)]
19138    async fn rescan_adds_and_removes_http_health_without_polling() {
19139        use tokio::{
19140            io::{AsyncReadExt, AsyncWriteExt},
19141            net::TcpListener,
19142        };
19143        let mut actor = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
19144        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
19145        actor.health.http = Some(format!("http://{}/health", listener.local_addr().unwrap()));
19146        // One millisecond separates successive probes without a polling delay.
19147        actor.health.cadence = Duration::from_millis(1);
19148        let (started_tx, mut started_rx) = mpsc::channel(8);
19149        let peer = tokio::spawn(async move {
19150            loop {
19151                let (mut socket, _) = listener.accept().await.unwrap();
19152                let mut request = [0; 1024];
19153                assert!(socket.read(&mut request).await.unwrap() > 0);
19154                started_tx.send(()).await.unwrap();
19155                socket
19156                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
19157                    .await
19158                    .unwrap();
19159            }
19160        });
19161        let tick = Instant::now();
19162        let turns = actor.turns();
19163        actor
19164            .module
19165            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
19166            .await
19167            .unwrap();
19168        let armed = actor
19169            .wait_for_select(|checkpoint| {
19170                checkpoint.turn > turns && checkpoint.next_probe_at.is_some()
19171            })
19172            .await;
19173        assert_eq!(armed.next_probe_at, Some(tick + Duration::from_millis(1)));
19174        assert_eq!(Instant::now(), tick);
19175        tokio::time::advance(Duration::from_millis(1)).await;
19176        let mut started = false;
19177        wait_for("successful HTTP probe", || {
19178            started |= started_rx.try_recv().is_ok();
19179            (started && actor.module.status().unwrap().health.status == SupervisorHealthStatus::Ok)
19180                .then_some(())
19181        })
19182        .await;
19183        assert!(started, "added HTTP check must start at its first deadline");
19184        assert_eq!(
19185            actor.module.status().unwrap().health.status,
19186            SupervisorHealthStatus::Ok
19187        );
19188        assert_eq!(Instant::now(), tick + Duration::from_millis(1));
19189        actor.health.http = None;
19190        let turns = actor.turns();
19191        actor
19192            .module
19193            .update_configuration(actor.spec.clone(), actor.health.clone(), None)
19194            .await
19195            .unwrap();
19196        let parked = actor
19197            .wait_for_select(|checkpoint| {
19198                checkpoint.turn > turns && checkpoint.next_probe_at.is_none()
19199            })
19200            .await;
19201        assert_eq!(parked.wake_after, None);
19202        let turns = actor.turns();
19203        tokio::time::advance(Duration::from_secs(60)).await;
19204        assert_eq!(
19205            actor.turns(),
19206            turns,
19207            "removed HTTP check must park the actor"
19208        );
19209        assert!(
19210            started_rx.try_recv().is_err(),
19211            "removed HTTP check must stay disarmed"
19212        );
19213        assert_eq!(
19214            actor.module.status().unwrap().health,
19215            ModuleHealthStatus::default()
19216        );
19217        peer.abort();
19218    }
19219}
19220
19221#[cfg(test)]
19222mod drain_busy_reprobe_tests {
19223    //! The drain's busy-gauge wait, driven against an in-process module
19224    //! connection whose health answers the test scripts. Time is paused, so
19225    //! every elapsed duration below is exact virtual time.
19226    use super::*;
19227    use std::collections::BTreeMap;
19228    use std::sync::Mutex as StdMutex;
19229    use subc_protocol::{manifest::Concurrency, session::ModuleControlResponse};
19230
19231    const MODULE_ID: &str = "drain-reprobe-module";
19232    const CONNECTION: u64 = 7;
19233    const GAUGE: &str = "runs_in_flight";
19234    /// The production default for both the health cadence and the drain
19235    /// ceiling, which is the pairing that used to cost a full ceiling.
19236    const CADENCE: Duration = Duration::from_secs(30);
19237    const CEILING: Duration = Duration::from_secs(30);
19238
19239    /// How the scripted module answers each `health.check`.
19240    #[derive(Clone, Copy)]
19241    enum Answer {
19242        /// Report the gauge busy until this instant, quiet from then on, after
19243        /// taking `latency` to answer.
19244        BusyUntil { until: Instant, latency: Duration },
19245        /// Answer at once, with metrics that leave the declared gauge out.
19246        OmitsGauge,
19247        /// Never answer.
19248        Silent,
19249    }
19250
19251    struct Drain {
19252        forwarding: Arc<ForwardingTable>,
19253        runtime: SupervisorRuntimeConfig,
19254        endpoint: crate::ModuleEndpointId,
19255        /// When each probe reached the module.
19256        probes: Arc<StdMutex<Vec<Instant>>>,
19257        responder: tokio::task::JoinHandle<()>,
19258    }
19259
19260    impl Drain {
19261        fn start(answer: Answer) -> Self {
19262            let registry = Arc::new(Registry::default());
19263            let forwarding = Arc::new(ForwardingTable::default());
19264            let health = HealthConfig {
19265                cadence: CADENCE,
19266                ..HealthConfig::default()
19267            };
19268            let runtime = Supervisor::new_for_test(registry, RestartPolicy::new(3, Duration::ZERO))
19269                .with_forwarding(forwarding.clone())
19270                .with_health_config(health)
19271                .runtime_config();
19272            let (tx, mut rx) = mpsc::channel::<crate::router::OutboundFrame>(8);
19273            let endpoint = forwarding
19274                .register_module_connection(
19275                    ConnectionId::new(CONNECTION),
19276                    MODULE_ID.to_string(),
19277                    subc_protocol::PROTOCOL_VERSION,
19278                    Concurrency::ModuleManaged,
19279                    FrameSink::new(tx),
19280                )
19281                .unwrap();
19282            let probes = Arc::new(StdMutex::new(Vec::new()));
19283            let responder = tokio::spawn({
19284                let forwarding = forwarding.clone();
19285                let probes = probes.clone();
19286                async move {
19287                    while let Some(frame) = rx.recv().await {
19288                        let body: Value = serde_json::from_slice(&frame.body).unwrap();
19289                        assert_eq!(body["op"], MODULE_CONTROL_OP_HEALTH_CHECK);
19290                        probes.lock().unwrap().push(Instant::now());
19291                        let metrics = match answer {
19292                            Answer::BusyUntil { until, latency } => {
19293                                sleep(latency).await;
19294                                let busy = u64::from(Instant::now() < until);
19295                                serde_json::json!({ GAUGE: busy })
19296                            }
19297                            Answer::OmitsGauge => serde_json::json!({ "queue_depth": 0 }),
19298                            Answer::Silent => continue,
19299                        };
19300                        // A probe abandoned at its deadline has no RPC left to
19301                        // complete, so a late answer may be refused.
19302                        let _ = forwarding.complete_module_control_rpc(
19303                            ConnectionId::new(CONNECTION),
19304                            frame.header.corr,
19305                            Some(MODULE_CONTROL_OP_HEALTH_CHECK),
19306                            ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19307                                status: HealthStatus::Ok,
19308                                detail: None,
19309                                metrics: Some(metrics),
19310                            }),
19311                        );
19312                    }
19313                }
19314            });
19315            Self {
19316                forwarding,
19317                runtime,
19318                endpoint,
19319                probes,
19320                responder,
19321            }
19322        }
19323
19324        /// Run one by-id drain wait with `ceiling`, returning its verdict and
19325        /// how long it took.
19326        async fn run(&self, ceiling: Duration) -> (bool, Duration) {
19327            let (drained, elapsed, _) = self.run_traced(ceiling).await;
19328            (drained, elapsed)
19329        }
19330
19331        /// [`Self::run`], also returning what the drain's probes read.
19332        async fn run_traced(&self, ceiling: Duration) -> (bool, Duration, DrainGaugeTrace) {
19333            let started = Instant::now();
19334            let mut trace = DrainGaugeTrace::new(&[GAUGE.to_string()]);
19335            let drained = wait_for_forwarding_quiescence(
19336                &self.forwarding,
19337                MODULE_ID,
19338                &self.runtime,
19339                self.endpoint,
19340                started + ceiling,
19341                &[GAUGE.to_string()],
19342                DrainScope::Active,
19343                &mut trace,
19344            )
19345            .await
19346            .unwrap();
19347            (drained, started.elapsed(), trace)
19348        }
19349
19350        fn probes(&self) -> Vec<Instant> {
19351            self.probes.lock().unwrap().clone()
19352        }
19353    }
19354
19355    impl Drop for Drain {
19356        fn drop(&mut self) {
19357            self.responder.abort();
19358        }
19359    }
19360
19361    #[tokio::test(start_paused = true)]
19362    async fn busy_at_first_probe_then_quiet_drains_long_before_the_ceiling() {
19363        let drain = Drain::start(Answer::BusyUntil {
19364            until: Instant::now() + Duration::from_secs(1),
19365            latency: Duration::ZERO,
19366        });
19367        let (drained, elapsed) = drain.run(CEILING).await;
19368        assert!(
19369            drained,
19370            "gauges that read zero during the drain must let it finish drained, \
19371             not wait out the {CADENCE:?} health cadence (elapsed {elapsed:?})"
19372        );
19373        assert!(
19374            elapsed < Duration::from_secs(3),
19375            "drain took {elapsed:?} after the gauges went quiet at 1s"
19376        );
19377        let probes = drain.probes();
19378        assert!(
19379            probes.len() >= 2,
19380            "the module was busy at the first probe, so a quiet verdict needs a second: {probes:?}"
19381        );
19382    }
19383
19384    /// The same shape in real time on a multi-threaded runtime: the first
19385    /// probe is answered busy at once, within a millisecond of the drain
19386    /// starting, and later probes read idle. The drain must keep probing
19387    /// after that first instant answer and end soon after the gauge falls.
19388    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
19389    async fn an_instant_busy_first_answer_does_not_stop_later_probes_in_real_time() {
19390        let drain = Drain::start(Answer::BusyUntil {
19391            until: Instant::now() + Duration::from_millis(600),
19392            latency: Duration::ZERO,
19393        });
19394        let (drained, elapsed, trace) = drain.run_traced(CEILING).await;
19395        assert!(drained, "the gauge fell at 600ms: {trace}");
19396        assert!(
19397            elapsed < Duration::from_secs(3),
19398            "drain took {elapsed:?} after the gauge fell at 600ms: {trace}"
19399        );
19400        let probes = drain.probes();
19401        assert!(
19402            probes.len() >= 2 && trace.probes as usize == probes.len(),
19403            "the drain must re-probe after the first busy answer: {probes:?}, {trace}"
19404        );
19405    }
19406
19407    #[tokio::test(start_paused = true)]
19408    async fn busy_throughout_ends_undrained_at_the_ceiling_with_bounded_probes() {
19409        let started = Instant::now();
19410        let drain = Drain::start(Answer::BusyUntil {
19411            until: started + Duration::from_secs(3600),
19412            latency: Duration::ZERO,
19413        });
19414        let (drained, elapsed) = drain.run(CEILING).await;
19415        assert!(!drained, "a module busy throughout must not drain");
19416        assert!(
19417            elapsed >= CEILING && elapsed < CEILING + drain_busy_reprobe_interval(),
19418            "a busy module is held until the ceiling and no longer: {elapsed:?}"
19419        );
19420        // Re-probing is paced by the interval, not a busy loop: at most one
19421        // probe per interval across the ceiling, plus the first at time zero.
19422        let probes = drain.probes();
19423        let max_probes = (CEILING.as_millis() / drain_busy_reprobe_interval().as_millis()) + 1;
19424        assert!(
19425            probes.len() as u128 <= max_probes,
19426            "{} probes in a {CEILING:?} drain exceeds the {max_probes} the interval allows",
19427            probes.len()
19428        );
19429        for pair in probes.windows(2) {
19430            assert!(
19431                pair[1] - pair[0] >= drain_busy_reprobe_interval(),
19432                "consecutive probes {:?} apart",
19433                pair[1] - pair[0]
19434            );
19435        }
19436    }
19437
19438    #[tokio::test(start_paused = true)]
19439    async fn a_slow_probe_is_never_overlapped_by_the_next() {
19440        // Each answer takes longer than the re-probe interval; the next probe
19441        // must wait for the previous answer and then the interval.
19442        let latency = Duration::from_secs(1);
19443        let drain = Drain::start(Answer::BusyUntil {
19444            until: Instant::now() + Duration::from_secs(3600),
19445            latency,
19446        });
19447        let (drained, _) = drain.run(Duration::from_secs(5)).await;
19448        assert!(!drained);
19449        let probes = drain.probes();
19450        assert!(probes.len() >= 2, "the drain must re-probe: {probes:?}");
19451        for pair in probes.windows(2) {
19452            assert!(
19453                pair[1] - pair[0] >= latency + drain_busy_reprobe_interval(),
19454                "a probe started {:?} after the previous one, before it could finish",
19455                pair[1] - pair[0]
19456            );
19457        }
19458    }
19459
19460    #[tokio::test(start_paused = true)]
19461    async fn an_unanswered_probe_cannot_hold_the_drain_past_its_ceiling() {
19462        let drain = Drain::start(Answer::Silent);
19463        let ceiling = Duration::from_secs(2);
19464        let (drained, elapsed) = drain.run(ceiling).await;
19465        assert!(!drained, "an unanswered probe counts as busy");
19466        assert!(
19467            elapsed >= ceiling && elapsed < ceiling + drain_busy_reprobe_interval(),
19468            "the probe deadline is capped at the drain ceiling: {elapsed:?}"
19469        );
19470        assert_eq!(
19471            drain.probes().len(),
19472            1,
19473            "the unanswered probe holds the only slot until the ceiling"
19474        );
19475    }
19476
19477    /// Every event logged while it is installed, as `message` plus fields.
19478    #[derive(Clone, Default)]
19479    struct LogCapture {
19480        events: Arc<StdMutex<Vec<BTreeMap<String, String>>>>,
19481    }
19482
19483    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for LogCapture {
19484        fn on_event(
19485            &self,
19486            event: &tracing::Event<'_>,
19487            _context: tracing_subscriber::layer::Context<'_, S>,
19488        ) {
19489            struct Fields(BTreeMap<String, String>);
19490            impl tracing::field::Visit for Fields {
19491                fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
19492                    self.0
19493                        .insert(field.name().to_string(), format!("{value:?}"));
19494                }
19495            }
19496            let mut fields = Fields(BTreeMap::new());
19497            event.record(&mut fields);
19498            self.events.lock().unwrap().push(fields.0);
19499        }
19500    }
19501
19502    impl LogCapture {
19503        fn install(&self) -> tracing::subscriber::DefaultGuard {
19504            use tracing_subscriber::layer::SubscriberExt;
19505            tracing::subscriber::set_default(tracing_subscriber::registry().with(self.clone()))
19506        }
19507
19508        fn with_message(&self, needle: &str) -> Vec<BTreeMap<String, String>> {
19509            self.events
19510                .lock()
19511                .unwrap()
19512                .iter()
19513                .filter(|fields| fields.get("message").is_some_and(|m| m.contains(needle)))
19514                .cloned()
19515                .collect()
19516        }
19517    }
19518
19519    /// A module that declares a busy gauge but leaves it out of its health
19520    /// answers holds a drain to its ceiling. The timeout line must say so by
19521    /// name, and the drain must warn about the missing gauge once, not on
19522    /// every probe.
19523    #[tokio::test(start_paused = true)]
19524    async fn a_missing_declared_gauge_is_named_on_the_drain_timeout_line() {
19525        let capture = LogCapture::default();
19526        let _guard = capture.install();
19527        let drain = Drain::start(Answer::OmitsGauge);
19528        let (drained, _, trace) = drain.run_traced(Duration::from_secs(2)).await;
19529        assert!(!drained, "a gauge never reported cannot read quiet");
19530        assert!(trace.probes >= 2, "the drain must re-probe: {trace:?}");
19531
19532        let missing = capture.with_message("lacks a declared busy gauge");
19533        assert_eq!(missing.len(), 1, "one warning per drain: {missing:?}");
19534        assert_eq!(
19535            missing[0].get("missing_gauges").map(String::as_str),
19536            Some(GAUGE)
19537        );
19538
19539        warn_drain_timed_out(
19540            MODULE_ID,
19541            Duration::from_secs(2),
19542            RouteCloseReason::Restart,
19543            &Default::default(),
19544            &trace,
19545        );
19546        let timeouts = capture.with_message("route drain timed out");
19547        assert_eq!(timeouts.len(), 1, "{timeouts:?}");
19548        let gauges = &timeouts[0]["busy_gauges"];
19549        assert!(
19550            gauges.starts_with(&format!("{GAUGE}: missing_from_health_body @")),
19551            "the timeout line must name the gauge and why it read busy: {gauges}"
19552        );
19553        assert!(
19554            gauges.ends_with("; no value ever read"),
19555            "no value was ever read for the gauge: {gauges}"
19556        );
19557        assert_eq!(timeouts[0]["gauge_probes"], trace.probes.to_string());
19558    }
19559
19560    /// The trace names a busy value and when it was read. For a probe that
19561    /// never got an answer, it names the probe's error kind and says that no
19562    /// value was ever read.
19563    #[tokio::test(start_paused = true)]
19564    async fn the_drain_trace_names_a_busy_value_and_an_unanswered_probe() {
19565        let busy = Drain::start(Answer::BusyUntil {
19566            until: Instant::now() + Duration::from_secs(3600),
19567            latency: Duration::ZERO,
19568        });
19569        let (_, _, trace) = busy.run_traced(Duration::from_secs(1)).await;
19570        let rendered = trace.to_string();
19571        assert!(
19572            rendered.starts_with(&format!("{GAUGE}: non_zero(1) @"))
19573                && rendered.contains("; last value non_zero(1) @"),
19574            "{rendered}"
19575        );
19576
19577        let silent = Drain::start(Answer::Silent);
19578        let (_, _, trace) = silent.run_traced(Duration::from_secs(1)).await;
19579        // The probe is capped at the 1 s ceiling, and its reading is stamped
19580        // when it gave up.
19581        assert_eq!(
19582            trace.to_string(),
19583            format!("{GAUGE}: probe_failed(no-answer) @1000ms; no value ever read")
19584        );
19585        assert_eq!(trace.probes, 1);
19586    }
19587
19588    /// A gauge value that is not a count reads busy and is shown as sent.
19589    #[test]
19590    fn a_gauge_that_is_not_a_count_is_busy_and_shown_as_sent() {
19591        let gauges = [GAUGE.to_string()];
19592        let verdicts = gauge_verdicts(Some(&serde_json::json!({ GAUGE: 0.0 })), &gauges);
19593        assert_eq!(verdicts, vec![GaugeVerdict::NotACount("0.0".to_string())]);
19594        assert_eq!(
19595            busy_gauge_observation(&verdicts),
19596            BusyGaugeObservation::Busy
19597        );
19598        let zero = gauge_verdicts(Some(&serde_json::json!({ GAUGE: 0 })), &gauges);
19599        assert_eq!(
19600            busy_gauge_observation(&zero),
19601            BusyGaugeObservation::Quiescent
19602        );
19603        let none = gauge_verdicts(None, &gauges);
19604        assert_eq!(busy_gauge_observation(&none), BusyGaugeObservation::Omitted);
19605    }
19606}
19607
19608#[cfg(test)]
19609mod health_evidence_tests {
19610    use super::{HealthProbeError, HealthProbeEvidence};
19611    use std::collections::HashSet;
19612
19613    /// The evidential asymmetry, asserted rather than described.
19614    ///
19615    /// Exactly ONE observation is proof a module cannot serve, and the one that
19616    /// fires under CPU starvation is not it. Before the split, all fifteen
19617    /// construction sites collapsed into a single String, so a timeout carried the
19618    /// same weight as a dead lane -- which is how a healthy module was restarted
19619    /// three times in one day.
19620    #[test]
19621    fn only_a_dead_lane_is_proof_of_death() {
19622        assert!(HealthProbeError::lane_dead("gone").is_proof_of_death());
19623        // Three non-proof classes, each for a different reason: silence is
19624        // consistent with health, a bad answer proves the module ALIVE, and a
19625        // daemon-side fault never reached the module at all.
19626        assert!(!HealthProbeError::no_answer("timed out").is_proof_of_death());
19627        assert!(!HealthProbeError::bad_answer("garbage").is_proof_of_death());
19628        assert!(!HealthProbeError::misconfigured("no table").is_proof_of_death());
19629    }
19630
19631    /// Labels must be distinct, or the operator-facing distinction is cosmetic.
19632    ///
19633    /// A shared label renders two different observations identically in the line an
19634    /// operator reads after an unexplained restart -- the exact confusion this
19635    /// change removes.
19636    #[test]
19637    fn every_evidence_class_has_a_distinct_label() {
19638        let labels = [
19639            HealthProbeError::lane_dead("").label(),
19640            HealthProbeError::no_answer("").label(),
19641            HealthProbeError::bad_answer("").label(),
19642            HealthProbeError::misconfigured("").label(),
19643        ];
19644        let unique: HashSet<_> = labels.iter().collect();
19645        assert_eq!(unique.len(), labels.len(), "labels collided: {labels:?}");
19646    }
19647
19648    /// The class is additional information, not a replacement.
19649    ///
19650    /// An operator needs both "this was silence" and the specific text saying how
19651    /// long we waited; a classification that swallowed the message would trade one
19652    /// missing distinction for another.
19653    #[test]
19654    fn classification_preserves_the_original_message() {
19655        let err = HealthProbeError::no_answer("module did not answer within 5s");
19656        assert_eq!(err.to_string(), "module did not answer within 5s");
19657        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19658    }
19659}
19660
19661#[cfg(test)]
19662mod health_tombstone_tests {
19663    use std::{path::PathBuf, sync::Arc, time::Duration};
19664
19665    use subc_protocol::{
19666        manifest::Concurrency,
19667        session::{HealthStatus, ModuleControlResponse},
19668    };
19669    use tokio::sync::mpsc;
19670
19671    use super::{
19672        probe_module_health, HealthAction, HealthConfig, HealthProbeEvidence, ModuleProtocol,
19673        ModuleSpec, RestartPolicy, Supervisor, SupervisorRuntimeConfig,
19674    };
19675    use crate::{
19676        control::ControlHandler,
19677        forwarding::{ForwardingTable, ModuleControlRpcCompletion, ModuleControlRpcOutcome},
19678        registry::{ConnectionId, Registry},
19679        router::FrameSink,
19680    };
19681
19682    struct ProbeHarness {
19683        spec: ModuleSpec,
19684        runtime: SupervisorRuntimeConfig,
19685        forwarding: Arc<ForwardingTable>,
19686        module_connection: ConnectionId,
19687        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19688        handler: ControlHandler,
19689        module: super::SupervisedModule,
19690    }
19691
19692    fn probe_harness() -> ProbeHarness {
19693        let registry = Arc::new(Registry::default());
19694        let forwarding = Arc::new(ForwardingTable::default());
19695        let supervisor_handle = super::SupervisorHandle::new();
19696        let health = HealthConfig {
19697            http: None,
19698            cadence: Duration::from_secs(30),
19699            deadline: Duration::from_secs(5),
19700            failure_threshold: 3,
19701            on_degraded: HealthAction::Report,
19702            on_failing: HealthAction::Report,
19703            critical: false,
19704        };
19705        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
19706            .with_forwarding(Arc::clone(&forwarding))
19707            .with_handle(supervisor_handle.clone())
19708            .with_health_config(health);
19709        let spec = ModuleSpec {
19710            script: None,
19711            module_id: "late-health-module".to_string(),
19712            program: PathBuf::from("disabled-module"),
19713            args: Vec::new(),
19714            env: Vec::new(),
19715            reserved: false,
19716            reserved_prefixes: Vec::new(),
19717            protocol: ModuleProtocol::Subc,
19718            overlap: Default::default(),
19719            carry_containment: false,
19720        };
19721        let module = supervisor
19722            .supervise_configured(spec.clone(), false)
19723            .unwrap();
19724        let runtime = supervisor.runtime_config();
19725        let handler = ControlHandler::with_forwarding(registry, Arc::clone(&forwarding))
19726            .with_supervisor(supervisor_handle);
19727        let module_connection = ConnectionId::new(700);
19728        let (module_tx, module_rx) = mpsc::channel(8);
19729        forwarding
19730            .register_module_connection(
19731                module_connection,
19732                spec.module_id.clone(),
19733                subc_protocol::PROTOCOL_VERSION,
19734                Concurrency::ModuleManaged,
19735                FrameSink::new(module_tx),
19736            )
19737            .unwrap();
19738
19739        ProbeHarness {
19740            spec,
19741            runtime,
19742            forwarding,
19743            module_connection,
19744            module_rx,
19745            handler,
19746            module,
19747        }
19748    }
19749
19750    async fn finish_after(
19751        harness: &mut ProbeHarness,
19752        stall: Duration,
19753    ) -> ModuleControlRpcCompletion {
19754        assert!(stall > harness.runtime.health.deadline);
19755        let deadline = harness.runtime.health.deadline;
19756        let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
19757        let answer = async {
19758            let frame = harness.module_rx.recv().await.expect("health.check frame");
19759            tokio::time::advance(deadline).await;
19760            tokio::task::yield_now().await;
19761            tokio::time::advance(stall - deadline).await;
19762            harness
19763                .forwarding
19764                .complete_module_control_rpc(
19765                    harness.module_connection,
19766                    frame.header.corr,
19767                    Some("health.check"),
19768                    ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19769                        status: HealthStatus::Ok,
19770                        detail: None,
19771                        metrics: None,
19772                    }),
19773                )
19774                .unwrap()
19775        };
19776        let (probe_result, completion) = tokio::join!(probe, answer);
19777        let err = probe_result.expect_err("probe must miss its deadline");
19778        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19779        completion
19780    }
19781
19782    async fn time_out_without_answer(harness: &mut ProbeHarness) {
19783        let deadline = harness.runtime.health.deadline;
19784        let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
19785        let exhaust_deadline = async {
19786            let _frame = harness.module_rx.recv().await.expect("health.check frame");
19787            tokio::time::advance(deadline).await;
19788            tokio::task::yield_now().await;
19789        };
19790        let (probe_result, ()) = tokio::join!(probe, exhaust_deadline);
19791        let err = probe_result.expect_err("probe must miss its deadline");
19792        assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19793    }
19794
19795    async fn run_probe_cycle(harness: &mut ProbeHarness, answer: bool) {
19796        let registry = Arc::clone(&harness.module.inner.registry);
19797        let snapshot = Arc::clone(&harness.module.inner.snapshot);
19798        let process_liveness = super::SupervisorProcessLiveness::default();
19799        let mut child = None;
19800        let cycle = super::run_health_probe_cycle(
19801            &harness.spec,
19802            &harness.runtime,
19803            &registry,
19804            &process_liveness,
19805            &snapshot,
19806            &mut child,
19807        );
19808        let peer = async {
19809            let frame = harness.module_rx.recv().await.expect("health.check frame");
19810            if answer {
19811                harness
19812                    .forwarding
19813                    .complete_module_control_rpc(
19814                        harness.module_connection,
19815                        frame.header.corr,
19816                        Some("health.check"),
19817                        ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19818                            status: HealthStatus::Ok,
19819                            detail: None,
19820                            metrics: Some(serde_json::json!({"ready": true})),
19821                        }),
19822                    )
19823                    .unwrap();
19824            } else {
19825                tokio::time::advance(harness.runtime.health.deadline).await;
19826                tokio::task::yield_now().await;
19827            }
19828        };
19829        tokio::join!(cycle, peer);
19830    }
19831
19832    #[tokio::test(start_paused = true)]
19833    async fn unanswered_probe_is_unknown_until_threshold_and_ok_report_recovers() {
19834        let mut harness = probe_harness();
19835        // Drive the probe cycle directly with an in-memory wire peer. Stop the
19836        // disabled module's monitor so only this test owns lifecycle transitions;
19837        // no OS process is launched, and a restart is observed at scheduling.
19838        let monitor = harness.module.inner.monitor.lock().unwrap().take().unwrap();
19839        monitor.abort();
19840        let _ = monitor.await;
19841        super::update_snapshot(&harness.module.inner.snapshot, None, |state| {
19842            state.enabled = true;
19843            state.state = super::ModuleState::Running;
19844            state.process_alive = true;
19845        })
19846        .unwrap();
19847
19848        run_probe_cycle(&mut harness, true).await;
19849        assert_eq!(
19850            harness.module.status().unwrap().health.status,
19851            super::SupervisorHealthStatus::Ok
19852        );
19853
19854        for failures in 1..harness.runtime.health.failure_threshold {
19855            run_probe_cycle(&mut harness, false).await;
19856            let status = harness.module.status().unwrap();
19857            assert_eq!(status.health.status, super::SupervisorHealthStatus::Unknown);
19858            assert_eq!(status.health.consecutive_failures, failures);
19859            assert!(status.health.last_probe_ms.is_some());
19860            assert!(status.health.detail.unwrap().starts_with("[no-answer]"));
19861            assert!(status.health.metrics.is_none());
19862            assert_eq!(status.state, super::ModuleState::Running);
19863            assert!(status.process_alive);
19864            assert_eq!(status.restart_count, 0);
19865            assert_eq!(status.lifetime_restarts, 0);
19866            assert!(status.health.last_action.is_none());
19867            assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_none());
19868        }
19869
19870        run_probe_cycle(&mut harness, true).await;
19871        let recovered = harness.module.status().unwrap();
19872        assert_eq!(recovered.health.status, super::SupervisorHealthStatus::Ok);
19873        assert_eq!(recovered.health.consecutive_failures, 0);
19874        assert!(recovered.health.detail.is_none());
19875        assert_eq!(
19876            recovered.health.metrics,
19877            Some(serde_json::json!({"ready": true}))
19878        );
19879        assert_eq!(recovered.lifetime_restarts, 0);
19880
19881        for failures in 1..=harness.runtime.health.failure_threshold {
19882            run_probe_cycle(&mut harness, false).await;
19883            let status = harness.module.status().unwrap();
19884            assert_eq!(status.health.consecutive_failures, failures);
19885            if failures < harness.runtime.health.failure_threshold {
19886                assert_eq!(status.health.status, super::SupervisorHealthStatus::Unknown);
19887                assert_eq!(status.state, super::ModuleState::Running);
19888                assert_eq!(status.lifetime_restarts, 0);
19889                assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_none());
19890            } else {
19891                assert_eq!(
19892                    status.health.status,
19893                    super::SupervisorHealthStatus::Unresponsive
19894                );
19895                assert_eq!(status.state, super::ModuleState::Restarting);
19896                assert_eq!(status.restart_count, 1);
19897                assert_eq!(status.lifetime_restarts, 1);
19898                assert_eq!(status.health.last_action.as_deref(), Some("restart"));
19899                assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_some());
19900            }
19901        }
19902    }
19903
19904    #[tokio::test(start_paused = true)]
19905    async fn late_health_answers_record_start_anchored_latency_for_two_stalls() {
19906        let mut harness = probe_harness();
19907
19908        let first = finish_after(&mut harness, Duration::from_secs(8)).await;
19909        let first_latency = match &first {
19910            ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
19911            other => panic!("late answer was not retained: {other:?}"),
19912        };
19913        assert!(harness.handler.observe_module_control_completion(first));
19914
19915        let second = finish_after(&mut harness, Duration::from_secs(11)).await;
19916        let second_latency = match &second {
19917            ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
19918            other => panic!("late answer was not retained: {other:?}"),
19919        };
19920        assert!(harness.handler.observe_module_control_completion(second));
19921
19922        assert_eq!(first_latency, Duration::from_secs(8));
19923        assert_eq!(
19924            second_latency - first_latency,
19925            Duration::from_secs(3),
19926            "latency must grow linearly with the additional stall"
19927        );
19928        let health = harness.module.status().unwrap().health;
19929        assert_eq!(health.late_answer_count, 2);
19930        assert_eq!(health.last_late_answer_latency_ms, Some(11_000));
19931    }
19932
19933    /// A module that answers every probe late must never march to the kill
19934    /// threshold: the late answer proves it is alive, so it must clear the miss
19935    /// streak the timeout recorded. Without the reset, a CPU-starved module
19936    /// that serves every probe seconds past the deadline accumulates
19937    /// `consecutive_failures` to the threshold and is killed — the exact
19938    /// sequence from the 2026-08-14 aft disable, where the daemon logged
19939    /// "proves the module is alive" five times while counting five misses.
19940    #[tokio::test(start_paused = true)]
19941    async fn late_answer_clears_the_consecutive_failure_streak() {
19942        let mut harness = probe_harness();
19943
19944        // Timeout recorded first: the probe path saw no answer in time.
19945        time_out_without_answer(&mut harness).await;
19946        harness
19947            .module
19948            .record_health_probe_failure_for_test("[no-answer] test miss")
19949            .unwrap();
19950        assert_eq!(
19951            harness.module.status().unwrap().health.consecutive_failures,
19952            1,
19953            "precondition: the miss must be on the streak before the late answer"
19954        );
19955
19956        // The stalled reply then lands: proof of life.
19957        let late = finish_after(&mut harness, Duration::from_secs(9)).await;
19958        assert!(matches!(
19959            late,
19960            ModuleControlRpcCompletion::LateHealthAnswer { .. }
19961        ));
19962        assert!(harness.handler.observe_module_control_completion(late));
19963
19964        let health = harness.module.status().unwrap().health;
19965        assert_eq!(
19966            health.consecutive_failures, 0,
19967            "a late answer is an answer: the streak must reset"
19968        );
19969        assert_eq!(health.late_answer_count, 1);
19970    }
19971
19972    #[tokio::test(start_paused = true)]
19973    async fn repeated_serial_probe_cycles_keep_one_tombstone_per_endpoint() {
19974        let mut harness = probe_harness();
19975
19976        for _ in 0..20 {
19977            time_out_without_answer(&mut harness).await;
19978            assert_eq!(
19979                harness.forwarding.health_probe_tombstone_count().unwrap(),
19980                1
19981            );
19982        }
19983    }
19984}
19985
19986#[cfg(test)]
19987mod child_env_tests {
19988    #[cfg(windows)]
19989    use super::{
19990        clear_current_process_facts, observed_launch_nonce_source, ModuleState, SupervisorSnapshot,
19991    };
19992    #[cfg(windows)]
19993    use std::sync::{Arc, OnceLock};
19994    #[cfg(windows)]
19995    #[test]
19996    fn windows_wire_spawn_prepares_pipe_and_keeps_phase_one_env() {
19997        let spec = spec(Vec::new());
19998        let mut command = Command::new("unused");
19999        let handoff = apply_wire_spawn_args(&mut command, &spec, None, None)
20000            .unwrap()
20001            .unwrap();
20002        let name = command
20003            .as_std()
20004            .get_envs()
20005            .find(|(key, _)| *key == OsStr::new(subc_os::launch_nonce::LAUNCH_NONCE_PIPE_ENV))
20006            .and_then(|(_, value)| value)
20007            .unwrap();
20008        assert_eq!(name, OsStr::new(handoff.name()));
20009        assert!(handoff.name().starts_with(r"\\.\pipe\subc-launch-"));
20010        assert!(command.as_std().get_envs().any(|(key, value)| key
20011            == OsStr::new(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV)
20012            && value == Some(OsStr::new("env"))));
20013        assert!(command
20014            .as_std()
20015            .get_envs()
20016            .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()));
20017    }
20018
20019    #[cfg(windows)]
20020    #[test]
20021    fn windows_source_reporting_tracks_consumption_and_resets_per_spawn() {
20022        let mut snapshot = SupervisorSnapshot::new(ModuleState::Running, true);
20023        snapshot.process_alive = true;
20024        snapshot.spawned_protocol = Some(ModuleProtocol::Subc);
20025        assert_eq!(
20026            observed_launch_nonce_source(&snapshot).as_deref(),
20027            Some("env")
20028        );
20029        let consumed = Arc::new(OnceLock::new());
20030        snapshot.pipe_consumed = Some(consumed.clone());
20031        assert_eq!(
20032            observed_launch_nonce_source(&snapshot).as_deref(),
20033            Some("env")
20034        );
20035        consumed.set(()).unwrap();
20036        assert_eq!(
20037            observed_launch_nonce_source(&snapshot).as_deref(),
20038            Some("pipe")
20039        );
20040        snapshot.pipe_consumed = Some(Arc::new(OnceLock::new()));
20041        assert_eq!(
20042            observed_launch_nonce_source(&snapshot).as_deref(),
20043            Some("env")
20044        );
20045        clear_current_process_facts(&mut snapshot);
20046        assert_eq!(observed_launch_nonce_source(&snapshot), None);
20047    }
20048    use super::{
20049        apply_child_env, apply_spawn_role, apply_wire_spawn_args, LaunchSpecDigest, ModuleProtocol,
20050        ModuleSpec, SpawnRole, SupervisorHandle, SPAWN_ROLE_SWAP_CANDIDATE, SUBC_ARG,
20051        SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV, SUBC_SPAWN_ROLE_ENV,
20052    };
20053    use std::{ffi::OsStr, path::PathBuf};
20054    use tokio::process::Command;
20055
20056    fn spec(env: Vec<(String, String)>) -> ModuleSpec {
20057        ModuleSpec {
20058            script: None,
20059            module_id: "env-plan".to_string(),
20060            program: PathBuf::from("/nonexistent"),
20061            args: Vec::new(),
20062            env,
20063            reserved: false,
20064            reserved_prefixes: Vec::new(),
20065            protocol: ModuleProtocol::Subc,
20066            overlap: Default::default(),
20067            carry_containment: false,
20068        }
20069    }
20070
20071    #[test]
20072    fn configured_launch_spec_digest_is_canonical_and_excludes_injected_inputs() {
20073        let base = spec(vec![("A".into(), "B=C".into()), ("Z".into(), "v".into())]);
20074        let digest = LaunchSpecDigest::from_spec(&base);
20075        let mut reordered = base.clone();
20076        reordered.env.reverse();
20077        reordered.module_id = "different-id".into();
20078        reordered.reserved = true;
20079        reordered.overlap = Default::default();
20080        assert_eq!(digest, LaunchSpecDigest::from_spec(&reordered));
20081        let mut delimiter_collision = base.clone();
20082        delimiter_collision.env[0] = ("A=B".into(), "C".into());
20083        assert_ne!(digest, LaunchSpecDigest::from_spec(&delimiter_collision));
20084        let mut changed = base.clone();
20085        changed.protocol = ModuleProtocol::None;
20086        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
20087        changed = base.clone();
20088        changed.args.push("--flag".into());
20089        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
20090        changed = base.clone();
20091        changed.program = PathBuf::from("/other");
20092        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
20093        changed = base.clone();
20094        changed.env[1].1 = "other".into();
20095        assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
20096        assert!(!format!("{digest:?}").contains("B=C"));
20097        assert!(!format!("{digest:?}").contains("[u8"));
20098    }
20099
20100    #[cfg(unix)]
20101    #[test]
20102    fn native_program_bytes_do_not_collapse_through_lossy_utf8() {
20103        use std::os::unix::ffi::OsStringExt;
20104        let mut left = spec(Vec::new());
20105        left.program = std::ffi::OsString::from_vec(vec![b'/', 0xff]).into();
20106        let mut right = left.clone();
20107        right.program = std::ffi::OsString::from_vec(vec![b'/', 0xfe]).into();
20108        assert_eq!(
20109            left.program.to_string_lossy(),
20110            right.program.to_string_lossy()
20111        );
20112        assert_ne!(
20113            LaunchSpecDigest::from_spec(&left),
20114            LaunchSpecDigest::from_spec(&right)
20115        );
20116    }
20117
20118    /// Ambient `CK_LOG` is REMOVED for an unconfigured module, and a configured
20119    /// one still gets its own.
20120    ///
20121    /// This is the narrow goal `env_clear()` was reached for, and the reason the
20122    /// fix is `env_remove` rather than deleting the line: an operator's ambient
20123    /// filter silently becoming an unconfigured module's log level is a real
20124    /// defect, just a much smaller one than clearing the environment.
20125    ///
20126    /// Asserted on the command plan rather than a spawned child because proving
20127    /// the ABSENCE of an inherited variable needs the parent's environment
20128    /// mutated, and `forbid(unsafe_code)` refuses that. `get_envs()` reports a
20129    /// removal as `(key, None)`, which is exactly the distinction wanted: not
20130    /// "absent because nobody set it" but "explicitly unset for the child".
20131    #[test]
20132    fn ambient_ck_log_is_removed_and_a_configured_one_survives() {
20133        let mut command = Command::new("/nonexistent");
20134        apply_child_env(&mut command, &spec(Vec::new()));
20135        let removed = command
20136            .as_std()
20137            .get_envs()
20138            .any(|(key, value)| key == OsStr::new("CK_LOG") && value.is_none());
20139        assert!(
20140            removed,
20141            "ambient CK_LOG must be explicitly removed for an unconfigured module"
20142        );
20143
20144        let mut configured = Command::new("/nonexistent");
20145        apply_child_env(
20146            &mut configured,
20147            &spec(vec![("CK_LOG".to_string(), "debug".to_string())]),
20148        );
20149        let effective = configured
20150            .as_std()
20151            .get_envs()
20152            .filter(|(key, _)| *key == OsStr::new("CK_LOG"))
20153            .last()
20154            .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
20155        assert_eq!(
20156            effective,
20157            Some(Some("debug".to_string())),
20158            "a module's configured CK_LOG must survive the ambient removal"
20159        );
20160    }
20161
20162    /// A `protocol: "none"` spawn carries NO `--subc` argument and NO launch
20163    /// nonce; a subc-wire spawn carries both. Asserted on the command plan for
20164    /// the same reason as the CK_LOG test above.
20165    ///
20166    /// The argument is the load-bearing half: a stock binary exits on an
20167    /// unknown flag before it listens, so with `--subc` appended the mode
20168    /// could not supervise the one process it exists for. Found by the first
20169    /// conformance run (nats-server: `flag provided but not defined: -subc`).
20170    #[test]
20171    fn protocol_none_spawn_carries_no_subc_argument_and_no_nonce() {
20172        let connection_file = std::path::Path::new("/run/subc-connection.json");
20173        let handle = SupervisorHandle::new();
20174
20175        let mut none_spec = spec(Vec::new());
20176        none_spec.protocol = ModuleProtocol::None;
20177        let mut none = Command::new("/nonexistent");
20178        let none_handoff =
20179            apply_wire_spawn_args(&mut none, &none_spec, Some(connection_file), Some(&handle))
20180                .expect("protocol-none spawn args apply");
20181        assert!(
20182            none_handoff.is_none(),
20183            "protocol:none spawn must not receive a nonce descriptor"
20184        );
20185        #[cfg(windows)]
20186        assert!(!none.as_std().get_envs().any(|(key, value)| key
20187            == OsStr::new(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV)
20188            && value.is_some()));
20189        assert!(
20190            !none.as_std().get_envs().any(|(key, value)| key
20191                == OsStr::new(subc_os::LAUNCH_NONCE_FD_ENV)
20192                && value.is_some()),
20193            "protocol:none spawn must not name a nonce descriptor"
20194        );
20195        let none_args: Vec<String> = none
20196            .as_std()
20197            .get_args()
20198            .map(|a| a.to_string_lossy().into_owned())
20199            .collect();
20200        assert!(
20201            !none_args.iter().any(|a| a == SUBC_ARG),
20202            "protocol:none argv must not carry --subc; got {none_args:?}"
20203        );
20204        let none_has_nonce = none
20205            .as_std()
20206            .get_envs()
20207            .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some());
20208        assert!(
20209            !none_has_nonce,
20210            "protocol:none spawn must not receive a launch nonce"
20211        );
20212        let none_has_module_id = none
20213            .as_std()
20214            .get_envs()
20215            .any(|(key, value)| key == OsStr::new(SUBC_MODULE_ID_ENV) && value.is_some());
20216        assert!(
20217            none_has_module_id,
20218            "SUBC_MODULE_ID is inert and stays on every path"
20219        );
20220        assert!(
20221            handle.spawn_nonce(&none_spec.module_id).is_none(),
20222            "no nonce record for a process that will never present one"
20223        );
20224
20225        // Control: the subc-wire path is unchanged by the branch above.
20226        let wire_spec = spec(Vec::new());
20227        let mut wire = Command::new("/nonexistent");
20228        let wire_handoff =
20229            apply_wire_spawn_args(&mut wire, &wire_spec, Some(connection_file), Some(&handle))
20230                .expect("subc-wire spawn args apply");
20231        let wire_fd_env = wire
20232            .as_std()
20233            .get_envs()
20234            .find(|(key, _)| *key == OsStr::new(subc_os::LAUNCH_NONCE_FD_ENV))
20235            .and_then(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
20236        #[cfg(unix)]
20237        assert_eq!(
20238            wire_fd_env,
20239            Some(wire_handoff.expect("a descriptor handoff").fd_env_value()),
20240            "a subc-wire spawn names the pipe it will receive at descriptor 3"
20241        );
20242        #[cfg(windows)]
20243        assert!(wire_handoff.is_some() && wire_fd_env.is_none());
20244        #[cfg(not(any(unix, windows)))]
20245        assert!(wire_handoff.is_none() && wire_fd_env.is_none());
20246        let wire_args: Vec<String> = wire
20247            .as_std()
20248            .get_args()
20249            .map(|a| a.to_string_lossy().into_owned())
20250            .collect();
20251        assert_eq!(
20252            wire_args,
20253            vec![
20254                SUBC_ARG.to_string(),
20255                connection_file.to_string_lossy().into_owned()
20256            ],
20257            "a subc-wire spawn still carries --subc <path>"
20258        );
20259        assert_eq!(
20260            wire.as_std()
20261                .get_envs()
20262                .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()),
20263            !cfg!(unix),
20264            "only Windows supplies the environment nonce"
20265        );
20266        assert!(handle.spawn_nonce(&wire_spec.module_id).is_some());
20267    }
20268
20269    /// A plain spawn EXPLICITLY REMOVES the spawn role, even when the module's
20270    /// spec tries to set it; only a swap candidate carries it.
20271    ///
20272    /// "Set it only on candidates" is not enough, because spawn applies the
20273    /// spec's env verbatim and the daemon's own environment is inherited: either
20274    /// could hand a plain restart the swap role, and a module reading it would
20275    /// warm on its long swap budget while callers wait. Asserted as an explicit
20276    /// removal (`(key, None)`), not mere absence, for the reason the `CK_LOG`
20277    /// test above gives.
20278    #[test]
20279    fn plain_spawn_removes_the_spawn_role_even_when_the_spec_sets_it() {
20280        let role = |command: &Command| {
20281            command
20282                .as_std()
20283                .get_envs()
20284                .filter(|(key, _)| *key == OsStr::new(SUBC_SPAWN_ROLE_ENV))
20285                .last()
20286                .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()))
20287        };
20288        let forged = spec(vec![(
20289            SUBC_SPAWN_ROLE_ENV.to_string(),
20290            SPAWN_ROLE_SWAP_CANDIDATE.to_string(),
20291        )]);
20292
20293        let mut plain = Command::new("/nonexistent");
20294        apply_child_env(&mut plain, &forged);
20295        apply_spawn_role(&mut plain, SpawnRole::Plain);
20296        assert_eq!(
20297            role(&plain),
20298            Some(None),
20299            "a plain spawn must remove SUBC_SPAWN_ROLE, whatever the spec says"
20300        );
20301
20302        let mut candidate = Command::new("/nonexistent");
20303        apply_child_env(&mut candidate, &spec(Vec::new()));
20304        apply_spawn_role(&mut candidate, SpawnRole::SwapCandidate);
20305        assert_eq!(
20306            role(&candidate),
20307            Some(Some(SPAWN_ROLE_SWAP_CANDIDATE.to_string()))
20308        );
20309    }
20310
20311    /// Daemon-private capture retention keys never reach the child.
20312    ///
20313    /// cortexkit-log exposes retention as a Rust struct with no environment
20314    /// names, so these entries are supervisor metadata. Passing them through
20315    /// would invent a public child-process contract by accident.
20316    #[test]
20317    fn daemon_private_capture_keys_are_not_passed_to_the_child() {
20318        let mut command = Command::new("/nonexistent");
20319        apply_child_env(
20320            &mut command,
20321            &spec(vec![
20322                (super::CAPTURE_KEEP_ENV.to_string(), "5".to_string()),
20323                ("KEPT".to_string(), "yes".to_string()),
20324            ]),
20325        );
20326        let keys: Vec<String> = command
20327            .as_std()
20328            .get_envs()
20329            .filter(|(_, value)| value.is_some())
20330            .map(|(key, _)| key.to_string_lossy().into_owned())
20331            .collect();
20332        assert!(keys.contains(&"KEPT".to_string()), "got {keys:?}");
20333        assert!(
20334            !keys.contains(&super::CAPTURE_KEEP_ENV.to_string()),
20335            "daemon-private capture key leaked to the child: {keys:?}"
20336        );
20337    }
20338}
20339
20340#[cfg(test)]
20341mod jitter_tests {
20342    use super::jittered_health_delay;
20343    use std::{collections::HashSet, time::Duration};
20344
20345    /// Module ids drawn from a real fleet, so the dispersal claim is about names
20346    /// that actually occur rather than invented ones.
20347    ///
20348    /// This is a SAMPLE, not a registry: the property under test is that distinct
20349    /// ids disperse, which holds for any set of distinct strings. Several entries
20350    /// are already historical (modules get renamed), and that costs nothing here --
20351    /// but it means a reader must not mistake this for the live module set, and a
20352    /// rename sweep will match it without there being anything to change.
20353    const FLEET: [&str; 14] = [
20354        "aft",
20355        "alfonso-core",
20356        "magic-context",
20357        "broca",
20358        "thalamus",
20359        "quota",
20360        "engram",
20361        "plexus",
20362        "cerebellum",
20363        "astrocyte",
20364        "synapse",
20365        "subc-mcp",
20366        "cortexkit-credentials",
20367        "subc-federation",
20368    ];
20369
20370    /// Probes must not converge after a fleet-wide restart.
20371    ///
20372    /// This is the property the jitter exists for: every module reconnects at
20373    /// once, and without dispersal all fourteen would then probe on the same
20374    /// tick forever. Nothing failed visibly when this went untested -- a
20375    /// convergent fleet still probes correctly, just in a burst, so the symptom
20376    /// is a periodic load spike that looks like whatever else is running.
20377    #[test]
20378    fn probe_delays_disperse_across_the_fleet() {
20379        let cadence = Duration::from_secs(30);
20380        let delays: HashSet<Duration> = FLEET
20381            .iter()
20382            .map(|id| jittered_health_delay(id, 0, cadence))
20383            .collect();
20384        assert_eq!(
20385            delays.len(),
20386            FLEET.len(),
20387            "every supervised module must land on its own probe offset"
20388        );
20389    }
20390
20391    /// The offset may only ever DELAY a probe, never bring it forward.
20392    ///
20393    /// A delay below the cadence would probe a module more often than
20394    /// configured, which is the opposite of what an operator asked for and
20395    /// would tighten the failure budget without anyone changing it.
20396    #[test]
20397    fn jitter_only_delays_and_stays_within_one_tenth_of_cadence() {
20398        let cadence = Duration::from_secs(30);
20399        let span = cadence / 10;
20400        for id in FLEET {
20401            for probe_index in 0..8 {
20402                let delay = jittered_health_delay(id, probe_index, cadence);
20403                assert!(
20404                    delay >= cadence,
20405                    "{id}#{probe_index}: jitter must not shorten the cadence"
20406                );
20407                assert!(
20408                    delay < cadence + span,
20409                    "{id}#{probe_index}: jitter must stay inside one tenth of the cadence"
20410                );
20411            }
20412        }
20413    }
20414
20415    /// A module keeps its offset across daemon restarts.
20416    ///
20417    /// The delay is derived rather than randomised precisely so a restart does
20418    /// not re-roll every module into a fresh chance of collision. A random
20419    /// source would satisfy the dispersal test above and quietly lose this.
20420    #[test]
20421    fn a_module_offset_is_stable_across_restarts() {
20422        let cadence = Duration::from_secs(30);
20423        for id in FLEET {
20424            assert_eq!(
20425                jittered_health_delay(id, 0, cadence),
20426                jittered_health_delay(id, 0, cadence),
20427                "{id}: the same module and probe index must produce the same offset"
20428            );
20429        }
20430    }
20431
20432    /// A zero cadence disables probing rather than producing a busy loop.
20433    #[test]
20434    fn zero_cadence_yields_zero_delay() {
20435        assert_eq!(
20436            jittered_health_delay("aft", 0, Duration::ZERO),
20437            Duration::ZERO
20438        );
20439    }
20440}
20441
20442#[cfg(all(test, target_os = "linux"))]
20443mod cgroup_placement_tests {
20444    use super::{
20445        apply_cgroup_placement, remove_module_cgroup, LaunchSpecDigest, ModuleProtocol, ModuleSpec,
20446        SuperviseError, SupervisedChild,
20447    };
20448    use crate::stderr_tail::{StderrRing, StderrTailConfig};
20449    use cortexkit_test_support::ScratchDir;
20450    use std::{
20451        fs, io,
20452        path::{Path, PathBuf},
20453        sync::{Arc, Mutex},
20454    };
20455    use tokio::process::Command;
20456
20457    #[tokio::test]
20458    async fn unique_spawn_cgroups_clean_up_across_restarts_and_shutdown() {
20459        use super::*;
20460        let dir = ScratchDir::new("unique-spawn-cgroups");
20461        let root = PathBuf::from(format!(
20462            "/sys/fs/cgroup/subc-unique-test-{}-{}",
20463            std::process::id(),
20464            unix_ms_now()
20465        ));
20466        if let Err(error) = fs::create_dir(&root) {
20467            assert!(
20468                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
20469                "required cgroup test cannot execute: {error}"
20470            );
20471            eprintln!("SKIP unique_spawn_cgroups_clean_up_across_restarts_and_shutdown: {error}");
20472            return;
20473        }
20474        let placement = subc_cgroup::prepare_at(&root).unwrap().unwrap();
20475        let group_count = || {
20476            fs::read_dir(root.join("subc-modules"))
20477                .unwrap()
20478                .map(|entry| entry.unwrap().file_type().unwrap())
20479                .filter(|kind| kind.is_dir())
20480                .count()
20481        };
20482        let supervisor =
20483            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
20484                .with_cgroup_placement(Some(placement.clone()));
20485        let runtime = supervisor.runtime_config();
20486        let mut spec = ModuleSpec {
20487            script: None,
20488            module_id: "unique-spawn".into(),
20489            program: PathBuf::from("/bin/sleep"),
20490            args: vec!["60".into()],
20491            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
20492                .into_iter()
20493                .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
20494                .collect(),
20495            reserved: false,
20496            reserved_prefixes: vec![],
20497            protocol: ModuleProtocol::None,
20498            overlap: Default::default(),
20499            carry_containment: false,
20500        };
20501        let spawn = |spec: &ModuleSpec| {
20502            spawn_child(
20503                spec,
20504                None,
20505                None,
20506                &runtime.stderr_ring,
20507                None,
20508                &runtime.child_roster,
20509                runtime.spawn_delivery(),
20510                Some(&placement),
20511                runtime.register_timeout,
20512            )
20513            .unwrap()
20514        };
20515        let mut live = spawn(&spec);
20516        for _ in 0..3 {
20517            // A new process can enter the old slot while retirement is pending.
20518            let next = spawn(&spec);
20519            assert_ne!(live.module_id, next.module_id);
20520            live.start_kill().unwrap();
20521            live.wait().await.unwrap();
20522            live = next;
20523            assert!(
20524                live.child.try_wait().unwrap().is_none(),
20525                "retiring the old slot must not kill the replacement"
20526            );
20527            assert_eq!(
20528                group_count(),
20529                1,
20530                "only the live spawn's cgroup should remain"
20531            );
20532        }
20533        supervisor.begin_daemon_shutdown();
20534        let reap = tokio::spawn(async move {
20535            live.wait().await.unwrap();
20536        });
20537        supervisor
20538            .end_children_for_daemon_shutdown(false, std::future::pending())
20539            .await;
20540        reap.await.unwrap();
20541        assert_eq!(group_count(), 0);
20542        // A normal exit uses the same tree-cleanup path as a killed spawn.
20543        spec.program = PathBuf::from("/bin/true");
20544        spec.args.clear();
20545        let fresh_roster = ChildRoster::default();
20546        let mut short = spawn_child(
20547            &spec,
20548            None,
20549            None,
20550            &runtime.stderr_ring,
20551            None,
20552            &fresh_roster,
20553            None,
20554            Some(&placement),
20555            runtime.register_timeout,
20556        )
20557        .unwrap();
20558        short.wait().await.unwrap();
20559        assert_eq!(group_count(), 0);
20560        spec.module_id = "_".repeat(255);
20561        let mut long_id = spawn_child(
20562            &spec,
20563            None,
20564            None,
20565            &runtime.stderr_ring,
20566            None,
20567            &fresh_roster,
20568            None,
20569            Some(&placement),
20570            runtime.register_timeout,
20571        )
20572        .unwrap();
20573        long_id.wait().await.unwrap();
20574        assert_eq!(
20575            group_count(),
20576            0,
20577            "valid long module IDs must not exceed cgroup NAME_MAX"
20578        );
20579        fs::remove_dir(root.join("subc-modules")).unwrap();
20580        fs::remove_dir(root).unwrap();
20581        eprintln!("EXECUTED unique_spawn_cgroups_clean_up_across_restarts_and_shutdown");
20582    }
20583
20584    #[test]
20585    fn failed_parent_cgroup_open_is_a_cgroup_supervision_error() {
20586        let path = Path::new("/definitely-missing-subc-cgroup");
20587        let mut command = Command::new("true");
20588        let error = apply_cgroup_placement(
20589            &mut command,
20590            &ModuleSpec {
20591                script: None,
20592                module_id: "broken-cgroup".to_string(),
20593                program: PathBuf::from("true"),
20594                args: Vec::new(),
20595                env: Vec::new(),
20596                reserved: false,
20597                reserved_prefixes: Vec::new(),
20598                protocol: ModuleProtocol::Subc,
20599                overlap: Default::default(),
20600                carry_containment: false,
20601            },
20602            path,
20603        )
20604        .expect_err("a parent cgroup open failure must reject the supervised spawn");
20605        let reason = error.to_string();
20606
20607        assert!(
20608            matches!(error, SuperviseError::Cgroup { .. }),
20609            "parent cgroup open must be reported as a cgroup supervision error: {reason}"
20610        );
20611        assert!(
20612            reason.contains("/definitely-missing-subc-cgroup/cgroup.procs"),
20613            "parent cgroup open failure must name cgroup.procs: {reason}"
20614        );
20615    }
20616
20617    #[tokio::test]
20618    async fn reaping_a_child_removes_its_empty_module_cgroup() {
20619        let root = ScratchDir::new("supervisor-reap-cgroup");
20620        fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
20621        let placement = subc_cgroup::prepare_at(&root)
20622            .expect("prepare scratch cgroup root")
20623            .expect("scratch root has a cgroup.procs marker");
20624        let module_id = "reaped-module";
20625        let module = placement
20626            .module_path(module_id)
20627            .expect("create scratch module cgroup");
20628        let child = Command::new("true")
20629            .env("XDG_DATA_HOME", root.path())
20630            .env("XDG_RUNTIME_DIR", root.path())
20631            .env("XDG_CONFIG_HOME", root.path())
20632            .spawn()
20633            .expect("spawn short-lived child");
20634        let pid = child.id().expect("spawned child has pid");
20635        let mut child = SupervisedChild {
20636            registration_channel: None,
20637            registration_spawn: None,
20638            live_program_binding: None,
20639            registered_config_connection: None,
20640            admission_base: None,
20641            registration_declaration: None,
20642            _program_binding: None,
20643            subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
20644            child: crate::supervise::containment::ProcessChild::plain(child, pid),
20645            exec: crate::activity::ExecOwner(Arc::new(crate::activity::ExecOutcome::new())),
20646            protocol: ModuleProtocol::Subc,
20647            module_id: module_id.to_string(),
20648            cgroup_placement: Some(placement),
20649            stdout_pump: None,
20650            stderr_pump: None,
20651            stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
20652            spawned_at: tokio::time::Instant::now(),
20653            config_delivery: None,
20654            registration_deadline: None,
20655            registration_watch: None,
20656            spawned_at_ms: 0,
20657            spawned_from: PathBuf::from("true"),
20658            launch_spec_digest: LaunchSpecDigest([0; 32]),
20659            spawned_file_identity: None,
20660            process_start_time: None,
20661            process_identity: None,
20662            pid,
20663            roster_guard: None,
20664            #[cfg(target_os = "macos")]
20665            privacy_exec: None,
20666            spawn_failure: None,
20667            admission_kill_sent: false,
20668        };
20669
20670        child.wait().await.expect("reap short-lived child");
20671
20672        assert!(
20673            !module.exists(),
20674            "waiting for a non-carried child must remove its empty cgroup before returning"
20675        );
20676        child.finish_exit(false).await.unwrap();
20677    }
20678
20679    #[test]
20680    fn non_empty_cgroup_removal_is_reported_without_blocking_teardown() {
20681        let root = ScratchDir::new("supervisor-non-empty-cgroup");
20682        fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
20683        let placement = subc_cgroup::prepare_at(&root)
20684            .expect("prepare scratch cgroup root")
20685            .expect("scratch root has a cgroup.procs marker");
20686        let module = placement
20687            .module_path("surviving-module")
20688            .expect("create scratch module cgroup");
20689        fs::write(module.join("surviving-process"), b"still present")
20690            .expect("make scratch cgroup non-empty");
20691        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
20692
20693        remove_module_cgroup(&placement, "surviving-module");
20694
20695        let logs = crate::router::test_log::captured_logs(&logs);
20696        assert!(
20697            module.exists(),
20698            "failed removal must leave the cgroup intact"
20699        );
20700        assert!(
20701            logs.contains("could not remove module cgroup after process exit; continuing teardown")
20702                && logs.contains("surviving-module"),
20703            "best-effort removal must report the failure without returning it: {logs}"
20704        );
20705    }
20706
20707    #[test]
20708    fn cgroup_pre_exec_spawn_failure_names_the_cgroup_path() {
20709        let cgroup_path = PathBuf::from("/sys/fs/cgroup/subc-modules/broken-module");
20710        let reason = SuperviseError::Spawn {
20711            program: PathBuf::from("/bin/true"),
20712            source: io::Error::from_raw_os_error(13),
20713            cgroup_path: Some(cgroup_path.clone()),
20714        }
20715        .to_string();
20716
20717        assert!(
20718            reason.contains(&cgroup_path.display().to_string()),
20719            "a pre_exec spawn failure must name the cgroup path: {reason}"
20720        );
20721    }
20722}
20723
20724#[cfg(test)]
20725mod spawn_subscriber_lag_tests {
20726    use super::*;
20727
20728    /// A subscriber whose connection stops draining is dropped once its frame
20729    /// channel fills. The client must learn that from a terminal Error frame
20730    /// after the frames already queued for it, not from a stream that simply
20731    /// goes quiet.
20732    #[tokio::test]
20733    async fn lagged_spawn_subscriber_receives_a_terminal_lagged_error_after_its_queued_frames() {
20734        let feed = SpawnEventFeed::default();
20735        feed.configure_incarnation("lag-incarnation".to_string());
20736        // A one-slot connection queue that nobody reads until the emits are
20737        // done: the forwarder parks on it and the subscriber channel fills.
20738        let (tx, mut rx) = mpsc::channel(1);
20739        feed.subscribe(ConnectionId::new(1), 7, 1, None, FrameSink::new(tx))
20740            .expect("subscribe");
20741        let emitted = SPAWN_SUBSCRIBER_BUFFER + 16;
20742        for index in 0..emitted {
20743            feed.emit_spawned(&format!("lag-module-{index}"), None, 1000, 0);
20744            // Let the forwarder take what it can so the fill point is the
20745            // subscriber channel, not a scheduling accident.
20746            tokio::task::yield_now().await;
20747        }
20748        assert_eq!(
20749            feed.subscriber_count(),
20750            0,
20751            "the lagged subscriber must be removed"
20752        );
20753
20754        let mut data = Vec::new();
20755        let mut last = None;
20756        loop {
20757            let next = tokio::time::timeout(Duration::from_secs(5), rx.recv())
20758                .await
20759                .expect("the forwarder must finish once the subscriber is dropped");
20760            let Some(outbound) = next else { break };
20761            let frame = outbound.frame;
20762            if frame.header.ty == FrameType::StreamData {
20763                assert!(last.is_none(), "no data may follow the terminal frame");
20764                let event: SpawnEvent = serde_json::from_slice(&frame.body).unwrap();
20765                data.push(event.cursor.seq);
20766            } else {
20767                assert!(last.is_none(), "exactly one terminal frame");
20768                last = Some(frame);
20769            }
20770        }
20771        assert!(!data.is_empty(), "queued frames drain before the terminal");
20772        for pair in data.windows(2) {
20773            assert_eq!(
20774                pair[1],
20775                pair[0] + 1,
20776                "queued frames arrive dense and in order"
20777            );
20778        }
20779        let terminal = last.expect("a lagged subscriber must receive a terminal frame");
20780        assert_eq!(terminal.header.ty, FrameType::Error);
20781        assert_eq!(terminal.header.corr, 7);
20782        let body: subc_protocol::ErrorBody = serde_json::from_slice(&terminal.body).unwrap();
20783        assert_eq!(body.code, SPAWN_SUBSCRIBER_LAGGED_CODE);
20784        let detail = body.detail.expect("lagged error carries detail");
20785        assert_eq!(
20786            detail["first_undelivered_cursor"]["seq"],
20787            data.last().unwrap() + 1,
20788            "the named cursor is the first event the subscriber did not receive"
20789        );
20790        assert_eq!(
20791            detail["first_undelivered_cursor"]["daemon_incarnation"],
20792            "lag-incarnation"
20793        );
20794    }
20795}
20796
20797#[cfg(test)]
20798mod terminal_history_read_concurrency_tests {
20799    use super::*;
20800    use crate::terminal_journal::read_pause;
20801    use cortexkit_test_support::ScratchDir;
20802    use std::sync::mpsc as std_mpsc;
20803
20804    fn journaled_ring(
20805        journal: &Arc<crate::terminal_journal::TerminalJournal>,
20806    ) -> Arc<Mutex<TerminalRing>> {
20807        Arc::new(Mutex::new(
20808            TerminalRing::new(TerminalRingConfig::default(), 1)
20809                .with_journal(Some(Arc::clone(journal))),
20810        ))
20811    }
20812
20813    fn crash(at_ms: u64) -> ExitReport {
20814        ExitReport {
20815            kind: ExitKind::Crash,
20816            code: Some(1),
20817            signal: None,
20818            at_ms,
20819        }
20820    }
20821
20822    /// Record an exit on another thread and report whether it finished within
20823    /// `bound`. The recorder thread is left running if it did not.
20824    fn record_within(
20825        module_id: &'static str,
20826        ring: &Arc<Mutex<TerminalRing>>,
20827        at_ms: u64,
20828        bound: Duration,
20829    ) -> bool {
20830        let ring = Arc::clone(ring);
20831        let (done, done_rx) = std_mpsc::channel();
20832        std::thread::spawn(move || {
20833            record_terminal(
20834                module_id,
20835                &ring,
20836                &SpawnEventFeed::default(),
20837                &crash(at_ms),
20838                TerminalDisposition::Restarting,
20839            );
20840            let _ = done.send(());
20841        });
20842        done_rx.recv_timeout(bound).is_ok()
20843    }
20844
20845    /// A history read in progress must not hold the journal writer (which every
20846    /// module's exit recording needs) or the module's own ring. Exits recorded
20847    /// while the read is paused complete promptly; the paused read answers as of
20848    /// the moment it started, and the next read has each exit exactly once.
20849    #[test]
20850    fn exits_recorded_during_a_paused_history_read_are_not_blocked_or_half_merged() {
20851        let dir = ScratchDir::new("terminal-history-concurrent-read");
20852        let path = dir.join("terminals.jsonl");
20853        let journal = Arc::new(crate::terminal_journal::TerminalJournal::open(
20854            path.clone(),
20855            "daemon".into(),
20856        ));
20857        let reader_ring = journaled_ring(&journal);
20858        let other_ring = journaled_ring(&journal);
20859        assert!(record_within(
20860            "reader-module",
20861            &reader_ring,
20862            10,
20863            Duration::from_secs(5)
20864        ));
20865
20866        let (started, release) = read_pause::install(&path);
20867        let reading = {
20868            let ring = Arc::clone(&reader_ring);
20869            std::thread::spawn(move || durable_terminal_history_of(&ring, "reader-module"))
20870        };
20871        started
20872            .recv_timeout(Duration::from_secs(5))
20873            .expect("the history read reached its pause");
20874
20875        let bound = Duration::from_secs(1);
20876        assert!(
20877            record_within("other-module", &other_ring, 20, bound),
20878            "another module's exit waited on a history read (journal writer held)"
20879        );
20880        assert!(
20881            record_within("reader-module", &reader_ring, 30, bound),
20882            "the read module's own exit waited on its history read (ring held)"
20883        );
20884
20885        drop(release);
20886        let paused = reading.join().unwrap();
20887        assert_eq!(
20888            paused.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
20889            vec![10],
20890            "an exit recorded after the read began lands in neither half of it"
20891        );
20892        assert_eq!(paused.journal_skipped_lines, 0);
20893        assert_eq!(paused.journal_read_errors, 0);
20894
20895        let after = durable_terminal_history_of(&reader_ring, "reader-module");
20896        assert_eq!(
20897            after.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
20898            vec![10, 30],
20899            "the next read merges ring and journal with no duplicate"
20900        );
20901        assert_eq!(after.journal_skipped_lines, 0);
20902    }
20903}
20904
20905/// What a restart does with the exited process's output readers. These drive
20906/// the same settle functions the supervisor calls, with a reader the test
20907/// holds, so a reader that has not been scheduled by the bound is a controlled
20908/// input rather than something only a loaded machine produces.
20909#[cfg(test)]
20910mod stderr_settle_tests {
20911    use std::{
20912        future::Future,
20913        io,
20914        pin::Pin,
20915        sync::{Arc, Mutex},
20916        task::{Context, Poll},
20917        time::Duration,
20918    };
20919
20920    use tokio::{
20921        io::{AsyncRead, ReadBuf},
20922        sync::oneshot,
20923        time::Instant,
20924    };
20925
20926    use super::{settle_stderr_pump, settle_stdout_pump, StderrPump};
20927    use crate::stderr_tail::{
20928        pump_stderr_to, pump_stdout_to, split_capture_stamp, untimed, CaptureState,
20929        ChildOutputSink, OutputSink, StderrRing, StderrTailConfig, TailEntry,
20930    };
20931
20932    const BOUND: Duration = Duration::from_millis(250);
20933
20934    /// Yields `before`, then stays pending until the gate is released, then
20935    /// yields `after` and reaches EOF. The bytes after the gate were written
20936    /// by a process that has already exited; only the reader is behind.
20937    struct HeldReader {
20938        before: Option<Vec<u8>>,
20939        gate: Option<oneshot::Receiver<()>>,
20940        after: io::Cursor<Vec<u8>>,
20941    }
20942
20943    impl AsyncRead for HeldReader {
20944        fn poll_read(
20945            mut self: Pin<&mut Self>,
20946            cx: &mut Context<'_>,
20947            buf: &mut ReadBuf<'_>,
20948        ) -> Poll<io::Result<()>> {
20949            if let Some(bytes) = self.before.take() {
20950                buf.put_slice(&bytes);
20951                return Poll::Ready(Ok(()));
20952            }
20953            if let Some(gate) = self.gate.as_mut() {
20954                match Pin::new(gate).poll(cx) {
20955                    Poll::Pending => return Poll::Pending,
20956                    Poll::Ready(_) => self.gate = None,
20957                }
20958            }
20959            Pin::new(&mut self.after).poll_read(cx, buf)
20960        }
20961    }
20962
20963    struct DiscardSink;
20964
20965    impl OutputSink for DiscardSink {
20966        fn write_line(&mut self, _line: &[u8]) {}
20967    }
20968
20969    fn line(text: &str) -> TailEntry {
20970        TailEntry::Line {
20971            text: text.to_string(),
20972            truncated: false,
20973            at_ms: None,
20974        }
20975    }
20976
20977    fn lock(ring: &Arc<Mutex<StderrRing>>) -> std::sync::MutexGuard<'_, StderrRing> {
20978        ring.lock().unwrap()
20979    }
20980
20981    /// Start a reader for a new process generation that delivers `before`
20982    /// immediately and `after` only once the returned sender fires (or is
20983    /// dropped).
20984    fn held_pump(
20985        ring: &Arc<Mutex<StderrRing>>,
20986        before: &str,
20987        after: &str,
20988    ) -> (StderrPump<tokio::task::JoinHandle<()>>, oneshot::Sender<()>) {
20989        let generation = lock(ring).begin_process();
20990        let (release, gate) = oneshot::channel();
20991        let reader = HeldReader {
20992            before: Some(before.as_bytes().to_vec()),
20993            gate: Some(gate),
20994            after: io::Cursor::new(after.as_bytes().to_vec()),
20995        };
20996        let task = tokio::spawn(pump_stderr_to(
20997            reader,
20998            Arc::clone(ring),
20999            generation,
21000            DiscardSink,
21001        ));
21002        (StderrPump { task, generation }, release)
21003    }
21004
21005    async fn wait_until(ring: &Arc<Mutex<StderrRing>>, done: impl Fn(&StderrRing) -> bool) {
21006        for _ in 0..1000 {
21007            if done(&lock(ring)) {
21008                return;
21009            }
21010            tokio::time::sleep(Duration::from_millis(1)).await;
21011        }
21012        panic!(
21013            "ring never reached the expected state: {:?}",
21014            lock(ring).snapshot(None, None)
21015        );
21016    }
21017
21018    #[tokio::test(start_paused = true)]
21019    async fn a_crash_line_the_reader_had_not_reached_by_the_bound_is_kept_before_the_restart() {
21020        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21021        let (pump, release) = held_pump(&ring, "booting\n", "config error: missing storage\n");
21022
21023        settle_stderr_pump("crasher", &ring, pump, BOUND).await;
21024        let before_release = lock(&ring).snapshot(None, None);
21025        assert!(
21026            matches!(before_release.capture, CaptureState::Incomplete { .. }),
21027            "a reader that has not reached EOF cannot claim a whole tail: {before_release:?}"
21028        );
21029
21030        // The restart: the next process starts and writes before the old
21031        // reader catches up.
21032        let next = lock(&ring).begin_process();
21033        lock(&ring).push_line_from(next, "next process booting");
21034        release.send(()).unwrap();
21035        wait_until(&ring, |ring| {
21036            ring.snapshot(None, None).capture == CaptureState::Captured
21037        })
21038        .await;
21039
21040        assert_eq!(
21041            untimed(lock(&ring).snapshot(None, None).entries),
21042            vec![
21043                line("booting"),
21044                line("config error: missing storage"),
21045                TailEntry::ProcessStart,
21046                line("next process booting"),
21047            ],
21048            "the crash's last line must survive a slow reader and stay in the crashed process's section"
21049        );
21050    }
21051
21052    #[tokio::test(start_paused = true)]
21053    async fn a_pipe_held_open_by_a_descendant_reads_incomplete_without_delaying_the_restart_past_the_bound(
21054    ) {
21055        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21056        // `_held` is never fired: a descendant keeps the pipe open for the
21057        // whole test.
21058        let (pump, _held) = held_pump(&ring, "parent exiting\n", "");
21059
21060        let started = Instant::now();
21061        settle_stderr_pump("orphaning", &ring, pump, BOUND).await;
21062        assert_eq!(
21063            started.elapsed(),
21064            BOUND,
21065            "the restart must wait exactly the bound for a pipe that stays open, no longer"
21066        );
21067
21068        let next = lock(&ring).begin_process();
21069        lock(&ring).push_line_from(next, "next process booting");
21070        tokio::time::sleep(Duration::from_secs(60)).await;
21071
21072        let snapshot = lock(&ring).snapshot(None, None);
21073        match &snapshot.capture {
21074            CaptureState::Incomplete { reason } => assert!(
21075                reason.contains("had not reached EOF") && reason.contains("250ms"),
21076                "the reason must say what is missing and after how long: {reason}"
21077            ),
21078            other => panic!("expected Incomplete while the pipe is held open, got {other:?}"),
21079        }
21080        assert_eq!(
21081            untimed(snapshot.entries),
21082            vec![
21083                line("parent exiting"),
21084                TailEntry::ProcessStart,
21085                line("next process booting"),
21086            ]
21087        );
21088    }
21089
21090    #[tokio::test(start_paused = true)]
21091    async fn a_reader_that_reaches_eof_within_the_bound_leaves_the_tail_captured() {
21092        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21093        let (pump, release) = held_pump(&ring, "one\n", "two\n");
21094        release.send(()).unwrap();
21095
21096        settle_stderr_pump("clean", &ring, pump, BOUND).await;
21097
21098        let snapshot = lock(&ring).snapshot(None, None);
21099        assert_eq!(snapshot.capture, CaptureState::Captured);
21100        assert_eq!(untimed(snapshot.entries), vec![line("one"), line("two")]);
21101    }
21102
21103    #[tokio::test(start_paused = true)]
21104    async fn stdout_buffered_past_the_exit_drain_bound_reaches_the_capture_file() {
21105        const BURST: usize = 150;
21106        let capture = cortexkit_test_support::ScratchDir::new("stdout-exit-drain");
21107        let path = capture.join("two-pipe.stderr.log");
21108        let sink = ChildOutputSink::open(&path, cortexkit_log::Retention::default()).unwrap();
21109        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21110        let generation = lock(&ring).begin_process();
21111        let stdout = (0..BURST)
21112            .map(|i| format!("out-{i:04}-{}\n", "o".repeat(64)))
21113            .collect::<String>();
21114        let stderr = (0..BURST)
21115            .map(|i| format!("err-{i:04}-{}\n", "e".repeat(64)))
21116            .collect::<String>();
21117        // Model a child that has written both bursts and exited. Hold the stdout
21118        // reader after one line and a partial prefix, as if pipe readiness or
21119        // capture-file writes had delayed it. The final line also needs EOF to
21120        // flush: neither complete nor partial buffered output may be discarded.
21121        let first_chunk = stdout.find('\n').unwrap() + 1 + "out-0001-".len();
21122        let (release, gate) = oneshot::channel();
21123        let reader = HeldReader {
21124            before: Some(stdout.as_bytes()[..first_chunk].to_vec()),
21125            gate: Some(gate),
21126            after: io::Cursor::new(stdout.as_bytes()[first_chunk..stdout.len() - 1].to_vec()),
21127        };
21128        let (finished, completion) = oneshot::channel();
21129        let stdout_sink = sink.clone();
21130        let pump = tokio::spawn(async move {
21131            pump_stdout_to(reader, stdout_sink).await;
21132            finished.send(()).unwrap();
21133        });
21134        pump_stderr_to(io::Cursor::new(stderr.into_bytes()), ring, generation, sink).await;
21135
21136        let started = Instant::now();
21137        settle_stdout_pump("two-pipe", pump, BOUND).await;
21138        assert_eq!(
21139            started.elapsed(),
21140            BOUND,
21141            "a late reader must not hold up restart"
21142        );
21143        assert_eq!(
21144            std::fs::read_to_string(&path).unwrap().lines().count(),
21145            BURST + 1
21146        );
21147
21148        release
21149            .send(())
21150            .expect("stdout reader must survive the exit drain bound");
21151        tokio::time::timeout(Duration::from_secs(1), completion)
21152            .await
21153            .expect("released stdout reader must reach EOF")
21154            .expect("stdout capture must finish at EOF, not be cancelled");
21155        let contents = std::fs::read_to_string(&path).unwrap();
21156        let mut lines = contents
21157            .lines()
21158            .map(|line| split_capture_stamp(line).expect("capture stamp").1)
21159            .collect::<Vec<_>>();
21160        let mut expected = (0..BURST)
21161            .flat_map(|i| {
21162                [
21163                    format!("out-{i:04}-{}", "o".repeat(64)),
21164                    format!("err-{i:04}-{}", "e".repeat(64)),
21165                ]
21166            })
21167            .collect::<Vec<_>>();
21168        lines.sort_unstable();
21169        expected.sort_unstable();
21170        assert_eq!(
21171            lines, expected,
21172            "both pipes must retain every complete line exactly once"
21173        );
21174    }
21175}
21176
21177/// Containment of a module's process tree (issue #109).
21178///
21179/// The behaviour these defend against is a module helper surviving its module:
21180/// on a real machine the Synapse embedding module's CUDA worker holds ~2.2 GB of
21181/// VRAM, so a leaked grandchild is a leaked GPU allocation, and a day of restarts
21182/// compounds it.
21183///
21184/// They run against the SUPERVISOR rather than the job-object crate because the
21185/// claim is about teardown: a crate-level test proves a job can reap a tree, not
21186/// that the daemon's drain path reaches it.
21187///
21188/// Windows-only, like the mechanism. On Unix this arm compiles out; the cgroup
21189/// lane there is a separate containment path with its own tests.
21190#[cfg(all(test, windows))]
21191mod job_containment_tests {
21192    use super::*;
21193    use cortexkit_test_support::ScratchDir;
21194    use std::{
21195        path::{Path, PathBuf},
21196        sync::{Arc, Mutex},
21197        time::{Duration, Instant},
21198    };
21199
21200    /// The stub, expected beside this test executable.
21201    ///
21202    /// The existence check is here for the reason its twin at `fake_aft_stub_path`
21203    /// documents: `--lib` does not build `[[bin]]` targets, and a bare spawn
21204    /// failure then reads as a broken test rather than an unbuilt dependency.
21205    fn stub_path() -> PathBuf {
21206        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
21207        assert!(
21208            path.exists(),
21209            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
21210             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
21211            path.display()
21212        );
21213        path
21214    }
21215
21216    /// Poll for the grandchild pid the stub records, and parse it.
21217    fn read_grandchild_pid(path: &Path) -> u32 {
21218        let deadline = Instant::now() + Duration::from_secs(10);
21219        loop {
21220            if let Ok(contents) = std::fs::read_to_string(path) {
21221                if let Ok(pid) = contents.trim().parse() {
21222                    return pid;
21223                }
21224            }
21225            assert!(
21226                Instant::now() < deadline,
21227                "the stub never recorded a grandchild pid at {}",
21228                path.display()
21229            );
21230            std::thread::sleep(Duration::from_millis(10));
21231        }
21232    }
21233
21234    /// Everything one fixture run needs, so the two tests below differ in exactly
21235    /// one place: whether the child is contained.
21236    struct Fixture {
21237        _dir: ScratchDir,
21238        _roster: ChildRoster,
21239        module_id: String,
21240        grandchild: u32,
21241        child: Option<SupervisedChild>,
21242        registry: Arc<Registry>,
21243        snapshot: Arc<Mutex<SupervisorSnapshot>>,
21244        terminal_ring: Arc<Mutex<TerminalRing>>,
21245        spawn_events: SpawnEventFeed,
21246    }
21247
21248    fn fixture(label: &str, module_id: &str) -> Fixture {
21249        fixture_with_carry(label, module_id, false)
21250    }
21251
21252    fn fixture_with_carry(label: &str, module_id: &str, carry_containment: bool) -> Fixture {
21253        let dir = ScratchDir::new(label);
21254        let pid_file = dir.join("grandchild.pid");
21255        let supervisor = Supervisor::new_for_test(
21256            Arc::new(Registry::default()),
21257            RestartPolicy::new(3, Duration::ZERO),
21258        );
21259        let runtime = supervisor.runtime_config();
21260        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21261        let spec = ModuleSpec {
21262            script: None,
21263            module_id: module_id.to_string(),
21264            program: stub_path(),
21265            // Zero args deliberately: a `--subc` argument would make the stub dial
21266            // a daemon that is not there, and the failure would land in the same
21267            // stderr ring this fixture exists to keep quiet.
21268            args: Vec::new(),
21269            env: vec![
21270                ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
21271                (
21272                    "FAKE_AFT_GRANDCHILD_PID_FILE".to_string(),
21273                    pid_file.display().to_string(),
21274                ),
21275            ],
21276            reserved: false,
21277            reserved_prefixes: Vec::new(),
21278            protocol: ModuleProtocol::Subc,
21279            overlap: Default::default(),
21280            carry_containment,
21281        };
21282        let child = spawn_and_mark_running(&spec, &runtime, &snapshot)
21283            .expect("spawn the supervised fixture");
21284        let grandchild = read_grandchild_pid(&pid_file);
21285        Fixture {
21286            _dir: dir,
21287            _roster: runtime.child_roster.clone(),
21288            module_id: module_id.to_string(),
21289            grandchild,
21290            child: Some(child),
21291            registry: Arc::new(Registry::default()),
21292            snapshot,
21293            terminal_ring: Arc::clone(&runtime.terminal_ring),
21294            spawn_events: SpawnEventFeed::default(),
21295        }
21296    }
21297
21298    async fn assert_admission_kill_reaps_grandchild(carry: bool) {
21299        let label = if carry {
21300            "admission-kill-carried-tree"
21301        } else {
21302            "admission-kill-plain-tree"
21303        };
21304        let mut fixture = fixture_with_carry(label, label, carry);
21305        let descendant = subc_os::Process::open(fixture.grandchild)
21306            .unwrap()
21307            .expect("the stub descendant must be alive before admission kill");
21308        assert!(descendant.observe().is_some());
21309        let child = fixture.child.as_mut().unwrap();
21310        assert_eq!(child.child.container().is_some(), carry);
21311        assert_eq!(child.job.is_some(), !carry);
21312
21313        child.start_admission_kill().unwrap();
21314        assert!(child.admission_kill_sent);
21315        let status = timeout(Duration::from_secs(10), child.wait())
21316            .await
21317            .unwrap()
21318            .unwrap();
21319        assert_eq!(
21320            status.code(),
21321            Some(admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE),
21322            "containment teardown must preserve the leader's distinctive status"
21323        );
21324        // Keep the child and its job/container alive: later exit finalization or
21325        // handle drop must not be what makes the descendant-death claim pass.
21326        assert!(
21327            descendant.wait_for_exit(Duration::from_secs(10)).unwrap(),
21328            "admission kill left a descendant running before exit finalization"
21329        );
21330        assert_eq!(child.child.container().is_some(), carry);
21331        assert_eq!(child.job.is_some(), !carry);
21332        child.finish_exit(false).await.unwrap();
21333    }
21334
21335    #[tokio::test]
21336    async fn admission_kill_reaps_grandchild_with_plain_job() {
21337        assert_admission_kill_reaps_grandchild(false).await;
21338    }
21339
21340    #[tokio::test]
21341    async fn admission_kill_reaps_grandchild_with_carried_job() {
21342        assert_admission_kill_reaps_grandchild(true).await;
21343    }
21344
21345    #[tokio::test]
21346    async fn admission_kill_retires_registration_before_wait() {
21347        let mut fixture = fixture("admission-registration", "admission-registration");
21348        let handle = SupervisorHandle::new();
21349        let spawn =
21350            RegistrationSpawn::new(&handle, "admission-registration", SpawnRole::Plain, None);
21351        spawn.ready();
21352        let child = fixture.child.as_mut().unwrap();
21353        child.registration_spawn = Some(spawn.clone());
21354        child.start_admission_kill().unwrap();
21355        assert!(
21356            !spawn.launch_ready(),
21357            "admission kill must retire before its caller can await the child"
21358        );
21359        timeout(Duration::from_secs(10), child.wait())
21360            .await
21361            .unwrap()
21362            .unwrap();
21363        child.finish_exit(false).await.unwrap();
21364    }
21365
21366    impl Fixture {
21367        /// Drain through the supervisor's own teardown path.
21368        async fn drain(&mut self) {
21369            let child = self
21370                .child
21371                .take()
21372                .expect("the fixture child is still present");
21373            drain_child_to_state(
21374                &self.module_id,
21375                ModuleProtocol::Subc,
21376                // No forwarding table in this fixture, so nothing reaches the
21377                // child over a connection.
21378                StopNotice::NotSent,
21379                &self.registry,
21380                None,
21381                &self.snapshot,
21382                &self.terminal_ring,
21383                &self.spawn_events,
21384                child,
21385                Duration::from_millis(500),
21386                ModuleState::Stopped,
21387                Some(false),
21388                &FailureContext::operator(),
21389            )
21390            .await
21391            .expect("drain the supervised fixture");
21392        }
21393    }
21394
21395    /// Teardown reaps the grandchild, not merely the direct child.
21396    ///
21397    /// This is the assertion the change exists for. Before containment the
21398    /// grandchild survived: it is a separate process, and `start_kill` is
21399    /// `TerminateProcess` scoped to one pid.
21400    #[tokio::test]
21401    async fn teardown_reaps_the_grandchild() {
21402        let mut fixture = fixture("teardown-grandchild", "tree-teardown");
21403        let grandchild = fixture.grandchild;
21404
21405        assert!(
21406            subc_jobobject::process_exists(grandchild),
21407            "grandchild {grandchild} must be alive before teardown, or this proves nothing"
21408        );
21409
21410        fixture.drain().await;
21411
21412        assert!(
21413            subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
21414            "grandchild {grandchild} outlived module teardown: the tree was not contained"
21415        );
21416    }
21417
21418    /// The mutation control: with containment withheld, the grandchild survives
21419    /// the same kill.
21420    ///
21421    /// This is the defect reproduction from #109 — a direct-child kill reaches
21422    /// one pid, and the grandchild is a different process. It spawns OUTSIDE the
21423    /// supervisor because `spawn_and_mark_running` now always contains on
21424    /// Windows, which is the point: there is no longer a path that spawns
21425    /// uncontained, so the control has to construct one.
21426    ///
21427    /// Its job is to keep `teardown_reaps_the_grandchild` honest. If the
21428    /// grandchild ever dies here, that test is passing for a reason unrelated to
21429    /// the job object and the containment claim is unproven.
21430    #[test]
21431    fn an_uncontained_grandchild_survives_a_direct_child_kill() {
21432        let dir = ScratchDir::new("teardown-uncontained");
21433        let pid_file = dir.join("grandchild.pid");
21434        let mut child = std::process::Command::new(stub_path())
21435            .env("FAKE_AFT_NEVER_CONNECT", "1")
21436            .env(
21437                "FAKE_AFT_GRANDCHILD_PID_FILE",
21438                pid_file.display().to_string(),
21439            )
21440            .stdin(std::process::Stdio::null())
21441            .stdout(std::process::Stdio::null())
21442            .stderr(std::process::Stdio::null())
21443            .spawn()
21444            .expect("spawn the uncontained fixture");
21445        let grandchild = read_grandchild_pid(&pid_file);
21446
21447        // Exactly what the pre-fix teardown did: kill the direct child.
21448        child.kill().expect("kill the direct child");
21449        let _ = child.wait();
21450
21451        assert!(
21452            subc_jobobject::process_exists(grandchild),
21453            "grandchild {grandchild} died with the direct child, so this control no longer \
21454             distinguishes contained from uncontained teardown and the regression test is \
21455             passing vacuously"
21456        );
21457
21458        // The orphan this control demonstrates is the leak the fix prevents, so
21459        // the control must not leave one behind.
21460        kill_tree(grandchild);
21461    }
21462
21463    /// Crash durability: closing the containment handle reaps the tree with no
21464    /// teardown code running at all.
21465    ///
21466    /// This is the case `taskkill /T` cannot cover — a daemon that dies cannot
21467    /// call anything — and it is why containment is a kernel property of the
21468    /// handle rather than a step in the drain. Discovered by getting the
21469    /// mutation control wrong: clearing `job` to "disable" containment instead
21470    /// killed the tree, which is the guarantee, not a mistake.
21471    #[tokio::test]
21472    async fn dropping_containment_reaps_the_grandchild() {
21473        let mut fixture = fixture("drop-containment", "tree-drop");
21474        let grandchild = fixture.grandchild;
21475
21476        assert!(subc_jobobject::process_exists(grandchild));
21477
21478        // No `drain` call, no kill: dropping the handle is the entire mechanism.
21479        fixture.child.as_mut().expect("child present").job = None;
21480
21481        assert!(
21482            subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
21483            "grandchild {grandchild} survived the containment handle closing, so a daemon \
21484             crash would leave the tree behind"
21485        );
21486    }
21487
21488    /// Kill a pid and its tree, then confirm it is gone.
21489    fn kill_tree(pid: u32) {
21490        let _ = std::process::Command::new("taskkill.exe")
21491            .args(["/PID", &pid.to_string(), "/T", "/F"])
21492            .stdin(std::process::Stdio::null())
21493            .stdout(std::process::Stdio::null())
21494            .stderr(std::process::Stdio::null())
21495            .status();
21496        assert!(
21497            subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10)),
21498            "could not clean up grandchild {pid}"
21499        );
21500    }
21501}
21502
21503#[cfg(test)]
21504mod privacy_trampoline_configuration_tests {
21505    #[tokio::test]
21506    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21507    async fn macos_spawn_without_a_configured_trampoline_refuses_by_name() {
21508        #[cfg(target_os = "macos")]
21509        {
21510            let supervisor = super::Supervisor::new(
21511                std::sync::Arc::new(crate::Registry::default()),
21512                super::RestartPolicy::default(),
21513            );
21514            let error = supervisor.spawn(spec()).unwrap_err();
21515            assert!(
21516                error
21517                    .to_string()
21518                    .contains("no privacy trampoline configured"),
21519                "{error}"
21520            );
21521        }
21522    }
21523
21524    #[tokio::test]
21525    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21526    async fn macos_wrong_trampoline_is_rejected_by_the_startup_probe() {
21527        #[cfg(target_os = "macos")]
21528        {
21529            let supervisor = super::Supervisor::new(
21530                std::sync::Arc::new(crate::Registry::default()),
21531                super::RestartPolicy::default(),
21532            )
21533            .with_privacy_trampoline(std::env::current_exe().unwrap());
21534            let error = supervisor.spawn(spec()).unwrap_err();
21535            assert!(
21536                error
21537                    .to_string()
21538                    .contains("binary does not implement the privacy trampoline protocol"),
21539                "{error}"
21540            );
21541        }
21542    }
21543
21544    #[cfg(target_os = "macos")]
21545    fn spec() -> super::ModuleSpec {
21546        super::ModuleSpec {
21547            module_id: "privacy-configuration".into(),
21548            program: "/bin/sleep".into(),
21549            args: vec!["30".into()],
21550            env: vec![],
21551            reserved: false,
21552            reserved_prefixes: vec![],
21553            protocol: subc_control::ModuleProtocol::None,
21554            overlap: super::ModuleOverlap::Exclusive,
21555            carry_containment: false,
21556            script: None,
21557        }
21558    }
21559}
21560
21561#[cfg(test)]
21562mod privacy_exec_boundary_tests {
21563    #[cfg(target_os = "macos")]
21564    use super::*;
21565    #[cfg(target_os = "macos")]
21566    use std::{
21567        io::{Read, Write},
21568        net::{TcpListener, TcpStream},
21569    };
21570
21571    /// Unit-test-only pause at the actual early image read, not at a later
21572    /// status read. Production supervisors never inspect this environment key.
21573    #[cfg(target_os = "macos")]
21574    pub(super) fn before_image_sample(spec: &ModuleSpec, pid: u32) {
21575        if let Some((_, path)) = spec
21576            .env
21577            .iter()
21578            .find(|(key, _)| key == "SUBC_TEST_PRIVACY_SAMPLE_BARRIER")
21579        {
21580            let mut barrier = TcpStream::connect(path).unwrap();
21581            barrier
21582                .set_read_timeout(Some(Duration::from_secs(30)))
21583                .unwrap();
21584            barrier.write_all(&pid.to_ne_bytes()).unwrap();
21585            let mut release = [0];
21586            barrier.read_exact(&mut release).unwrap();
21587            assert_eq!(&release, b"X");
21588        }
21589    }
21590
21591    #[cfg(target_os = "macos")]
21592    fn spec(program: &str, args: &[&str]) -> ModuleSpec {
21593        ModuleSpec {
21594            script: None,
21595            module_id: "privacy-boundary".into(),
21596            program: program.into(),
21597            args: args.iter().map(|arg| (*arg).into()).collect(),
21598            env: vec![],
21599            reserved: false,
21600            reserved_prefixes: vec![],
21601            protocol: ModuleProtocol::None,
21602            overlap: ModuleOverlap::Exclusive,
21603            carry_containment: false,
21604        }
21605    }
21606
21607    #[cfg(target_os = "macos")]
21608    async fn accept(listener: TcpListener) -> TcpStream {
21609        // Socket readiness, not elapsed time, establishes both pause points.
21610        let listener = tokio::net::TcpListener::from_std({
21611            listener.set_nonblocking(true).unwrap();
21612            listener
21613        })
21614        .unwrap();
21615        let (stream, _) = tokio::time::timeout(Duration::from_secs(30), listener.accept())
21616            .await
21617            .unwrap()
21618            .unwrap();
21619        let stream = stream.into_std().unwrap();
21620        stream.set_nonblocking(false).unwrap();
21621        stream
21622            .set_read_timeout(Some(Duration::from_secs(30)))
21623            .unwrap();
21624        stream
21625    }
21626
21627    #[tokio::test]
21628    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21629    async fn macos_roster_withholds_a_nonnull_trampoline_image_until_exec_confirmation() {
21630        #[cfg(target_os = "macos")]
21631        {
21632            let root = cortexkit_test_support::ScratchDir::new("privacy-roster-barrier");
21633            // Loopback sockets also work when the replay adapter's TMPDIR is
21634            // longer than Darwin's Unix-domain socket path limit.
21635            let exec_listener = TcpListener::bind("127.0.0.1:0").unwrap();
21636            let sample_listener = TcpListener::bind("127.0.0.1:0").unwrap();
21637            let record = root.join("live-children.json");
21638            let supervisor =
21639                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21640                    .with_live_children_record(&record);
21641            let runtime = supervisor.runtime_config();
21642            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21643            let mut spec = spec("/bin/sleep", &["30"]);
21644            spec.env = vec![
21645                (
21646                    "SUBC_TEST_PRIVACY_EXEC_BARRIER".into(),
21647                    exec_listener.local_addr().unwrap().to_string(),
21648                ),
21649                (
21650                    "SUBC_TEST_PRIVACY_SAMPLE_BARRIER".into(),
21651                    sample_listener.local_addr().unwrap().to_string(),
21652                ),
21653            ];
21654            let spawn = tokio::task::spawn_blocking(move || {
21655                spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap()
21656            });
21657            let mut sample = accept(sample_listener).await;
21658            let mut pid = [0; 4];
21659            sample.read_exact(&mut pid).unwrap();
21660            let pid = u32::from_ne_bytes(pid);
21661            let mut exec = accept(exec_listener).await;
21662            let mut ready = [0];
21663            exec.read_exact(&mut ready).unwrap();
21664            assert_eq!(&ready, b"R");
21665            // The early read is guaranteed to see a real, non-null trampoline
21666            // image: the fixture has reached its barrier and cannot exec yet.
21667            let trampoline = subc_os::file_identity(&test_privacy_trampoline()).unwrap();
21668            assert_eq!(
21669                observe_spawned_image(pid).unwrap().executable,
21670                Some(trampoline)
21671            );
21672            sample.write_all(b"X").unwrap();
21673            let mut child = spawn.await.unwrap();
21674            let early = crate::live_children::read_record(&record).unwrap();
21675            assert_eq!(early.len(), 1);
21676            assert_eq!(early[0].pid, pid);
21677            assert_eq!(
21678                early[0].executable, None,
21679                "unconfirmed trampoline image entered the roster"
21680            );
21681            assert!(child.report_ready.get().is_none());
21682            // The barrier's duration is unrelated to the production five-second
21683            // exec budget. Start the test's confirmation budget upon release.
21684            child.privacy_exec.as_mut().unwrap().deadline =
21685                tokio::time::Instant::now() + Duration::from_secs(30);
21686            exec.write_all(b"X").unwrap();
21687            child.confirm_privacy_exec().await;
21688            assert_eq!(child.spawn_failure, None);
21689            assert!(child.report_ready.get().is_some());
21690            let confirmed = crate::live_children::read_record(&record).unwrap();
21691            let module = subc_os::file_identity(std::path::Path::new("/bin/sleep")).unwrap();
21692            assert_ne!(module, trampoline);
21693            assert_eq!(confirmed[0].executable, Some(module.into()));
21694            child.start_kill().unwrap();
21695            child.wait().await.unwrap();
21696            child.release_roster();
21697        }
21698    }
21699
21700    #[tokio::test]
21701    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21702    async fn macos_unstamped_reexec_records_the_observed_native_image() {
21703        #[cfg(target_os = "macos")]
21704        {
21705            let root = cortexkit_test_support::ScratchDir::new("privacy-reexec");
21706            let record = root.join("live-children.json");
21707            let supervisor =
21708                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21709                    .with_live_children_record(&record);
21710            let runtime = supervisor.runtime_config();
21711            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21712            let fixture = crate::config_gate::program::native_fixture_for_test();
21713            let mut spec = spec(
21714                "/bin/sh",
21715                &["-c", "exec \"$1\" 600", "reexec", fixture.to_str().unwrap()],
21716            );
21717            spec.env
21718                .push(("SUBC_TEST_PRIVACY_IMAGE_DELAY_MS".into(), "5".into()));
21719            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21720            let native_image = subc_os::file_identity(&fixture).unwrap();
21721            // Native image installation, not shell startup speed, establishes
21722            // that this launch has crossed the re-exec boundary before sampling.
21723            let reexec = tokio::time::timeout(Duration::from_secs(5), async {
21724                while observe_spawned_image(child.pid).and_then(|image| image.executable)
21725                    != Some(native_image)
21726                {
21727                    tokio::time::sleep(Duration::from_millis(1)).await;
21728                }
21729            })
21730            .await;
21731            child.confirm_privacy_exec().await;
21732            let failure = child.spawn_failure.clone();
21733            let ready = child.report_ready.get().is_some();
21734            let confirmed = crate::live_children::read_record(&record).unwrap();
21735            child.start_kill().unwrap();
21736            tokio::time::timeout(Duration::from_secs(5), child.wait())
21737                .await
21738                .unwrap()
21739                .unwrap();
21740            child.release_roster();
21741
21742            reexec.expect("the shell must re-exec the native fixture");
21743            assert_eq!(
21744                failure, None,
21745                "an unstamped program may re-exec before observation"
21746            );
21747            assert!(ready);
21748            assert_eq!(confirmed.len(), 1);
21749            assert_eq!(confirmed[0].executable, Some(native_image.into()));
21750        }
21751    }
21752
21753    #[tokio::test]
21754    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21755    async fn macos_unstamped_ack_without_exec_still_refuses_the_trampoline() {
21756        #[cfg(target_os = "macos")]
21757        {
21758            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
21759            let supervisor =
21760                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
21761            let runtime = supervisor.runtime_config();
21762            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21763            let fixture = crate::config_gate::program::native_fixture_for_test();
21764            let mut spec = spec(fixture.to_str().unwrap(), &["600"]);
21765            spec.env.push((
21766                "SUBC_TEST_PRIVACY_EXEC_BARRIER".into(),
21767                listener.local_addr().unwrap().to_string(),
21768            ));
21769            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21770            let mut exec = accept(listener).await;
21771            let mut ready = [0];
21772            exec.read_exact(&mut ready).unwrap();
21773            assert_eq!(&ready, b"R");
21774            assert_eq!(
21775                observe_spawned_image(child.pid).unwrap().executable,
21776                subc_os::file_identity(&test_privacy_trampoline())
21777            );
21778            // Simulate a broken trampoline that acknowledges exec but keeps
21779            // running its own image, held at the fixture's pre-exec barrier.
21780            let (reader, writer) = std::io::pipe().unwrap();
21781            drop(writer);
21782            child.privacy_exec.as_mut().unwrap().reader =
21783                tokio::io::unix::AsyncFd::new(reader).unwrap();
21784            child.confirm_privacy_exec().await;
21785            let failure = child.spawn_failure.clone();
21786            let ready = child.report_ready.get().is_some();
21787            child.start_kill().unwrap();
21788            tokio::time::timeout(Duration::from_secs(5), child.wait())
21789                .await
21790                .unwrap()
21791                .unwrap();
21792            child.release_roster();
21793            assert_eq!(
21794                failure.as_deref(),
21795                Some("privacy identity trampoline did not exec the module")
21796            );
21797            assert!(!ready);
21798        }
21799    }
21800
21801    #[tokio::test]
21802    #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21803    async fn macos_resumed_121_is_a_module_exit_not_a_trampoline_refusal() {
21804        #[cfg(target_os = "macos")]
21805        {
21806            let registry = Arc::new(Registry::default());
21807            let policy = RestartPolicy::new(0, Duration::ZERO);
21808            let fixture = crate::config_gate::program::native_fixture_for_test();
21809            let spec = spec(fixture.to_str().unwrap(), &["exit121"]);
21810            let scratch = cortexkit_test_support::ScratchDir::new("resumed-exit");
21811            let supervisor = Supervisor::new_for_test(Arc::clone(&registry), policy)
21812                .with_config_runtime(suspended_spawn_tests::gated_owner(&scratch, &spec, true));
21813            let runtime = supervisor.runtime_config();
21814            let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21815            // A module cannot exit before suspended admission. After resume,
21816            // retain the real exit status even when it resembles a refusal.
21817            let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21818            child.confirm_privacy_exec().await;
21819            assert_eq!(child.spawn_failure, None);
21820            assert!(child.report_ready.get().is_some());
21821            let pid = child.pid;
21822            tokio::task::spawn_blocking(move || {
21823                subc_os::fork_exec_test::wait_for_child_exit_without_reaping(pid)
21824            })
21825            .await
21826            .unwrap()
21827            .unwrap();
21828            let status = child.wait().await.unwrap();
21829            assert_eq!(status.code(), Some(121));
21830            assert!(child.privacy_exec.is_none());
21831            let report = classify_reaped_child_exit(&snapshot, &child, &status);
21832            on_child_exit(
21833                &spec,
21834                policy,
21835                &registry,
21836                &snapshot,
21837                &runtime.terminal_ring,
21838                &runtime.spawn_events,
21839                &runtime.child_roster,
21840                report,
21841                true,
21842            )
21843            .await;
21844            let state = lock_snapshot(&snapshot).unwrap();
21845            assert_eq!(state.state, ModuleState::Failed);
21846            assert_eq!(state.last_exit.as_ref().unwrap().code, Some(121));
21847            assert_eq!(state.reported_pid(), None);
21848            drop(state);
21849            let history = runtime.terminal_ring.lock().unwrap().snapshot();
21850            assert_eq!(history.entries.len(), 1);
21851            let terminal = &history.entries[0];
21852            assert_eq!(terminal.exit_code, Some(121));
21853            assert_eq!(terminal.exit_kind, subc_control::TerminalExitKind::Crash);
21854            assert_eq!(terminal.disposition, TerminalDisposition::Failed);
21855            assert_eq!(
21856                terminal.disposition_detail.as_deref(),
21857                Some(policy.budget_exhausted_detail().as_str()),
21858                "module exit 121 was classified as a trampoline refusal: {terminal:?}"
21859            );
21860            assert_eq!(child.spawn_failure, None);
21861            child.release_roster();
21862        }
21863    }
21864}
21865
21866#[cfg(all(test, target_os = "macos"))]
21867#[path = "supervise/suspended_spawn_tests.rs"]
21868mod suspended_spawn_tests;
21869
21870/// The daemon's real spawn path hands a subc-wire child its launch nonce on
21871/// descriptor 3, without an environment copy. The shell records the nonce
21872/// and its environment after exec so these tests observe the real handover.
21873#[cfg(all(test, unix))]
21874mod launch_nonce_descriptor_tests {
21875    use super::{ChildRoster, ModuleProtocol, ModuleSpec, SupervisorHandle};
21876    use crate::stderr_tail::{StderrRing, StderrTailConfig};
21877    use cortexkit_test_support::ScratchDir;
21878    use std::{
21879        path::PathBuf,
21880        sync::{Arc, Mutex},
21881        time::{Duration, Instant},
21882    };
21883
21884    async fn probe(role: super::SpawnRole) {
21885        let scratch = ScratchDir::new("launch-nonce-descriptor");
21886        let fd_copy = scratch.join("from-descriptor");
21887        let env_copy = scratch.join("environment");
21888        let script = format!(
21889            "env > '{env}.tmp' && mv '{env}.tmp' '{env}'; cat <&3 > '{fd}.tmp' && mv '{fd}.tmp' '{fd}'; sleep 30",
21890            fd = fd_copy.display(), env = env_copy.display(),
21891        );
21892        let xdg = |name: &str| (name.to_string(), scratch.join(name).display().to_string());
21893        let spec = ModuleSpec {
21894            script: None,
21895            module_id: "nonce-descriptor-probe".to_string(),
21896            program: PathBuf::from("/bin/sh"),
21897            args: vec!["-c".to_string(), script],
21898            env: vec![
21899                xdg("XDG_DATA_HOME"),
21900                xdg("XDG_RUNTIME_DIR"),
21901                xdg("XDG_CONFIG_HOME"),
21902                ("SUBC_LAUNCH_NONCE".to_string(), "must-not-leak".to_string()),
21903            ],
21904            reserved: true,
21905            reserved_prefixes: Vec::new(),
21906            protocol: ModuleProtocol::Subc,
21907            overlap: Default::default(),
21908            carry_containment: false,
21909        };
21910        let handle = SupervisorHandle::new();
21911        let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21912        let roster = ChildRoster::default();
21913        #[cfg(target_os = "macos")]
21914        {
21915            let path = super::test_privacy_trampoline();
21916            roster.set_privacy_trampoline(super::probe_privacy_trampoline(&path).map(|()| path));
21917        }
21918        let child = super::spawn_child_in_slot(
21919            &spec,
21920            None,
21921            Some(&handle),
21922            &ring,
21923            None,
21924            &roster,
21925            None,
21926            #[cfg(target_os = "linux")]
21927            None,
21928            role,
21929            matches!(role, super::SpawnRole::SwapCandidate),
21930            super::DEFAULT_REGISTER_TIMEOUT,
21931        )
21932        .expect("spawn probe");
21933        let deadline = Instant::now() + Duration::from_secs(10);
21934        while !(fd_copy.exists() && env_copy.exists()) {
21935            assert!(Instant::now() < deadline, "probe never wrote its copies");
21936            tokio::time::sleep(Duration::from_millis(20)).await;
21937        }
21938        let nonce = std::fs::read_to_string(fd_copy).unwrap();
21939        assert!(!nonce.is_empty());
21940        let environment = std::fs::read_to_string(env_copy).unwrap();
21941        assert!(environment
21942            .lines()
21943            .any(|line| line.starts_with("SUBC_LAUNCH_NONCE_FD=3:")));
21944        let copy = environment
21945            .lines()
21946            .find_map(|line| line.strip_prefix("SUBC_LAUNCH_NONCE="));
21947        assert_eq!(
21948            copy, None,
21949            "Unix children must never receive the environment nonce"
21950        );
21951        if matches!(role, super::SpawnRole::Plain) {
21952            assert_eq!(
21953                handle.spawn_nonce(&spec.module_id).as_deref(),
21954                Some(nonce.as_str())
21955            );
21956        }
21957        drop(child);
21958    }
21959
21960    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
21961    async fn a_spawned_module_receives_its_nonce_only_on_descriptor_3() {
21962        probe(super::SpawnRole::Plain).await;
21963    }
21964
21965    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
21966    async fn swap_candidate_receives_its_nonce_only_on_descriptor_3() {
21967        probe(super::SpawnRole::SwapCandidate).await;
21968    }
21969}
21970
21971#[cfg(all(test, target_os = "linux"))]
21972#[path = "supervise/cgroup_reap_tests.rs"]
21973mod cgroup_reap_tests;
21974
21975#[cfg(all(test, target_os = "linux"))]
21976mod cgroup_containment_tests {
21977    use super::*;
21978    use cortexkit_test_support::ScratchDir;
21979
21980    #[tokio::test]
21981    async fn linux_subtree_memory_covers_module_children() {
21982        let dir = ScratchDir::new("subtree-memory");
21983        let root = PathBuf::from(format!(
21984            "/sys/fs/cgroup/subc-memory-test-{}-{}",
21985            std::process::id(),
21986            unix_ms_now()
21987        ));
21988        if let Err(error) = std::fs::create_dir(&root) {
21989            assert!(
21990                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
21991                "required cgroup test cannot execute: {error}"
21992            );
21993            eprintln!("SKIP linux_subtree_memory_covers_module_children: {error}");
21994            return;
21995        }
21996        let placement = subc_cgroup::prepare_at(&root)
21997            .unwrap()
21998            .expect("delegated cgroup");
21999        let supervisor = Supervisor::new_for_test(
22000            Arc::new(Registry::default()),
22001            RestartPolicy::new(3, Duration::ZERO),
22002        )
22003        .with_cgroup_placement(Some(placement));
22004        let ready = dir.join("ready");
22005        let module = supervisor
22006            .spawn(ModuleSpec {
22007                script: None,
22008                module_id: "memory-tree".into(),
22009                program: PathBuf::from("/bin/sh"),
22010                args: vec![
22011                    "-c".into(),
22012                    "sleep 600 & sleep 600 & sleep 600 & echo ready > \"$1\"; wait".into(),
22013                    "fixture".into(),
22014                    ready.display().to_string(),
22015                ],
22016                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
22017                    .into_iter()
22018                    .map(|key| (key.into(), dir.display().to_string()))
22019                    .collect(),
22020                reserved: false,
22021                reserved_prefixes: Vec::new(),
22022                protocol: ModuleProtocol::None,
22023                overlap: Default::default(),
22024                carry_containment: false,
22025            })
22026            .unwrap();
22027        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
22028        while !ready.exists() {
22029            assert!(
22030                tokio::time::Instant::now() < deadline,
22031                "children never started"
22032            );
22033            tokio::time::sleep(Duration::from_millis(10)).await;
22034        }
22035        let readings = crate::subtree_resources::read(vec![module.subtree_target()]).await;
22036        let reading = &readings[0];
22037        assert!(
22038            reading.process_count.is_some_and(|count| count >= 4),
22039            "{reading:?}"
22040        );
22041        assert!(
22042            reading.memory_bytes.is_some_and(|bytes| bytes > 0),
22043            "{reading:?}"
22044        );
22045        module.stop().await.unwrap();
22046        drop(module);
22047        std::fs::remove_dir(root.join("subc-modules")).unwrap();
22048        std::fs::remove_dir(&root).unwrap();
22049        eprintln!("EXECUTED linux_subtree_memory_covers_module_children: {reading:?}");
22050    }
22051
22052    fn running(pid: u32) -> bool {
22053        // An orphan can remain a zombie until the container init reaps it.
22054        std::fs::read_to_string(format!("/proc/{pid}/stat"))
22055            .ok()
22056            .and_then(|stat| {
22057                stat.rsplit_once(") ")
22058                    .map(|(_, rest)| rest.starts_with('Z'))
22059            })
22060            .is_some_and(|zombie| !zombie)
22061    }
22062
22063    #[tokio::test]
22064    async fn linux_teardown_reaps_the_grandchild() {
22065        teardown_tree("linux_teardown_reaps_the_grandchild", false).await;
22066    }
22067
22068    #[tokio::test]
22069    async fn linux_shutdown_straggler_reaps_the_grandchild() {
22070        teardown_tree("linux_shutdown_straggler_reaps_the_grandchild", true).await;
22071    }
22072
22073    async fn teardown_tree(test_name: &str, shutdown: bool) {
22074        let dir = ScratchDir::new(test_name);
22075        let root = PathBuf::from(format!(
22076            "/sys/fs/cgroup/subc-tree-test-{test_name}-{}-{}",
22077            std::process::id(),
22078            unix_ms_now()
22079        ));
22080        if let Err(error) = std::fs::create_dir(&root) {
22081            assert!(
22082                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
22083                "required cgroup test cannot execute: {error}"
22084            );
22085            eprintln!(
22086                "SKIP {test_name}: no writable delegated cgroup at {}: {error}",
22087                root.display()
22088            );
22089            return;
22090        }
22091        let placement = subc_cgroup::prepare_at(&root)
22092            .expect("prepare isolated kernel cgroup")
22093            .expect("isolated cgroup is delegated");
22094        let module_id = "tree-teardown";
22095        let module = placement
22096            .module_path(module_id)
22097            .expect("create isolated module cgroup");
22098        if !module.join("cgroup.kill").exists() {
22099            std::fs::remove_dir(&module).unwrap();
22100            std::fs::remove_dir(root.join("subc-modules")).unwrap();
22101            std::fs::remove_dir(&root).unwrap();
22102            assert!(
22103                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
22104                "required cgroup.kill interface unavailable"
22105            );
22106            eprintln!("SKIP {test_name}: cgroup.kill unavailable (kernel < 5.14)");
22107            return;
22108        }
22109        let supervisor = Supervisor::new_for_test(
22110            Arc::new(Registry::default()),
22111            RestartPolicy::new(3, Duration::ZERO),
22112        )
22113        .with_cgroup_placement(Some(placement));
22114        let mut runtime = supervisor.runtime_config();
22115        runtime.child_roster = runtime
22116            .child_roster
22117            .for_module(Arc::new(Mutex::new(Duration::from_millis(100))));
22118        let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
22119        let pid_file = dir.join("grandchild.pid");
22120        let spec = ModuleSpec {
22121            script: None,
22122            module_id: module_id.to_string(),
22123            program: PathBuf::from("/bin/sh"),
22124            args: vec![
22125                "-c".into(),
22126                "trap '' TERM; sleep 600 & echo $! > \"$1\"; wait".into(),
22127                "fixture".into(),
22128                pid_file.display().to_string(),
22129            ],
22130            env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
22131                .into_iter()
22132                .map(|key| (key.to_string(), dir.display().to_string()))
22133                .collect(),
22134            reserved: false,
22135            reserved_prefixes: Vec::new(),
22136            protocol: ModuleProtocol::None,
22137            overlap: Default::default(),
22138            carry_containment: false,
22139        };
22140        let child =
22141            spawn_and_mark_running(&spec, &runtime, &snapshot).expect("spawn supervised tree");
22142        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
22143        let grandchild: u32 = loop {
22144            if let Ok(contents) = std::fs::read_to_string(&pid_file) {
22145                if let Ok(pid) = contents.trim().parse() {
22146                    break pid;
22147                }
22148            }
22149            assert!(
22150                tokio::time::Instant::now() < deadline,
22151                "grandchild pid was not recorded"
22152            );
22153            tokio::time::sleep(Duration::from_millis(10)).await;
22154        };
22155        assert!(
22156            running(grandchild),
22157            "grandchild must be alive before teardown"
22158        );
22159        if shutdown {
22160            let mut child = child;
22161            crate::child_roster::end_children_for_daemon_shutdown(
22162                &runtime.child_roster,
22163                false,
22164                std::future::pending(),
22165            )
22166            .await;
22167            child.wait().await.expect("reap shutdown straggler");
22168        } else {
22169            drain_child_to_state(
22170                module_id,
22171                ModuleProtocol::None,
22172                StopNotice::NotSent,
22173                &Registry::default(),
22174                None,
22175                &snapshot,
22176                &runtime.terminal_ring,
22177                &SpawnEventFeed::default(),
22178                child,
22179                Duration::from_millis(100),
22180                ModuleState::Stopped,
22181                Some(false),
22182                &FailureContext::operator(),
22183            )
22184            .await
22185            .expect("real supervisor teardown");
22186        }
22187        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
22188        while running(grandchild) && tokio::time::Instant::now() < deadline {
22189            tokio::time::sleep(Duration::from_millis(10)).await;
22190        }
22191        let survived = running(grandchild);
22192        // Kill a surviving grandchild so a failed test does not leave it behind.
22193        if survived {
22194            let pid = rustix::process::Pid::from_raw(grandchild as i32).unwrap();
22195            let _ = rustix::process::kill_process(pid, rustix::process::Signal::KILL);
22196            tokio::time::sleep(Duration::from_millis(100)).await;
22197        }
22198        if module.exists() {
22199            std::fs::remove_dir(&module).expect("remove empty module cgroup");
22200        }
22201        std::fs::remove_dir(root.join("subc-modules")).unwrap();
22202        std::fs::remove_dir(&root).unwrap();
22203        assert!(
22204            !survived,
22205            "grandchild {grandchild} outlived module teardown"
22206        );
22207        eprintln!("EXECUTED {test_name}: grandchild {grandchild} killed in isolated cgroup");
22208    }
22209}
22210
22211/// A slow live-children record write on the restart path must not stop the
22212/// daemon from answering the replacement module's authentication handshake.
22213#[cfg(all(test, unix))]
22214mod record_write_stall_tests {
22215    use super::*;
22216    use std::sync::atomic::{AtomicBool, Ordering};
22217    use subc_transport::{authenticate_client, ConnectionInfo, Endpoint, SCHEMA_VERSION};
22218
22219    /// `subc-client-rs` gives the whole handshake this long before the module
22220    /// exits with `Timeout { stage: ServerProof }`.
22221    const MODULE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
22222    /// How long the replacement's admission write is held: longer than the
22223    /// module's deadline, standing in for the delay a busy disk can add
22224    /// across the two syncs in that write.
22225    const HELD_RECORD_WRITE: Duration = Duration::from_secs(3);
22226
22227    /// A module that runs `/bin/sleep` directly, not through `/bin/sh -c`.
22228    /// On macOS every module is launched through the privacy trampoline, and
22229    /// a module that is not a `#!` script is admitted only if its running
22230    /// image is the configured program. With `/bin/sh -c "exec sleep 600"`
22231    /// the shell soon replaces itself with `/bin/sleep`, which does not match
22232    /// the configured `/bin/sh`. The image is read only after the spawn's
22233    /// live-children record write, and here that write lasted long enough for
22234    /// the shell to have exec'd every time, so each process was refused and
22235    /// killed right after spawn, and the supervisor crash-looped it with
22236    /// backoff until its restart budget ran out. The restart this test
22237    /// measures would then never produce a module at all.
22238    fn sleeping_spec() -> ModuleSpec {
22239        ModuleSpec {
22240            script: None,
22241            module_id: "record-write-stall".into(),
22242            program: "/bin/sleep".into(),
22243            args: vec!["600".into()],
22244            env: vec![],
22245            reserved: false,
22246            reserved_prefixes: vec![],
22247            protocol: ModuleProtocol::None,
22248            overlap: Default::default(),
22249            carry_containment: false,
22250        }
22251    }
22252
22253    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
22254    async fn module_auth_completes_while_the_restart_waits_on_the_record_write() {
22255        let home = cortexkit_test_support::ScratchDir::new("record-write-stall");
22256        let supervisor =
22257            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
22258                .with_live_children_record(home.join("live-children.json"));
22259        let module = supervisor.spawn(sleeping_spec()).unwrap();
22260        // `reported_pid` names a process only once it is confirmed as the
22261        // module (on macOS, once the trampoline's image check has passed), so
22262        // a process the daemon is about to refuse and kill never counts as
22263        // the running module, here or in the final wait below.
22264        let old_pid = tokio::time::timeout(Duration::from_secs(10), async {
22265            loop {
22266                if let Some(pid) = lock_snapshot(&module.inner.snapshot)
22267                    .unwrap()
22268                    .reported_pid()
22269                {
22270                    return pid;
22271                }
22272                tokio::time::sleep(Duration::from_millis(10)).await;
22273            }
22274        })
22275        .await
22276        .expect("the first process was admitted as the module");
22277
22278        // The daemon's listener, served by this runtime's workers like the
22279        // supervisor's own tasks.
22280        let key = vec![0x42; 32];
22281        let daemon_id = [0x24; 16];
22282        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
22283        let port = listener.local_addr().unwrap().port();
22284        let server = tokio::spawn(crate::server::serve_listener(
22285            listener,
22286            Arc::new(crate::router::Router::with_default_self_handler()),
22287            crate::server::ServerAuth::with_limits(
22288                key.clone(),
22289                daemon_id,
22290                "test",
22291                crate::server::DEFAULT_AUTH_DEADLINE,
22292                4,
22293            ),
22294        ));
22295
22296        // Hold the write that admits the replacement, once, and say when it
22297        // has started.
22298        let (held_tx, held_rx) = std::sync::mpsc::channel();
22299        let armed = AtomicBool::new(true);
22300        supervisor
22301            .child_roster
22302            .set_record_write_hook_for_test(move |live| {
22303                let admitting_replacement = live.values().any(|entry| entry.pid != old_pid);
22304                if admitting_replacement && armed.swap(false, Ordering::SeqCst) {
22305                    let _ = held_tx.send(());
22306                    std::thread::sleep(HELD_RECORD_WRITE);
22307                }
22308            });
22309
22310        // The replacement module, as a separate process would be: its own
22311        // thread and runtime, so only the daemon's runtime can be stalled.
22312        let module_process = std::thread::spawn(move || {
22313            held_rx
22314                .recv_timeout(Duration::from_secs(30))
22315                .expect("the restart reached the replacement's record write");
22316            let conn = ConnectionInfo {
22317                schema: SCHEMA_VERSION,
22318                wire_version: None,
22319                endpoints: vec![Endpoint {
22320                    host: "127.0.0.1".to_owned(),
22321                    port,
22322                }],
22323                key,
22324                daemon_id,
22325                pid: std::process::id(),
22326                daemon_ver: "test".to_owned(),
22327            };
22328            tokio::runtime::Builder::new_current_thread()
22329                .enable_all()
22330                .build()
22331                .unwrap()
22332                .block_on(async {
22333                    let started = Instant::now();
22334                    let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
22335                        .await
22336                        .unwrap();
22337                    let result =
22338                        authenticate_client(&mut stream, &conn, MODULE_AUTH_DEADLINE).await;
22339                    (result, started.elapsed())
22340                })
22341        });
22342
22343        module.restart(Some(0)).await.unwrap();
22344        let (auth, elapsed) = tokio::task::spawn_blocking(move || module_process.join().unwrap())
22345            .await
22346            .unwrap();
22347        assert!(
22348            auth.is_ok(),
22349            "the daemon must answer a module's handshake while a restart waits on the \
22350             live-children record write; got {auth:?} after {elapsed:?}"
22351        );
22352
22353        tokio::time::timeout(Duration::from_secs(20), async {
22354            while lock_snapshot(&module.inner.snapshot)
22355                .unwrap()
22356                .reported_pid()
22357                .is_none_or(|pid| pid == old_pid)
22358            {
22359                tokio::time::sleep(Duration::from_millis(10)).await;
22360            }
22361        })
22362        .await
22363        .expect("the restart published its replacement");
22364        module.stop().await.unwrap();
22365        server.abort();
22366    }
22367}
22368
22369#[cfg(all(test, unix))]
22370mod retained_status_tests {
22371    use super::*;
22372
22373    #[tokio::test]
22374    async fn cached_container_block_is_visible_in_status_and_health_without_rechecking() {
22375        use crate::live_children::{ContainerIdentity, RetainedReason};
22376        for (reason, carried, expected) in [
22377            (
22378                RetainedReason::ContainerSurvivors(vec![4242]),
22379                true,
22380                Some("waiting: container survivors (pids [4242])".to_owned()),
22381            ),
22382            (
22383                RetainedReason::ContainerUnverifiable("member inspection denied".into()),
22384                true,
22385                Some(
22386                    "waiting: container survivors could not be verified: member inspection denied"
22387                        .to_owned(),
22388                ),
22389            ),
22390            (RetainedReason::Survived, false, None),
22391        ] {
22392            let supervisor =
22393                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
22394            let spec = ModuleSpec {
22395                script: None,
22396                module_id: "retained-status-fixture".into(),
22397                program: PathBuf::from("/not-spawned"),
22398                args: Vec::new(),
22399                env: Vec::new(),
22400                reserved: false,
22401                reserved_prefixes: Vec::new(),
22402                protocol: ModuleProtocol::None,
22403                overlap: ModuleOverlap::Exclusive,
22404                carry_containment: carried,
22405            };
22406            let module = supervisor
22407                .supervise_configured(spec.clone(), false)
22408                .unwrap();
22409            // No process is launched. Invalid group zero is deliberate: if a
22410            // status read wrongly rechecks, verification changes the reason
22411            // and fails the assertions without signalling any real process.
22412            let guard = supervisor
22413                .child_roster
22414                .admit(
22415                    spec.module_id,
22416                    0,
22417                    ModuleProtocol::None,
22418                    None,
22419                    crate::child_roster::RecordedIdentity {
22420                        container: carried.then_some(ContainerIdentity {
22421                            pgid: Some(0),
22422                            created_start_time: Some(0),
22423                            cgroup_path: None,
22424                            ..ContainerIdentity::test_metadata()
22425                        }),
22426                        ..crate::child_roster::RecordedIdentity::default()
22427                    },
22428                )
22429                .unwrap();
22430            guard.retain(reason);
22431            let status = module.status().unwrap();
22432            assert_eq!(status.waiting_for_previous_detail, expected.clone());
22433            assert_eq!(status.health.detail, expected);
22434            assert!(!status.process_alive);
22435        }
22436    }
22437}
22438
22439fn registration_child_is_running(child: &mut SupervisedChild) -> bool {
22440    child.try_wait().is_ok_and(|status| status.is_none())
22441}