Skip to main content

dynamo_runtime/
system_health.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! System health monitoring and health check management
17
18use std::{
19    collections::{HashMap, HashSet},
20    sync::{Arc, OnceLock},
21    time::Instant,
22};
23use tokio::sync::mpsc;
24
25use crate::component;
26use crate::config::HealthStatus;
27use crate::metrics::{MetricsHierarchy, prometheus_names::distributed_runtime};
28
29/// Withholds readiness for one endpoint until dropped, so the endpoint's owner
30/// decides when it is serviceable rather than its transport registration.
31///
32/// Two effects, matching [`SystemHealth::hold_endpoint_readiness`]: transport
33/// registration no longer marks the named endpoint ready, and while any hold is
34/// outstanding [`SystemHealth::get_health_status`] reports not-ready for the
35/// whole process.
36///
37/// Take the hold *before* the endpoint registers with its transport — that is
38/// what makes it race-free on both request planes, since the NATS path publishes
39/// readiness from a spawned task.
40///
41/// Never let one drop while the `SystemHealth` mutex is held: `Drop` takes that
42/// lock and it is not reentrant.
43pub struct ReadinessHold {
44    system_health: Arc<parking_lot::Mutex<SystemHealth>>,
45    endpoint: String,
46}
47
48impl ReadinessHold {
49    pub fn take(system_health: Arc<parking_lot::Mutex<SystemHealth>>, endpoint: &str) -> Self {
50        system_health.lock().hold_endpoint_readiness(endpoint);
51        Self {
52            system_health,
53            endpoint: endpoint.to_string(),
54        }
55    }
56}
57
58impl Drop for ReadinessHold {
59    fn drop(&mut self) {
60        self.system_health
61            .lock()
62            .release_endpoint_readiness(&self.endpoint);
63    }
64}
65
66/// Health check target containing instance info and payload
67#[derive(Clone, Debug)]
68pub struct HealthCheckTarget {
69    pub instance: component::Instance,
70    pub payload: serde_json::Value,
71}
72
73/// The two signals an endpoint sends its health check task.
74#[derive(Clone, Default)]
75struct EndpointNotifiers {
76    /// A successful response: resets the idle timer and marks the endpoint ready.
77    activity: Arc<tokio::sync::Notify>,
78    /// A completed engine forward pass: restarts a waiting canary's timeout.
79    progress: Arc<tokio::sync::Notify>,
80}
81
82/// Current Health Status
83/// If use_endpoint_health_status is set then
84/// initialize the endpoint_health hashmap to the
85/// starting health status
86#[derive(Clone)]
87pub struct SystemHealth {
88    system_health: HealthStatus,
89    endpoint_health: Arc<std::sync::RwLock<HashMap<String, HealthStatus>>>,
90    /// Maps endpoint subject to health check target (instance + payload)
91    health_check_targets: Arc<std::sync::RwLock<HashMap<String, HealthCheckTarget>>>,
92    /// Maps endpoint subject to its specific health check notifiers
93    health_check_notifiers: Arc<std::sync::RwLock<HashMap<String, EndpointNotifiers>>>,
94    /// Endpoints whose owner publishes readiness itself. Transport registration
95    /// does not mark these ready; see [`SystemHealth::hold_endpoint_readiness`].
96    readiness_holds: Arc<std::sync::RwLock<HashSet<String>>>,
97    /// Channel for new endpoint registrations
98    /// This solves the race condition where HealthCheckManager starts before endpoints are registered
99    /// Using a channel ensures no registrations are lost.
100    new_endpoint_tx: mpsc::UnboundedSender<String>,
101    new_endpoint_rx: Arc<parking_lot::Mutex<Option<mpsc::UnboundedReceiver<String>>>>,
102    use_endpoint_health_status: Vec<String>,
103    health_check_enabled: bool,
104    health_path: String,
105    live_path: String,
106    start_time: Instant,
107    uptime_gauge: OnceLock<prometheus::Gauge>,
108}
109
110impl SystemHealth {
111    pub fn new(
112        starting_health_status: HealthStatus,
113        use_endpoint_health_status: Vec<String>,
114        health_check_enabled: bool,
115        health_path: String,
116        live_path: String,
117    ) -> Self {
118        // Force NotReady when canary is enabled — canary verifies before marking Ready.
119        let initial_endpoint_status = if health_check_enabled {
120            HealthStatus::NotReady
121        } else {
122            starting_health_status.clone()
123        };
124        let mut endpoint_health = HashMap::new();
125        for endpoint in &use_endpoint_health_status {
126            endpoint_health.insert(endpoint.clone(), initial_endpoint_status.clone());
127        }
128
129        // Create the channel for endpoint registration notifications
130        let (tx, rx) = mpsc::unbounded_channel();
131
132        SystemHealth {
133            system_health: starting_health_status,
134            endpoint_health: Arc::new(std::sync::RwLock::new(endpoint_health)),
135            health_check_targets: Arc::new(std::sync::RwLock::new(HashMap::new())),
136            health_check_notifiers: Arc::new(std::sync::RwLock::new(HashMap::new())),
137            readiness_holds: Arc::new(std::sync::RwLock::new(HashSet::new())),
138            new_endpoint_tx: tx,
139            new_endpoint_rx: Arc::new(parking_lot::Mutex::new(Some(rx))),
140            use_endpoint_health_status,
141            health_check_enabled,
142            health_path,
143            live_path,
144            start_time: Instant::now(),
145            uptime_gauge: OnceLock::new(),
146        }
147    }
148
149    pub fn health_check_enabled(&self) -> bool {
150        self.health_check_enabled
151    }
152
153    /// Signal endpoint transport registration. Endpoints with a canary target stay
154    /// NotReady until verification succeeds. Payload-less endpoints cannot run a
155    /// canary, so transport registration is their readiness signal.
156    pub fn set_endpoint_registered(&self, endpoint: &str) {
157        if self.readiness_holds.read().unwrap().contains(endpoint) {
158            return;
159        }
160        let has_health_check_target = self
161            .health_check_targets
162            .read()
163            .unwrap()
164            .contains_key(endpoint);
165        if !self.health_check_enabled || !has_health_check_target {
166            self.set_endpoint_health_status(endpoint, HealthStatus::Ready);
167        }
168    }
169
170    /// Withhold readiness for `endpoint` until [`release_endpoint_readiness`].
171    ///
172    /// Two effects, because one alone is not enough: transport registration no
173    /// longer marks this endpoint ready, and while any hold is outstanding
174    /// [`get_health_status`] reports not-ready for the whole process. Without the
175    /// second, a sibling endpoint registering unheld would answer the health route
176    /// on the held endpoint's behalf.
177    ///
178    /// Take the hold *before* the endpoint registers with its transport — that is
179    /// what makes this race-free on both request planes, since the NATS path
180    /// publishes readiness from a spawned task. Prefer [`ReadinessHold`], which
181    /// pairs this with its release.
182    ///
183    /// [`get_health_status`]: SystemHealth::get_health_status
184    ///
185    /// [`release_endpoint_readiness`]: SystemHealth::release_endpoint_readiness
186    pub fn hold_endpoint_readiness(&self, endpoint: &str) {
187        self.readiness_holds
188            .write()
189            .unwrap()
190            .insert(endpoint.to_string());
191    }
192
193    /// Drop a [`hold_endpoint_readiness`] hold. Readiness is not published here —
194    /// the owner writes it.
195    ///
196    /// [`hold_endpoint_readiness`]: SystemHealth::hold_endpoint_readiness
197    pub fn release_endpoint_readiness(&self, endpoint: &str) {
198        self.readiness_holds.write().unwrap().remove(endpoint);
199    }
200
201    pub fn set_health_status(&mut self, status: HealthStatus) {
202        self.system_health = status;
203    }
204
205    pub fn set_endpoint_health_status(&self, endpoint: &str, status: HealthStatus) {
206        let mut endpoint_health = self.endpoint_health.write().unwrap();
207        endpoint_health.insert(endpoint.to_string(), status);
208    }
209
210    /// Returns the overall health status and endpoint health statuses
211    /// System health is determined by ALL endpoints that have registered health checks
212    pub fn get_health_status(&self) -> (bool, HashMap<String, String>) {
213        let health_check_targets = self.health_check_targets.read().unwrap();
214        let endpoint_health = self.endpoint_health.read().unwrap();
215        let mut endpoints: HashMap<String, String> = HashMap::new();
216
217        for (endpoint, status) in endpoint_health.iter() {
218            endpoints.insert(
219                endpoint.clone(),
220                if *status == HealthStatus::Ready {
221                    "ready".to_string()
222                } else {
223                    "notready".to_string()
224                },
225            );
226        }
227
228        // An owner that has withheld an endpoint's readiness has not yet declared
229        // itself serviceable. Report not-ready for the whole process rather than
230        // letting some other endpoint's registration answer for it.
231        if !self.readiness_holds.read().unwrap().is_empty() {
232            return (false, endpoints);
233        }
234
235        let healthy = if !self.use_endpoint_health_status.is_empty() {
236            self.use_endpoint_health_status.iter().all(|endpoint| {
237                endpoint_health
238                    .get(endpoint)
239                    .is_some_and(|status| *status == HealthStatus::Ready)
240            })
241        } else {
242            // If we have registered health check targets, use them to determine health
243            if !health_check_targets.is_empty() {
244                health_check_targets
245                    .iter()
246                    .all(|(endpoint_subject, _target)| {
247                        endpoint_health
248                            .get(endpoint_subject)
249                            .is_some_and(|status| *status == HealthStatus::Ready)
250                    })
251            } else if self.health_check_enabled && !endpoint_health.is_empty() {
252                // A payload-less endpoint cannot register a canary target. When
253                // canaries are enabled, its transport registration is therefore
254                // the strongest available readiness signal.
255                endpoint_health
256                    .values()
257                    .all(|status| *status == HealthStatus::Ready)
258            } else {
259                // No health check targets registered, use simple system health
260                self.system_health == HealthStatus::Ready
261            }
262        };
263
264        (healthy, endpoints)
265    }
266
267    /// Register a health check target for an endpoint
268    pub fn register_health_check_target(
269        &self,
270        endpoint_subject: &str,
271        instance: component::Instance,
272        payload: serde_json::Value,
273    ) {
274        let key = endpoint_subject.to_owned();
275
276        // Atomically check+insert under a single write lock to avoid races.
277        let inserted = {
278            let mut targets = self.health_check_targets.write().unwrap();
279            match targets.entry(key.clone()) {
280                std::collections::hash_map::Entry::Occupied(_) => false,
281                std::collections::hash_map::Entry::Vacant(v) => {
282                    v.insert(HealthCheckTarget { instance, payload });
283                    true
284                }
285            }
286        };
287
288        if !inserted {
289            tracing::warn!(
290                "Attempted to re-register health check for endpoint '{}'; ignoring.",
291                key
292            );
293            return;
294        }
295
296        // Create and store the notifiers for this endpoint (idempotent).
297        {
298            let mut notifiers = self.health_check_notifiers.write().unwrap();
299            notifiers.entry(key.clone()).or_default();
300        }
301
302        // Initialize endpoint health status conservatively to NotReady.
303        {
304            let mut endpoint_health = self.endpoint_health.write().unwrap();
305            endpoint_health
306                .entry(key.clone())
307                .or_insert(HealthStatus::NotReady);
308        }
309
310        if let Err(e) = self.new_endpoint_tx.send(key.clone()) {
311            tracing::error!(
312                "Failed to send endpoint '{}' registration to health check manager: {}. \
313                 Health checks will not be performed for this endpoint.",
314                key,
315                e
316            );
317        }
318    }
319
320    /// Get all health check targets
321    pub fn get_health_check_targets(&self) -> Vec<(String, HealthCheckTarget)> {
322        let targets = self.health_check_targets.read().unwrap();
323        targets
324            .iter()
325            .map(|(k, v)| (k.clone(), v.clone()))
326            .collect()
327    }
328
329    /// Check if any health check targets are registered
330    pub fn has_health_check_targets(&self) -> bool {
331        let targets = self.health_check_targets.read().unwrap();
332        !targets.is_empty()
333    }
334
335    /// Get list of endpoints with health check targets
336    pub fn get_health_check_endpoints(&self) -> Vec<String> {
337        let targets = self.health_check_targets.read().unwrap();
338        targets.keys().cloned().collect()
339    }
340
341    /// Get health check target for a specific endpoint
342    pub fn get_health_check_target(&self, endpoint: &str) -> Option<HealthCheckTarget> {
343        let targets = self.health_check_targets.read().unwrap();
344        targets.get(endpoint).cloned()
345    }
346
347    /// Get the endpoint health status (Ready/NotReady)
348    pub fn get_endpoint_health_status(&self, endpoint: &str) -> Option<HealthStatus> {
349        let endpoint_health = self.endpoint_health.read().unwrap();
350        endpoint_health.get(endpoint).cloned()
351    }
352
353    /// Get the endpoint-specific health check notifier
354    pub fn get_endpoint_health_check_notifier(
355        &self,
356        endpoint_subject: &str,
357    ) -> Option<Arc<tokio::sync::Notify>> {
358        let notifiers = self.health_check_notifiers.read().unwrap();
359        notifiers.get(endpoint_subject).map(|n| n.activity.clone())
360    }
361
362    /// Get the notifier an engine fires when it completes a forward pass.
363    ///
364    /// A canary waiting for its response restarts its timeout on it: a long
365    /// prefill streams nothing until it ends, and a canary queued behind it is
366    /// not answered until then. Firing it never changes the endpoint's health
367    /// status or the idle timer.
368    pub fn get_endpoint_progress_notifier(
369        &self,
370        endpoint_subject: &str,
371    ) -> Option<Arc<tokio::sync::Notify>> {
372        let notifiers = self.health_check_notifiers.read().unwrap();
373        notifiers.get(endpoint_subject).map(|n| n.progress.clone())
374    }
375
376    /// Take the receiver for new endpoint registrations (can only be called once)
377    /// This is used by HealthCheckManager to receive notifications of new endpoints
378    pub fn take_new_endpoint_receiver(&self) -> Option<mpsc::UnboundedReceiver<String>> {
379        self.new_endpoint_rx.lock().take()
380    }
381
382    /// Initialize the uptime gauge using the provided metrics registry
383    pub fn initialize_uptime_gauge<T: MetricsHierarchy>(&self, registry: &T) -> anyhow::Result<()> {
384        let gauge = registry.metrics().create_gauge(
385            distributed_runtime::UPTIME_SECONDS,
386            "Total uptime of the DistributedRuntime in seconds",
387            &[],
388        )?;
389        self.uptime_gauge
390            .set(gauge)
391            .map_err(|_| anyhow::anyhow!("uptime_gauge already initialized"))?;
392        Ok(())
393    }
394
395    /// Get the current uptime as a Duration
396    pub fn uptime(&self) -> std::time::Duration {
397        self.start_time.elapsed()
398    }
399
400    /// Update the uptime gauge with the current uptime value
401    pub fn update_uptime_gauge(&self) {
402        if let Some(gauge) = self.uptime_gauge.get() {
403            gauge.set(self.uptime().as_secs_f64());
404        }
405    }
406
407    /// Get the health check path
408    pub fn health_path(&self) -> &str {
409        &self.health_path
410    }
411
412    /// Get the liveness check path
413    pub fn live_path(&self) -> &str {
414        &self.live_path
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use crate::component::{Instance, TransportType};
422
423    const ENDPOINT: &str = "generate";
424
425    fn system_health(health_check_enabled: bool) -> SystemHealth {
426        SystemHealth::new(
427            HealthStatus::NotReady,
428            // Deprecated and ignored in practice (see RuntimeConfig::from_settings),
429            // so the realistic case is an empty vector.
430            Vec::new(),
431            health_check_enabled,
432            "/health".to_string(),
433            "/live".to_string(),
434        )
435    }
436
437    fn instance() -> Instance {
438        Instance {
439            component: "backend".to_string(),
440            endpoint: ENDPOINT.to_string(),
441            namespace: "dynamo".to_string(),
442            instance_id: 1,
443            transport: TransportType::Tcp("127.0.0.1:0".to_string()),
444            device_type: None,
445            request_plane_codec: None,
446        }
447    }
448
449    /// A worker that registers a health-check payload reports ready once its
450    /// endpoint is registered, with the canary off.
451    #[test]
452    fn registered_target_makes_the_worker_ready_with_canary_off() {
453        let health = system_health(false);
454        health.register_health_check_target(ENDPOINT, instance(), serde_json::json!({}));
455        health.set_endpoint_registered(ENDPOINT);
456
457        let (healthy, endpoints) = health.get_health_status();
458        assert!(healthy, "a registered, ready endpoint must report healthy");
459        assert_eq!(endpoints.get(ENDPOINT).map(String::as_str), Some("ready"));
460    }
461
462    /// Regression guard for the push-egress health-check bug.
463    ///
464    /// `health_check_targets` is populated ONLY by passing a
465    /// `health_check_payload` to `serve_endpoint`. An earlier revision of the
466    /// push-egress path skipped that payload to avoid the `start_with_registration`
467    /// bail, on the theory that it merely disabled the canary. It does not: with
468    /// the map empty, `get_health_status` stops consulting endpoint status at all
469    /// and falls through to the process-wide `system_health`, which starts
470    /// `NotReady` and which the TRT-LLM worker never sets. The endpoint is marked
471    /// ready and the worker still reports 503 — on default settings, since this
472    /// path does not depend on the canary being enabled.
473    #[test]
474    fn ready_endpoint_without_a_registered_target_still_reports_unhealthy() {
475        let health = system_health(false);
476        // No register_health_check_target: this is the "skip the payload" case.
477        health.set_endpoint_registered(ENDPOINT);
478
479        let (healthy, endpoints) = health.get_health_status();
480        assert_eq!(
481            endpoints.get(ENDPOINT).map(String::as_str),
482            Some("ready"),
483            "the endpoint itself is ready"
484        );
485        assert!(
486            !healthy,
487            "with no health-check target the endpoint's readiness is ignored and \
488             the worker falls back to system_health (NotReady) — this is the 503"
489        );
490    }
491
492    /// A held endpoint does not become ready on transport registration, so its
493    /// owner can keep the route at 503 until every mandatory endpoint is up.
494    #[test]
495    fn held_endpoint_is_not_ready_on_transport_registration() {
496        let health = system_health(false);
497        health.hold_endpoint_readiness(ENDPOINT);
498        health.set_endpoint_registered(ENDPOINT);
499        assert_ne!(
500            health.get_endpoint_health_status(ENDPOINT),
501            Some(HealthStatus::Ready),
502            "a held endpoint must not be marked ready by transport registration"
503        );
504
505        health.release_endpoint_readiness(ENDPOINT);
506        health.set_endpoint_registered(ENDPOINT);
507        assert_eq!(
508            health.get_endpoint_health_status(ENDPOINT),
509            Some(HealthStatus::Ready),
510            "after release the owner's registration signal publishes readiness"
511        );
512    }
513
514    /// A sibling endpoint registering while another is held must not answer the
515    /// health route on the held endpoint's behalf. With the canary on and no
516    /// registered target, `get_health_status` otherwise reduces to "every
517    /// endpoint present in the map is ready", which a held endpoint is absent
518    /// from.
519    #[test]
520    fn an_unheld_sibling_endpoint_cannot_report_the_worker_ready() {
521        let health = system_health(true);
522        health.hold_endpoint_readiness(ENDPOINT);
523        health.set_endpoint_registered(ENDPOINT);
524        health.set_endpoint_registered("rl_system");
525
526        assert!(
527            !health.get_health_status().0,
528            "a held endpoint must keep the worker not-ready however many siblings register"
529        );
530
531        health.release_endpoint_readiness(ENDPOINT);
532        health.set_endpoint_registered(ENDPOINT);
533        assert!(health.get_health_status().0);
534    }
535
536    /// A hold suppresses the *whole process's* readiness, but the per-endpoint
537    /// suppression inside `set_endpoint_registered` stays scoped to the endpoint
538    /// it names — a sibling still records its own transport registration.
539    #[test]
540    fn a_hold_does_not_suppress_a_siblings_endpoint_flag() {
541        let health = system_health(false);
542        health.hold_endpoint_readiness(ENDPOINT);
543        health.set_endpoint_registered("other");
544        assert_eq!(
545            health.get_endpoint_health_status("other"),
546            Some(HealthStatus::Ready)
547        );
548    }
549
550    /// The fallthrough is only escapable by setting system health directly,
551    /// which in this repo only the vLLM worker does.
552    #[test]
553    fn without_targets_health_tracks_system_health_only() {
554        let mut health = system_health(false);
555        health.set_endpoint_registered(ENDPOINT);
556        assert!(!health.get_health_status().0);
557
558        health.set_health_status(HealthStatus::Ready);
559        assert!(
560            health.get_health_status().0,
561            "with no targets, system_health alone decides"
562        );
563    }
564
565    /// Payload-less workers cannot run a canary. With canaries enabled, endpoint
566    /// registration is therefore sufficient to make the worker healthy.
567    #[test]
568    fn payloadless_endpoint_is_ready_with_canary_on() {
569        let health = system_health(true);
570        health.set_endpoint_registered(ENDPOINT);
571
572        let (healthy, endpoints) = health.get_health_status();
573        assert!(
574            healthy,
575            "a registered payload-less endpoint must report healthy"
576        );
577        assert_eq!(endpoints.get(ENDPOINT).map(String::as_str), Some("ready"));
578    }
579
580    /// With the canary on, endpoint registration deliberately does NOT mark the
581    /// endpoint ready — the canary does, after verifying a real generation. A
582    /// push endpoint therefore needs a locally registered engine for the canary
583    /// to dispatch to, which is why `serve_endpoint` registers a pull engine
584    /// alongside the push ingress.
585    #[test]
586    fn canary_enabled_withholds_ready_until_verified() {
587        let health = system_health(true);
588        health.register_health_check_target(ENDPOINT, instance(), serde_json::json!({}));
589        health.set_endpoint_registered(ENDPOINT);
590
591        assert!(
592            !health.get_health_status().0,
593            "canary must verify before the worker reports ready"
594        );
595
596        health.set_endpoint_health_status(ENDPOINT, HealthStatus::Ready);
597        assert!(
598            health.get_health_status().0,
599            "after the canary marks it ready the worker is healthy"
600        );
601    }
602
603    /// Engine progress must not reach the activity notifier, which marks the
604    /// endpoint ready: a completed forward pass is not a successful response.
605    #[test]
606    fn engine_progress_does_not_notify_activity() {
607        use futures::FutureExt;
608
609        let health = system_health(true);
610        assert!(health.get_endpoint_progress_notifier(ENDPOINT).is_none());
611
612        health.register_health_check_target(ENDPOINT, instance(), serde_json::json!({}));
613        let activity = health.get_endpoint_health_check_notifier(ENDPOINT).unwrap();
614        let progress = health.get_endpoint_progress_notifier(ENDPOINT).unwrap();
615
616        progress.notify_one();
617        assert!(activity.notified().now_or_never().is_none());
618        assert!(progress.notified().now_or_never().is_some());
619    }
620}