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