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    pub(crate) fn with_owned_live_children_record(
1213        self,
1214        owner: &crate::run_dir_lock::RunDirLock,
1215        protected: &crate::live_children::AdoptedPids,
1216    ) -> Self {
1217        self.child_roster.record_to_owned(owner, protected);
1218        self
1219    }
1220
1221    #[cfg(target_os = "linux")]
1222    pub fn with_cgroup_placement(
1223        mut self,
1224        cgroup_placement: Option<subc_cgroup::Placement>,
1225    ) -> Self {
1226        self.child_roster
1227            .set_cgroup_placement(cgroup_placement.clone());
1228        self.cgroup_placement = cgroup_placement;
1229        self
1230    }
1231}
1232
1233impl Default for Supervisor {
1234    fn default() -> Self {
1235        Self::new(Arc::new(Registry::default()), RestartPolicy::default())
1236    }
1237}
1238
1239/// Handle to one supervised child process.
1240#[derive(Clone)]
1241pub struct SupervisedModule {
1242    inner: Arc<SupervisedModuleInner>,
1243}
1244
1245struct SupervisedModuleInner {
1246    retained: crate::child_roster::RetainedView,
1247    module_id: String,
1248    registry: Arc<Registry>,
1249    snapshot: SharedSnapshot,
1250    configuration: Arc<Mutex<SupervisedConfiguration>>,
1251    stderr_ring: Arc<Mutex<StderrRing>>,
1252    terminal_ring: Arc<Mutex<TerminalRing>>,
1253    commands: mpsc::Sender<SupervisorCommand>,
1254    monitor: Mutex<Option<JoinHandle<()>>>,
1255    effective_drain_timeout: Arc<Mutex<Duration>>,
1256    provenance_probe: ExecutableIdentityProbe,
1257}
1258
1259impl fmt::Debug for SupervisedModule {
1260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261        f.debug_struct("SupervisedModule")
1262            .field("module_id", &self.inner.module_id)
1263            .field("status", &self.status())
1264            .finish_non_exhaustive()
1265    }
1266}
1267
1268impl SupervisedModule {
1269    pub fn module_id(&self) -> &str {
1270        &self.inner.module_id
1271    }
1272
1273    pub fn state(&self) -> Result<ModuleState, SuperviseError> {
1274        Ok(lock_snapshot(&self.inner.snapshot)?.state)
1275    }
1276
1277    pub(crate) fn registration_end_reason(
1278        &self,
1279    ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
1280        let snapshot = lock_snapshot(&self.inner.snapshot)?;
1281        Ok(match snapshot.state {
1282            ModuleState::Draining if snapshot.draining_to_replace => {
1283                Some(RegistrationEndReason::SupervisorRestart)
1284            }
1285            ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
1286            ModuleState::Restarting if snapshot.draining_to_replace => {
1287                Some(RegistrationEndReason::SupervisorRestart)
1288            }
1289            _ => None,
1290        })
1291    }
1292
1293    /// The module's retained stderr, newest lines last.
1294    ///
1295    /// Deliberately NOT on [`Self::status`]: a bounded tail is kilobytes per
1296    /// module, `supervisor.list` renders every module, and putting it in the
1297    /// shared snapshot would make each status read carry a payload almost nobody
1298    /// asked for. Callers that want the text ask for it.
1299    pub fn stderr_tail(
1300        &self,
1301        max_lines: Option<usize>,
1302        max_bytes: Option<usize>,
1303    ) -> StderrTailSnapshot {
1304        self.inner
1305            .stderr_ring
1306            .lock()
1307            .unwrap_or_else(|poisoned| poisoned.into_inner())
1308            .snapshot(max_lines, max_bytes)
1309    }
1310
1311    /// The module's bounded terminal history, oldest retained exit first.
1312    ///
1313    /// The daemon-start stamp distinguishes a quiet supervisor from a replacement
1314    /// daemon whose in-memory history was necessarily reset.
1315    pub fn terminal_history(&self) -> TerminalHistorySnapshot {
1316        self.inner
1317            .terminal_ring
1318            .lock()
1319            .unwrap_or_else(|poisoned| poisoned.into_inner())
1320            .snapshot()
1321    }
1322
1323    /// Retained observations from the current ring and all journal generations.
1324    ///
1325    /// Blocking: this reads the journal files. Async callers use
1326    /// `Self::read_durable_terminal_history`.
1327    pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
1328        durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
1329    }
1330
1331    /// [`Self::durable_terminal_history`] on a blocking thread, so the journal
1332    /// read (up to every retained generation) never occupies a runtime worker.
1333    /// Fails only if the blocking task could not finish (runtime shutdown or a
1334    /// panic in the read).
1335    pub(crate) async fn read_durable_terminal_history(
1336        &self,
1337    ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
1338        let terminal_ring = Arc::clone(&self.inner.terminal_ring);
1339        let module_id = self.inner.module_id.clone();
1340        tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
1341            .await
1342    }
1343
1344    pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
1345        self.status_with_snapshot_lock(&self.inner.snapshot, None)
1346            .map(|(status, _)| status)
1347    }
1348
1349    pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
1350        let state = lock_snapshot(&self.inner.snapshot)?;
1351        Ok(state
1352            .failed_retry
1353            .pending
1354            .filter(|_| state.state == ModuleState::Failed && state.enabled)
1355            .map(|retry| {
1356                unix_ms_now().saturating_add(
1357                    u64::try_from(
1358                        retry
1359                            .deadline
1360                            .saturating_duration_since(Instant::now())
1361                            .as_millis(),
1362                    )
1363                    .unwrap_or(u64::MAX),
1364                )
1365            }))
1366    }
1367
1368    #[cfg(all(test, unix))]
1369    pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
1370        lock_snapshot(&self.inner.snapshot)
1371            .unwrap()
1372            .failed_retry
1373            .pending
1374            .map(|retry| retry.deadline)
1375    }
1376
1377    /// Read status for a channel-0 renderer and report a contended snapshot lock.
1378    ///
1379    /// Internal supervision callers use [`Self::status`] so writer-side machinery
1380    /// does not produce reader-observability logs.
1381    pub(crate) fn status_for_control(
1382        &self,
1383        caller: &'static str,
1384    ) -> Result<ModuleStatus, SuperviseError> {
1385        self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
1386            .map(|(status, _)| status)
1387    }
1388
1389    fn status_with_snapshot_lock(
1390        &self,
1391        snapshot: &SharedSnapshot,
1392        caller: Option<&'static str>,
1393    ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
1394        let restart_policy = self
1395            .inner
1396            .configuration
1397            .lock()
1398            .map_err(|_| SuperviseError::StatePoisoned {
1399                module_id: Some(self.inner.module_id.clone()),
1400            })?
1401            .restart_policy;
1402        let mut guard = match caller {
1403            Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
1404            None => lock_snapshot(snapshot)?,
1405        };
1406        // Read the budget through the pruning path so a reader sees the same
1407        // in-window count the restart decision would use, not a stale total.
1408        let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
1409        let snapshot = guard.clone();
1410        drop(guard);
1411        let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
1412            SuperviseError::StatePoisoned {
1413                module_id: Some(self.inner.module_id.clone()),
1414            }
1415        })?;
1416        let registration_active = self
1417            .inner
1418            .registry
1419            .get_module(&self.inner.module_id)
1420            .map_err(SuperviseError::Registry)?
1421            .is_some();
1422        let protocol = snapshot
1423            .spawned_protocol
1424            .unwrap_or(self.declared_protocol()?);
1425        let running_process =
1426            snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
1427        // Registration is the difference between the two protocols and the only
1428        // one: a subc module that has not registered cannot serve a request even
1429        // though its process is up, and a `none` module never registers at all,
1430        // so requiring it there would pin `live` to false for the whole life of
1431        // a perfectly healthy process.
1432        let live = match protocol {
1433            ModuleProtocol::Subc => running_process && registration_active,
1434            ModuleProtocol::None => running_process,
1435        };
1436        // Read only the retained cache: a status read must not resend signals,
1437        // rewrite the record, or keep the containment resource alive.
1438        let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
1439        let carry_configured = self
1440            .inner
1441            .configuration
1442            .lock()
1443            .map_err(|_| SuperviseError::StatePoisoned {
1444                module_id: Some(self.inner.module_id.clone()),
1445            })?
1446            .spec
1447            .carry_containment;
1448        let recovery_block = carries_containment(
1449            carry_configured,
1450            self.inner
1451                .retained
1452                .has_carried_container(&self.inner.module_id),
1453        )
1454        .then(|| self.inner.retained.recovery_block())
1455        .flatten();
1456        let launch_nonce_source = observed_launch_nonce_source(&snapshot);
1457        let pid = snapshot.reported_pid();
1458        let mut health = snapshot.health;
1459        if let Some(detail) = recovery_block
1460            .as_ref()
1461            .or_else(|| retained.as_ref().map(|(_, detail)| detail))
1462        {
1463            health.detail = Some(match health.detail {
1464                Some(previous) => format!("{previous}; {detail}"),
1465                None => detail.clone(),
1466            });
1467        }
1468
1469        Ok((
1470            ModuleStatus {
1471                admission_refused: snapshot.admission_refused,
1472                #[cfg(windows)]
1473                nonce_pipe_refusal: snapshot.nonce_pipe_refusal,
1474                legacy_registration_spawn: snapshot.legacy_registration_spawn,
1475                registration_declaration: snapshot.registration_declaration.clone(),
1476                stop_reason: snapshot.stop_reason,
1477                waiting_for_previous_pid: retained
1478                    .as_ref()
1479                    .map(|(pid, _)| *pid)
1480                    .filter(|pid| *pid > 0)
1481                    .or(snapshot.waiting_for_previous_pid),
1482                waiting_for_previous_detail: recovery_block
1483                    .or_else(|| retained.map(|(_, detail)| detail))
1484                    .or(snapshot.waiting_for_previous_detail),
1485                module_id: self.inner.module_id.clone(),
1486                launch_nonce_source,
1487                state: snapshot.state,
1488                enabled: snapshot.enabled,
1489                process_alive: snapshot.process_alive,
1490                registration_active,
1491                protocol,
1492                live,
1493                restart_count,
1494                lifetime_restarts: snapshot.lifetime_restarts,
1495                spawn_generation: snapshot.spawn_generation,
1496                swap_outcome: snapshot.swap_outcome,
1497                max_restarts: restart_policy.max_restarts,
1498                restart_window: restart_policy.window,
1499                drain_timeout,
1500                restart_backoff: restart_policy.backoff,
1501                restart_max_backoff: restart_policy.max_backoff,
1502                pid,
1503                spawned_at_ms: snapshot.spawned_at_ms,
1504                spawned_from: snapshot.spawned_from,
1505                launch_spec_digest: snapshot.launch_spec_digest,
1506                process_start_time: snapshot.process_start_time,
1507                last_exit: snapshot.last_exit,
1508                health,
1509            },
1510            snapshot.spawned_file_identity.clone(),
1511        ))
1512    }
1513
1514    #[cfg(test)]
1515    pub(crate) fn hold_snapshot_for_test(
1516        &self,
1517        acquired: std::sync::mpsc::Sender<()>,
1518        hold: Duration,
1519    ) -> std::thread::JoinHandle<()> {
1520        let snapshot = Arc::clone(&self.inner.snapshot);
1521        std::thread::spawn(move || {
1522            let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
1523            acquired
1524                .send(())
1525                .expect("test receiver waits for snapshot lock");
1526            std::thread::sleep(hold);
1527        })
1528    }
1529
1530    /// The status and the running-image check for `supervisor.provenance`,
1531    /// taken from one status read. The exec acknowledgement can land between
1532    /// two separate reads, and the reply would then pair "no pid yet" with an
1533    /// image observed after the module started, which describes no single
1534    /// moment.
1535    pub(crate) async fn status_and_running_image_agreement(
1536        &self,
1537    ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
1538        let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
1539        let image = self
1540            .inner
1541            .provenance_probe
1542            .observe(
1543                status.pid,
1544                status.spawned_from.as_deref(),
1545                identity,
1546                status.process_start_time,
1547            )
1548            .await;
1549        Ok((status, image))
1550    }
1551
1552    pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
1553        let snapshot = match lock_snapshot(&self.inner.snapshot) {
1554            Ok(snapshot) => snapshot.clone(),
1555            Err(_) => {
1556                return subc_control::RunningImageAgreement::Unavailable {
1557                    reason: subc_control::RunningImageUnavailableReason::NotRunning,
1558                };
1559            }
1560        };
1561        self.inner
1562            .provenance_probe
1563            .observe(
1564                snapshot.reported_pid(),
1565                snapshot.spawned_from.as_deref(),
1566                snapshot.spawned_file_identity.clone(),
1567                snapshot.process_start_time,
1568            )
1569            .await
1570    }
1571
1572    /// Memory and CPU time of the module's current process, read now. Only the
1573    /// process the supervisor spawned is read, not processes it has started.
1574    pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
1575        #[cfg(windows)]
1576        {
1577            let image = lock_snapshot(&self.inner.snapshot)
1578                .ok()
1579                .and_then(|snapshot| {
1580                    snapshot
1581                        .spawned_file_identity
1582                        .as_ref()
1583                        .and_then(|identity| identity.windows_image.clone())
1584                });
1585            match image {
1586                Some(image) => {
1587                    crate::child_resources::read_windows_handle(image.process(), image.start_time())
1588                }
1589                None => subc_control::ChildResourceUsage::Unavailable {
1590                    reason: subc_control::ChildResourceUnavailableReason::NotRunning,
1591                },
1592            }
1593        }
1594        #[cfg(not(windows))]
1595        {
1596            let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
1597                Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
1598                Err(_) => {
1599                    return subc_control::ChildResourceUsage::Unavailable {
1600                        reason: subc_control::ChildResourceUnavailableReason::Unreadable,
1601                    }
1602                }
1603            };
1604            crate::child_resources::read(pid, start_time)
1605        }
1606    }
1607
1608    #[cfg(all(test, any(target_os = "linux", windows)))]
1609    pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
1610        self.inner
1611            .snapshot
1612            .try_lock()
1613            .map(|snapshot| snapshot.subtree_target.clone())
1614            .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
1615    }
1616
1617    #[cfg(test)]
1618    pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
1619        self.inner.snapshot.lock().unwrap().subtree_target = target;
1620    }
1621
1622    pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
1623        let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
1624        Ok(match snapshot.state {
1625            ModuleState::Restarting => true,
1626            ModuleState::Failed | ModuleState::Disabled => false,
1627            _ if snapshot.enabled && snapshot.respawn_pending => true,
1628            _ => daemon_will_restart(
1629                &mut snapshot,
1630                &self
1631                    .inner
1632                    .configuration
1633                    .lock()
1634                    .map_err(|_| SuperviseError::StatePoisoned {
1635                        module_id: Some(self.inner.module_id.clone()),
1636                    })?
1637                    .restart_policy,
1638                Instant::now(),
1639            ),
1640        })
1641    }
1642
1643    #[cfg(test)]
1644    pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
1645        self.is_warming_with_snapshot_lock(None)
1646    }
1647
1648    pub(crate) fn is_warming_for_control(
1649        &self,
1650        caller: &'static str,
1651    ) -> Result<bool, SuperviseError> {
1652        self.is_warming_with_snapshot_lock(Some(caller))
1653    }
1654
1655    fn is_warming_with_snapshot_lock(
1656        &self,
1657        caller: Option<&'static str>,
1658    ) -> Result<bool, SuperviseError> {
1659        let snapshot = match caller {
1660            Some(caller) => {
1661                lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
1662            }
1663            None => lock_snapshot(&self.inner.snapshot)?,
1664        }
1665        .clone();
1666        Ok(matches!(
1667            snapshot.state,
1668            ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
1669        ))
1670    }
1671
1672    /// The current process's protocol, or the configured protocol when down.
1673    /// A rescan stores the next launch spec without changing how an existing
1674    /// process registers, serves routes, is probed, or exits.
1675    pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
1676        let configured = self
1677            .inner
1678            .configuration
1679            .lock()
1680            .map_err(|_| SuperviseError::StatePoisoned {
1681                module_id: Some(self.inner.module_id.clone()),
1682            })?
1683            .spec
1684            .protocol;
1685        let state = lock_snapshot(&self.inner.snapshot)?;
1686        Ok(state.spawned_protocol.unwrap_or(configured))
1687    }
1688
1689    pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
1690        let configuration =
1691            self.inner
1692                .configuration
1693                .lock()
1694                .map_err(|_| SuperviseError::StatePoisoned {
1695                    module_id: Some(self.inner.module_id.clone()),
1696                })?;
1697        Ok((configuration.spec.clone(), configuration.health.clone()))
1698    }
1699
1700    pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
1701        self.inner
1702            .configuration
1703            .lock()
1704            .map(|configuration| configuration.register_timeout)
1705            .map_err(|_| SuperviseError::StatePoisoned {
1706                module_id: Some(self.inner.module_id.clone()),
1707            })
1708    }
1709
1710    pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
1711        self.inner
1712            .configuration
1713            .lock()
1714            .map(|configuration| configuration.enabled)
1715            .map_err(|_| SuperviseError::StatePoisoned {
1716                module_id: Some(self.inner.module_id.clone()),
1717            })
1718    }
1719
1720    /// Replace this module's launch spec, keeping its health and drain policy,
1721    /// the way a rescan does for a changed config entry. The running process is
1722    /// untouched; the next spawn (a restart, or a swap's candidate) uses it.
1723    #[cfg(any(test, feature = "test-support"))]
1724    pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
1725        let (_, health) = self.configuration()?;
1726        let drain_timeout_ms = u64::try_from(
1727            self.inner
1728                .effective_drain_timeout
1729                .lock()
1730                .unwrap_or_else(|poisoned| poisoned.into_inner())
1731                .as_millis(),
1732        )
1733        .ok();
1734        self.update_configuration(spec, health, drain_timeout_ms)
1735            .await
1736    }
1737
1738    pub(crate) async fn update_configuration(
1739        &self,
1740        spec: ModuleSpec,
1741        health: HealthConfig,
1742        drain_timeout_ms: Option<u64>,
1743    ) -> Result<(), SuperviseError> {
1744        if spec.module_id != self.inner.module_id {
1745            return Err(SuperviseError::InvalidSpec {
1746                reason: "a supervised module's module_id cannot be changed".to_string(),
1747            });
1748        }
1749        validate_spec(&spec)?;
1750        let (reply_tx, reply_rx) = oneshot::channel();
1751        self.inner
1752            .commands
1753            .send(SupervisorCommand::UpdateConfiguration {
1754                spec: spec.clone(),
1755                health: health.clone(),
1756                drain_timeout_ms,
1757                reply: reply_tx,
1758            })
1759            .await
1760            .map_err(|_| SuperviseError::CommandClosed {
1761                module_id: self.inner.module_id.clone(),
1762            })?;
1763        reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
1764            module_id: self.inner.module_id.clone(),
1765        })??;
1766        let mut configuration =
1767            self.inner
1768                .configuration
1769                .lock()
1770                .map_err(|_| SuperviseError::StatePoisoned {
1771                    module_id: Some(self.inner.module_id.clone()),
1772                })?;
1773        configuration.spec = spec;
1774        configuration.health = health;
1775        Ok(())
1776    }
1777}
1778
1779impl Drop for SupervisedModuleInner {
1780    fn drop(&mut self) {
1781        let Ok(mut monitor) = self.monitor.lock() else {
1782            return;
1783        };
1784        if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
1785            let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
1786                state.state = ModuleState::Stopped;
1787                clear_current_process_facts(state);
1788            });
1789            monitor.abort();
1790        }
1791        let _ = monitor.take();
1792    }
1793}
1794
1795/// Successful daemon-local swap disposition. Supersession leaves the incumbent
1796/// serving until an approved replacement starts with the latest configured
1797/// command; the legacy control acknowledgment does not carry this disposition.
1798#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1799pub enum SwapOutcome {
1800    Cutover,
1801    SupersededByConfigRestart,
1802}
1803
1804impl SwapOutcome {
1805    pub fn as_str(self) -> &'static str {
1806        match self {
1807            Self::Cutover => "cutover",
1808            Self::SupersededByConfigRestart => "superseded_by_config_restart",
1809        }
1810    }
1811}
1812
1813#[derive(Debug)]
1814pub enum SuperviseError {
1815    UpgradeInProgress,
1816    ConfigHeld {
1817        module_id: String,
1818        code: String,
1819        detail: String,
1820    },
1821    ConfigDeliveryDeferred {
1822        module_id: String,
1823    },
1824    InvalidSpec {
1825        reason: String,
1826    },
1827    Spawn {
1828        program: PathBuf,
1829        source: io::Error,
1830        cgroup_path: Option<PathBuf>,
1831    },
1832    Cgroup {
1833        module_id: String,
1834        source: io::Error,
1835    },
1836    /// The cryptographic random-number generator failed while generating a
1837    /// reserved module's launch nonce. Fail loud rather than spawn a reserved
1838    /// module without its identity binding.
1839    LaunchNonce {
1840        reason: String,
1841    },
1842    Wait {
1843        module_id: String,
1844        source: io::Error,
1845    },
1846    Kill {
1847        module_id: String,
1848        source: io::Error,
1849    },
1850    Forwarding(ForwardingError),
1851    Registry(RegistryError),
1852    ReloadUnavailable {
1853        module_id: String,
1854        reason: String,
1855    },
1856    /// An operator restart/reload was requested for a module that is currently
1857    /// disabled. Restart/reload cycle a *running* module; a disabled module must
1858    /// be explicitly re-enabled (set_enabled(true)) rather than silently started
1859    /// by a restart, so these commands are rejected instead of re-enabling it.
1860    Disabled {
1861        module_id: String,
1862    },
1863    ReloadFailed {
1864        module_id: String,
1865        reason: String,
1866    },
1867    RegistrationStillActive {
1868        module_id: String,
1869        waited: Duration,
1870    },
1871    StatePoisoned {
1872        module_id: Option<String>,
1873    },
1874    CommandClosed {
1875        module_id: String,
1876    },
1877    /// A restart or reload arrived while a swap's candidate was warming. The
1878    /// swap owns the module until it cuts over or fails; a stop or disable
1879    /// would have aborted it instead.
1880    SwapInProgress {
1881        module_id: String,
1882    },
1883    /// A swap was refused before anything was spawned.
1884    SwapRefused {
1885        module_id: String,
1886        reason: SwapRefusal,
1887    },
1888    /// A swap spawned a candidate and gave up on it. The candidate has been
1889    /// killed and its slot freed; the incumbent was left serving and was never
1890    /// drained, except in the one `CutoverLost` case described on that arm.
1891    SwapFailed {
1892        module_id: String,
1893        arm: SwapFailureArm,
1894        detail: String,
1895        /// How the candidate exited, when it exited on its own before the
1896        /// supervisor gave up on it.
1897        candidate_exit: Option<ExitReport>,
1898    },
1899}
1900
1901/// Why a swap was refused before a candidate was spawned.
1902#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1903pub enum SwapRefusal {
1904    /// The module's config does not declare `overlap: "safe"`.
1905    OverlapExclusive,
1906    /// The module is not registered, so there is no incumbent to keep serving
1907    /// and nothing a swap would improve on; a plain restart is the tool.
1908    NotRegistered,
1909    /// The module does not speak the subc wire, so a candidate could never
1910    /// register or declare itself ready.
1911    ProtocolNone,
1912    /// The supervisor lacks the forwarding table (to cut routes over) or the
1913    /// shared handle (to admit the candidate's HELLO) that a swap needs.
1914    NotConfigured,
1915    /// A swap is already open for this module.
1916    AlreadySwapping,
1917}
1918
1919impl SwapRefusal {
1920    pub fn as_str(self) -> &'static str {
1921        match self {
1922            Self::OverlapExclusive => "overlap_exclusive",
1923            Self::NotRegistered => "not_registered",
1924            Self::ProtocolNone => "protocol_none",
1925            Self::NotConfigured => "not_configured",
1926            Self::AlreadySwapping => "already_swapping",
1927        }
1928    }
1929}
1930
1931/// Which failure arm ended a swap. Every arm but one leaves the incumbent
1932/// serving and undrained; see `CutoverLost`.
1933#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1934pub enum SwapFailureArm {
1935    /// The candidate process could not be started.
1936    SpawnFailed,
1937    /// The candidate did not register within the readiness budget.
1938    NeverRegistered,
1939    /// The candidate registered but did not declare itself ready in time.
1940    NeverReady,
1941    /// The candidate exited before cutover.
1942    CandidateExited,
1943    /// The candidate declared itself ready but failed its health probe.
1944    CandidateUnhealthy,
1945    /// An operator stop, disable or retire arrived while the candidate warmed.
1946    /// The candidate was killed and the operator's command then carried out on
1947    /// the incumbent.
1948    Interrupted,
1949    /// The candidate's connection closed at the moment of cutover. If it
1950    /// closed before forwarding moved, the incumbent is untouched. If it closed
1951    /// between the forwarding and registry halves of cutover, forwarding can no
1952    /// longer route to the incumbent, so the module is restarted plainly.
1953    CutoverLost,
1954}
1955
1956impl SwapFailureArm {
1957    pub fn as_str(self) -> &'static str {
1958        match self {
1959            Self::SpawnFailed => "spawn_failed",
1960            Self::NeverRegistered => "never_registered",
1961            Self::NeverReady => "never_ready",
1962            Self::CandidateExited => "candidate_exited",
1963            Self::CandidateUnhealthy => "candidate_unhealthy",
1964            Self::Interrupted => "interrupted",
1965            Self::CutoverLost => "cutover_lost",
1966        }
1967    }
1968}
1969
1970impl SuperviseError {
1971    pub(crate) fn is_config_gate_error(&self) -> bool {
1972        match self {
1973            Self::ConfigHeld { .. } => true,
1974            Self::Spawn { source, .. } => source
1975                .get_ref()
1976                .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
1977            _ => false,
1978        }
1979    }
1980}
1981
1982impl fmt::Display for SuperviseError {
1983    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1984        match self {
1985            Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
1986            Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
1987            Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
1988            Self::Spawn {
1989                program,
1990                source,
1991                cgroup_path: Some(cgroup_path),
1992            } => write!(
1993                f,
1994                "failed to place module in cgroup '{}' while spawning '{}': {source}",
1995                cgroup_path.display(),
1996                program.display()
1997            ),
1998            Self::Spawn {
1999                program,
2000                source,
2001                cgroup_path: None,
2002            } => write!(
2003                f,
2004                "failed to spawn module '{}': {source}",
2005                program.display()
2006            ),
2007            Self::Cgroup { module_id, source } => {
2008                write!(
2009                    f,
2010                    "failed to prepare cgroup for module '{module_id}': {source}"
2011                )
2012            }
2013            Self::LaunchNonce { reason } => {
2014                write!(
2015                    f,
2016                    "failed to generate reserved-module launch nonce: {reason}"
2017                )
2018            }
2019            Self::Wait { module_id, source } => {
2020                write!(f, "failed to wait for module '{module_id}': {source}")
2021            }
2022            Self::Kill { module_id, source } => {
2023                write!(f, "failed to kill module '{module_id}': {source}")
2024            }
2025            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
2026            Self::Registry(err) => write!(f, "registry error: {err}"),
2027            Self::ReloadUnavailable { module_id, reason } => {
2028                write!(f, "reload unavailable for module '{module_id}': {reason}")
2029            }
2030            Self::Disabled { module_id } => {
2031                write!(
2032                    f,
2033                    "module '{module_id}' is disabled; enable it before restart or reload"
2034                )
2035            }
2036            Self::ReloadFailed { module_id, reason } => {
2037                write!(f, "reload failed for module '{module_id}': {reason}")
2038            }
2039            Self::RegistrationStillActive { module_id, waited } => write!(
2040                f,
2041                "module '{module_id}' registration remained active after waiting {waited:?}"
2042            ),
2043            Self::StatePoisoned { module_id } => match module_id {
2044                Some(module_id) => {
2045                    write!(f, "supervisor state for module '{module_id}' was poisoned")
2046                }
2047                None => write!(f, "supervisor state was poisoned"),
2048            },
2049            Self::CommandClosed { module_id } => {
2050                write!(
2051                    f,
2052                    "supervisor command channel for module '{module_id}' is closed"
2053                )
2054            }
2055            Self::UpgradeInProgress => f.write_str("daemon upgrade is in progress"),
2056            Self::SwapInProgress { module_id } => write!(
2057                f,
2058                "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
2059            ),
2060            Self::SwapRefused { module_id, reason } => match reason {
2061                SwapRefusal::OverlapExclusive => write!(
2062                    f,
2063                    "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"
2064                ),
2065                SwapRefusal::NotRegistered => write!(
2066                    f,
2067                    "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
2068                ),
2069                SwapRefusal::ProtocolNone => write!(
2070                    f,
2071                    "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
2072                ),
2073                SwapRefusal::NotConfigured => write!(
2074                    f,
2075                    "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
2076                ),
2077                SwapRefusal::AlreadySwapping => {
2078                    write!(f, "module '{module_id}' is already being swapped")
2079                }
2080            },
2081            Self::SwapFailed {
2082                module_id,
2083                arm,
2084                detail,
2085                ..
2086            } => write!(
2087                f,
2088                "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
2089                arm.as_str()
2090            ),
2091        }
2092    }
2093}
2094
2095impl Error for SuperviseError {
2096    fn source(&self) -> Option<&(dyn Error + 'static)> {
2097        match self {
2098            Self::Spawn { source, .. }
2099            | Self::Cgroup { source, .. }
2100            | Self::Wait { source, .. }
2101            | Self::Kill { source, .. } => Some(source),
2102            Self::Forwarding(err) => Some(err),
2103            Self::Registry(err) => Some(err),
2104            Self::LaunchNonce { .. }
2105            | Self::ConfigDeliveryDeferred { .. }
2106            | Self::ConfigHeld { .. }
2107            | Self::InvalidSpec { .. }
2108            | Self::ReloadUnavailable { .. }
2109            | Self::Disabled { .. }
2110            | Self::ReloadFailed { .. }
2111            | Self::RegistrationStillActive { .. }
2112            | Self::StatePoisoned { .. }
2113            | Self::CommandClosed { .. }
2114            | Self::SwapInProgress { .. }
2115            | Self::UpgradeInProgress
2116            | Self::SwapRefused { .. }
2117            | Self::SwapFailed { .. } => None,
2118        }
2119    }
2120}
2121
2122fn unix_ms_now() -> u64 {
2123    SystemTime::now()
2124        .duration_since(UNIX_EPOCH)
2125        .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
2126        .unwrap_or(0)
2127}
2128
2129fn update_snapshot(
2130    snapshot: &SharedSnapshot,
2131    module_id: Option<&str>,
2132    update: impl FnOnce(&mut SupervisorSnapshot),
2133) -> Result<(), SuperviseError> {
2134    let mut state = lock_snapshot(snapshot).map_err(|_| SuperviseError::StatePoisoned {
2135        module_id: module_id.map(ToOwned::to_owned),
2136    })?;
2137    update(&mut state);
2138    Ok(())
2139}
2140
2141const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
2142
2143fn lock_snapshot_for_control<'a>(
2144    snapshot: &'a SharedSnapshot,
2145    module_id: &str,
2146    caller: &'static str,
2147) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
2148    let started_at = Instant::now();
2149    let guard = lock_snapshot(snapshot)?;
2150    let waited = started_at.elapsed();
2151    if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
2152        warn!(
2153            module_id = %module_id,
2154            waited_ms = waited.as_millis() as u64,
2155            caller = %caller,
2156            "slow snapshot lock"
2157        );
2158    }
2159    Ok(guard)
2160}
2161
2162fn lock_snapshot(
2163    snapshot: &SharedSnapshot,
2164) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
2165    let guard = match snapshot.try_lock() {
2166        Ok(guard) => return Ok(guard),
2167        Err(TryLockError::Poisoned(guard)) => Err(guard),
2168        Err(TryLockError::WouldBlock) => {
2169            // A held launch record must not pin a daemon worker: that worker
2170            // may also have to route and deliver the busy reply to a module.
2171            if tokio::runtime::Handle::try_current().is_ok_and(|handle| {
2172                handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
2173            }) {
2174                tokio::task::block_in_place(|| snapshot.lock())
2175            } else {
2176                snapshot.lock()
2177            }
2178        }
2179    };
2180    guard.map_err(|_| SuperviseError::StatePoisoned { module_id: None })
2181}
2182
2183#[cfg(all(test, unix))]
2184mod restart_ordering_tests;
2185
2186#[cfg(all(test, target_os = "macos"))]
2187#[path = "supervise/suspended_spawn_tests.rs"]
2188mod suspended_spawn_tests;
2189
2190#[cfg(all(test, target_os = "linux"))]
2191#[path = "supervise/cgroup_reap_tests.rs"]
2192mod cgroup_reap_tests;
2193
2194#[cfg(test)]
2195#[path = "supervise/supervise_tests.rs"]
2196mod tests;
2197
2198#[cfg(test)]
2199#[path = "supervise/spawn_record_tests.rs"]
2200mod spawn_record_tests;
2201
2202#[cfg(all(test, target_os = "linux"))]
2203#[path = "supervise/spawn_image_tests.rs"]
2204mod spawn_image_tests;
2205
2206#[cfg(test)]
2207#[path = "supervise/slot_registration_wait_tests.rs"]
2208mod slot_registration_wait_tests;
2209
2210#[cfg(test)]
2211#[path = "supervise/terminal_history_tests.rs"]
2212mod terminal_history_tests;
2213
2214#[cfg(all(test, unix))]
2215#[path = "supervise/health_event_tests.rs"]
2216mod health_event_tests;
2217
2218#[cfg(test)]
2219#[path = "supervise/drain_busy_reprobe_tests.rs"]
2220mod drain_busy_reprobe_tests;
2221
2222#[cfg(test)]
2223#[path = "supervise/health_evidence_tests.rs"]
2224mod health_evidence_tests;
2225
2226#[cfg(test)]
2227#[path = "supervise/health_tombstone_tests.rs"]
2228mod health_tombstone_tests;
2229
2230#[cfg(test)]
2231#[path = "supervise/child_env_tests.rs"]
2232mod child_env_tests;
2233
2234#[cfg(test)]
2235#[path = "supervise/jitter_tests.rs"]
2236mod jitter_tests;
2237
2238#[cfg(all(test, target_os = "linux"))]
2239#[path = "supervise/cgroup_placement_tests.rs"]
2240mod cgroup_placement_tests;
2241
2242#[cfg(test)]
2243#[path = "supervise/spawn_subscriber_lag_tests.rs"]
2244mod spawn_subscriber_lag_tests;
2245
2246#[cfg(test)]
2247#[path = "supervise/terminal_history_read_concurrency_tests.rs"]
2248mod terminal_history_read_concurrency_tests;
2249
2250/// What a restart does with the exited process's output readers. These drive
2251/// the same settle functions the supervisor calls, with a reader the test
2252/// holds, so a reader that has not been scheduled by the bound is a controlled
2253/// input rather than something only a loaded machine produces.
2254#[cfg(test)]
2255#[path = "supervise/stderr_settle_tests.rs"]
2256mod stderr_settle_tests;
2257
2258/// Containment of a module's process tree.
2259///
2260/// The behaviour these defend against is a module helper surviving its module:
2261/// on a real machine the Synapse embedding module's CUDA worker holds ~2.2 GB of
2262/// VRAM, so a leaked grandchild is a leaked GPU allocation, and a day of restarts
2263/// compounds it.
2264///
2265/// They run against the SUPERVISOR rather than the job-object crate because the
2266/// claim is about teardown: a crate-level test proves a job can reap a tree, not
2267/// that the daemon's drain path reaches it.
2268///
2269/// Windows-only, like the mechanism. On Unix this arm compiles out; the cgroup
2270/// lane there is a separate containment path with its own tests.
2271#[cfg(all(test, windows))]
2272#[path = "supervise/job_containment_tests.rs"]
2273mod job_containment_tests;
2274
2275#[cfg(test)]
2276#[path = "supervise/privacy_trampoline_configuration_tests.rs"]
2277mod privacy_trampoline_configuration_tests;
2278
2279#[cfg(test)]
2280#[path = "supervise/privacy_exec_boundary_tests.rs"]
2281mod privacy_exec_boundary_tests;
2282
2283/// The daemon's real spawn path hands a subc-wire child its launch nonce on
2284/// descriptor 3, without an environment copy. The shell records the nonce
2285/// and its environment after exec so these tests observe the real handover.
2286#[cfg(all(test, unix))]
2287#[path = "supervise/launch_nonce_descriptor_tests.rs"]
2288mod launch_nonce_descriptor_tests;
2289
2290#[cfg(all(test, target_os = "linux"))]
2291#[path = "supervise/cgroup_containment_tests.rs"]
2292mod cgroup_containment_tests;
2293
2294/// A slow live-children record write on the restart path must not stop the
2295/// daemon from answering the replacement module's authentication handshake.
2296#[cfg(all(test, unix))]
2297#[path = "supervise/record_write_stall_tests.rs"]
2298mod record_write_stall_tests;
2299
2300#[cfg(all(test, unix))]
2301#[path = "supervise/retained_status_tests.rs"]
2302mod retained_status_tests;