Skip to main content

dynamo_runtime/
health_check.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::DistributedRuntime;
5use crate::config::HealthStatus;
6use crate::engine::AsyncEngine;
7use crate::pipeline::SingleIn;
8use crate::protocols::maybe_error::MaybeError;
9use futures::StreamExt;
10use parking_lot::Mutex;
11use std::collections::HashMap;
12use std::sync::Arc;
13use std::time::Duration;
14use tokio::task::JoinHandle;
15use tracing::{debug, error, info, warn};
16
17/// Longest a canary waits for its response, however many forward passes the
18/// engine completes meanwhile. It bounds a stall after the forward pass, where
19/// passes continue but nothing is answered. Longer than any expected prefill.
20const CANARY_MAX_WAIT: Duration = Duration::from_secs(600);
21
22/// Configuration for health check behavior
23pub struct HealthCheckConfig {
24    /// Wait time before sending canary health checks (when no activity)
25    pub canary_wait_time: Duration,
26    /// Timeout for health check requests
27    pub request_timeout: Duration,
28}
29
30impl Default for HealthCheckConfig {
31    fn default() -> Self {
32        Self {
33            canary_wait_time: Duration::from_secs(crate::config::DEFAULT_CANARY_WAIT_TIME_SECS),
34            request_timeout: Duration::from_secs(
35                crate::config::DEFAULT_HEALTH_CHECK_REQUEST_TIMEOUT_SECS,
36            ),
37        }
38    }
39}
40
41/// Health check manager that monitors endpoint health
42pub struct HealthCheckManager {
43    drt: DistributedRuntime,
44    config: HealthCheckConfig,
45    /// Track per-endpoint health check tasks
46    /// Maps: endpoint_subject -> task_handle
47    endpoint_tasks: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
48}
49
50impl HealthCheckManager {
51    pub fn new(drt: DistributedRuntime, config: HealthCheckConfig) -> Self {
52        Self {
53            drt,
54            config,
55            endpoint_tasks: Arc::new(Mutex::new(HashMap::new())),
56        }
57    }
58
59    /// Start the health check manager by spawning per-endpoint monitoring tasks
60    pub async fn start(self: Arc<Self>) -> anyhow::Result<()> {
61        // Get all registered endpoints at startup
62        let targets = self.drt.system_health().lock().get_health_check_targets();
63
64        info!(
65            "Starting health check tasks for {} endpoints with canary_wait_time: {:?}",
66            targets.len(),
67            self.config.canary_wait_time
68        );
69
70        // Spawn a health check task for each registered endpoint
71        for (endpoint_subject, _target) in targets {
72            self.spawn_endpoint_health_check_task(endpoint_subject);
73        }
74
75        // CRITICAL: Spawn a task to monitor for NEW endpoints registered after startup
76        // This uses a channel-based approach to guarantee no lost notifications
77        // Will return an error if the receiver has already been taken
78        self.spawn_new_endpoint_monitor().await?;
79
80        info!("HealthCheckManager started successfully with channel-based endpoint discovery");
81        Ok(())
82    }
83
84    /// Spawn a dedicated health check task for a specific endpoint
85    fn spawn_endpoint_health_check_task(self: &Arc<Self>, endpoint_subject: String) {
86        let manager = self.clone();
87        let canary_wait = self.config.canary_wait_time;
88        let endpoint_subject_clone = endpoint_subject.clone();
89
90        // Get the endpoint-specific notifier
91        let notifier = self
92            .drt
93            .system_health()
94            .lock()
95            .get_endpoint_health_check_notifier(&endpoint_subject)
96            .expect("Notifier should exist for registered endpoint");
97        let progress = self
98            .drt
99            .system_health()
100            .lock()
101            .get_endpoint_progress_notifier(&endpoint_subject)
102            .expect("Notifier should exist for registered endpoint");
103
104        let task = tokio::spawn(async move {
105            let endpoint_subject = endpoint_subject_clone;
106            info!("Health check task started for: {}", endpoint_subject);
107
108            // The last canary sent. It can outlive the canary wait: behind a long
109            // request it keeps waiting while the engine makes progress.
110            let mut canary: Option<JoinHandle<()>> = None;
111
112            loop {
113                // Wait for either timeout or activity notification
114                tokio::select! {
115                    _ = tokio::time::sleep(canary_wait) => {
116                        if canary.as_ref().is_some_and(|canary| !canary.is_finished()) {
117                            // Don't queue another canary behind the one still waiting.
118                            continue;
119                        }
120
121                        // Timeout - send health check for this specific endpoint
122                        debug!("Canary timer expired for {}, sending health check", endpoint_subject);
123
124                        // Get the health check payload for this endpoint
125                        let target = manager.drt.system_health().lock().get_health_check_target(&endpoint_subject);
126
127                        if let Some(target) = target {
128                            match manager.send_health_check_request(&endpoint_subject, &target.payload, progress.clone()) {
129                                Ok(sent) => canary = Some(sent),
130                                Err(e) => error!("Failed to send health check for {}: {}", endpoint_subject, e),
131                            }
132                        } else {
133                            // This should never happen - targets are registered at startup and never removed
134                            error!(
135                                "CRITICAL: Health check target for {} disappeared unexpectedly! This indicates a bug. Stopping health check task.",
136                                endpoint_subject
137                            );
138                            break;
139                        }
140                    }
141
142                    _ = notifier.notified() => {
143                        // Activity detected - reset timer for this endpoint only.
144                        // A notification marks a non-error response chunk or clean
145                        // stream completion, even for an empty stream. Neither path
146                        // requires a successful publish.
147                        debug!("Activity detected for {}, resetting health check timer", endpoint_subject);
148                        manager.drt.system_health().lock().set_endpoint_health_status(
149                            &endpoint_subject,
150                            crate::config::HealthStatus::Ready,
151                        );
152                    }
153                }
154            }
155
156            info!("Health check task for {} exiting", endpoint_subject);
157        });
158
159        // Store the task handle
160        self.endpoint_tasks
161            .lock()
162            .insert(endpoint_subject.clone(), task);
163
164        info!(
165            "Spawned health check task for endpoint: {}",
166            endpoint_subject
167        );
168    }
169
170    /// Spawn a task to monitor for newly registered endpoints
171    /// Returns an error if duplicate endpoints are detected, indicating a bug in the system
172    async fn spawn_new_endpoint_monitor(self: &Arc<Self>) -> anyhow::Result<()> {
173        let manager = self.clone();
174
175        // Get the receiver (can only be taken once)
176        let mut rx = manager
177            .drt
178            .system_health()
179            .lock()
180            .take_new_endpoint_receiver()
181            .ok_or_else(|| {
182                anyhow::anyhow!("Endpoint receiver already taken - this should only be called once")
183            })?;
184
185        tokio::spawn(async move {
186            info!("Starting dynamic endpoint discovery monitor with channel-based notifications");
187
188            while let Some(endpoint_subject) = rx.recv().await {
189                debug!(
190                    "Received endpoint registration via channel: {}",
191                    endpoint_subject
192                );
193
194                let already_exists = {
195                    let tasks = manager.endpoint_tasks.lock();
196                    tasks.contains_key(&endpoint_subject)
197                };
198
199                if already_exists {
200                    error!(
201                        "CRITICAL: Received registration for endpoint '{}' that already has a health check task!",
202                        endpoint_subject
203                    );
204                    break;
205                }
206
207                info!(
208                    "Spawning health check task for new endpoint: {}",
209                    endpoint_subject
210                );
211                manager.spawn_endpoint_health_check_task(endpoint_subject);
212            }
213
214            info!("Endpoint discovery monitor exiting - no new endpoints will be monitored!");
215        });
216
217        info!("Dynamic endpoint discovery monitor started");
218        Ok(())
219    }
220
221    /// Send a health check request via the local endpoint registry (in-process).
222    /// Returns the task that waits for the response and records the result.
223    fn send_health_check_request(
224        &self,
225        endpoint_subject: &str,
226        payload: &serde_json::Value,
227        progress: Arc<tokio::sync::Notify>,
228    ) -> anyhow::Result<JoinHandle<()>> {
229        debug!(
230            "Sending health check to {} via local registry",
231            endpoint_subject
232        );
233
234        let engine = self
235            .drt
236            .local_endpoint_registry()
237            .get(endpoint_subject)
238            .ok_or_else(|| {
239                anyhow::anyhow!(
240                    "Endpoint '{}' not found in local registry, engine may still be initializing",
241                    endpoint_subject
242                )
243            })?;
244
245        // Clone what we need for the spawned task
246        let system_health = self.drt.system_health().clone();
247        let endpoint_subject_owned = endpoint_subject.to_string();
248        let payload = payload.clone();
249        let timeout = self.config.request_timeout;
250        let max_wait = CANARY_MAX_WAIT.max(timeout);
251
252        // Spawn task to send health check and wait for response
253        let canary = tokio::spawn(async move {
254            let result = timeout_unless_progress(timeout, max_wait, &progress, async {
255                let request = SingleIn::new(payload);
256                match engine.generate(request).await {
257                    Ok(mut response_stream) => {
258                        // Get the first response to verify endpoint is alive.
259                        // Check for errors
260                        let is_healthy = if let Some(response) = response_stream.next().await {
261                            if let Some(error) = response.err() {
262                                warn!(
263                                    "Health check error response from {}: {:?}",
264                                    endpoint_subject_owned, error
265                                );
266                                false
267                            } else {
268                                debug!("Health check successful for {}", endpoint_subject_owned);
269                                true
270                            }
271                        } else {
272                            warn!(
273                                "Health check got no response from {}",
274                                endpoint_subject_owned
275                            );
276                            false
277                        };
278
279                        tokio::spawn(async move {
280                            // We need to consume the rest of the stream to avoid warnings on the frontend.
281                            response_stream.for_each(|_| async {}).await;
282                        });
283
284                        // Update health status based on response
285                        system_health.lock().set_endpoint_health_status(
286                            &endpoint_subject_owned,
287                            if is_healthy {
288                                HealthStatus::Ready
289                            } else {
290                                HealthStatus::NotReady
291                            },
292                        );
293                    }
294                    Err(e) => {
295                        error!(
296                            "Health check request failed for {}: {}",
297                            endpoint_subject_owned, e
298                        );
299                        system_health.lock().set_endpoint_health_status(
300                            &endpoint_subject_owned,
301                            HealthStatus::NotReady,
302                        );
303                    }
304                }
305            })
306            .await;
307
308            // Handle timeout
309            if result.is_none() {
310                warn!("Health check timeout for {}", endpoint_subject_owned);
311                system_health
312                    .lock()
313                    .set_endpoint_health_status(&endpoint_subject_owned, HealthStatus::NotReady);
314            }
315
316            debug!("Health check completed for {}", endpoint_subject_owned);
317        });
318
319        Ok(canary)
320    }
321}
322
323/// Wait for `check`, giving up once `timeout` passes with neither a result nor
324/// engine progress, or after `max_wait` in total.
325///
326/// A canary sent during a long prefill is not answered until the prefill ends,
327/// so it keeps waiting while the engine completes forward passes. It still
328/// fails `timeout` after the passes stop.
329async fn timeout_unless_progress<T>(
330    timeout: Duration,
331    max_wait: Duration,
332    progress: &tokio::sync::Notify,
333    check: impl std::future::Future<Output = T>,
334) -> Option<T> {
335    tokio::pin!(check);
336    let deadline = tokio::time::sleep(max_wait);
337    tokio::pin!(deadline);
338    loop {
339        tokio::select! {
340            biased;
341            output = &mut check => return Some(output),
342            _ = &mut deadline => return None,
343            _ = progress.notified() => {}
344            _ = tokio::time::sleep(timeout) => return None,
345        }
346    }
347}
348
349/// Start health check manager for the distributed runtime
350pub async fn start_health_check_manager(
351    drt: DistributedRuntime,
352    config: Option<HealthCheckConfig>,
353) -> anyhow::Result<()> {
354    let config = config.unwrap_or_default();
355    let manager = Arc::new(HealthCheckManager::new(drt, config));
356
357    // Start the health check manager (this spawns per-endpoint tasks internally)
358    manager.start().await?;
359
360    Ok(())
361}
362
363/// Get health check status for all endpoints
364pub async fn get_health_check_status(
365    drt: &DistributedRuntime,
366) -> anyhow::Result<serde_json::Value> {
367    // Get endpoints list from SystemHealth
368    let endpoint_subjects: Vec<String> = drt.system_health().lock().get_health_check_endpoints();
369
370    let mut endpoint_statuses = HashMap::new();
371
372    // Check each endpoint's health status
373    {
374        let system_health = drt.system_health();
375        let system_health_lock = system_health.lock();
376        for endpoint_subject in &endpoint_subjects {
377            let health_status = system_health_lock
378                .get_endpoint_health_status(endpoint_subject)
379                .unwrap_or(HealthStatus::NotReady);
380
381            let is_healthy = matches!(health_status, HealthStatus::Ready);
382
383            endpoint_statuses.insert(
384                endpoint_subject.clone(),
385                serde_json::json!({
386                    "healthy": is_healthy,
387                    "status": format!("{:?}", health_status),
388                }),
389            );
390        }
391    }
392
393    let overall_healthy = endpoint_statuses
394        .values()
395        .all(|v| v["healthy"].as_bool().unwrap_or(false));
396
397    Ok(serde_json::json!({
398        "status": if overall_healthy { "ready" } else { "notready" },
399        "endpoints_checked": endpoint_subjects.len(),
400        "endpoint_statuses": endpoint_statuses,
401    }))
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407    use tokio::sync::Notify;
408    use tokio::time::Instant;
409
410    const TIMEOUT: Duration = Duration::from_secs(3);
411    const MAX_WAIT: Duration = Duration::from_secs(60);
412
413    /// The engine completes a forward pass every 2 s, `passes` times, then stops.
414    fn engine_progress(passes: u32) -> Arc<Notify> {
415        let progress = Arc::new(Notify::new());
416        let engine = progress.clone();
417        tokio::spawn(async move {
418            for _ in 0..passes {
419                tokio::time::sleep(Duration::from_secs(2)).await;
420                engine.notify_one();
421            }
422        });
423        progress
424    }
425
426    async fn unanswered(progress: &Notify) -> Duration {
427        let start = Instant::now();
428        let check = std::future::pending::<()>();
429        assert_eq!(
430            timeout_unless_progress(TIMEOUT, MAX_WAIT, progress, check).await,
431            None
432        );
433        start.elapsed()
434    }
435
436    #[tokio::test(start_paused = true)]
437    async fn check_without_progress_times_out() {
438        assert_eq!(unanswered(&Notify::new()).await, TIMEOUT);
439    }
440
441    /// A canary queued behind a long prefill is answered when the prefill ends,
442    /// long after the timeout.
443    #[tokio::test(start_paused = true)]
444    async fn check_outlasts_the_timeout_while_the_engine_makes_progress() {
445        let progress = engine_progress(10);
446        let check = async {
447            tokio::time::sleep(Duration::from_secs(15)).await;
448            "answered"
449        };
450
451        let result = timeout_unless_progress(TIMEOUT, MAX_WAIT, &progress, check).await;
452
453        assert_eq!(result, Some("answered"));
454    }
455
456    /// A stalled engine is detected `timeout` after its last forward pass.
457    #[tokio::test(start_paused = true)]
458    async fn check_times_out_once_progress_stops() {
459        let progress = engine_progress(10);
460
461        assert_eq!(
462            unanswered(&progress).await,
463            Duration::from_secs(20) + TIMEOUT
464        );
465    }
466
467    /// Passes that never stop do not keep an unanswered canary waiting forever.
468    #[tokio::test(start_paused = true)]
469    async fn check_times_out_at_the_cap_despite_progress() {
470        let progress = engine_progress(u32::MAX);
471
472        assert_eq!(unanswered(&progress).await, MAX_WAIT);
473    }
474}
475
476// ============================================================
477// Full pipeline tests: push_handler → notify → HealthCheckManager
478// These tests use the real HealthCheckManager (spawn_endpoint_health_check_task)
479// and the real push_handler pipeline (TwoPartCodec + TCP + engine.generate()).
480// ============================================================
481#[cfg(all(test, feature = "integration"))]
482mod push_handler_notify_tests {
483    use super::*;
484    use crate::component::{Instance, TransportType};
485    use crate::config::HealthStatus;
486    use crate::distributed::distributed_test_utils::create_test_drt_async;
487    use crate::engine::{AsyncEngine, AsyncEngineContextProvider};
488    use crate::local_endpoint_registry::LocalAsyncEngine;
489    use crate::pipeline::network::codec::{TwoPartCodec, TwoPartMessage};
490    use crate::pipeline::network::{
491        ConnectionInfo, Ingress, PushWorkHandler, quic_response::QuicResponseServer,
492    };
493    use crate::pipeline::{ManyOut, ResponseStream, SingleIn};
494    use crate::protocols::annotated::Annotated;
495    use async_trait::async_trait;
496    use bytes::Bytes;
497    use futures::stream;
498    use std::sync::Arc;
499    use std::time::Duration;
500
501    type TestRequest = serde_json::Value;
502    type TestResponse = Annotated<serde_json::Value>;
503
504    /// A mock engine that streams a configurable sequence of success/error chunks.
505    /// Used both as the push_handler pipeline engine and registered in
506    /// the local endpoint registry for health check requests.
507    struct MockStreamingEngine {
508        num_chunks: usize,
509        /// If set, chunks at these indices will be error responses.
510        error_indices: Vec<usize>,
511    }
512
513    impl MockStreamingEngine {
514        fn success(num_chunks: usize) -> Arc<Self> {
515            Arc::new(Self {
516                num_chunks,
517                error_indices: vec![],
518            })
519        }
520
521        fn all_errors(num_chunks: usize) -> Arc<Self> {
522            Arc::new(Self {
523                num_chunks,
524                error_indices: (0..num_chunks).collect(),
525            })
526        }
527
528        fn with_error_at(num_chunks: usize, error_indices: Vec<usize>) -> Arc<Self> {
529            Arc::new(Self {
530                num_chunks,
531                error_indices,
532            })
533        }
534    }
535
536    #[async_trait]
537    impl AsyncEngine<SingleIn<TestRequest>, ManyOut<TestResponse>, anyhow::Error>
538        for MockStreamingEngine
539    {
540        async fn generate(
541            &self,
542            input: SingleIn<TestRequest>,
543        ) -> anyhow::Result<ManyOut<TestResponse>> {
544            let (_data, ctx) = input.into_parts();
545            let chunks: Vec<TestResponse> = (0..self.num_chunks)
546                .map(|i| {
547                    if self.error_indices.contains(&i) {
548                        Annotated::from_error(format!("mock error at chunk {i}"))
549                    } else {
550                        Annotated::from_data(serde_json::json!({"token": i}))
551                    }
552                })
553                .collect();
554            Ok(ResponseStream::new(
555                Box::pin(stream::iter(chunks)),
556                ctx.context(),
557            ))
558        }
559    }
560
561    /// Encodes a request as a TwoPartCodec payload with the given connection info.
562    fn encode_request(
563        request_id: &str,
564        connection_info: ConnectionInfo,
565        request_body: &serde_json::Value,
566    ) -> Bytes {
567        let control = serde_json::json!({
568            "id": request_id,
569            "request_type": "single_in",
570            "response_type": "many_out",
571            "connection_info": connection_info,
572        });
573        let header = serde_json::to_vec(&control).unwrap();
574        let data = serde_json::to_vec(request_body).unwrap();
575        let msg = TwoPartMessage::new(Bytes::from(header), Bytes::from(data));
576        TwoPartCodec::default().encode_message(msg).unwrap()
577    }
578
579    /// Sets up a QUIC server and registers a response stream for push_handler
580    /// to connect back to.
581    async fn setup_quic_receiver(
582        request_id: &str,
583    ) -> (
584        Arc<QuicResponseServer>,
585        ConnectionInfo,
586        crate::pipeline::network::StreamProvider<crate::pipeline::network::StreamReceiver>,
587    ) {
588        let shutdown = crate::CancellationToken::new();
589        let address = "127.0.0.1:0".parse().unwrap();
590        let server = QuicResponseServer::new(address, address, shutdown).unwrap();
591        let context = crate::pipeline::Context::with_id_and_metadata(
592            (),
593            request_id.to_string(),
594            Default::default(),
595        );
596        let registered = server.register_response(context.context());
597        let (connection_info, provider) = registered.into_parts();
598
599        (server, connection_info, provider)
600    }
601
602    /// Registers an endpoint in the DRT with the given engine in local registry.
603    /// Returns the notifier that the real HealthCheckManager will listen on.
604    fn register_endpoint(
605        drt: &crate::DistributedRuntime,
606        endpoint_name: &str,
607        local_engine: LocalAsyncEngine,
608    ) -> Arc<tokio::sync::Notify> {
609        let payload = serde_json::json!({
610            "prompt": "health",
611            "_health_check": true
612        });
613        drt.system_health().lock().register_health_check_target(
614            endpoint_name,
615            Instance {
616                component: "test_component".to_string(),
617                endpoint: endpoint_name.to_string(),
618                namespace: "test_namespace".to_string(),
619                instance_id: 0,
620                transport: TransportType::Nats(endpoint_name.to_string()),
621                device_type: None,
622                request_plane_codec: None,
623            },
624            payload,
625        );
626
627        drt.local_endpoint_registry()
628            .register(endpoint_name.to_string(), local_engine);
629
630        drt.system_health()
631            .lock()
632            .get_endpoint_health_check_notifier(endpoint_name)
633            .expect("Notifier should exist for registered endpoint")
634    }
635
636    /// Helper: send a request through the ingress pipeline.
637    async fn send_request(ingress: &Ingress<SingleIn<TestRequest>, ManyOut<TestResponse>>) {
638        let request_id = uuid::Uuid::new_v4().to_string();
639        let (_server, connection_info, _provider) = setup_quic_receiver(&request_id).await;
640        let payload = encode_request(
641            &request_id,
642            connection_info,
643            &serde_json::json!({"prompt": "test"}),
644        );
645        let result = ingress.handle_payload(payload, Some(request_id)).await;
646        assert!(result.is_ok(), "handle_payload should succeed");
647    }
648
649    /// Helper: assert endpoint health status.
650    fn assert_status(
651        drt: &crate::DistributedRuntime,
652        endpoint_name: &str,
653        expected: HealthStatus,
654        msg: &str,
655    ) {
656        let status = drt
657            .system_health()
658            .lock()
659            .get_endpoint_health_status(endpoint_name);
660        assert_eq!(status, Some(expected), "{msg}");
661    }
662
663    /// Helper: create ingress pipeline with given engine and notifier.
664    fn create_ingress(
665        _drt: &crate::DistributedRuntime,
666        engine: Arc<MockStreamingEngine>,
667        notifier: Arc<tokio::sync::Notify>,
668    ) -> Arc<Ingress<SingleIn<TestRequest>, ManyOut<TestResponse>>> {
669        let ingress =
670            Ingress::<SingleIn<TestRequest>, ManyOut<TestResponse>>::for_engine(engine).unwrap();
671        ingress
672            .set_endpoint_health_check_notifier(notifier)
673            .unwrap();
674        ingress
675            .set_quic_response_client_pool(
676                crate::pipeline::network::quic_response::process_client_pool_from_env().unwrap(),
677            )
678            .unwrap();
679        ingress
680    }
681
682    /// Helper: start HealthCheckManager with given canary wait.
683    async fn start_manager(drt: &crate::DistributedRuntime, canary_wait_ms: u64) {
684        let config = HealthCheckConfig {
685            canary_wait_time: Duration::from_millis(canary_wait_ms),
686            request_timeout: Duration::from_secs(1),
687        };
688        let manager = Arc::new(HealthCheckManager::new(drt.clone(), config));
689        manager.start().await.unwrap();
690    }
691
692    // =================================================================
693    // Test 1: Successful streaming → notification → Ready
694    // Canary engine returns errors, so Ready can only come from notify.
695    // =================================================================
696    #[tokio::test]
697    async fn test_successful_streaming_sets_ready() {
698        let drt = create_test_drt_async().await;
699        let endpoint = "test.successful_streaming";
700
701        let notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::all_errors(1));
702        assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
703
704        let ingress = create_ingress(&drt, MockStreamingEngine::success(5), notifier);
705        start_manager(&drt, 500).await;
706
707        send_request(&ingress).await;
708        tokio::time::sleep(Duration::from_millis(200)).await;
709
710        // Ready can only come from notification (canary engine errors)
711        assert_status(
712            &drt,
713            endpoint,
714            HealthStatus::Ready,
715            "successful streaming should set Ready via notification path",
716        );
717    }
718
719    // =================================================================
720    // Test 2: Idle engine → canary fires → successful health check → Ready
721    // =================================================================
722    #[tokio::test]
723    async fn test_canary_fires_on_idle_engine() {
724        let drt = create_test_drt_async().await;
725        let endpoint = "test.canary_idle";
726
727        let _notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::success(1));
728        assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
729
730        start_manager(&drt, 50).await;
731        tokio::time::sleep(Duration::from_millis(300)).await;
732
733        // No requests sent — canary fired and succeeded
734        assert_status(
735            &drt,
736            endpoint,
737            HealthStatus::Ready,
738            "canary should fire and set Ready on idle engine",
739        );
740    }
741
742    // =================================================================
743    // Test 3: Error streaming → no notification → canary errors → NotReady
744    // =================================================================
745    #[tokio::test]
746    async fn test_error_streaming_stays_not_ready() {
747        let drt = create_test_drt_async().await;
748        let endpoint = "test.error_streaming";
749
750        let notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::all_errors(1));
751        assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
752
753        // Pipeline streams only errors — no notifications sent
754        let ingress = create_ingress(&drt, MockStreamingEngine::all_errors(3), notifier);
755        start_manager(&drt, 50).await;
756
757        send_request(&ingress).await;
758        // Wait for canary to fire (50ms wait + margin)
759        tokio::time::sleep(Duration::from_millis(300)).await;
760
761        // Error streaming didn't notify, canary fired but engine also errored
762        assert_status(
763            &drt,
764            endpoint,
765            HealthStatus::NotReady,
766            "error streaming should not notify, canary also errors — stays NotReady",
767        );
768    }
769
770    // =================================================================
771    // Test 4: Idle engine → canary fires → failing health check → NotReady
772    // =================================================================
773    #[tokio::test]
774    async fn test_idle_engine_with_failing_canary() {
775        let drt = create_test_drt_async().await;
776        let endpoint = "test.canary_fails";
777
778        let _notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::all_errors(1));
779        assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
780
781        start_manager(&drt, 50).await;
782        tokio::time::sleep(Duration::from_millis(300)).await;
783
784        // No requests sent, canary fired but engine returned error
785        assert_status(
786            &drt,
787            endpoint,
788            HealthStatus::NotReady,
789            "canary fired but engine errored, status stays NotReady",
790        );
791    }
792
793    // =================================================================
794    // Test 5: Mixed streaming (success + trailing error) → Ready
795    // Successful chunks notify before the error, so status becomes Ready.
796    // Canary engine errors, proving Ready came from notification path.
797    // =================================================================
798    #[tokio::test]
799    async fn test_mixed_streaming_sets_ready() {
800        let drt = create_test_drt_async().await;
801        let endpoint = "test.mixed_streaming";
802
803        let notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::all_errors(1));
804        assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
805
806        // 5 chunks: 4 success + error at index 4
807        let ingress = create_ingress(
808            &drt,
809            MockStreamingEngine::with_error_at(5, vec![4]),
810            notifier,
811        );
812        start_manager(&drt, 500).await;
813
814        send_request(&ingress).await;
815        tokio::time::sleep(Duration::from_millis(200)).await;
816
817        // Successful chunks notified before the error chunk
818        assert_status(
819            &drt,
820            endpoint,
821            HealthStatus::Ready,
822            "successful chunks should set Ready despite trailing error",
823        );
824    }
825}
826
827// ===============================
828// Integration Tests (require DRT)
829// ===============================
830#[cfg(all(test, feature = "integration"))]
831mod integration_tests {
832    use super::*;
833    use crate::distributed::distributed_test_utils::create_test_drt_async;
834    use std::sync::Arc;
835    use std::time::Duration;
836
837    #[tokio::test]
838    async fn test_initialization() {
839        let drt = create_test_drt_async().await;
840
841        let canary_wait_time = Duration::from_secs(5);
842        let request_timeout = Duration::from_secs(3);
843
844        let config = HealthCheckConfig {
845            canary_wait_time,
846            request_timeout,
847        };
848
849        let manager = HealthCheckManager::new(drt.clone(), config);
850
851        assert_eq!(manager.config.canary_wait_time, canary_wait_time);
852        assert_eq!(manager.config.request_timeout, request_timeout);
853    }
854
855    #[tokio::test]
856    async fn test_payload_registration() {
857        let drt = create_test_drt_async().await;
858
859        let endpoint = "test.endpoint";
860        let payload = serde_json::json!({
861            "prompt": "test",
862            "_health_check": true
863        });
864
865        drt.system_health().lock().register_health_check_target(
866            endpoint,
867            crate::component::Instance {
868                component: "test_component".to_string(),
869                endpoint: "test_endpoint".to_string(),
870                namespace: "test_namespace".to_string(),
871                instance_id: 12345,
872                transport: crate::component::TransportType::Nats(endpoint.to_string()),
873                device_type: None,
874                request_plane_codec: None,
875            },
876            payload.clone(),
877        );
878
879        let retrieved = drt
880            .system_health()
881            .lock()
882            .get_health_check_target(endpoint)
883            .map(|t| t.payload);
884        assert!(retrieved.is_some());
885        assert_eq!(retrieved.unwrap(), payload);
886
887        // Verify endpoint appears in the list
888        let endpoints = drt.system_health().lock().get_health_check_endpoints();
889        assert!(endpoints.contains(&endpoint.to_string()));
890    }
891
892    #[tokio::test]
893    async fn test_spawn_per_endpoint_tasks() {
894        let drt = create_test_drt_async().await;
895
896        for i in 0..3 {
897            let endpoint = format!("test.endpoint.{}", i);
898            let payload = serde_json::json!({
899                "prompt": format!("test{}", i),
900                "_health_check": true
901            });
902            drt.system_health().lock().register_health_check_target(
903                &endpoint,
904                crate::component::Instance {
905                    component: "test_component".to_string(),
906                    endpoint: format!("test_endpoint_{}", i),
907                    namespace: "test_namespace".to_string(),
908                    instance_id: i,
909                    transport: crate::component::TransportType::Nats(endpoint.clone()),
910                    device_type: None,
911                    request_plane_codec: None,
912                },
913                payload,
914            );
915        }
916
917        let config = HealthCheckConfig {
918            canary_wait_time: Duration::from_secs(5),
919            request_timeout: Duration::from_secs(1),
920        };
921
922        let manager = Arc::new(HealthCheckManager::new(drt.clone(), config));
923        manager.clone().start().await.unwrap();
924
925        // Verify all endpoints have their own health check tasks
926        let tasks = manager.endpoint_tasks.lock();
927        // Should have 3 tasks (one for each endpoint)
928        assert_eq!(tasks.len(), 3);
929        // Check that all endpoints are represented in tasks
930        let endpoints: Vec<String> = tasks.keys().cloned().collect();
931        assert!(endpoints.contains(&"test.endpoint.0".to_string()));
932        assert!(endpoints.contains(&"test.endpoint.1".to_string()));
933        assert!(endpoints.contains(&"test.endpoint.2".to_string()));
934    }
935
936    #[tokio::test]
937    async fn test_endpoint_health_check_notifier_created() {
938        let drt = create_test_drt_async().await;
939
940        let endpoint = "test.endpoint.notifier";
941        let payload = serde_json::json!({
942            "prompt": "test",
943            "_health_check": true
944        });
945
946        // Register the endpoint
947        drt.system_health().lock().register_health_check_target(
948            endpoint,
949            crate::component::Instance {
950                component: "test_component".to_string(),
951                endpoint: "test_endpoint_notifier".to_string(),
952                namespace: "test_namespace".to_string(),
953                instance_id: 999,
954                transport: crate::component::TransportType::Nats(endpoint.to_string()),
955                device_type: None,
956                request_plane_codec: None,
957            },
958            payload.clone(),
959        );
960
961        // Verify that a notifier was created for this endpoint
962        let notifier = drt
963            .system_health()
964            .lock()
965            .get_endpoint_health_check_notifier(endpoint);
966
967        assert!(
968            notifier.is_some(),
969            "Endpoint should have a notifier created"
970        );
971
972        // Verify we can notify it without panicking
973        if let Some(notifier) = notifier {
974            notifier.notify_one();
975        }
976
977        // Initially, the endpoint should be Ready (default after registration)
978        let status = drt
979            .system_health()
980            .lock()
981            .get_endpoint_health_status(endpoint);
982        assert_eq!(status, Some(HealthStatus::NotReady));
983    }
984}