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;
8
9mod spawn;
10#[cfg(target_os = "linux")]
11#[cfg(test)]
12use spawn::apply_cgroup_placement;
13pub(crate) use spawn::apply_child_env;
14#[cfg(test)]
15use spawn::apply_spawn_role;
16#[cfg(test)]
17use spawn::apply_wire_spawn_args;
18#[cfg(all(test, any(unix, windows)))]
19use spawn::apply_wire_spawn_args_for_admission;
20use spawn::carries_containment;
21#[cfg(unix)]
22use spawn::is_launch_deferral;
23use spawn::kill_and_reap_rejected_child;
24#[cfg(target_os = "linux")]
25pub(crate) use spawn::kill_module_cgroup;
26#[cfg(all(test, target_os = "linux"))]
27use spawn::launch_child_in_slot;
28#[cfg(target_os = "linux")]
29#[cfg(test)]
30use spawn::linux_exec_committed;
31#[cfg(not(windows))]
32use spawn::observe_spawned_image;
33use spawn::observed_launch_nonce_source;
34#[cfg(all(test, target_os = "linux"))]
35use spawn::prepare_child_in_slot;
36#[cfg(all(test, windows))]
37use spawn::prepare_windows_registration_pipe;
38use spawn::previous_instance_error;
39use spawn::recovery_block_error;
40#[cfg(target_os = "linux")]
41#[cfg(test)]
42use spawn::remove_module_cgroup;
43#[cfg(target_os = "linux")]
44#[cfg(test)]
45use spawn::sample_after_linux_exec;
46use spawn::set_running;
47#[cfg(test)]
48use spawn::spawn_and_mark_running;
49#[cfg(all(test, unix))]
50use spawn::spawn_child;
51use spawn::spawn_child_async;
52#[cfg(all(test, unix))]
53use spawn::spawn_child_in_slot;
54use spawn::spawn_child_in_slot_async;
55#[cfg(all(test, target_os = "linux"))]
56use spawn::spawn_plan_stale;
57pub(crate) use spawn::validate_spec;
58#[cfg(windows)]
59pub(crate) use spawn::windows_spawn_capture;
60#[cfg(test)]
61use spawn::AfterFirstSpawnHook;
62#[cfg(test)]
63use spawn::CapturedRegistrationChannels;
64#[cfg(test)]
65use spawn::CapturedRegistrationEndpoint;
66pub(crate) use spawn::LaunchSpecDigest;
67pub use spawn::ModuleOverlap;
68pub use spawn::ModuleSpec;
69#[cfg(any(all(test, unix), target_os = "linux", target_os = "macos"))]
70pub(crate) use spawn::RegisteredConfiguredModule;
71pub use spawn::ScriptEntry;
72pub use spawn::ScriptRuntime;
73pub(crate) use spawn::SpawnProgramBinding;
74#[cfg(any(unix, windows))]
75use spawn::SpawnRegistrationChannel;
76use spawn::SpawnRole;
77// Only the Unix admission path and its tests read the deadline by this name.
78#[cfg(unix)]
79use spawn::ADMISSION_TIMEOUT;
80#[cfg(feature = "test-support")]
81pub use spawn::CHILD_ADMISSION_TIMEOUT;
82pub use spawn::SPAWN_ROLE_SWAP_CANDIDATE;
83pub use spawn::SUBC_ARG;
84pub use spawn::SUBC_SPAWN_ROLE_ENV;
85
86mod privacy_exec;
87#[cfg(target_os = "macos")]
88use privacy_exec::privacy_command;
89#[cfg(all(test, target_os = "macos"))]
90use privacy_exec::probe_privacy_trampoline;
91#[cfg(all(test, target_os = "macos"))]
92pub(crate) use privacy_exec::test_privacy_trampoline;
93#[cfg(target_os = "macos")]
94use privacy_exec::PrivacyExec;
95
96mod actor;
97#[cfg(all(test, unix))]
98use actor::handle_supervisor_command;
99use actor::supervise_loop;
100#[cfg(all(test, unix))]
101use actor::supervisor_sleep;
102#[cfg(test)]
103use actor::ActorSelectCheckpoint;
104use actor::NextAction;
105use actor::SupervisorCommand;
106pub(crate) mod handover;
107pub(crate) mod live_upgrade;
108mod restart;
109use restart::finish_reload_child;
110use restart::reload_child;
111use restart::restart_child;
112use restart::restart_child_with_budget_policy;
113use restart::set_child_enabled;
114use restart::set_child_enabled_with_budget_policy;
115#[cfg(test)]
116use restart::ReloadExitRecordGate;
117
118mod health_probe;
119#[cfg(test)]
120use health_probe::handle_health_probe_failure;
121#[cfg(all(test, unix))]
122use health_probe::handle_health_report;
123#[cfg(test)]
124use health_probe::health_restart_child;
125#[cfg(test)]
126use health_probe::jittered_health_delay;
127pub(crate) use health_probe::parse_http_probe_url;
128use health_probe::probe_endpoint_health;
129#[cfg(all(test, unix))]
130use health_probe::probe_http_health;
131use health_probe::probe_module_health;
132use health_probe::record_health_action;
133use health_probe::run_health_probe_cycle;
134use health_probe::running_protocol;
135pub use health_probe::HealthAction;
136pub use health_probe::HealthConfig;
137#[cfg(test)]
138use health_probe::HealthProbeError;
139use health_probe::HealthProbeEvidence;
140use health_probe::HealthProbeRuntime;
141pub use health_probe::ModuleHealthStatus;
142
143mod drain;
144use drain::begin_forwarding_drain;
145use drain::begin_forwarding_drain_if_configured;
146use drain::begin_forwarding_drain_with;
147use drain::begin_forwarding_drain_with_timeout;
148#[cfg(test)]
149use drain::busy_gauge_observation;
150use drain::control_flags;
151pub(crate) use drain::declared_busy_gauges;
152#[cfg(test)]
153use drain::drain_busy_reprobe_interval;
154#[cfg(test)]
155use drain::drain_child_to_state;
156use drain::drain_optional_child;
157#[cfg(test)]
158use drain::drained_after_quiescence_wait;
159#[cfg(test)]
160use drain::gauge_verdicts;
161use drain::request_graceful_stop;
162use drain::terminal_disposition;
163#[cfg(test)]
164use drain::wait_for_forwarding_quiescence;
165#[cfg(test)]
166use drain::warn_drain_timed_out;
167#[cfg(test)]
168use drain::BusyGaugeObservation;
169#[cfg(test)]
170use drain::DrainGaugeTrace;
171use drain::DrainScope;
172use drain::ForwardingDrainContext;
173#[cfg(test)]
174use drain::GaugeVerdict;
175use drain::StopNotice;
176pub use drain::DEFAULT_DRAIN_TIMEOUT;
177
178mod exit;
179#[cfg(test)]
180use exit::apply_deliberate_severance_marker;
181use exit::classify_exit;
182use exit::classify_reaped_child_exit;
183use exit::clear_current_process_facts;
184use exit::durable_terminal_history_of;
185use exit::fail_after_wait_error;
186use exit::fail_snapshot;
187#[cfg(test)]
188use exit::on_child_exit;
189use exit::on_child_exit_with_detail;
190use exit::publish_after_terminal_record;
191#[cfg(test)]
192use exit::record_deliberate_severance;
193#[cfg(test)]
194use exit::record_terminal;
195use exit::record_terminal_with_detail;
196#[cfg(test)]
197use exit::record_wait_error_terminal;
198#[cfg(any(unix, test))]
199use exit::settle_stderr_pump;
200#[cfg(any(unix, test))]
201use exit::settle_stdout_pump;
202use exit::untrack_if_registration_released;
203use exit::wait_error_exit_report;
204
205mod spawn_events;
206use spawn_events::SpawnEventFeed;
207pub(crate) use spawn_events::SpawnSubscribeRefusal;
208pub use spawn_events::SPAWN_EVENT_RING_CAPACITY;
209#[cfg(test)]
210use spawn_events::SPAWN_SUBSCRIBER_BUFFER;
211#[cfg(test)]
212use spawn_events::SPAWN_SUBSCRIBER_LAGGED_CODE;
213
214mod roster;
215pub use roster::ModuleProcessLiveness;
216pub use roster::SupervisorProcessLiveness;
217mod resource_launch;
218pub(crate) use resource_launch::{ResourceCommitError, ResourceLaunch};
219
220use std::{
221    collections::{HashMap, HashSet, VecDeque},
222    error::Error,
223    fmt, io,
224    path::PathBuf,
225    process::{ExitStatus, Stdio},
226    sync::{Arc, Mutex, OnceLock, TryLockError},
227    time::{Duration, SystemTime, UNIX_EPOCH},
228};
229
230use cortexkit_log::Retention;
231use serde_json::Value;
232use sha2::{Digest, Sha256};
233use subc_control::{
234    ClientControlPush, LiveSpawn, ModuleProtocol, RouteCloseReason, SpawnCursor, SpawnEvent,
235    SpawnEventKind, SpawnSnapshot, SupervisorHealthStatus, TerminalDisposition, TerminalExitKind,
236};
237use subc_protocol::{
238    manifest::{SelfSignalKind, SignalAnchor},
239    session::{
240        HealthReport, HealthStatus, ModuleControlCommand, ModuleControlRequest,
241        MODULE_CONTROL_OP_HEALTH_CHECK,
242    },
243    Flags, FrameType, Principal, Priority, SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV,
244};
245use tokio::{
246    process::{Child, Command},
247    sync::{mpsc, oneshot, watch, Mutex as AsyncMutex},
248    task::JoinHandle,
249    time::{sleep, sleep_until, timeout, timeout_at, Instant},
250};
251use tracing::{debug, error, info, warn};
252
253use crate::{
254    child_output::StderrPump,
255    child_roster::ChildRoster,
256    daemon_config::{
257        CAPTURE_KEEP_ENV, CAPTURE_MAX_AGE_DAYS_ENV, CAPTURE_MAX_FILE_MB_ENV, CK_LOG_ENV,
258    },
259    forwarding::{
260        CloseReason, ForwardingError, ForwardingTable, GoodbyeTarget, ModuleControlRpcOutcome,
261        ModuleDrainTarget, PendingModuleControlRpc,
262    },
263    provenance::{ExecutableIdentityProbe, SpawnedFileIdentity},
264    registry::{ConnectionId, RegistrationEndReason, RegistryError},
265    stderr_tail::{ChildOutputSink, StderrRing, StderrTailConfig, StderrTailSnapshot},
266    terminal_ring::{TerminalHistorySnapshot, TerminalRecord, TerminalRing, TerminalRingConfig},
267    Frame, FrameSink, Registry,
268};
269
270#[cfg(not(windows))]
271use crate::provenance::spawned_file_identity;
272
273#[path = "supervise_swap.rs"]
274mod swap;
275use swap::OpenSwap;
276use swap::PromotionObserverSlot;
277pub(crate) use swap::SwapHelloAdmission;
278pub(crate) use swap::SwapPromotionObserver;
279pub use swap::DEFAULT_SWAP_READY_TIMEOUT;
280
281#[path = "supervise_activity.rs"]
282mod activity;
283
284#[cfg(unix)]
285#[path = "supervise/admission.rs"]
286mod admission;
287mod admission_exit;
288#[cfg(all(test, target_os = "linux"))]
289mod async_spawn_tests;
290#[cfg(all(test, windows))]
291mod carried_job_tests;
292mod config_delivery;
293use config_delivery::cancel_deferred_reload;
294use config_delivery::defer_config_spawn;
295use config_delivery::hold_config_respawn;
296use config_delivery::hold_config_spawn;
297use config_delivery::record_approved_attempt_failure;
298use config_delivery::try_park_config_attempt;
299use config_delivery::CONFIG_ADMISSION_RETRY_DELAY;
300mod content_binding;
301mod program_binding;
302mod registration;
303pub(crate) mod resume_hello;
304use registration::arm_registration_deadline;
305use registration::constant_time_eq;
306use registration::handle_reload_child_registration_failure;
307use registration::handle_reload_spawn_failure;
308pub(crate) use registration::notify_registration_release;
309use registration::registration_child_is_running;
310use registration::registration_failure_exit_report;
311use registration::release_dead_registration;
312use registration::wait_for_registration_after_reload;
313use registration::wait_for_registration_release;
314use registration::wait_for_slot_registration_release;
315use registration::watch_registration;
316#[cfg(test)]
317use registration::IdentitySamplePause;
318use registration::RegistrationWaitOutcome;
319use registration::RegistrationWatch;
320use registration::ReloadRegistrationFailure;
321pub(crate) use registration::ReservedHelloRejection;
322pub(crate) use registration::ReservedHelloVerification;
323pub(crate) use registration::DEFAULT_REGISTER_TIMEOUT;
324use registration::REGISTRY_RELEASE_POLL;
325use registration::REGISTRY_RELEASE_TIMEOUT;
326pub(crate) mod script;
327/// Each launch nonce, mapped to its launch's module id and the launch.
328type NonceLaunches = HashMap<String, (String, std::sync::Weak<RegistrationSpawn>)>;
329pub(crate) use registration::NonceAttestation;
330#[cfg(all(test, unix))]
331pub(crate) use registration::RegistrationProof;
332pub(crate) use registration::RegistrationSpawn;
333pub(crate) use registration::REGISTRATION_CHANNEL_CLOSED;
334#[cfg(all(test, unix))]
335pub(crate) mod unix_channel_placement_tests;
336use program_binding::ProgramBindingPublication;
337mod config_exit_failure;
338#[cfg(all(test, any(target_os = "linux", windows)))]
339mod missing_path_tests;
340#[cfg(all(test, unix))]
341mod program_binding_tests;
342#[cfg(all(test, windows))]
343mod program_binding_windows_tests;
344#[cfg(all(test, windows))]
345mod windows_channel_tests;
346pub use config_exit_failure::ModuleStopReason;
347mod unregistered_stop;
348use unregistered_stop::stop_unregistered_child;
349#[cfg(target_os = "linux")]
350#[path = "supervise/cgroup_label.rs"]
351mod cgroup_label;
352#[cfg(all(test, unix))]
353mod config_exit_hold_tests;
354pub(crate) mod containment;
355#[cfg(all(test, unix))]
356mod containment_tests;
357#[cfg(target_os = "linux")]
358mod ordinary_cgroup;
359#[cfg(unix)]
360pub(crate) mod plain_group;
361#[cfg(all(test, target_os = "linux"))]
362mod plain_group_regression;
363mod slow_retry;
364use slow_retry::{FailedRetry, FailureContext};
365mod host_health;
366use host_health::HostHealth;
367
368#[cfg(test)]
369mod crash_admission_tests;
370mod crash_budget;
371use crash_budget::budgeted_restart_child;
372use crash_budget::daemon_will_restart;
373use crash_budget::log_crash_respawn;
374use crash_budget::reset_restart_count;
375use crash_budget::respawn_still_pending;
376use crash_budget::schedule_respawn;
377use crash_budget::CrashRestartSchedule;
378pub use crash_budget::RestartPolicy;
379#[cfg(all(test, unix))]
380mod mark_readiness_tests;
381#[cfg(all(test, unix))]
382mod slow_retry_tests;
383use crash_budget::{admit_running_child_async, spawn_and_mark_running_async};
384
385struct SupervisedChild {
386    registration_spawn: Option<Arc<RegistrationSpawn>>,
387    /// Owned daemon endpoint, retained for the per-spawn registration service.
388    #[cfg(any(unix, windows))]
389    registration_channel: Option<SpawnRegistrationChannel>,
390    live_program_binding: Option<Arc<content_binding::LiveProgramBinding>>,
391    registered_config_connection: Option<ConnectionId>,
392    admission_base: Option<subc_config::Digest>,
393    registration_declaration: Option<String>,
394    _program_binding: Option<ProgramBindingPublication>,
395    subtree_target: crate::subtree_resources::Target,
396    child: containment::ProcessChild,
397    exec: crate::activity::ExecOwner,
398    #[cfg(windows)]
399    nonce_delivery: Option<subc_os::LaunchNoncePipeDelivery>,
400    #[cfg(target_os = "macos")]
401    privacy_exec: Option<PrivacyExec>,
402    /// Set once this launch's exec acknowledgement confirms the module image.
403    /// On macOS the pid first runs the `ck-subc` launch trampoline (see
404    /// `subc_os::privacy_identity`), which then replaces itself with the
405    /// module. The supervisor owns and can kill that pid from spawn, but
406    /// status readers report it only after this latch is set, so nothing
407    /// reports the trampoline's image as the module's.
408    #[cfg(target_os = "macos")]
409    report_ready: Arc<OnceLock<()>>,
410    /// Supervisor failure detail retained for the terminal record, including
411    /// image refusals and first-HELLO timeouts after a successful spawn.
412    spawn_failure: Option<String>,
413    /// Set only after a kill requested because launch admission failed was
414    /// accepted, never for an operator, health, or shutdown kill.
415    admission_kill_sent: bool,
416    /// The protocol this process was launched with. A reload can store a new
417    /// launch spec with a different protocol, but that takes effect only at the
418    /// next spawn, so this process keeps being handled by the protocol it
419    /// actually speaks.
420    protocol: ModuleProtocol,
421    /// This container's cgroup name: a bounded module/slot label followed by a
422    /// unique suffix (when cgroup placement is on). Carried replacements reuse
423    /// the name; ordinary launches each get a fresh container. A
424    /// retired process in a slot may still be draining when a later one is
425    /// spawned into that slot, so the suffix keeps the later process out of
426    /// the retired one's cgroup, which is the domain a kill applies to.
427    #[cfg(target_os = "linux")]
428    module_id: String,
429    #[cfg(target_os = "linux")]
430    cgroup_placement: Option<subc_cgroup::Placement>,
431    #[cfg(target_os = "linux")]
432    unresolved_cgroup: Option<ordinary_cgroup::Unresolved>,
433    /// The job for an ordinary, non-carried launch. For carried
434    /// launches the actor owns it and the child holds only a weak container link.
435    ///
436    /// Dropping this handle is what reaps a surviving tree when no supervisor
437    /// code runs — a daemon crash — because the job carries
438    /// `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`.
439    ///
440    /// That limit is not crash-only, and the difference is worth knowing: a
441    /// Windows daemon *stop* is `taskkill` or the scheduler's `/End` — the
442    /// SIGTERM handler is `#[cfg(unix)]` — so the daemon dies with no stop
443    /// notice and the kernel closes the job handle, `TerminateProcess`ing every
444    /// module at once. Before this change they survived that, saw EOF on the
445    /// control socket, and ran their own teardown; Unix keeps that path
446    /// deliberately, so a module can seal a WAL or close a capture rather than
447    /// be killed mid-write. So this trades graceful teardown on every Windows
448    /// daemon stop for containment on a crash, which is the right way round
449    /// today: orphaned GPU workers are a reported, recurring problem, and the
450    /// modules that write most heavily do not run on Windows.
451    ///
452    /// The fix is a real Windows stop path — the daemon draining before it
453    /// exits, the twin of the Unix SIGTERM handler. Once it exists, this limit
454    /// reaches only what the drain left behind, which is what it should reach.
455    #[cfg(windows)]
456    job: Option<Arc<Mutex<subc_jobobject::JobObject>>>,
457    stdout_pump: Option<tokio::sync::oneshot::Receiver<()>>,
458    stderr_pump: Option<StderrPump>,
459    #[cfg(unix)]
460    capture_stop: Option<crate::child_output::StopReaders>,
461    #[cfg(unix)]
462    late_output_lost: bool,
463    stderr_ring: Arc<Mutex<StderrRing>>,
464    /// Conservative monotonic bound sampled before `command.spawn()`, not when
465    /// identity recording finishes or the spawn generation is published.
466    spawned_at: Instant,
467    config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
468    /// Ordinary spawns must send their first HELLO within this budget. Once
469    /// accepted, a later disconnect must not restart the registration clock.
470    registration_deadline: Option<Instant>,
471    registration_watch: Option<RegistrationWatch>,
472    spawned_at_ms: u64,
473    spawned_from: PathBuf,
474    launch_spec_digest: LaunchSpecDigest,
475    spawned_file_identity: Option<SpawnedFileIdentity>,
476    process_start_time: Option<u64>,
477    process_identity: Option<ProcessIdentity>,
478    pid: u32,
479    /// This process's entry in the daemon's child roster, released when the
480    /// process is reaped or this handle is dropped.
481    roster_guard: Option<crate::child_roster::RosterGuard>,
482}
483
484/// Typed lifecycle state for a supervised module.
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub enum ModuleState {
487    Starting,
488    Running,
489    Unresponsive,
490    Restarting,
491    Draining,
492    Stopped,
493    Failed,
494    Disabled,
495}
496
497impl fmt::Display for ModuleState {
498    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499        f.write_str(match self {
500            Self::Starting => "starting",
501            Self::Running => "running",
502            Self::Unresponsive => "unresponsive",
503            Self::Restarting => "restarting",
504            Self::Draining => "draining",
505            Self::Stopped => "stopped",
506            Self::Failed => "failed",
507            Self::Disabled => "disabled",
508        })
509    }
510}
511
512/// Supervisor classification of a child-process exit.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub enum ExitKind {
515    Clean,
516    Crash,
517    DeliberateSeverance,
518}
519
520impl From<ExitKind> for TerminalExitKind {
521    fn from(kind: ExitKind) -> Self {
522        match kind {
523            ExitKind::Clean => Self::Clean,
524            ExitKind::Crash => Self::Crash,
525            ExitKind::DeliberateSeverance => Self::DeliberateSeverance,
526        }
527    }
528}
529
530/// Exact process identity retained when a supervised module registers its
531/// connection. PID reuse makes a PID alone insufficient evidence of ownership.
532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
533pub(crate) struct ProcessIdentity {
534    pub(crate) pid: u32,
535    pub(crate) start_time: u64,
536}
537
538/// Last observed child exit, if any.
539#[derive(Debug, Clone, PartialEq, Eq)]
540pub struct ExitReport {
541    pub kind: ExitKind,
542    pub code: Option<i32>,
543    pub signal: Option<i32>,
544    pub at_ms: u64,
545}
546
547/// Point-in-time module status answerable by subc without forwarding to the
548/// module process.
549#[derive(Debug, Clone, PartialEq)]
550pub struct ModuleStatus {
551    pub(crate) admission_refused: Option<String>,
552    #[cfg(windows)]
553    pub(crate) nonce_pipe_refusal: Option<&'static str>,
554    pub(crate) legacy_registration_spawn: bool,
555    pub(crate) registration_declaration: Option<String>,
556    pub module_id: String,
557    /// Retained configuration-exit infrastructure failure. Cleared only after a
558    /// successful launch; an ordinary stop has no infrastructure stop reason.
559    pub stop_reason: Option<ModuleStopReason>,
560    /// A previous daemon's unresolved process, not a child owned by this supervisor.
561    pub waiting_for_previous_pid: Option<u32>,
562    /// Why the previous instance still prevents a new start.
563    pub waiting_for_previous_detail: Option<String>,
564    /// The daemon's Windows per-spawn record: `pipe` after the process it
565    /// spawned read all nonce bytes, otherwise absent.
566    /// List/status reports use this record, not the source the module sends
567    /// in its registration message's manifest.provenance.launch_nonce_source.
568    pub launch_nonce_source: Option<String>,
569    pub state: ModuleState,
570    pub enabled: bool,
571    pub process_alive: bool,
572    pub registration_active: bool,
573    /// The module's declared wire protocol, carried beside `live` because it is
574    /// what makes `live` readable: the two fields answer one question together.
575    /// While a process is alive this is its launch declaration, not a later
576    /// pending-reload edit. When down it is the configured next launch protocol.
577    pub protocol: ModuleProtocol,
578    /// Whether the module is serving, under the strongest definition the daemon
579    /// can assert for its protocol.
580    ///
581    /// A subc module must also be REGISTERED: its process being alive says
582    /// nothing about whether it can take a request. A `protocol: "none"` module
583    /// never registers, so that term is dropped and this falls back to "enabled,
584    /// running, and the process the daemon launched is alive" -- which is all
585    /// the daemon observes about a process that speaks no subc wire. It stays a
586    /// `bool` on the wire for compatibility; renderers pair it with `protocol`
587    /// rather than printing it bare.
588    pub live: bool,
589    /// Crash restarts spent INSIDE `restart_window` as of this read. Older
590    /// restarts have already released their slot, so this count can go down
591    /// without anybody touching the module.
592    pub restart_count: u32,
593    /// Replacement processes spawned over this module's entire supervisor lifetime;
594    /// unlike `restart_count`, this value is never reset by an operator action
595    /// and never falls out of a window.
596    pub lifetime_restarts: u32,
597    pub spawn_generation: u64,
598    /// Retained daemon-local outcome; the legacy control response omits it.
599    pub swap_outcome: Option<SwapOutcome>,
600    /// The budget `restart_count` is spent against. Carried alongside the count
601    /// because the count alone does not say how close the module is to being
602    /// disabled, and reporting one without the other is what makes an
603    /// about-to-be-retired module look ordinary.
604    pub max_restarts: u32,
605    /// The span `restart_count` is counted over. Carried with the pair above for
606    /// the same reason they are carried together: "2 of 3" means one thing for a
607    /// ten-minute window and something else entirely for a lifetime.
608    pub restart_window: Duration,
609    /// Effective drain and restart timing policy used by this running module.
610    /// These values are carried together with the restart budget so status
611    /// readers can compare configured intent with what the supervisor applied.
612    pub drain_timeout: Duration,
613    pub restart_backoff: Duration,
614    pub restart_max_backoff: Duration,
615    /// The module's process. On macOS this stays absent while the `ck-subc`
616    /// launch trampoline is still running in that pid, and appears once the
617    /// exec acknowledgement confirms the module image has replaced it. Launch
618    /// time and the supervisor's own hold on the process are unaffected.
619    pub pid: Option<u32>,
620    pub spawned_at_ms: Option<u64>,
621    pub spawned_from: Option<PathBuf>,
622    pub(crate) launch_spec_digest: Option<LaunchSpecDigest>,
623    pub process_start_time: Option<u64>,
624    pub last_exit: Option<ExitReport>,
625    pub health: ModuleHealthStatus,
626}
627
628#[derive(Debug, Clone, PartialEq)]
629struct SupervisorSnapshot {
630    admission_refused: Option<String>,
631    #[cfg(windows)]
632    nonce_pipe_refusal: Option<&'static str>,
633    /// Distinguishes an admission-parked actor from an unrelated terminal exit.
634    config_hold_parked: bool,
635    /// Preserve daemon attribution for a paused start so a failing release can
636    /// schedule the next slow retry instead of treating the start as operator work.
637    config_hold_daemon_initiated: bool,
638    /// The approval that owns the parked attempt, not whichever approval is latest.
639    config_hold_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
640    /// Retain an approved launch failure across competing reconciliation passes.
641    approved_start_failure: Option<(crate::config_gate::runtime::ApprovalIdentity, String)>,
642    legacy_registration_spawn: bool,
643    registration_declaration: Option<String>,
644    stop_reason: Option<ModuleStopReason>,
645    config_exit_failed_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
646    subtree_target: crate::subtree_resources::Target,
647    failed_retry: FailedRetry,
648    exec_outcome: Option<Arc<crate::activity::ExecOutcome>>,
649    #[cfg(windows)]
650    pipe_consumed: Option<Arc<OnceLock<()>>>,
651    /// Counts running-child loop turns, not executor polls of a parked wait.
652    #[cfg(test)]
653    actor_turns: u64,
654    /// Running select after exec confirmation and with no unconsumed registry
655    /// event. Recording a spawn or starting a loop turn is not this barrier.
656    #[cfg(test)]
657    actor_select: Option<ActorSelectCheckpoint>,
658    state: ModuleState,
659    enabled: bool,
660    process_alive: bool,
661    spawned_protocol: Option<ModuleProtocol>,
662    spawn_failure: Option<String>,
663    waiting_for_previous_pid: Option<u32>,
664    waiting_for_previous_detail: Option<String>,
665    /// When each crash restart was spent, oldest first. This IS the crash
666    /// budget: its in-window length is the count an operator sees and the count
667    /// the restart decision is made against, so there is no second counter that
668    /// can disagree with it. Bounded by `max_restarts`, and cleared by the same
669    /// operator actions that used to zero the old lifetime counter.
670    crash_restarts: VecDeque<Instant>,
671    lifetime_restarts: u32,
672    /// Successful child spawns in this daemon incarnation.
673    ///
674    /// `lifetime_restarts` was considered and rejected: it starts at zero
675    /// (line 640), successful initial/operator spawns in `set_running` do not
676    /// increment it (lines 5264-5274), and crash/deliberate retry bookkeeping
677    /// increments before a successful replacement exists (lines 604, 3846,
678    /// and 3921), so a failed spawn can consume it. This counter moves only
679    /// when a live PID is accepted below.
680    spawn_generation: u64,
681    swap_outcome: Option<SwapOutcome>,
682    pid: Option<u32>,
683    #[cfg(target_os = "macos")]
684    report_ready: Option<Arc<OnceLock<()>>>,
685    /// Last reaped child, retained after current process facts are cleared.
686    reaped_pid: Option<u32>,
687    /// Whether a replacement has already been scheduled for the current process.
688    respawn_pending: bool,
689    /// A second restart is waiting for the replacement already scheduled.
690    coalesced_restart_pending: bool,
691    spawned_at_ms: Option<u64>,
692    spawned_from: Option<PathBuf>,
693    launch_spec_digest: Option<LaunchSpecDigest>,
694    spawned_file_identity: Option<SpawnedFileIdentity>,
695    process_start_time: Option<u64>,
696    deliberate_severance: Option<ProcessIdentity>,
697    last_exit: Option<ExitReport>,
698    /// Diagnostic attached to the next drain's terminal record, if any.
699    drain_disposition_detail: Option<String>,
700    health: ModuleHealthStatus,
701    last_probe_evidence: Option<HealthProbeEvidence>,
702    /// Whether the current process was started as a swap candidate and so
703    /// lives in the module's alternate cgroup. The next swap's candidate takes
704    /// the other one, so the two processes of a swap never share a cgroup. A
705    /// plain spawn always uses the primary cgroup.
706    in_alternate_slot: bool,
707    /// Whether the current `Draining` state ends in a replacement process
708    /// (restart, reload, health restart) rather than a stop. Only meaningful
709    /// while `state` is `Draining`; every entry into that state rewrites it.
710    /// It is what lets route.open answer the retryable `module_reloading` to a
711    /// consumer that reaches a still-registered process mid-restart, instead of
712    /// the `supervisor_not_live` a stop or disable deserves.
713    draining_to_replace: bool,
714    /// Whether a configuration update has been applied since the current
715    /// process was spawned, so that process runs an older spec than the one
716    /// the supervisor now holds. A queued restart is only coalesced into a
717    /// fresher process when this is false: a restart requested to pick up a
718    /// new configuration must not be satisfied by a process that predates it.
719    configuration_updated_since_spawn: bool,
720}
721
722impl SupervisorSnapshot {
723    /// The pid that status, provenance and resource readings may report. While
724    /// the launch trampoline still runs in the pid, reading its executable or
725    /// resource use would describe `ck-subc`, not the module, so none is
726    /// reported until the exec acknowledgement confirms the module image.
727    fn reported_pid(&self) -> Option<u32> {
728        #[cfg(target_os = "macos")]
729        if self
730            .report_ready
731            .as_ref()
732            .is_some_and(|ready| ready.get().is_none())
733        {
734            return None;
735        }
736        self.pid
737    }
738
739    fn starting() -> Self {
740        Self::new(ModuleState::Starting, true)
741    }
742
743    fn disabled() -> Self {
744        Self::new(ModuleState::Disabled, false)
745    }
746
747    /// Give the module its full budget back, as an operator restart, reload, or
748    /// re-enable does. `lifetime_restarts` deliberately does not move: it is the
749    /// ledger of what actually happened, and an operator action does not unmake
750    /// replacements that already ran.
751    fn clear_crash_restarts(&mut self) {
752        self.crash_restarts.clear();
753    }
754
755    fn new(state: ModuleState, enabled: bool) -> Self {
756        Self {
757            admission_refused: None,
758            #[cfg(windows)]
759            nonce_pipe_refusal: None,
760            config_hold_parked: false,
761            config_hold_daemon_initiated: false,
762            config_hold_approval: None,
763            approved_start_failure: None,
764            legacy_registration_spawn: false,
765            registration_declaration: None,
766            stop_reason: None,
767            config_exit_failed_approval: None,
768            subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
769            failed_retry: FailedRetry::default(),
770            exec_outcome: None,
771            #[cfg(test)]
772            actor_turns: 0,
773            #[cfg(test)]
774            actor_select: None,
775            state,
776            enabled,
777            process_alive: false,
778            #[cfg(windows)]
779            pipe_consumed: None,
780            spawned_protocol: None,
781            spawn_failure: None,
782            waiting_for_previous_pid: None,
783            waiting_for_previous_detail: None,
784            crash_restarts: VecDeque::new(),
785            lifetime_restarts: 0,
786            spawn_generation: 0,
787            swap_outcome: None,
788            pid: None,
789            #[cfg(target_os = "macos")]
790            report_ready: None,
791            reaped_pid: None,
792            respawn_pending: false,
793            coalesced_restart_pending: false,
794            spawned_at_ms: None,
795            spawned_from: None,
796            launch_spec_digest: None,
797            spawned_file_identity: None,
798            process_start_time: None,
799            deliberate_severance: None,
800            last_exit: None,
801            drain_disposition_detail: None,
802            health: ModuleHealthStatus::default(),
803            last_probe_evidence: None,
804            in_alternate_slot: false,
805            draining_to_replace: false,
806            configuration_updated_since_spawn: false,
807        }
808    }
809}
810
811type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
812
813#[derive(Debug, Clone, Copy)]
814enum RespawnKind {
815    Spawn,
816    CrashRestart,
817    Reload,
818}
819
820#[derive(Debug, Clone)]
821struct PendingRespawn {
822    deadline: Instant,
823    kind: RespawnKind,
824    daemon_initiated: bool,
825    approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
826}
827
828impl PendingRespawn {
829    fn failure_context(&self, runtime: &SupervisorRuntimeConfig) -> FailureContext {
830        FailureContext {
831            approval: self.approval.clone(),
832            ..runtime.failure_context(self.daemon_initiated)
833        }
834    }
835}
836
837type ReloadReply = oneshot::Sender<Result<(), SuperviseError>>;
838
839#[derive(Debug, Clone)]
840struct SupervisorRuntimeConfig {
841    registry: Arc<Registry>,
842    config_delivery: Option<config_delivery::ConfigDelivery>,
843    /// Retained across an operation's deferred backoff, until its child starts.
844    recovery_is_daemon: bool,
845    start_requester: Option<Principal>,
846    pending_activity_restart: bool,
847    provenance_probe: ExecutableIdentityProbe,
848    /// Restart operations hand their backoff to the loop, which keeps serving commands.
849    scheduled_respawn: Arc<Mutex<Option<PendingRespawn>>>,
850    /// A reload acknowledges completion only after its replacement registers.
851    deferred_reload_reply: Arc<Mutex<Option<ReloadReply>>>,
852    restart_policy: RestartPolicy,
853    register_timeout: Duration,
854    /// This module's RESOLVED drain budget: per-module config when present,
855    /// else `default_drain_timeout`.
856    drain_timeout: Duration,
857    /// Shared with the status handle so the attested value changes atomically
858    /// when a rescan updates the running drain policy.
859    effective_drain_timeout: Arc<Mutex<Duration>>,
860    /// The supervisor-wide fallback, kept so a configuration update that
861    /// REMOVES the per-module override can re-resolve to it.
862    default_drain_timeout: Duration,
863    health: HealthConfig,
864    host_health: HostHealth,
865    connection_file_path: Option<PathBuf>,
866    capture_logs_dir: Option<PathBuf>,
867    forwarding: Option<Arc<ForwardingTable>>,
868    supervisor_handle: Option<SupervisorHandle>,
869    #[cfg(any(target_os = "linux", target_os = "macos"))]
870    replacement_ticket: Option<live_upgrade::ReplacementTicket>,
871    /// This module's stderr tail, shared with the [`SupervisedModule`] that answers
872    /// status queries.
873    ///
874    /// One ring per module, held across every respawn. The lines explaining an exit
875    /// are written BEFORE that exit, so a ring recreated per process would be empty
876    /// exactly when it is asked for.
877    stderr_ring: Arc<Mutex<StderrRing>>,
878    terminal_ring: Arc<Mutex<TerminalRing>>,
879    spawn_events: SpawnEventFeed,
880    child_roster: ChildRoster,
881    #[cfg(target_os = "linux")]
882    cgroup_placement: Option<subc_cgroup::Placement>,
883    #[cfg(test)]
884    test_seed_stale_facts_before_enable_spawn: bool,
885    #[cfg(test)]
886    test_reload_exit_record_gate: Option<Arc<ReloadExitRecordGate>>,
887}
888
889impl SupervisorRuntimeConfig {
890    fn failure_context(&self, daemon_initiated: bool) -> FailureContext {
891        FailureContext {
892            daemon_initiated,
893            approval: None,
894            shutdown: self.child_roster.shutdown_flag(),
895        }
896    }
897}
898
899#[derive(Debug, Clone, PartialEq, Eq)]
900struct SupervisedConfiguration {
901    spec: ModuleSpec,
902    enabled: bool,
903    health: HealthConfig,
904    register_timeout: Duration,
905    restart_policy: RestartPolicy,
906}
907
908/// Shared lookup table for module handles and launch authority. The supervisor
909/// records each launch and the control handler verifies HELLOs and route opens.
910#[derive(Debug, Clone, Default)]
911pub struct SupervisorHandle {
912    pub(crate) pending_adoptions: resume_hello::PendingAdoptions,
913    upgrade_state: live_upgrade::UpgradeState,
914    #[cfg(test)]
915    resource_commit_pause: Arc<Mutex<Option<resource_launch::ResourceCommitPause>>>,
916    #[cfg(test)]
917    registration_test_channels: CapturedRegistrationChannels,
918    registration_service: Arc<Mutex<Option<registration::RegistrationService>>>,
919    registration_connections: Arc<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
920    registration_launches: Arc<Mutex<Vec<std::sync::Weak<RegistrationSpawn>>>>,
921    gate_runtime: Arc<Mutex<Option<std::sync::Weak<crate::config_gate::runtime::RuntimeOwner>>>>,
922    program_bindings: program_binding::ProgramBindings,
923    #[cfg(test)]
924    identity_sample_pause: Arc<Mutex<Option<IdentitySamplePause>>>,
925    #[cfg(all(test, unix))]
926    plain_identity_policy_pause: Arc<Mutex<Option<(String, IdentitySamplePause)>>>,
927    host_health: HostHealth,
928    restart_intent: Arc<Mutex<DaemonRestartIntent>>,
929    activity: Arc<Mutex<Option<crate::activity::ActivityLedger>>>,
930    activity_images: Arc<Mutex<HashMap<String, activity::ActivityImage>>>,
931    modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
932    /// Module ids the supervisor has taken on. An id is added BEFORE the
933    /// module's first process is spawned and removed only when the module
934    /// leaves the roster (see [`Self::retire`]), so it is always a superset of
935    /// the keys of `modules`.
936    ///
937    /// `modules` cannot answer "is this module configured?" on its own: a
938    /// [`SupervisedModule`] only exists once its process has been spawned, and
939    /// a fast child can connect, register, sync its scopes and ask about them
940    /// before the supervisor has inserted it. Answering "not configured" in that
941    /// gap makes scope admission refuse with the terminal "will never sync"
942    /// instead of the retryable "has not synced yet".
943    configured_ids: Arc<Mutex<HashSet<String>>>,
944    spawn_events: SpawnEventFeed,
945    /// The current expected launch nonce for each reserved module_id. Set when the
946    /// supervisor spawns the reserved module; checked when a HELLO claims that id. A
947    /// non-reserved module never has an entry here and is never nonce-checked.
948    /// Reserved module ids and the nonce that authorizes their next HELLO.
949    /// `None` means RESERVED WITH NO LEGITIMATE HOLDER — a reserved module that
950    /// has never been spawned (e.g. configured `enabled: false`) — and refuses
951    /// every HELLO. Before this was expressible, a reserved-but-never-spawned id
952    /// had NO entry and admitted anyone: the reservation protected the nonce
953    /// holder, not the NAME (found live by CKCRED's canary probe registering
954    /// against a reserved scratch id).
955    reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
956    /// Reservations installed only to prevent HELLO for a protocol:none process.
957    /// Replacement by a subc process releases them; explicitly reserved ids are
958    /// never placed in this set and still require an operator release.
959    implicit_protocol_none: Arc<Mutex<HashSet<String>>>,
960    /// Module ids removed by an executed rescan and the unix-millisecond removal time.
961    ///
962    /// This is deliberately in-memory only: subc is state-free across daemon
963    /// restarts, and the tombstone only explains the hours-after-removal window
964    /// while this executing daemon is still alive. Do not persist it in a store.
965    removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
966    /// The current launch nonce for every supervised spawn. This is separate from
967    /// reserved_nonces because consumer route.open attestation applies to all spawned
968    /// modules, while HELLO id-squatting protection remains opt-in via `reserved`.
969    spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
970    /// The launch each live launch nonce was minted for, keyed by nonce, with
971    /// the launch's module id, so a nonce-attested consumer or registration
972    /// resolves to that launch's authority record. An entry whose launch has
973    /// ended stays while its nonce still authorizes, so a nonce whose record
974    /// is gone is told apart from one that never had a record.
975    nonce_launches: Arc<Mutex<NonceLaunches>>,
976    /// Reserved namespace prefixes mapped to the supervised owner module whose
977    /// current spawn nonce authorizes HELLO claims below the prefix.
978    ///
979    /// Per §2.6 this is not a same-user security barrier: a same-user process can
980    /// read the key file and launch nonce env. Like exact reserved ids, it prevents
981    /// accidental collisions and lower-trust processes from squatting protected
982    /// namespaces.
983    reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
984    /// Blue/green swaps in progress, by module id. An entry exists from just
985    /// before the candidate process is spawned until the swap has failed, or
986    /// has cut over and the old process is gone. While it exists, HELLO for the
987    /// id is gated on the swap token (see [`Self::swap_hello_admission`]) and
988    /// consumer attestation accepts both processes' nonces.
989    swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
990    /// Told when a swap promotes its candidate; see [`SwapPromotionObserver`].
991    promotion_observer: PromotionObserverSlot,
992    /// Serializes module-set reconciliation with operator lifecycle commands. Without
993    /// this daemon-wide ordering, a rescan could retire or update a module while a
994    /// concurrent reload still held its old handle and launch specification.
995    operation_lock: Arc<AsyncMutex<()>>,
996}
997
998#[derive(Debug)]
999struct DaemonRestartIntent {
1000    expires: Option<Duration>,
1001    window: Duration,
1002}
1003
1004impl Default for DaemonRestartIntent {
1005    fn default() -> Self {
1006        Self {
1007            expires: None,
1008            window: Duration::from_secs(120),
1009        }
1010    }
1011}
1012
1013impl SupervisorHandle {
1014    pub(crate) fn module_is_gated(&self, module: &str) -> bool {
1015        let runtime = {
1016            let Ok(runtime) = self.gate_runtime.lock() else {
1017                return true;
1018            };
1019            runtime.clone()
1020        };
1021        runtime.is_some_and(|runtime| {
1022            runtime
1023                .upgrade()
1024                .is_none_or(|owner| owner.module_is_gated(module))
1025        })
1026    }
1027    pub(crate) fn announce_daemon_restart(&self) -> u64 {
1028        let mut intent = self
1029            .restart_intent
1030            .lock()
1031            .unwrap_or_else(|p| p.into_inner());
1032        intent.expires = Some(subc_uptime::suspend_inclusive_now() + intent.window);
1033        unix_ms_now().saturating_add(intent.window.as_millis() as u64)
1034    }
1035
1036    #[cfg(feature = "test-support")]
1037    pub(crate) fn set_shutdown_intent_window(&self, window: Duration) {
1038        self.restart_intent
1039            .lock()
1040            .unwrap_or_else(|p| p.into_inner())
1041            .window = window;
1042    }
1043
1044    #[cfg(unix)]
1045    fn take_daemon_shutdown_reason(&self) -> RouteCloseReason {
1046        let expiry = self
1047            .restart_intent
1048            .lock()
1049            .unwrap_or_else(|p| p.into_inner())
1050            .expires
1051            .take();
1052        if expiry.is_some_and(|expiry| subc_uptime::suspend_inclusive_now() < expiry) {
1053            RouteCloseReason::Restart
1054        } else {
1055            RouteCloseReason::Disable
1056        }
1057    }
1058
1059    pub fn new() -> Self {
1060        Self::default()
1061    }
1062
1063    pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
1064        Arc::clone(&self.operation_lock)
1065    }
1066}
1067
1068/// Process supervisor for subc-owned singleton modules.
1069#[derive(Debug, Clone)]
1070pub struct Supervisor {
1071    registry: Arc<Registry>,
1072    config_delivery: Option<config_delivery::ConfigDelivery>,
1073    restart_policy: RestartPolicy,
1074    drain_timeout: Duration,
1075    connection_file_path: Option<PathBuf>,
1076    capture_logs_dir: Option<PathBuf>,
1077    forwarding: Option<Arc<ForwardingTable>>,
1078    process_liveness: Arc<SupervisorProcessLiveness>,
1079    supervisor_handle: Option<SupervisorHandle>,
1080    health: HealthConfig,
1081    host_health: HostHealth,
1082    daemon_start_clock: crate::clock::StartClock,
1083    terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
1084    spawn_events: SpawnEventFeed,
1085    provenance_probe: ExecutableIdentityProbe,
1086    /// Every process spawned through this supervisor (and its clones) and not
1087    /// yet reaped, so daemon shutdown can end them.
1088    child_roster: ChildRoster,
1089    #[cfg(target_os = "linux")]
1090    cgroup_placement: Option<subc_cgroup::Placement>,
1091    #[cfg(test)]
1092    test_after_first_spawn: AfterFirstSpawnHook,
1093}
1094
1095impl Supervisor {
1096    pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
1097        Self {
1098            registry,
1099            config_delivery: None,
1100            restart_policy,
1101            drain_timeout: DEFAULT_DRAIN_TIMEOUT,
1102            connection_file_path: None,
1103            capture_logs_dir: None,
1104            forwarding: None,
1105            process_liveness: Arc::new(SupervisorProcessLiveness::default()),
1106            supervisor_handle: None,
1107            health: HealthConfig::default(),
1108            host_health: HostHealth::default(),
1109            daemon_start_clock: crate::clock::StartClock::capture(),
1110            terminal_journal: None,
1111            spawn_events: SpawnEventFeed::default(),
1112            provenance_probe: ExecutableIdentityProbe::default(),
1113            child_roster: ChildRoster::default(),
1114            #[cfg(target_os = "linux")]
1115            cgroup_placement: None,
1116            #[cfg(test)]
1117            test_after_first_spawn: AfterFirstSpawnHook::default(),
1118        }
1119    }
1120
1121    pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
1122        self.drain_timeout = drain_timeout;
1123        self
1124    }
1125
1126    /// The drain budget a module gets when its config entry sets none.
1127    pub(crate) fn default_drain_timeout(&self) -> Duration {
1128        self.drain_timeout
1129    }
1130
1131    pub fn with_process_liveness(
1132        mut self,
1133        process_liveness: Arc<SupervisorProcessLiveness>,
1134    ) -> Self {
1135        self.process_liveness = process_liveness;
1136        self
1137    }
1138
1139    /// Connect configuration delivery to observed process lifecycle events.
1140    pub fn with_config_runtime(
1141        mut self,
1142        owner: Arc<crate::config_gate::runtime::RuntimeOwner>,
1143    ) -> Self {
1144        if let Some(handle) = &self.supervisor_handle {
1145            handle.install_binding_retirement(&owner);
1146        }
1147        self.config_delivery = Some(config_delivery::ConfigDelivery(owner));
1148        self
1149    }
1150
1151    pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
1152        self.connection_file_path = Some(connection_file_path.into());
1153        self
1154    }
1155
1156    /// Enables daemon-owned capture files for supervised stdout and stderr.
1157    pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
1158        self.capture_logs_dir = Some(logs_dir.into());
1159        self
1160    }
1161
1162    /// Names this daemon lifetime in spawn events, independently of whether a
1163    /// terminal journal is configured.
1164    pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
1165        // A millisecond start stamp can repeat after clock rollback or a rapid
1166        // restart. Use the connection file's random daemon_id instead: it already
1167        // identifies this daemon lifetime independently of the wall clock.
1168        self.spawn_events.configure_incarnation(daemon_incarnation);
1169        self
1170    }
1171
1172    /// Enables best-effort history shared by every supervised module. Without
1173    /// it, terminal history is kept only in each module's in-memory ring.
1174    pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
1175        let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
1176        this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
1177            path,
1178            daemon_incarnation,
1179        )));
1180        this
1181    }
1182
1183    pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
1184        self.child_roster.counters = forwarding.counters();
1185        self.forwarding = Some(forwarding);
1186        self
1187    }
1188
1189    pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
1190        if let Some(delivery) = &self.config_delivery {
1191            supervisor_handle.install_binding_retirement(&delivery.0);
1192        }
1193        self.host_health = supervisor_handle.host_health.clone();
1194        self.spawn_events = supervisor_handle.spawn_events.clone();
1195        self.supervisor_handle = Some(supervisor_handle);
1196        self
1197    }
1198
1199    pub fn with_health_config(mut self, health: HealthConfig) -> Self {
1200        self.health = health;
1201        self
1202    }
1203
1204    /// Keeps a record of every live child at `path`, rewritten on each spawn and
1205    /// reap, for the orphan sweep a later daemon runs at boot. Without it no
1206    /// record is kept.
1207    pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
1208        self.child_roster.record_to(path.into());
1209        self
1210    }
1211
1212    #[cfg(any(target_os = "linux", target_os = "macos"))]
1213    pub(crate) fn with_resume_roster(
1214        self,
1215        path: PathBuf,
1216        protected: &crate::live_children::AdoptedPids,
1217    ) -> Self {
1218        self.child_roster.record_to_with_adopted(path, protected);
1219        self
1220    }
1221
1222    #[cfg(target_os = "linux")]
1223    pub fn with_cgroup_placement(
1224        mut self,
1225        cgroup_placement: Option<subc_cgroup::Placement>,
1226    ) -> Self {
1227        self.child_roster
1228            .set_cgroup_placement(cgroup_placement.clone());
1229        self.cgroup_placement = cgroup_placement;
1230        self
1231    }
1232}
1233
1234impl Default for Supervisor {
1235    fn default() -> Self {
1236        Self::new(Arc::new(Registry::default()), RestartPolicy::default())
1237    }
1238}
1239
1240/// Handle to one supervised child process.
1241#[derive(Clone)]
1242pub struct SupervisedModule {
1243    inner: Arc<SupervisedModuleInner>,
1244}
1245
1246struct SupervisedModuleInner {
1247    retained: crate::child_roster::RetainedView,
1248    module_id: String,
1249    registry: Arc<Registry>,
1250    snapshot: SharedSnapshot,
1251    configuration: Arc<Mutex<SupervisedConfiguration>>,
1252    stderr_ring: Arc<Mutex<StderrRing>>,
1253    terminal_ring: Arc<Mutex<TerminalRing>>,
1254    commands: mpsc::Sender<SupervisorCommand>,
1255    monitor: Mutex<Option<JoinHandle<()>>>,
1256    effective_drain_timeout: Arc<Mutex<Duration>>,
1257    provenance_probe: ExecutableIdentityProbe,
1258}
1259
1260impl fmt::Debug for SupervisedModule {
1261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1262        f.debug_struct("SupervisedModule")
1263            .field("module_id", &self.inner.module_id)
1264            .field("status", &self.status())
1265            .finish_non_exhaustive()
1266    }
1267}
1268
1269impl SupervisedModule {
1270    pub fn module_id(&self) -> &str {
1271        &self.inner.module_id
1272    }
1273
1274    pub fn state(&self) -> Result<ModuleState, SuperviseError> {
1275        Ok(lock_snapshot(&self.inner.snapshot)?.state)
1276    }
1277
1278    pub(crate) fn registration_end_reason(
1279        &self,
1280    ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
1281        let snapshot = lock_snapshot(&self.inner.snapshot)?;
1282        Ok(match snapshot.state {
1283            ModuleState::Draining if snapshot.draining_to_replace => {
1284                Some(RegistrationEndReason::SupervisorRestart)
1285            }
1286            ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
1287            ModuleState::Restarting if snapshot.draining_to_replace => {
1288                Some(RegistrationEndReason::SupervisorRestart)
1289            }
1290            _ => None,
1291        })
1292    }
1293
1294    /// The module's retained stderr, newest lines last.
1295    ///
1296    /// Deliberately NOT on [`Self::status`]: a bounded tail is kilobytes per
1297    /// module, `supervisor.list` renders every module, and putting it in the
1298    /// shared snapshot would make each status read carry a payload almost nobody
1299    /// asked for. Callers that want the text ask for it.
1300    pub fn stderr_tail(
1301        &self,
1302        max_lines: Option<usize>,
1303        max_bytes: Option<usize>,
1304    ) -> StderrTailSnapshot {
1305        self.inner
1306            .stderr_ring
1307            .lock()
1308            .unwrap_or_else(|poisoned| poisoned.into_inner())
1309            .snapshot(max_lines, max_bytes)
1310    }
1311
1312    /// The module's bounded terminal history, oldest retained exit first.
1313    ///
1314    /// The daemon-start stamp distinguishes a quiet supervisor from a replacement
1315    /// daemon whose in-memory history was necessarily reset.
1316    pub fn terminal_history(&self) -> TerminalHistorySnapshot {
1317        self.inner
1318            .terminal_ring
1319            .lock()
1320            .unwrap_or_else(|poisoned| poisoned.into_inner())
1321            .snapshot()
1322    }
1323
1324    /// Retained observations from the current ring and all journal generations.
1325    ///
1326    /// Blocking: this reads the journal files. Async callers use
1327    /// `Self::read_durable_terminal_history`.
1328    pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
1329        durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
1330    }
1331
1332    /// [`Self::durable_terminal_history`] on a blocking thread, so the journal
1333    /// read (up to every retained generation) never occupies a runtime worker.
1334    /// Fails only if the blocking task could not finish (runtime shutdown or a
1335    /// panic in the read).
1336    pub(crate) async fn read_durable_terminal_history(
1337        &self,
1338    ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
1339        let terminal_ring = Arc::clone(&self.inner.terminal_ring);
1340        let module_id = self.inner.module_id.clone();
1341        tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
1342            .await
1343    }
1344
1345    pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
1346        self.status_with_snapshot_lock(&self.inner.snapshot, None)
1347            .map(|(status, _)| status)
1348    }
1349
1350    pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
1351        let state = lock_snapshot(&self.inner.snapshot)?;
1352        Ok(state
1353            .failed_retry
1354            .pending
1355            .filter(|_| state.state == ModuleState::Failed && state.enabled)
1356            .map(|retry| {
1357                unix_ms_now().saturating_add(
1358                    u64::try_from(
1359                        retry
1360                            .deadline
1361                            .saturating_duration_since(Instant::now())
1362                            .as_millis(),
1363                    )
1364                    .unwrap_or(u64::MAX),
1365                )
1366            }))
1367    }
1368
1369    #[cfg(all(test, unix))]
1370    pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
1371        lock_snapshot(&self.inner.snapshot)
1372            .unwrap()
1373            .failed_retry
1374            .pending
1375            .map(|retry| retry.deadline)
1376    }
1377
1378    /// Read status for a channel-0 renderer and report a contended snapshot lock.
1379    ///
1380    /// Internal supervision callers use [`Self::status`] so writer-side machinery
1381    /// does not produce reader-observability logs.
1382    pub(crate) fn status_for_control(
1383        &self,
1384        caller: &'static str,
1385    ) -> Result<ModuleStatus, SuperviseError> {
1386        self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
1387            .map(|(status, _)| status)
1388    }
1389
1390    fn status_with_snapshot_lock(
1391        &self,
1392        snapshot: &SharedSnapshot,
1393        caller: Option<&'static str>,
1394    ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
1395        let restart_policy = self
1396            .inner
1397            .configuration
1398            .lock()
1399            .map_err(|_| SuperviseError::StatePoisoned {
1400                module_id: Some(self.inner.module_id.clone()),
1401            })?
1402            .restart_policy;
1403        let mut guard = match caller {
1404            Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
1405            None => lock_snapshot(snapshot)?,
1406        };
1407        // Read the budget through the pruning path so a reader sees the same
1408        // in-window count the restart decision would use, not a stale total.
1409        let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
1410        let snapshot = guard.clone();
1411        drop(guard);
1412        let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
1413            SuperviseError::StatePoisoned {
1414                module_id: Some(self.inner.module_id.clone()),
1415            }
1416        })?;
1417        let registration_active = self
1418            .inner
1419            .registry
1420            .get_module(&self.inner.module_id)
1421            .map_err(SuperviseError::Registry)?
1422            .is_some();
1423        let protocol = snapshot
1424            .spawned_protocol
1425            .unwrap_or(self.declared_protocol()?);
1426        let running_process =
1427            snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
1428        // Registration is the difference between the two protocols and the only
1429        // one: a subc module that has not registered cannot serve a request even
1430        // though its process is up, and a `none` module never registers at all,
1431        // so requiring it there would pin `live` to false for the whole life of
1432        // a perfectly healthy process.
1433        let live = match protocol {
1434            ModuleProtocol::Subc => running_process && registration_active,
1435            ModuleProtocol::None => running_process,
1436        };
1437        // Read only the retained cache: a status read must not resend signals,
1438        // rewrite the record, or keep the containment resource alive.
1439        let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
1440        let carry_configured = self
1441            .inner
1442            .configuration
1443            .lock()
1444            .map_err(|_| SuperviseError::StatePoisoned {
1445                module_id: Some(self.inner.module_id.clone()),
1446            })?
1447            .spec
1448            .carry_containment;
1449        let recovery_block = carries_containment(
1450            carry_configured,
1451            self.inner
1452                .retained
1453                .has_carried_container(&self.inner.module_id),
1454        )
1455        .then(|| self.inner.retained.recovery_block())
1456        .flatten();
1457        let launch_nonce_source = observed_launch_nonce_source(&snapshot);
1458        let pid = snapshot.reported_pid();
1459        let mut health = snapshot.health;
1460        if let Some(detail) = recovery_block
1461            .as_ref()
1462            .or_else(|| retained.as_ref().map(|(_, detail)| detail))
1463        {
1464            health.detail = Some(match health.detail {
1465                Some(previous) => format!("{previous}; {detail}"),
1466                None => detail.clone(),
1467            });
1468        }
1469
1470        Ok((
1471            ModuleStatus {
1472                admission_refused: snapshot.admission_refused,
1473                #[cfg(windows)]
1474                nonce_pipe_refusal: snapshot.nonce_pipe_refusal,
1475                legacy_registration_spawn: snapshot.legacy_registration_spawn,
1476                registration_declaration: snapshot.registration_declaration.clone(),
1477                stop_reason: snapshot.stop_reason,
1478                waiting_for_previous_pid: retained
1479                    .as_ref()
1480                    .map(|(pid, _)| *pid)
1481                    .filter(|pid| *pid > 0)
1482                    .or(snapshot.waiting_for_previous_pid),
1483                waiting_for_previous_detail: recovery_block
1484                    .or_else(|| retained.map(|(_, detail)| detail))
1485                    .or(snapshot.waiting_for_previous_detail),
1486                module_id: self.inner.module_id.clone(),
1487                launch_nonce_source,
1488                state: snapshot.state,
1489                enabled: snapshot.enabled,
1490                process_alive: snapshot.process_alive,
1491                registration_active,
1492                protocol,
1493                live,
1494                restart_count,
1495                lifetime_restarts: snapshot.lifetime_restarts,
1496                spawn_generation: snapshot.spawn_generation,
1497                swap_outcome: snapshot.swap_outcome,
1498                max_restarts: restart_policy.max_restarts,
1499                restart_window: restart_policy.window,
1500                drain_timeout,
1501                restart_backoff: restart_policy.backoff,
1502                restart_max_backoff: restart_policy.max_backoff,
1503                pid,
1504                spawned_at_ms: snapshot.spawned_at_ms,
1505                spawned_from: snapshot.spawned_from,
1506                launch_spec_digest: snapshot.launch_spec_digest,
1507                process_start_time: snapshot.process_start_time,
1508                last_exit: snapshot.last_exit,
1509                health,
1510            },
1511            snapshot.spawned_file_identity.clone(),
1512        ))
1513    }
1514
1515    #[cfg(test)]
1516    pub(crate) fn hold_snapshot_for_test(
1517        &self,
1518        acquired: std::sync::mpsc::Sender<()>,
1519        hold: Duration,
1520    ) -> std::thread::JoinHandle<()> {
1521        let snapshot = Arc::clone(&self.inner.snapshot);
1522        std::thread::spawn(move || {
1523            let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
1524            acquired
1525                .send(())
1526                .expect("test receiver waits for snapshot lock");
1527            std::thread::sleep(hold);
1528        })
1529    }
1530
1531    /// The status and the running-image check for `supervisor.provenance`,
1532    /// taken from one status read. The exec acknowledgement can land between
1533    /// two separate reads, and the reply would then pair "no pid yet" with an
1534    /// image observed after the module started, which describes no single
1535    /// moment.
1536    pub(crate) async fn status_and_running_image_agreement(
1537        &self,
1538    ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
1539        let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
1540        let image = self
1541            .inner
1542            .provenance_probe
1543            .observe(
1544                status.pid,
1545                status.spawned_from.as_deref(),
1546                identity,
1547                status.process_start_time,
1548            )
1549            .await;
1550        Ok((status, image))
1551    }
1552
1553    pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
1554        let snapshot = match lock_snapshot(&self.inner.snapshot) {
1555            Ok(snapshot) => snapshot.clone(),
1556            Err(_) => {
1557                return subc_control::RunningImageAgreement::Unavailable {
1558                    reason: subc_control::RunningImageUnavailableReason::NotRunning,
1559                };
1560            }
1561        };
1562        self.inner
1563            .provenance_probe
1564            .observe(
1565                snapshot.reported_pid(),
1566                snapshot.spawned_from.as_deref(),
1567                snapshot.spawned_file_identity.clone(),
1568                snapshot.process_start_time,
1569            )
1570            .await
1571    }
1572
1573    /// Memory and CPU time of the module's current process, read now. Only the
1574    /// process the supervisor spawned is read, not processes it has started.
1575    pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
1576        #[cfg(windows)]
1577        {
1578            let image = lock_snapshot(&self.inner.snapshot)
1579                .ok()
1580                .and_then(|snapshot| {
1581                    snapshot
1582                        .spawned_file_identity
1583                        .as_ref()
1584                        .and_then(|identity| identity.windows_image.clone())
1585                });
1586            match image {
1587                Some(image) => {
1588                    crate::child_resources::read_windows_handle(image.process(), image.start_time())
1589                }
1590                None => subc_control::ChildResourceUsage::Unavailable {
1591                    reason: subc_control::ChildResourceUnavailableReason::NotRunning,
1592                },
1593            }
1594        }
1595        #[cfg(not(windows))]
1596        {
1597            let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
1598                Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
1599                Err(_) => {
1600                    return subc_control::ChildResourceUsage::Unavailable {
1601                        reason: subc_control::ChildResourceUnavailableReason::Unreadable,
1602                    }
1603                }
1604            };
1605            crate::child_resources::read(pid, start_time)
1606        }
1607    }
1608
1609    #[cfg(all(test, any(target_os = "linux", windows)))]
1610    pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
1611        self.inner
1612            .snapshot
1613            .try_lock()
1614            .map(|snapshot| snapshot.subtree_target.clone())
1615            .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
1616    }
1617
1618    #[cfg(test)]
1619    pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
1620        self.inner.snapshot.lock().unwrap().subtree_target = target;
1621    }
1622
1623    pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
1624        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
1625        Ok(match snapshot.state {
1626            ModuleState::Restarting => true,
1627            ModuleState::Failed | ModuleState::Disabled => false,
1628            _ if snapshot.enabled && snapshot.respawn_pending => true,
1629            _ => daemon_will_restart(
1630                &mut snapshot,
1631                &self
1632                    .inner
1633                    .configuration
1634                    .lock()
1635                    .map_err(|_| SuperviseError::StatePoisoned {
1636                        module_id: Some(self.inner.module_id.clone()),
1637                    })?
1638                    .restart_policy,
1639                Instant::now(),
1640            ),
1641        })
1642    }
1643
1644    #[cfg(test)]
1645    pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
1646        self.is_warming_with_snapshot_lock(None)
1647    }
1648
1649    pub(crate) fn is_warming_for_control(
1650        &self,
1651        caller: &'static str,
1652    ) -> Result<bool, SuperviseError> {
1653        self.is_warming_with_snapshot_lock(Some(caller))
1654    }
1655
1656    fn is_warming_with_snapshot_lock(
1657        &self,
1658        caller: Option<&'static str>,
1659    ) -> Result<bool, SuperviseError> {
1660        let snapshot = match caller {
1661            Some(caller) => {
1662                lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
1663            }
1664            None => lock_snapshot(&self.inner.snapshot)?,
1665        }
1666        .clone();
1667        Ok(matches!(
1668            snapshot.state,
1669            ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
1670        ))
1671    }
1672
1673    /// The current process's protocol, or the configured protocol when down.
1674    /// A rescan stores the next launch spec without changing how an existing
1675    /// process registers, serves routes, is probed, or exits.
1676    pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
1677        let configured = self
1678            .inner
1679            .configuration
1680            .lock()
1681            .map_err(|_| SuperviseError::StatePoisoned {
1682                module_id: Some(self.inner.module_id.clone()),
1683            })?
1684            .spec
1685            .protocol;
1686        let state = lock_snapshot(&self.inner.snapshot)?;
1687        Ok(state.spawned_protocol.unwrap_or(configured))
1688    }
1689
1690    pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
1691        let configuration =
1692            self.inner
1693                .configuration
1694                .lock()
1695                .map_err(|_| SuperviseError::StatePoisoned {
1696                    module_id: Some(self.inner.module_id.clone()),
1697                })?;
1698        Ok((configuration.spec.clone(), configuration.health.clone()))
1699    }
1700
1701    pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
1702        self.inner
1703            .configuration
1704            .lock()
1705            .map(|configuration| configuration.register_timeout)
1706            .map_err(|_| SuperviseError::StatePoisoned {
1707                module_id: Some(self.inner.module_id.clone()),
1708            })
1709    }
1710
1711    pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
1712        self.inner
1713            .configuration
1714            .lock()
1715            .map(|configuration| configuration.enabled)
1716            .map_err(|_| SuperviseError::StatePoisoned {
1717                module_id: Some(self.inner.module_id.clone()),
1718            })
1719    }
1720
1721    /// Replace this module's launch spec, keeping its health and drain policy,
1722    /// the way a rescan does for a changed config entry. The running process is
1723    /// untouched; the next spawn (a restart, or a swap's candidate) uses it.
1724    #[cfg(any(test, feature = "test-support"))]
1725    pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
1726        let (_, health) = self.configuration()?;
1727        let drain_timeout_ms = u64::try_from(
1728            self.inner
1729                .effective_drain_timeout
1730                .lock()
1731                .unwrap_or_else(|poisoned| poisoned.into_inner())
1732                .as_millis(),
1733        )
1734        .ok();
1735        self.update_configuration(spec, health, drain_timeout_ms)
1736            .await
1737    }
1738
1739    pub(crate) async fn update_configuration(
1740        &self,
1741        spec: ModuleSpec,
1742        health: HealthConfig,
1743        drain_timeout_ms: Option<u64>,
1744    ) -> Result<(), SuperviseError> {
1745        if spec.module_id != self.inner.module_id {
1746            return Err(SuperviseError::InvalidSpec {
1747                reason: "a supervised module's module_id cannot be changed".to_string(),
1748            });
1749        }
1750        validate_spec(&spec)?;
1751        let (reply_tx, reply_rx) = oneshot::channel();
1752        self.inner
1753            .commands
1754            .send(SupervisorCommand::UpdateConfiguration {
1755                spec: spec.clone(),
1756                health: health.clone(),
1757                drain_timeout_ms,
1758                reply: reply_tx,
1759            })
1760            .await
1761            .map_err(|_| SuperviseError::CommandClosed {
1762                module_id: self.inner.module_id.clone(),
1763            })?;
1764        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
1765            module_id: self.inner.module_id.clone(),
1766        })??;
1767        let mut configuration =
1768            self.inner
1769                .configuration
1770                .lock()
1771                .map_err(|_| SuperviseError::StatePoisoned {
1772                    module_id: Some(self.inner.module_id.clone()),
1773                })?;
1774        configuration.spec = spec;
1775        configuration.health = health;
1776        Ok(())
1777    }
1778}
1779
1780impl Drop for SupervisedModuleInner {
1781    fn drop(&mut self) {
1782        let Ok(mut monitor) = self.monitor.lock() else {
1783            return;
1784        };
1785        if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
1786            let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
1787                state.state = ModuleState::Stopped;
1788                clear_current_process_facts(state);
1789            });
1790            monitor.abort();
1791        }
1792        let _ = monitor.take();
1793    }
1794}
1795
1796/// Successful daemon-local swap disposition. Supersession leaves the incumbent
1797/// serving until an approved replacement starts with the latest configured
1798/// command; the legacy control acknowledgment does not carry this disposition.
1799#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1800pub enum SwapOutcome {
1801    Cutover,
1802    SupersededByConfigRestart,
1803}
1804
1805impl SwapOutcome {
1806    pub fn as_str(self) -> &'static str {
1807        match self {
1808            Self::Cutover => "cutover",
1809            Self::SupersededByConfigRestart => "superseded_by_config_restart",
1810        }
1811    }
1812}
1813
1814#[derive(Debug)]
1815pub enum SuperviseError {
1816    UpgradeInProgress,
1817    ConfigHeld {
1818        module_id: String,
1819        code: String,
1820        detail: String,
1821    },
1822    ConfigDeliveryDeferred {
1823        module_id: String,
1824    },
1825    InvalidSpec {
1826        reason: String,
1827    },
1828    Spawn {
1829        program: PathBuf,
1830        source: io::Error,
1831        cgroup_path: Option<PathBuf>,
1832    },
1833    Cgroup {
1834        module_id: String,
1835        source: io::Error,
1836    },
1837    /// The cryptographic random-number generator failed while generating a
1838    /// reserved module's launch nonce. Fail loud rather than spawn a reserved
1839    /// module without its identity binding.
1840    LaunchNonce {
1841        reason: String,
1842    },
1843    Wait {
1844        module_id: String,
1845        source: io::Error,
1846    },
1847    Kill {
1848        module_id: String,
1849        source: io::Error,
1850    },
1851    Forwarding(ForwardingError),
1852    Registry(RegistryError),
1853    ReloadUnavailable {
1854        module_id: String,
1855        reason: String,
1856    },
1857    /// An operator restart/reload was requested for a module that is currently
1858    /// disabled. Restart/reload cycle a *running* module; a disabled module must
1859    /// be explicitly re-enabled (set_enabled(true)) rather than silently started
1860    /// by a restart, so these commands are rejected instead of re-enabling it.
1861    Disabled {
1862        module_id: String,
1863    },
1864    ReloadFailed {
1865        module_id: String,
1866        reason: String,
1867    },
1868    RegistrationStillActive {
1869        module_id: String,
1870        waited: Duration,
1871    },
1872    StatePoisoned {
1873        module_id: Option<String>,
1874    },
1875    CommandClosed {
1876        module_id: String,
1877    },
1878    /// A restart or reload arrived while a swap's candidate was warming. The
1879    /// swap owns the module until it cuts over or fails; a stop or disable
1880    /// would have aborted it instead.
1881    SwapInProgress {
1882        module_id: String,
1883    },
1884    /// A swap was refused before anything was spawned.
1885    SwapRefused {
1886        module_id: String,
1887        reason: SwapRefusal,
1888    },
1889    /// A swap spawned a candidate and gave up on it. The candidate has been
1890    /// killed and its slot freed; the incumbent was left serving and was never
1891    /// drained, except in the one `CutoverLost` case described on that arm.
1892    SwapFailed {
1893        module_id: String,
1894        arm: SwapFailureArm,
1895        detail: String,
1896        /// How the candidate exited, when it exited on its own before the
1897        /// supervisor gave up on it.
1898        candidate_exit: Option<ExitReport>,
1899    },
1900}
1901
1902/// Why a swap was refused before a candidate was spawned.
1903#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1904pub enum SwapRefusal {
1905    /// The module's config does not declare `overlap: "safe"`.
1906    OverlapExclusive,
1907    /// The module is not registered, so there is no incumbent to keep serving
1908    /// and nothing a swap would improve on; a plain restart is the tool.
1909    NotRegistered,
1910    /// The module does not speak the subc wire, so a candidate could never
1911    /// register or declare itself ready.
1912    ProtocolNone,
1913    /// The supervisor lacks the forwarding table (to cut routes over) or the
1914    /// shared handle (to admit the candidate's HELLO) that a swap needs.
1915    NotConfigured,
1916    /// A swap is already open for this module.
1917    AlreadySwapping,
1918}
1919
1920impl SwapRefusal {
1921    pub fn as_str(self) -> &'static str {
1922        match self {
1923            Self::OverlapExclusive => "overlap_exclusive",
1924            Self::NotRegistered => "not_registered",
1925            Self::ProtocolNone => "protocol_none",
1926            Self::NotConfigured => "not_configured",
1927            Self::AlreadySwapping => "already_swapping",
1928        }
1929    }
1930}
1931
1932/// Which failure arm ended a swap. Every arm but one leaves the incumbent
1933/// serving and undrained; see `CutoverLost`.
1934#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1935pub enum SwapFailureArm {
1936    /// The candidate process could not be started.
1937    SpawnFailed,
1938    /// The candidate did not register within the readiness budget.
1939    NeverRegistered,
1940    /// The candidate registered but did not declare itself ready in time.
1941    NeverReady,
1942    /// The candidate exited before cutover.
1943    CandidateExited,
1944    /// The candidate declared itself ready but failed its health probe.
1945    CandidateUnhealthy,
1946    /// An operator stop, disable or retire arrived while the candidate warmed.
1947    /// The candidate was killed and the operator's command then carried out on
1948    /// the incumbent.
1949    Interrupted,
1950    /// The candidate's connection closed at the moment of cutover. If it
1951    /// closed before forwarding moved, the incumbent is untouched. If it closed
1952    /// between the forwarding and registry halves of cutover, forwarding can no
1953    /// longer route to the incumbent, so the module is restarted plainly.
1954    CutoverLost,
1955}
1956
1957impl SwapFailureArm {
1958    pub fn as_str(self) -> &'static str {
1959        match self {
1960            Self::SpawnFailed => "spawn_failed",
1961            Self::NeverRegistered => "never_registered",
1962            Self::NeverReady => "never_ready",
1963            Self::CandidateExited => "candidate_exited",
1964            Self::CandidateUnhealthy => "candidate_unhealthy",
1965            Self::Interrupted => "interrupted",
1966            Self::CutoverLost => "cutover_lost",
1967        }
1968    }
1969}
1970
1971impl SuperviseError {
1972    pub(crate) fn is_config_gate_error(&self) -> bool {
1973        match self {
1974            Self::ConfigHeld { .. } => true,
1975            Self::Spawn { source, .. } => source
1976                .get_ref()
1977                .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
1978            _ => false,
1979        }
1980    }
1981}
1982
1983impl fmt::Display for SuperviseError {
1984    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1985        match self {
1986            Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
1987            Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
1988            Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
1989            Self::Spawn {
1990                program,
1991                source,
1992                cgroup_path: Some(cgroup_path),
1993            } => write!(
1994                f,
1995                "failed to place module in cgroup '{}' while spawning '{}': {source}",
1996                cgroup_path.display(),
1997                program.display()
1998            ),
1999            Self::Spawn {
2000                program,
2001                source,
2002                cgroup_path: None,
2003            } => write!(
2004                f,
2005                "failed to spawn module '{}': {source}",
2006                program.display()
2007            ),
2008            Self::Cgroup { module_id, source } => {
2009                write!(
2010                    f,
2011                    "failed to prepare cgroup for module '{module_id}': {source}"
2012                )
2013            }
2014            Self::LaunchNonce { reason } => {
2015                write!(
2016                    f,
2017                    "failed to generate reserved-module launch nonce: {reason}"
2018                )
2019            }
2020            Self::Wait { module_id, source } => {
2021                write!(f, "failed to wait for module '{module_id}': {source}")
2022            }
2023            Self::Kill { module_id, source } => {
2024                write!(f, "failed to kill module '{module_id}': {source}")
2025            }
2026            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
2027            Self::Registry(err) => write!(f, "registry error: {err}"),
2028            Self::ReloadUnavailable { module_id, reason } => {
2029                write!(f, "reload unavailable for module '{module_id}': {reason}")
2030            }
2031            Self::Disabled { module_id } => {
2032                write!(
2033                    f,
2034                    "module '{module_id}' is disabled; enable it before restart or reload"
2035                )
2036            }
2037            Self::ReloadFailed { module_id, reason } => {
2038                write!(f, "reload failed for module '{module_id}': {reason}")
2039            }
2040            Self::RegistrationStillActive { module_id, waited } => write!(
2041                f,
2042                "module '{module_id}' registration remained active after waiting {waited:?}"
2043            ),
2044            Self::StatePoisoned { module_id } => match module_id {
2045                Some(module_id) => {
2046                    write!(f, "supervisor state for module '{module_id}' was poisoned")
2047                }
2048                None => write!(f, "supervisor state was poisoned"),
2049            },
2050            Self::CommandClosed { module_id } => {
2051                write!(
2052                    f,
2053                    "supervisor command channel for module '{module_id}' is closed"
2054                )
2055            }
2056            Self::UpgradeInProgress => f.write_str("daemon upgrade is in progress"),
2057            Self::SwapInProgress { module_id } => write!(
2058                f,
2059                "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
2060            ),
2061            Self::SwapRefused { module_id, reason } => match reason {
2062                SwapRefusal::OverlapExclusive => write!(
2063                    f,
2064                    "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"
2065                ),
2066                SwapRefusal::NotRegistered => write!(
2067                    f,
2068                    "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
2069                ),
2070                SwapRefusal::ProtocolNone => write!(
2071                    f,
2072                    "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
2073                ),
2074                SwapRefusal::NotConfigured => write!(
2075                    f,
2076                    "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
2077                ),
2078                SwapRefusal::AlreadySwapping => {
2079                    write!(f, "module '{module_id}' is already being swapped")
2080                }
2081            },
2082            Self::SwapFailed {
2083                module_id,
2084                arm,
2085                detail,
2086                ..
2087            } => write!(
2088                f,
2089                "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
2090                arm.as_str()
2091            ),
2092        }
2093    }
2094}
2095
2096impl Error for SuperviseError {
2097    fn source(&self) -> Option<&(dyn Error + 'static)> {
2098        match self {
2099            Self::Spawn { source, .. }
2100            | Self::Cgroup { source, .. }
2101            | Self::Wait { source, .. }
2102            | Self::Kill { source, .. } => Some(source),
2103            Self::Forwarding(err) => Some(err),
2104            Self::Registry(err) => Some(err),
2105            Self::LaunchNonce { .. }
2106            | Self::ConfigDeliveryDeferred { .. }
2107            | Self::ConfigHeld { .. }
2108            | Self::InvalidSpec { .. }
2109            | Self::ReloadUnavailable { .. }
2110            | Self::Disabled { .. }
2111            | Self::ReloadFailed { .. }
2112            | Self::RegistrationStillActive { .. }
2113            | Self::StatePoisoned { .. }
2114            | Self::CommandClosed { .. }
2115            | Self::SwapInProgress { .. }
2116            | Self::UpgradeInProgress
2117            | Self::SwapRefused { .. }
2118            | Self::SwapFailed { .. } => None,
2119        }
2120    }
2121}
2122
2123fn unix_ms_now() -> u64 {
2124    SystemTime::now()
2125        .duration_since(UNIX_EPOCH)
2126        .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
2127        .unwrap_or(0)
2128}
2129
2130fn update_snapshot(
2131    snapshot: &SharedSnapshot,
2132    module_id: Option<&str>,
2133    update: impl FnOnce(&mut SupervisorSnapshot),
2134) -> Result<(), SuperviseError> {
2135    let mut state = lock_snapshot(snapshot).map_err(|_| SuperviseError::StatePoisoned {
2136        module_id: module_id.map(ToOwned::to_owned),
2137    })?;
2138    update(&mut state);
2139    Ok(())
2140}
2141
2142const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
2143
2144fn lock_snapshot_for_control<'a>(
2145    snapshot: &'a SharedSnapshot,
2146    module_id: &str,
2147    caller: &'static str,
2148) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
2149    let started_at = Instant::now();
2150    let guard = lock_snapshot(snapshot)?;
2151    let waited = started_at.elapsed();
2152    if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
2153        warn!(
2154            module_id = %module_id,
2155            waited_ms = waited.as_millis() as u64,
2156            caller = %caller,
2157            "slow snapshot lock"
2158        );
2159    }
2160    Ok(guard)
2161}
2162
2163fn lock_snapshot(
2164    snapshot: &SharedSnapshot,
2165) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
2166    let guard = match snapshot.try_lock() {
2167        Ok(guard) => return Ok(guard),
2168        Err(TryLockError::Poisoned(guard)) => Err(guard),
2169        Err(TryLockError::WouldBlock) => {
2170            // A held launch record must not pin a daemon worker: that worker
2171            // may also have to route and deliver the busy reply to a module.
2172            if tokio::runtime::Handle::try_current().is_ok_and(|handle| {
2173                handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
2174            }) {
2175                tokio::task::block_in_place(|| snapshot.lock())
2176            } else {
2177                snapshot.lock()
2178            }
2179        }
2180    };
2181    guard.map_err(|_| SuperviseError::StatePoisoned { module_id: None })
2182}
2183
2184#[cfg(all(test, unix))]
2185mod restart_ordering_tests;
2186
2187#[cfg(all(test, target_os = "macos"))]
2188#[path = "supervise/suspended_spawn_tests.rs"]
2189mod suspended_spawn_tests;
2190
2191#[cfg(all(test, target_os = "linux"))]
2192#[path = "supervise/cgroup_reap_tests.rs"]
2193mod cgroup_reap_tests;
2194
2195#[cfg(test)]
2196#[path = "supervise/supervise_tests.rs"]
2197mod tests;
2198
2199#[cfg(test)]
2200#[path = "supervise/spawn_record_tests.rs"]
2201mod spawn_record_tests;
2202
2203#[cfg(all(test, target_os = "linux"))]
2204#[path = "supervise/spawn_image_tests.rs"]
2205mod spawn_image_tests;
2206
2207#[cfg(test)]
2208#[path = "supervise/slot_registration_wait_tests.rs"]
2209mod slot_registration_wait_tests;
2210
2211#[cfg(test)]
2212#[path = "supervise/terminal_history_tests.rs"]
2213mod terminal_history_tests;
2214
2215#[cfg(all(test, unix))]
2216#[path = "supervise/health_event_tests.rs"]
2217mod health_event_tests;
2218
2219#[cfg(test)]
2220#[path = "supervise/drain_busy_reprobe_tests.rs"]
2221mod drain_busy_reprobe_tests;
2222
2223#[cfg(test)]
2224#[path = "supervise/health_evidence_tests.rs"]
2225mod health_evidence_tests;
2226
2227#[cfg(test)]
2228#[path = "supervise/health_tombstone_tests.rs"]
2229mod health_tombstone_tests;
2230
2231#[cfg(test)]
2232#[path = "supervise/child_env_tests.rs"]
2233mod child_env_tests;
2234
2235#[cfg(test)]
2236#[path = "supervise/jitter_tests.rs"]
2237mod jitter_tests;
2238
2239#[cfg(all(test, target_os = "linux"))]
2240#[path = "supervise/cgroup_placement_tests.rs"]
2241mod cgroup_placement_tests;
2242
2243#[cfg(test)]
2244#[path = "supervise/spawn_subscriber_lag_tests.rs"]
2245mod spawn_subscriber_lag_tests;
2246
2247#[cfg(test)]
2248#[path = "supervise/terminal_history_read_concurrency_tests.rs"]
2249mod terminal_history_read_concurrency_tests;
2250
2251/// What a restart does with the exited process's output readers. These drive
2252/// the same settle functions the supervisor calls, with a reader the test
2253/// holds, so a reader that has not been scheduled by the bound is a controlled
2254/// input rather than something only a loaded machine produces.
2255#[cfg(test)]
2256#[path = "supervise/stderr_settle_tests.rs"]
2257mod stderr_settle_tests;
2258
2259/// Containment of a module's process tree.
2260///
2261/// The behaviour these defend against is a module helper surviving its module:
2262/// on a real machine the Synapse embedding module's CUDA worker holds ~2.2 GB of
2263/// VRAM, so a leaked grandchild is a leaked GPU allocation, and a day of restarts
2264/// compounds it.
2265///
2266/// They run against the SUPERVISOR rather than the job-object crate because the
2267/// claim is about teardown: a crate-level test proves a job can reap a tree, not
2268/// that the daemon's drain path reaches it.
2269///
2270/// Windows-only, like the mechanism. On Unix this arm compiles out; the cgroup
2271/// lane there is a separate containment path with its own tests.
2272#[cfg(all(test, windows))]
2273#[path = "supervise/job_containment_tests.rs"]
2274mod job_containment_tests;
2275
2276#[cfg(test)]
2277#[path = "supervise/privacy_trampoline_configuration_tests.rs"]
2278mod privacy_trampoline_configuration_tests;
2279
2280#[cfg(test)]
2281#[path = "supervise/privacy_exec_boundary_tests.rs"]
2282mod privacy_exec_boundary_tests;
2283
2284/// The daemon's real spawn path hands a subc-wire child its launch nonce on
2285/// descriptor 3, without an environment copy. The shell records the nonce
2286/// and its environment after exec so these tests observe the real handover.
2287#[cfg(all(test, unix))]
2288#[path = "supervise/launch_nonce_descriptor_tests.rs"]
2289mod launch_nonce_descriptor_tests;
2290
2291#[cfg(all(test, target_os = "linux"))]
2292#[path = "supervise/cgroup_containment_tests.rs"]
2293mod cgroup_containment_tests;
2294
2295/// A slow live-children record write on the restart path must not stop the
2296/// daemon from answering the replacement module's authentication handshake.
2297#[cfg(all(test, unix))]
2298#[path = "supervise/record_write_stall_tests.rs"]
2299mod record_write_stall_tests;
2300
2301#[cfg(all(test, unix))]
2302#[path = "supervise/retained_status_tests.rs"]
2303mod retained_status_tests;