Skip to main content

subc_daemon/
supervise.rs

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