Skip to main content

subc_daemon/supervise/
health_probe.rs

1use super::*;
2
3const DEFAULT_HEALTH_CADENCE: Duration = Duration::from_secs(30);
4const DEFAULT_HEALTH_DEADLINE: Duration = Duration::from_secs(5);
5const DEFAULT_HEALTH_FAILURE_THRESHOLD: u32 = 3;
6const MAX_HEALTH_METRICS_BYTES: usize = 16 * 1024;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum HealthAction {
10    Report,
11    Restart,
12    Alert,
13}
14
15impl fmt::Display for HealthAction {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        f.write_str(match self {
18            Self::Report => "report",
19            Self::Restart => "restart",
20            Self::Alert => "alert",
21        })
22    }
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct HealthConfig {
27    /// Optional loopback HTTP endpoint for a managed non-wire process.
28    /// Changing it applies live on rescan; the process protocol changes only
29    /// at its next spawn.
30    pub http: Option<String>,
31    pub cadence: Duration,
32    pub deadline: Duration,
33    pub failure_threshold: u32,
34    pub on_degraded: HealthAction,
35    pub on_failing: HealthAction,
36    pub critical: bool,
37}
38
39impl Default for HealthConfig {
40    fn default() -> Self {
41        Self {
42            http: None,
43            cadence: DEFAULT_HEALTH_CADENCE,
44            deadline: DEFAULT_HEALTH_DEADLINE,
45            failure_threshold: DEFAULT_HEALTH_FAILURE_THRESHOLD,
46            on_degraded: HealthAction::Report,
47            on_failing: HealthAction::Report,
48            critical: false,
49        }
50    }
51}
52
53/// The supervisor's view of one module's health, relayed to clients over
54/// channel-0 and rendered by `ck health`.
55///
56/// THIS TYPE IS WHERE THE ABSENCE MEANINGS ARE CREATED, which is why they are
57/// stated here rather than only at the wire type a consumer reads. A reader can
58/// look up what `None` means; only a writer can silently change it, and the
59/// writer has no reason to go looking at a downstream contract before editing.
60///
61/// `last_probe_ms: None` MEANS NEVER PROBED, not probed-long-ago. It is cleared
62/// back to `None` on re-registration precisely so a respawned module does not
63/// carry its predecessor's timestamp — so an old value and an absent one call for
64/// opposite readings, and anything that defaulted this to a number would make a
65/// never-probed module indistinguishable from one probed at the epoch.
66///
67/// `detail` and `metrics` are `None` when the module published none on this
68/// probe, which does not mean it reported nothing wrong — it is also the shape
69/// when the probe never reached it. `last_probe_ms` is what separates those.
70///
71/// `summary` is `None` when the latest answer carried none, when it broke the
72/// summary rule and was dropped, or when no answer has arrived since the last
73/// failed probe or spawn.
74#[derive(Debug, Clone, PartialEq)]
75pub struct ModuleHealthStatus {
76    pub status: SupervisorHealthStatus,
77    pub last_probe_ms: Option<u64>,
78    pub detail: Option<String>,
79    /// The module's plain sentence for a person, already checked against
80    /// the summary rule in `crate::health_summary`.
81    pub summary: Option<String>,
82    pub metrics: Option<Value>,
83    pub consecutive_failures: u32,
84    /// Number of replies received after a recurring health probe's deadline.
85    /// Unlike a timeout, every increment proves the module was alive.
86    pub late_answer_count: u64,
87    /// End-to-end latency of the newest late reply, measured from probe start.
88    pub last_late_answer_latency_ms: Option<u64>,
89    pub last_action: Option<String>,
90    /// Set together with `last_action`; the pair moves as one, and both being
91    /// absent means no escalation has ever been taken rather than that the last
92    /// one succeeded.
93    pub last_action_ms: Option<u64>,
94}
95
96impl Default for ModuleHealthStatus {
97    fn default() -> Self {
98        Self {
99            status: SupervisorHealthStatus::Unknown,
100            last_probe_ms: None,
101            detail: None,
102            summary: None,
103            metrics: None,
104            consecutive_failures: 0,
105            late_answer_count: 0,
106            last_late_answer_latency_ms: None,
107            last_action: None,
108            last_action_ms: None,
109        }
110    }
111}
112
113impl SupervisorHandle {
114    pub(crate) fn record_late_health_answer(
115        &self,
116        module_id: &str,
117        latency_ms: u64,
118    ) -> Result<bool, SuperviseError> {
119        let Some(module) = self.get(module_id) else {
120            return Ok(false);
121        };
122        self.host_health.record_late_module(module_id);
123        update_snapshot(&module.inner.snapshot, Some(module_id), |state| {
124            state.health.late_answer_count = state.health.late_answer_count.saturating_add(1);
125            state.health.last_late_answer_latency_ms = Some(latency_ms);
126            // A late answer is an answer: the module served the probe, just past
127            // the deadline. Leaving the miss streak in place while logging
128            // "proves the module is alive" is how a CPU-starved module that
129            // answers every probe a few seconds late still marches to the
130            // threshold and gets killed — the exact kill class `NoAnswer` is
131            // excluded from `is_proof_of_death` to prevent. Slow-but-answering
132            // is degradation, and degradation reports; it does not restart.
133            state.health.consecutive_failures = 0;
134        })?;
135        Ok(true)
136    }
137
138    pub(crate) fn spawn_host_health_monitor(&self) -> JoinHandle<()> {
139        self.host_health.spawn_monitor()
140    }
141}
142
143impl SupervisedModule {
144    /// Test-only: put one probe miss on the streak, the way
145    /// `handle_health_probe_failure` does, so tests can assert what a later
146    /// event does to the streak without driving the whole probe loop.
147    #[cfg(test)]
148    pub(crate) fn record_health_probe_failure_for_test(
149        &self,
150        detail: &str,
151    ) -> Result<(), SuperviseError> {
152        update_snapshot(&self.inner.snapshot, Some(&self.inner.module_id), |state| {
153            state.health.consecutive_failures = state.health.consecutive_failures.saturating_add(1);
154            state.health.detail = Some(detail.to_string());
155        })
156    }
157}
158
159#[derive(Debug, Default)]
160pub(super) struct HealthProbeRuntime {
161    spawn_generation: Option<u64>,
162    configured_health: Option<HealthConfig>,
163    pub(super) registered_connection: Option<crate::ConnectionId>,
164    pub(super) advertised: bool,
165    pub(super) next_probe_at: Option<Instant>,
166    probe_index: u64,
167}
168
169pub(super) fn running_protocol(spec: &ModuleSpec, snapshot: &SharedSnapshot) -> ModuleProtocol {
170    lock_snapshot(snapshot)
171        .ok()
172        .and_then(|state| state.spawned_protocol)
173        .unwrap_or(spec.protocol)
174}
175
176impl HealthProbeRuntime {
177    pub(super) fn refresh_registration(
178        &mut self,
179        spec: &ModuleSpec,
180        runtime: &SupervisorRuntimeConfig,
181        registry: &Registry,
182        snapshot: &SharedSnapshot,
183    ) {
184        let generation = lock_snapshot(snapshot)
185            .ok()
186            .map(|state| state.spawn_generation);
187        if self.spawn_generation != generation {
188            // A replacement cannot reuse a deadline that is already due for its
189            // predecessor. HTTP children get a full cadence to start; wire
190            // children still wait for their own health-advertising HELLO.
191            *self = Self {
192                spawn_generation: generation,
193                ..Self::default()
194            };
195        }
196        if self.configured_health.as_ref() != Some(&runtime.health) {
197            self.configured_health = Some(runtime.health.clone());
198            self.next_probe_at = None;
199            self.registered_connection = None;
200            self.probe_index = 0;
201        }
202        // A non-wire process never registers. Only an explicitly configured
203        // HTTP endpoint can arm its health probe; an absent HELLO is not a
204        // health failure for that kind of process.
205        if running_protocol(spec, snapshot) == ModuleProtocol::None {
206            self.registered_connection = None;
207            self.advertised = runtime.health.http.is_some();
208            if !self.advertised {
209                self.next_probe_at = None;
210                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
211                    let unknown = ModuleHealthStatus::default();
212                    if state.health != unknown {
213                        state.health = unknown;
214                        state.last_probe_evidence = None;
215                    }
216                });
217            } else if self.next_probe_at.is_none() {
218                self.next_probe_at = Some(
219                    Instant::now()
220                        + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
221                );
222            }
223            return;
224        }
225
226        let registration = match registry.get_module(&spec.module_id) {
227            Ok(registration) => registration,
228            Err(err) => {
229                warn!(module_id = %spec.module_id, error = %err, "health prober could not read registry");
230                self.advertised = false;
231                self.next_probe_at = None;
232                return;
233            }
234        };
235
236        let Some(registration) = registration else {
237            self.registered_connection = None;
238            self.advertised = false;
239            self.next_probe_at = None;
240            return;
241        };
242
243        let advertised = registration
244            .control_ops
245            .iter()
246            .any(|op| op == MODULE_CONTROL_OP_HEALTH_CHECK);
247        if !advertised {
248            self.registered_connection = Some(registration.connection_id);
249            self.advertised = false;
250            self.next_probe_at = None;
251            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
252                if state.health.status != SupervisorHealthStatus::Unknown
253                    || state.health.consecutive_failures != 0
254                    || state.health.last_probe_ms.is_some()
255                    || state.health.detail.is_some()
256                    || state.health.summary.is_some()
257                    || state.health.metrics.is_some()
258                {
259                    state.health.status = SupervisorHealthStatus::Unknown;
260                    state.last_probe_evidence = None;
261                    state.health.consecutive_failures = 0;
262                    state.health.last_probe_ms = None;
263                    state.health.detail = None;
264                    state.health.summary = None;
265                    state.health.metrics = None;
266                }
267            });
268            return;
269        }
270
271        let reregistered = self.registered_connection != Some(registration.connection_id);
272        self.registered_connection = Some(registration.connection_id);
273        self.advertised = true;
274        if reregistered || self.next_probe_at.is_none() {
275            self.probe_index = 0;
276            self.next_probe_at = Some(
277                Instant::now() + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
278            );
279            let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
280                state.health.status = SupervisorHealthStatus::Unknown;
281                state.last_probe_evidence = None;
282                state.health.consecutive_failures = 0;
283                state.health.detail = None;
284                state.health.summary = None;
285                state.health.metrics = None;
286            });
287        }
288    }
289
290    pub(super) fn wake_at(&self) -> Option<Instant> {
291        if !self.advertised {
292            return None;
293        }
294        self.next_probe_at
295    }
296
297    pub(super) fn due(&self) -> bool {
298        self.advertised
299            && self
300                .next_probe_at
301                .is_some_and(|next| Instant::now() >= next)
302    }
303
304    pub(super) fn schedule_next(&mut self, spec: &ModuleSpec, cadence: Duration) {
305        self.probe_index = self.probe_index.wrapping_add(1);
306        self.next_probe_at = Some(
307            Instant::now() + jittered_health_delay(&spec.module_id, self.probe_index, cadence),
308        );
309    }
310}
311
312/// Evidence is separate from diagnostic prose so host starvation can hold only
313/// silence-based restarts. A missing lane is still actionable during overload;
314/// a timeout can instead mean the host has not scheduled a healthy module.
315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
316pub(super) enum HealthProbeEvidence {
317    /// The module's control lane is gone. Proof of death.
318    LaneDead,
319    /// No reply within the deadline. Proves nothing about the module's state.
320    NoAnswer,
321    /// The module replied, but not with a usable health report. Proves it is alive.
322    BadAnswer,
323    /// The daemon could not ask. Says nothing about the module.
324    Misconfigured,
325}
326
327#[derive(Debug)]
328pub(super) struct HealthProbeError {
329    pub(super) evidence: HealthProbeEvidence,
330    message: String,
331}
332
333impl HealthProbeError {
334    pub(super) fn lane_dead(message: impl Into<String>) -> Self {
335        Self::with(HealthProbeEvidence::LaneDead, message)
336    }
337
338    pub(super) fn no_answer(message: impl Into<String>) -> Self {
339        Self::with(HealthProbeEvidence::NoAnswer, message)
340    }
341
342    pub(super) fn bad_answer(message: impl Into<String>) -> Self {
343        Self::with(HealthProbeEvidence::BadAnswer, message)
344    }
345
346    pub(super) fn misconfigured(message: impl Into<String>) -> Self {
347        Self::with(HealthProbeEvidence::Misconfigured, message)
348    }
349
350    fn with(evidence: HealthProbeEvidence, message: impl Into<String>) -> Self {
351        Self {
352            evidence,
353            message: message.into(),
354        }
355    }
356
357    /// Whether this observation is proof the module cannot serve.
358    ///
359    /// Only `LaneDead` qualifies. `NoAnswer` is deliberately excluded: it is the
360    /// variant that fires under CPU starvation, and treating it as proof is the
361    /// defect this enum exists to make impossible to reintroduce silently.
362    ///
363    /// Outside a host-overload hold, silence still reaches the normal failure
364    /// threshold so an isolated, genuinely wedged module can recover.
365    #[allow(dead_code)]
366    pub(super) fn is_proof_of_death(&self) -> bool {
367        matches!(self.evidence, HealthProbeEvidence::LaneDead)
368    }
369
370    /// Short stable label for logs and the health snapshot.
371    ///
372    /// An operator reading `ck health` currently cannot tell "the module is gone"
373    /// from "the module did not answer in five seconds", because both render as
374    /// prose in the same field. These labels are what make the two
375    /// distinguishable at a glance, and they are what a later restart-policy
376    /// change will be argued from.
377    pub(super) fn label(&self) -> &'static str {
378        match self.evidence {
379            HealthProbeEvidence::LaneDead => "lane-dead",
380            HealthProbeEvidence::NoAnswer => "no-answer",
381            HealthProbeEvidence::BadAnswer => "bad-answer",
382            HealthProbeEvidence::Misconfigured => "daemon-misconfigured",
383        }
384    }
385}
386
387impl fmt::Display for HealthProbeError {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        f.write_str(&self.message)
390    }
391}
392
393pub(super) async fn run_health_probe_cycle(
394    spec: &ModuleSpec,
395    runtime: &SupervisorRuntimeConfig,
396    registry: &Registry,
397    process_liveness: &SupervisorProcessLiveness,
398    snapshot: &SharedSnapshot,
399    child: &mut Option<SupervisedChild>,
400) {
401    let now_ms = unix_ms_now();
402    let delivery_probe = match &runtime.config_delivery {
403        Some(delivery) => {
404            delivery
405                .health_probe(&spec.module_id, runtime.forwarding.as_deref(), registry)
406                .await
407        }
408        None => None,
409    };
410    let http = (running_protocol(spec, snapshot) == ModuleProtocol::None)
411        .then_some(runtime.health.http.as_deref())
412        .flatten();
413    let result = match http {
414        Some(url) => probe_http_health(url, runtime.health.deadline)
415            .await
416            .map(|report| (report, None)),
417        None => probe_module_health_from(&spec.module_id, runtime, None)
418            .await
419            .map(|(report, probed)| (report, Some(probed))),
420    };
421    match result {
422        Ok((report, probed)) => {
423            handle_health_report(
424                spec,
425                runtime,
426                registry,
427                process_liveness,
428                snapshot,
429                child,
430                report,
431                now_ms,
432                delivery_probe,
433                probed,
434            )
435            .await;
436        }
437        Err(err) => {
438            if http.is_some() {
439                let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
440                    state.health.status = SupervisorHealthStatus::Failing;
441                });
442            }
443            handle_health_probe_failure(
444                spec,
445                runtime,
446                registry,
447                process_liveness,
448                snapshot,
449                child,
450                err,
451                now_ms,
452                delivery_probe,
453            )
454            .await;
455        }
456    }
457}
458
459pub(crate) struct HttpProbeTarget<'a> {
460    address: std::net::SocketAddr,
461    localhost: bool,
462    authority: &'a str,
463    path: String,
464}
465
466/// Resolve only literal loopback endpoints, without DNS, redirects, proxies,
467/// or TLS. A URL cannot turn a local health check into an outbound connection.
468pub(crate) fn parse_http_probe_url(url: &str) -> Result<HttpProbeTarget<'_>, String> {
469    if url.bytes().any(|b| b <= b' ' || b == 127) || url.contains('#') {
470        return Err("must not contain whitespace, controls, or a fragment".into());
471    }
472    let rest = url
473        .strip_prefix("http://")
474        .ok_or("must use plain http://")?;
475    let split = rest.find(['/', '?']).unwrap_or(rest.len());
476    let (authority, suffix) = rest.split_at(split);
477    let (host, port) = if let Some(rest) = authority.strip_prefix("[::1]") {
478        ("::1", rest)
479    } else {
480        let split = authority.find(':').unwrap_or(authority.len());
481        authority.split_at(split)
482    };
483    let ip: std::net::IpAddr = match host {
484        "127.0.0.1" | "localhost" => std::net::Ipv4Addr::LOCALHOST.into(),
485        "::1" => std::net::Ipv6Addr::LOCALHOST.into(),
486        _ => return Err("host must be 127.0.0.1, [::1], or localhost".into()),
487    };
488    let port = if port.is_empty() {
489        80
490    } else {
491        port.strip_prefix(':')
492            .and_then(|p| p.parse::<u16>().ok())
493            .filter(|p| *p > 0)
494            .ok_or("must have a valid nonzero TCP port")?
495    };
496    let path = if suffix.is_empty() {
497        "/".into()
498    } else if suffix.starts_with('?') {
499        format!("/{suffix}")
500    } else {
501        suffix.into()
502    };
503    Ok(HttpProbeTarget {
504        address: std::net::SocketAddr::new(ip, port),
505        localhost: host == "localhost",
506        authority,
507        path,
508    })
509}
510
511pub(super) async fn probe_http_health(
512    url: &str,
513    deadline: Duration,
514) -> Result<HealthReport, HealthProbeError> {
515    use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
516    let target = parse_http_probe_url(url).map_err(HealthProbeError::misconfigured)?;
517    // Keep partial diagnostics outside the timed future so cancellation does
518    // not discard a status line or body bytes already received.
519    let mut response_status = String::new();
520    let mut body = Vec::new();
521    let probe = async {
522        // Resolve localhost ourselves so a hosts-file override cannot turn
523        // this into an outbound request, while IPv6-only local servers work.
524        let connection = match tokio::net::TcpStream::connect(target.address).await {
525            Err(_) if target.localhost => {
526                tokio::net::TcpStream::connect((
527                    std::net::Ipv6Addr::LOCALHOST,
528                    target.address.port(),
529                ))
530                .await
531            }
532            result => result,
533        };
534        let mut stream = connection.map_err(|error| {
535            HealthProbeError::no_answer(format!("HTTP connect failed: {error}"))
536        })?;
537        stream.write_all(format!("GET {} HTTP/1.1\r\nHost: {}\r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n", target.path, target.authority).as_bytes()).await
538            .map_err(|error| HealthProbeError::no_answer(format!("HTTP write failed: {error}")))?;
539        let mut reader = BufReader::new(stream);
540        let mut budget = 16 * 1024;
541        let status = http_line(&mut reader, &mut budget).await?;
542        let mut words = status.split_ascii_whitespace();
543        let version = words.next();
544        let code = words
545            .next()
546            .filter(|word| word.len() == 3)
547            .and_then(|word| word.parse::<u16>().ok());
548        if !matches!(version, Some("HTTP/1.1" | "HTTP/1.0"))
549            || !code.is_some_and(|code| (100..600).contains(&code))
550        {
551            return Err(HealthProbeError::bad_answer(format!(
552                "invalid HTTP status: {status}"
553            )));
554        }
555        let code = code.expect("validated status code");
556        response_status = status.clone();
557        let mut length = None;
558        let mut chunked = false;
559        loop {
560            let line = http_line(&mut reader, &mut budget).await?;
561            if line.is_empty() {
562                break;
563            }
564            if let Some((name, value)) = line.split_once(':') {
565                if name.eq_ignore_ascii_case("content-length") {
566                    length = Some(value.trim().parse::<u64>().map_err(|_| {
567                        HealthProbeError::bad_answer("invalid HTTP Content-Length")
568                    })?);
569                } else if name.eq_ignore_ascii_case("transfer-encoding") {
570                    chunked = value.trim().eq_ignore_ascii_case("chunked");
571                }
572            }
573        }
574        if chunked {
575            while body.len() < 200 {
576                let line = http_line(&mut reader, &mut budget).await?;
577                let size = u64::from_str_radix(line.split(';').next().unwrap_or("").trim(), 16)
578                    .map_err(|_| HealthProbeError::bad_answer("invalid HTTP chunk size"))?;
579                if size == 0 {
580                    break;
581                }
582                let count = size.min((200 - body.len()) as u64) as usize;
583                let start = body.len();
584                (&mut reader)
585                    .take(count as u64)
586                    .read_to_end(&mut body)
587                    .await
588                    .map_err(|error| {
589                        HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
590                    })?;
591                if body.len() - start != count {
592                    return Err(HealthProbeError::bad_answer("truncated HTTP chunk"));
593                }
594                if size > count as u64 || body.len() == 200 {
595                    break;
596                }
597                if !http_line(&mut reader, &mut budget).await?.is_empty() {
598                    return Err(HealthProbeError::bad_answer("invalid HTTP chunk delimiter"));
599                }
600            }
601        } else {
602            reader
603                .take(length.unwrap_or(200).min(200))
604                .read_to_end(&mut body)
605                .await
606                .map_err(|error| {
607                    HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
608                })?;
609        }
610        if (200..300).contains(&code) {
611            Ok(HealthReport::ok())
612        } else {
613            Err(HealthProbeError::bad_answer(
614                "HTTP health endpoint returned non-2xx",
615            ))
616        }
617    };
618    let mut result = timeout(deadline, probe).await.unwrap_or_else(|_| {
619        Err(HealthProbeError::no_answer(format!(
620            "HTTP probe timed out after {deadline:?}"
621        )))
622    });
623    if let Err(error) = &mut result {
624        if !response_status.is_empty() {
625            error.message = format!(
626                "{}; {response_status}: {}",
627                error.message,
628                String::from_utf8_lossy(&body)
629            );
630        }
631    }
632    result
633}
634
635async fn http_line(
636    reader: &mut tokio::io::BufReader<tokio::net::TcpStream>,
637    remaining: &mut usize,
638) -> Result<String, HealthProbeError> {
639    use tokio::io::{AsyncBufReadExt, AsyncReadExt};
640    let mut line = Vec::new();
641    (&mut *reader)
642        .take(*remaining as u64)
643        .read_until(b'\n', &mut line)
644        .await
645        .map_err(|error| {
646            HealthProbeError::no_answer(format!("HTTP header read failed: {error}"))
647        })?;
648    *remaining -= line.len();
649    if !line.ends_with(b"\r\n") {
650        return Err(HealthProbeError::bad_answer(
651            "HTTP headers are incomplete or exceed 16 KiB",
652        ));
653    }
654    line.truncate(line.len() - 2);
655    String::from_utf8(line).map_err(|_| HealthProbeError::bad_answer("HTTP header is not UTF-8"))
656}
657
658pub(super) async fn probe_module_health(
659    module_id: &str,
660    runtime: &SupervisorRuntimeConfig,
661    drain_deadline: Option<Instant>,
662) -> Result<HealthReport, HealthProbeError> {
663    probe_module_health_from(module_id, runtime, drain_deadline)
664        .await
665        .map(|(report, _)| report)
666}
667
668/// [`probe_module_health`], also returning the connection whose registration
669/// answered, so its answer is credited to that registration and no other.
670async fn probe_module_health_from(
671    module_id: &str,
672    runtime: &SupervisorRuntimeConfig,
673    drain_deadline: Option<Instant>,
674) -> Result<(HealthReport, ConnectionId), HealthProbeError> {
675    let Some(forwarding) = runtime.forwarding.as_ref() else {
676        return Err(HealthProbeError::misconfigured(
677            "supervisor was not configured with a forwarding table",
678        ));
679    };
680    let probe_started_at = Instant::now();
681    let mut deadline = probe_started_at + runtime.health.deadline;
682    if let Some(drain_deadline) = drain_deadline {
683        deadline = deadline.min(drain_deadline);
684    }
685    let pending = if drain_deadline.is_some() {
686        forwarding.begin_drain_health_probe_rpc_for(
687            module_id,
688            MODULE_CONTROL_OP_HEALTH_CHECK,
689            probe_started_at,
690            deadline,
691        )
692    } else {
693        forwarding.begin_health_probe_rpc_for(
694            module_id,
695            MODULE_CONTROL_OP_HEALTH_CHECK,
696            probe_started_at,
697            deadline,
698        )
699    }
700    .map_err(|err| {
701        // The endpoint is not registered, so there is no live control lane to
702        // ask. That is the module being absent, not slow.
703        HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
704    })?;
705    let probed = pending.endpoint.connection_id;
706    await_health_probe(forwarding, pending, deadline, runtime.health.deadline)
707        .await
708        .map(|report| (report, probed))
709}
710
711/// [`probe_module_health`] for one endpoint rather than the id's active one.
712///
713/// A swap probes two processes that no by-id lookup reaches: its candidate
714/// before cutover, and its superseded incumbent (for busy gauges) while the
715/// incumbent drains. `deadline_cap` bounds the probe the way a drain deadline
716/// bounds the by-id drain probe.
717pub(super) async fn probe_endpoint_health(
718    endpoint: crate::ModuleEndpointId,
719    runtime: &SupervisorRuntimeConfig,
720    deadline_cap: Option<Instant>,
721) -> Result<HealthReport, HealthProbeError> {
722    let Some(forwarding) = runtime.forwarding.as_ref() else {
723        return Err(HealthProbeError::misconfigured(
724            "supervisor was not configured with a forwarding table",
725        ));
726    };
727    let probe_started_at = Instant::now();
728    let mut deadline = probe_started_at + runtime.health.deadline;
729    if let Some(cap) = deadline_cap {
730        deadline = deadline.min(cap);
731    }
732    let pending = forwarding
733        .begin_endpoint_health_probe_rpc_for(
734            endpoint,
735            MODULE_CONTROL_OP_HEALTH_CHECK,
736            probe_started_at,
737            deadline,
738        )
739        .map_err(|err| {
740            HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
741        })?;
742    await_health_probe(forwarding, pending, deadline, runtime.health.deadline).await
743}
744
745/// Send a begun health probe and classify its answer.
746async fn await_health_probe(
747    forwarding: &ForwardingTable,
748    pending: PendingModuleControlRpc,
749    deadline: Instant,
750    probe_budget: Duration,
751) -> Result<HealthReport, HealthProbeError> {
752    let PendingModuleControlRpc {
753        endpoint,
754        module_sink,
755        negotiated_ver,
756        corr,
757        receiver,
758    } = pending;
759    let body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).map_err(|err| {
760        HealthProbeError::misconfigured(format!("failed to encode health.check: {err}"))
761    })?;
762    let frame = Frame::build_with_version(
763        negotiated_ver,
764        FrameType::Request,
765        control_flags(),
766        0,
767        0,
768        corr,
769        body,
770    )
771    .map_err(|err| {
772        HealthProbeError::misconfigured(format!("failed to build health.check frame: {err}"))
773    })?;
774
775    // The enqueue itself must be bounded by the probe deadline: FrameSink.send
776    // blocks waiting for capacity when the module's egress queue is full, and an
777    // unbounded await here freezes the whole supervision actor (it stops polling
778    // Child::wait and supervisor commands), making the module unrecoverable
779    // in-band. On timeout the probe fails like any transport failure.
780    match timeout_at(deadline, module_sink.send(frame)).await {
781        Ok(Ok(())) => {}
782        Ok(Err(err)) => {
783            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
784            // A closed sink means the module's egress channel is gone -- the
785            // receiving half is dropped when its connection tears down. Proof.
786            return Err(HealthProbeError::lane_dead(format!(
787                "failed to send health.check: {err}"
788            )));
789        }
790        Err(_elapsed) => {
791            let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
792            // A full egress queue means the module is not draining its socket, which
793            // is consistent with a wedged module AND with one whose reader is merely
794            // starved. Silence, not proof.
795            return Err(HealthProbeError::no_answer(
796                "health.check send timed out before enqueue (module egress full)",
797            ));
798        }
799    }
800
801    match timeout_at(deadline, receiver).await {
802        Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => Err(HealthProbeError::bad_answer(
803            "health.check returned an unexpected config response",
804        )),
805        // Each arm records WHAT WAS OBSERVED. Four of them are the module
806        // demonstrably answering -- rejected, non-health, malformed, wrong op --
807        // and those prove it is alive even though the probe failed.
808        Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
809            response.health_report().ok_or_else(|| {
810                HealthProbeError::bad_answer("health.check RPC returned a non-health response")
811            })
812        }
813        Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => Err(HealthProbeError::bad_answer(
814            format!("health.check rejected: {}", body.message),
815        )),
816        Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
817            Err(HealthProbeError::lane_dead(message))
818        }
819        Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
820            Err(HealthProbeError::bad_answer(message))
821        }
822        Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
823            Err(HealthProbeError::bad_answer(format!(
824                "expected module-control op '{expected}', got '{actual}'"
825            )))
826        }
827        // A reply that crosses the deadline before this waiter observes it is
828        // still proof of life. The forwarding path records its end-to-end latency
829        // before delivering this classification.
830        Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => Err(HealthProbeError::bad_answer(
831            "module answered health.check after its daemon deadline",
832        )),
833        Ok(Err(_)) => Err(HealthProbeError::misconfigured(
834            "health.check waiter was canceled before the module responded",
835        )),
836        Err(_) => {
837            let _ = forwarding.tombstone_health_probe_rpc(endpoint, corr);
838            Err(HealthProbeError::no_answer(format!(
839                "module did not answer health.check within {probe_budget:?}"
840            )))
841        }
842    }
843}
844
845/// Act on a health probe's answer. `probed` is the connection whose
846/// registration answered (`None` for an HTTP probe, which reaches no
847/// registration); only that registration's spawn is credited with readiness.
848#[allow(clippy::too_many_arguments)]
849pub(super) async fn handle_health_report(
850    spec: &ModuleSpec,
851    runtime: &SupervisorRuntimeConfig,
852    registry: &Registry,
853    process_liveness: &SupervisorProcessLiveness,
854    snapshot: &SharedSnapshot,
855    child: &mut Option<SupervisedChild>,
856    report: HealthReport,
857    now_ms: u64,
858    delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
859    probed: Option<ConnectionId>,
860) {
861    let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
862        (Some(delivery), Some(probe)) => {
863            delivery
864                .health_result(
865                    &spec.module_id,
866                    runtime.forwarding.as_deref(),
867                    registry,
868                    probe,
869                    report.status == HealthStatus::Ok,
870                )
871                .await
872        }
873        _ => false,
874    };
875    if let (Some(delivery), Some(spawn)) = (
876        &runtime.config_delivery,
877        child
878            .as_ref()
879            .and_then(|child| child.config_delivery.as_ref()),
880    ) {
881        delivery
882            .mark_readiness(
883                &spec.module_id,
884                runtime.forwarding.as_deref(),
885                probed,
886                spawn,
887                report.status == HealthStatus::Ok,
888            )
889            .await;
890    }
891    let status = supervisor_health_status(report.status);
892    let detail = report.detail.clone();
893    let summary =
894        crate::health_summary::relayed_health_summary(&spec.module_id, report.summary.clone());
895    let metrics = truncate_health_metrics(report.metrics);
896    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
897        state.health.status = status;
898        state.last_probe_evidence = None;
899        state.health.last_probe_ms = Some(now_ms);
900        state.health.detail = detail.clone();
901        state.health.summary = summary.clone();
902        state.health.metrics = metrics.clone();
903        state.health.consecutive_failures = 0;
904        state.failed_retry.observe_health(
905            report.status == HealthStatus::Ok,
906            runtime.restart_policy.window,
907        );
908    });
909
910    if delivery_failed {
911        return;
912    }
913    let action = match report.status {
914        HealthStatus::Ok => return,
915        HealthStatus::Degraded => runtime.health.on_degraded,
916        HealthStatus::Failing => runtime.health.on_failing,
917    };
918    apply_l3_health_action(
919        spec,
920        runtime,
921        registry,
922        process_liveness,
923        snapshot,
924        child,
925        status,
926        detail.as_deref(),
927        action,
928        now_ms,
929    )
930    .await;
931}
932
933#[allow(clippy::too_many_arguments)]
934pub(super) async fn handle_health_probe_failure(
935    spec: &ModuleSpec,
936    runtime: &SupervisorRuntimeConfig,
937    registry: &Registry,
938    process_liveness: &SupervisorProcessLiveness,
939    snapshot: &SharedSnapshot,
940    child: &mut Option<SupervisedChild>,
941    err: HealthProbeError,
942    now_ms: u64,
943    delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
944) {
945    let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
946        (Some(delivery), Some(probe)) => {
947            delivery
948                .health_result(
949                    &spec.module_id,
950                    runtime.forwarding.as_deref(),
951                    registry,
952                    probe,
953                    false,
954                )
955                .await
956        }
957        _ => false,
958    };
959    let threshold = runtime.health.failure_threshold.max(1);
960    let held = if err.evidence == HealthProbeEvidence::NoAnswer {
961        runtime.host_health.record_late_module(&spec.module_id)
962    } else {
963        false
964    };
965    let mut failures = 0;
966    // Carry the evidence class into the operator-visible detail. Without it,
967    // "module did not answer within 5s" and "the control lane is gone" are two
968    // prose strings in the same field, and the reader has to know the codebase to
969    // tell which one is proof of anything.
970    let detail = if held {
971        format!("[{}] {err}; host overloaded", err.label())
972    } else {
973        format!("[{}] {err}", err.label())
974    };
975    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
976        state.last_probe_evidence = Some(err.evidence);
977        state
978            .failed_retry
979            .observe_health(false, runtime.restart_policy.window);
980        // A failed wire probe invalidates the last report, even before the
981        // restart threshold. HTTP probes already mark failures as Failing.
982        if held {
983            state.health.status = SupervisorHealthStatus::Degraded;
984        } else if state.spawned_protocol.unwrap_or(spec.protocol) == ModuleProtocol::Subc {
985            state.health.status = SupervisorHealthStatus::Unknown;
986        }
987        state.health.last_probe_ms = Some(now_ms);
988        // Held silence breaks the streak: after the host recovers, only new
989        // failures count. Replaying pre-overload misses would restart immediately.
990        state.health.consecutive_failures = if held {
991            0
992        } else {
993            state.health.consecutive_failures.saturating_add(1)
994        };
995        state.health.detail = Some(detail.clone());
996        // The failed probe invalidates the module's last sentence along with
997        // the rest of its last report.
998        state.health.summary = None;
999        state.health.metrics = None;
1000        failures = state.health.consecutive_failures;
1001    });
1002
1003    if delivery_failed {
1004        return;
1005    }
1006    if held || failures < threshold {
1007        warn!(
1008            module_id = %spec.module_id,
1009            consecutive_failures = failures,
1010            threshold,
1011            evidence = err.label(),
1012            detail = %detail,
1013            "health.check probe failed"
1014        );
1015        return;
1016    }
1017
1018    let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
1019        state.state = ModuleState::Unresponsive;
1020        state.health.status = SupervisorHealthStatus::Unresponsive;
1021    });
1022    // The evidence class is logged at the kill site because this is the line an
1023    // operator reads after an unexplained restart. A streak of `no-answer` under
1024    // machine load is the known false-positive shape; a `lane-dead` is not.
1025    if runtime.health.critical {
1026        error!(
1027            module_id = %spec.module_id,
1028            status = "unresponsive",
1029            evidence = err.label(),
1030            detail = %detail,
1031            "critical module health alert"
1032        );
1033    } else {
1034        warn!(
1035            module_id = %spec.module_id,
1036            status = "unresponsive",
1037            evidence = err.label(),
1038            detail = %detail,
1039            "module health threshold breached"
1040        );
1041    }
1042    if let Err(err) = health_restart_child(
1043        spec,
1044        runtime,
1045        registry,
1046        process_liveness,
1047        snapshot,
1048        child,
1049        SupervisorHealthStatus::Unresponsive,
1050        Some(&detail),
1051        now_ms,
1052    )
1053    .await
1054    {
1055        error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
1056    }
1057}
1058
1059#[allow(clippy::too_many_arguments)]
1060async fn apply_l3_health_action(
1061    spec: &ModuleSpec,
1062    runtime: &SupervisorRuntimeConfig,
1063    registry: &Registry,
1064    process_liveness: &SupervisorProcessLiveness,
1065    snapshot: &SharedSnapshot,
1066    child: &mut Option<SupervisedChild>,
1067    status: SupervisorHealthStatus,
1068    detail: Option<&str>,
1069    action: HealthAction,
1070    now_ms: u64,
1071) {
1072    record_health_action(snapshot, &spec.module_id, action.to_string(), now_ms);
1073    match action {
1074        HealthAction::Report => {
1075            info!(
1076                module_id = %spec.module_id,
1077                status = ?status,
1078                detail,
1079                "module reported non-ok health"
1080            );
1081        }
1082        HealthAction::Alert => {
1083            error!(
1084                module_id = %spec.module_id,
1085                status = ?status,
1086                detail,
1087                "module health alert"
1088            );
1089        }
1090        HealthAction::Restart => {
1091            if let Err(err) = health_restart_child(
1092                spec,
1093                runtime,
1094                registry,
1095                process_liveness,
1096                snapshot,
1097                child,
1098                status,
1099                detail,
1100                now_ms,
1101            )
1102            .await
1103            {
1104                error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
1105            }
1106        }
1107    }
1108}
1109
1110#[allow(clippy::too_many_arguments)]
1111pub(super) async fn health_restart_child(
1112    spec: &ModuleSpec,
1113    runtime: &SupervisorRuntimeConfig,
1114    registry: &Registry,
1115    process_liveness: &SupervisorProcessLiveness,
1116    snapshot: &SharedSnapshot,
1117    child: &mut Option<SupervisedChild>,
1118    status: SupervisorHealthStatus,
1119    detail: Option<&str>,
1120    now_ms: u64,
1121) -> Result<(), SuperviseError> {
1122    budgeted_restart_child(
1123        spec,
1124        runtime,
1125        registry,
1126        process_liveness,
1127        snapshot,
1128        child,
1129        status,
1130        detail,
1131        now_ms,
1132        true,
1133    )
1134    .await
1135}
1136
1137pub(super) fn record_health_action(
1138    snapshot: &SharedSnapshot,
1139    module_id: &str,
1140    action: String,
1141    now_ms: u64,
1142) {
1143    let _ = update_snapshot(snapshot, Some(module_id), |state| {
1144        state.health.last_action = Some(action);
1145        state.health.last_action_ms = Some(now_ms);
1146    });
1147}
1148
1149fn supervisor_health_status(status: HealthStatus) -> SupervisorHealthStatus {
1150    match status {
1151        HealthStatus::Ok => SupervisorHealthStatus::Ok,
1152        HealthStatus::Degraded => SupervisorHealthStatus::Degraded,
1153        HealthStatus::Failing => SupervisorHealthStatus::Failing,
1154    }
1155}
1156
1157/// Caps the metrics blob stored in the cached supervisor snapshot, which is
1158/// returned to every `supervisor.list` and `supervisor.health` caller.
1159///
1160/// This cap is deliberately NOT applied on the one-shot `supervisor.health_probe`
1161/// path: that request exists to return a module's complete metrics object, and
1162/// `ck health <module-id>` documents it as the way to see what the cached view
1163/// truncates. The asymmetry is the feature.
1164///
1165/// So a new caller must decide which side it is on rather than assume the cap is
1166/// universal. Reaching for it on a fresh-probe path would silently reintroduce
1167/// the truncation that path exists to avoid.
1168fn truncate_health_metrics(metrics: Option<Value>) -> Option<Value> {
1169    let metrics = metrics?;
1170    match serde_json::to_vec(&metrics) {
1171        Ok(encoded) if encoded.len() > MAX_HEALTH_METRICS_BYTES => Some(serde_json::json!({
1172            "truncated": true,
1173            "original_bytes": encoded.len(),
1174        })),
1175        Ok(_) | Err(_) => Some(metrics),
1176    }
1177}
1178
1179/// Spread health probes so a fleet-wide restart does not converge them.
1180///
1181/// The delay is derived from the module id and probe index rather than a random
1182/// source, so it is deterministic per module: a module keeps its own offset
1183/// across daemon restarts instead of re-rolling into a collision.
1184pub(super) fn jittered_health_delay(
1185    module_id: &str,
1186    probe_index: u64,
1187    cadence: Duration,
1188) -> Duration {
1189    if cadence.is_zero() {
1190        return Duration::ZERO;
1191    }
1192    let cadence_ms = cadence.as_millis() as u64;
1193    // This early return is REDUNDANT, deliberately, and a mutation run will show
1194    // it surviving removal. Recording why here so the next person to notice does
1195    // not have to re-derive it:
1196    //
1197    // - It is unreachable in practice. `positive_millis` in daemon_config rejects
1198    //   a zero cadence and builds the Duration from whole milliseconds, so a
1199    //   sub-millisecond cadence cannot come from config.
1200    // - Even if reached it changes no answer. The `.max(1)` below makes the span
1201    //   1, and `hash % 1` is 0, so the fall-through returns `cadence` unchanged
1202    //   -- exactly what this returns.
1203    //
1204    // Kept as a guard against a future widening of the config parser (accepting
1205    // microseconds, say), which would make the sub-millisecond case reachable.
1206    // The `.max(1)` is the load-bearing half TODAY: remove it and the modulo
1207    // divides by zero. Remove this and nothing changes.
1208    if cadence_ms == 0 {
1209        return cadence;
1210    }
1211    // Note that this never returns less than one cadence, including for the FIRST
1212    // probe. So a freshly registered module reports health `unknown` for a full
1213    // cadence plus jitter -- 30-33s at the default -- no matter how quickly it is
1214    // ready to answer.
1215    //
1216    // That is a property of the supervisor's schedule, not of any module: an
1217    // operator watching a restart sees `unknown` and cannot tell it from a module
1218    // that is slow to warm. Measured on two unrelated modules, both flipping to
1219    // `ok` between 22s and 32s after restart.
1220    //
1221    // Left as-is because spreading the first probe is what keeps a fleet-wide
1222    // restart from firing fourteen simultaneous probes into a cold machine. The
1223    // alternative -- probe at t+0 and jitter only from the second onward -- trades
1224    // that thundering herd for a faster first reading.
1225    let jitter_span = (cadence_ms / 10).max(1);
1226    let hash = module_id.as_bytes().iter().fold(
1227        probe_index.wrapping_mul(0x9E37_79B9_7F4A_7C15),
1228        |acc, byte| {
1229            acc.wrapping_mul(1099511628211)
1230                .wrapping_add(u64::from(*byte))
1231        },
1232    );
1233    cadence + Duration::from_millis(hash % jitter_span)
1234}