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