Skip to main content

dynamo_runtime/
system_status_server.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4// TODO: (DEP-635) this file should be renamed to system_http_server.rs
5//  it is being used not just for status, health, but others like loras management.
6
7#[cfg(test)]
8mod probe_tests;
9
10use crate::config::HealthStatus;
11use crate::config::environment_names::logging as env_logging;
12use crate::config::environment_names::runtime::canary as env_canary;
13use crate::config::environment_names::runtime::system as env_system;
14use crate::metrics::MetricsHierarchy;
15use crate::traits::DistributedRuntimeProvider;
16use crate::utils::ip_resolver::{
17    DefaultIpResolver, IpResolutionError, IpResolver, resolve_advertise_ip_for_bind,
18};
19use axum::{
20    Router,
21    body::Bytes,
22    extract::{Json, Path, State},
23    http::StatusCode,
24    response::{IntoResponse, Response},
25    routing::{any, delete, get, post},
26    serve::Listener,
27};
28use futures::StreamExt;
29use serde::{Deserialize, Serialize};
30use serde_json::json;
31use std::collections::HashMap;
32use std::io;
33use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
34use std::sync::{Arc, OnceLock};
35use std::time::{Duration, Instant};
36use tokio::{net::TcpListener, task::JoinHandle};
37use tokio_util::sync::CancellationToken;
38use tower_http::trace::TraceLayer;
39
40/// Selects probe semantics for the runtime-owned HTTP server.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum SystemProbePolicy {
43    /// Preserve the configured worker health handler for both probes.
44    #[default]
45    Worker,
46    /// Static liveness and readiness based on runtime dependencies, not the engine.
47    RuntimeOnly,
48}
49
50/// System status server information containing socket address and handle
51#[derive(Debug)]
52pub struct SystemStatusServerInfo {
53    pub socket_addr: SocketAddr,
54    pub handle: Option<Arc<JoinHandle<()>>>,
55}
56
57impl SystemStatusServerInfo {
58    pub fn new(socket_addr: SocketAddr, handle: Option<JoinHandle<()>>) -> Self {
59        Self {
60            socket_addr,
61            handle: handle.map(Arc::new),
62        }
63    }
64
65    pub fn address(&self) -> String {
66        self.socket_addr.to_string()
67    }
68
69    pub fn hostname(&self) -> String {
70        self.socket_addr.ip().to_string()
71    }
72
73    pub fn port(&self) -> u16 {
74        self.socket_addr.port()
75    }
76
77    /// Return an address that is served by the bound socket.
78    ///
79    /// A wildcard bind is replaced with a usable address from the same address
80    /// family. If interface enumeration fails, the same-family loopback is
81    /// used so IPv4 and IPv6 are never combined.
82    pub fn advertised_socket_addr(&self) -> SocketAddr {
83        match advertised_socket_addr(self.socket_addr, &DefaultIpResolver) {
84            Ok(address) => {
85                if self.socket_addr.ip().is_unspecified() && address.ip().is_loopback() {
86                    static WARNED: std::sync::Once = std::sync::Once::new();
87                    WARNED.call_once(|| {
88                        tracing::warn!(
89                            bind = %self.socket_addr,
90                            advertised = %address,
91                            "System status server found no non-loopback address in the bound family, so remote callers cannot reach the advertised address; on IPv6-only hosts, set DYN_SYSTEM_HOST=::"
92                        );
93                    });
94                }
95                address
96            }
97            Err(error) => {
98                let fallback = match self.socket_addr.ip() {
99                    IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::LOCALHOST),
100                    IpAddr::V6(_) => IpAddr::V6(Ipv6Addr::LOCALHOST),
101                };
102                tracing::warn!(
103                    %error,
104                    %fallback,
105                    "Failed to resolve the system status advertisement address; using loopback"
106                );
107                SocketAddr::new(fallback, self.socket_addr.port())
108            }
109        }
110    }
111}
112
113fn advertised_socket_addr<R: IpResolver>(
114    bound: SocketAddr,
115    resolver: &R,
116) -> Result<SocketAddr, IpResolutionError> {
117    let advertise_ip = resolve_advertise_ip_for_bind(bound.ip(), resolver)?;
118    Ok(SocketAddr::new(advertise_ip, bound.port()))
119}
120
121impl Clone for SystemStatusServerInfo {
122    fn clone(&self) -> Self {
123        Self {
124            socket_addr: self.socket_addr,
125            handle: self.handle.clone(),
126        }
127    }
128}
129
130/// System status server state containing the distributed runtime reference
131pub struct SystemStatusState {
132    // global drt registry is for printing out the entire Prometheus format output
133    root_drt: Arc<crate::DistributedRuntime>,
134    // Last /metrics render, behind the gate that serializes renders. Overlapping
135    // scrapes wait here on the runtime and share one blocking render.
136    last_scrape: Arc<tokio::sync::Mutex<LastScrape>>,
137    // Discovery metadata (only for Kubernetes backend)
138    discovery_metadata: Option<Arc<tokio::sync::RwLock<crate::discovery::DiscoveryMetadata>>>,
139}
140
141/// The most recent `/metrics` render and when it started collecting.
142#[derive(Default)]
143struct LastScrape {
144    started_at: Option<Instant>,
145    text: bytes::Bytes,
146}
147
148impl SystemStatusState {
149    /// Create new system status server state with the provided distributed runtime
150    pub fn new(
151        drt: Arc<crate::DistributedRuntime>,
152        discovery_metadata: Option<Arc<tokio::sync::RwLock<crate::discovery::DiscoveryMetadata>>>,
153    ) -> anyhow::Result<Self> {
154        Ok(Self {
155            root_drt: drt,
156            last_scrape: Arc::new(tokio::sync::Mutex::new(LastScrape::default())),
157            discovery_metadata,
158        })
159    }
160
161    /// Get a reference to the distributed runtime
162    pub fn drt(&self) -> &crate::DistributedRuntime {
163        &self.root_drt
164    }
165
166    /// Get a reference to the discovery metadata if available
167    pub fn discovery_metadata(
168        &self,
169    ) -> Option<&Arc<tokio::sync::RwLock<crate::discovery::DiscoveryMetadata>>> {
170        self.discovery_metadata.as_ref()
171    }
172}
173
174/// Request body for POST /v1/loras
175#[derive(Debug, Clone, Deserialize, Serialize)]
176pub struct LoadLoraRequest {
177    pub lora_name: String,
178    pub source: LoraSource,
179}
180
181/// Source information for loading a LoRA
182#[derive(Debug, Clone, Deserialize, Serialize)]
183pub struct LoraSource {
184    pub uri: String,
185}
186
187/// Response body for LoRA operations
188#[derive(Debug, Clone, Deserialize, Serialize)]
189pub struct LoraResponse {
190    pub status: String,
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub message: Option<String>,
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub lora_name: Option<String>,
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub lora_id: Option<u64>,
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub loras: Option<serde_json::Value>,
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub count: Option<usize>,
201}
202
203const SYSTEM_STATUS_REBIND_BACKOFF: Duration = Duration::from_secs(1);
204
205/// Start the complete system HTTP server after runtime initialization.
206pub async fn spawn_system_status_server(
207    host: &str,
208    port: u16,
209    cancel_token: CancellationToken,
210    drt: Arc<crate::DistributedRuntime>,
211    discovery_metadata: Option<Arc<tokio::sync::RwLock<crate::discovery::DiscoveryMetadata>>>,
212    policy: SystemProbePolicy,
213) -> anyhow::Result<(SocketAddr, JoinHandle<()>)> {
214    // Create system status server state with the provided distributed runtime
215    let server_state = Arc::new(SystemStatusState::new(drt, discovery_metadata)?);
216    let app = build_system_status_router(server_state, policy);
217
218    let initial_bind_address = format!("{}:{}", host, port);
219    tracing::info!("[spawn_system_status_server] binding to: {initial_bind_address}");
220    let (listener, actual_address) = bind_system_status_listener(&initial_bind_address)
221        .await
222        .map_err(|error| {
223            tracing::error!("Failed to bind to address {initial_bind_address}: {error}");
224            error
225        })?;
226    tracing::info!("[spawn_system_status_server] system status server bound to: {actual_address}");
227
228    // Reuse the concrete address so an ephemeral port remains stable across rebinds.
229    let listener =
230        RebindingTcpListener::new(listener, actual_address, SYSTEM_STATUS_REBIND_BACKOFF);
231    let observer = cancel_token.child_token();
232
233    // Spawn the server in the background and return the handle
234    let handle = tokio::spawn(async move {
235        if let Err(e) = axum::serve(listener, app)
236            .with_graceful_shutdown(observer.cancelled_owned())
237            .await
238        {
239            tracing::error!("System status server error: {e}");
240        }
241    });
242
243    Ok((actual_address, handle))
244}
245
246fn build_system_status_router(
247    server_state: Arc<SystemStatusState>,
248    policy: SystemProbePolicy,
249) -> Router {
250    let system_health = server_state.drt().system_health();
251    let (health_path, live_path) = {
252        let health = system_health.lock();
253        (
254            health.health_path().to_string(),
255            health.live_path().to_string(),
256        )
257    };
258    let mut app = match policy {
259        SystemProbePolicy::Worker => Router::new()
260            .route(
261                &health_path,
262                get({
263                    let state = Arc::clone(&server_state);
264                    move || health_handler(state)
265                }),
266            )
267            .route(
268                &live_path,
269                get({
270                    let state = Arc::clone(&server_state);
271                    move || health_handler(state)
272                }),
273            ),
274        SystemProbePolicy::RuntimeOnly => Router::new()
275            .route(&live_path, get(|| async { StatusCode::OK }))
276            .route(
277                &health_path,
278                get({
279                    let state = Arc::clone(&server_state);
280                    move || runtime_health_handler(state)
281                }),
282            ),
283    };
284    // Check if LoRA feature is enabled
285    let lora_enabled =
286        crate::config::env_is_truthy(crate::config::environment_names::llm::DYN_LORA_ENABLED);
287
288    app = app
289        .route(
290            "/metrics",
291            get({
292                let state = Arc::clone(&server_state);
293                move || metrics_handler(state)
294            }),
295        )
296        .route(
297            "/metadata",
298            get({
299                let state = Arc::clone(&server_state);
300                move || metadata_handler(state)
301            }),
302        )
303        .route(
304            "/engine/{*path}",
305            any({
306                let state = Arc::clone(&server_state);
307                move |path, method, body| engine_route_handler(state, path, method, body)
308            }),
309        );
310
311    // Add LoRA routes only if DYN_LORA_ENABLED is set to true
312    if lora_enabled {
313        app = app
314            .route(
315                "/v1/loras",
316                get({
317                    let state = Arc::clone(&server_state);
318                    move || list_loras_handler(State(state))
319                })
320                .post({
321                    let state = Arc::clone(&server_state);
322                    move |body| load_lora_handler(State(state), body)
323                }),
324            )
325            .route(
326                "/v1/loras/{*lora_name}",
327                delete({
328                    let state = Arc::clone(&server_state);
329                    move |path| unload_lora_handler(State(state), path)
330                }),
331            );
332    }
333
334    // Self-hosted MDC files. Always mounted; empty registry → 404.
335    // The endpoint triple disambiguates multi-LocalModel-per-DRT; the
336    // suffix segment (LoRA slug or `_base`) scopes per-registration so
337    // detaching one doesn't wipe another's entries.
338    app.route(
339        "/v1/metadata/{namespace}/{component}/{endpoint}/{model_slug}/{model_suffix}/{*filename}",
340        get({
341            let state = Arc::clone(&server_state);
342            move |path| metadata_file_handler(State(state), path)
343        }),
344    )
345    .fallback(|uri: axum::http::Uri| async move {
346        tracing::debug!(%uri, "system status server has no route for this request");
347        (StatusCode::NOT_FOUND, "Route not found").into_response()
348    })
349    .layer(TraceLayer::new_for_http().make_span_with(crate::logging::make_system_request_span))
350}
351
352async fn bind_system_status_listener(
353    address: &str,
354) -> anyhow::Result<(TcpListener, std::net::SocketAddr)> {
355    let listener = TcpListener::bind(address)
356        .await
357        .map_err(|error| anyhow::anyhow!("Failed to bind to address: {error}"))?;
358
359    let actual_address = listener.local_addr()?;
360
361    Ok((listener, actual_address))
362}
363
364/// Axum's [`Listener::accept`] cannot return an error, so recovery must happen here.
365struct RebindingTcpListener {
366    /// Concrete address returned by the initial bind, including an assigned ephemeral port.
367    address: std::net::SocketAddr,
368    listener: Option<TcpListener>,
369    rebind_backoff: Duration,
370}
371
372impl RebindingTcpListener {
373    fn new(listener: TcpListener, address: std::net::SocketAddr, rebind_backoff: Duration) -> Self {
374        Self {
375            address,
376            listener: Some(listener),
377            rebind_backoff,
378        }
379    }
380}
381
382impl Listener for RebindingTcpListener {
383    type Io = tokio::net::TcpStream;
384    type Addr = std::net::SocketAddr;
385
386    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
387        let mut next_rebind = tokio::time::Instant::now();
388        loop {
389            let Some(listener) = self.listener.as_ref() else {
390                tokio::time::sleep_until(next_rebind).await;
391                next_rebind = tokio::time::Instant::now() + self.rebind_backoff;
392                tracing::debug!(address = %self.address, "System status server rebinding");
393                match TcpListener::bind(self.address).await {
394                    Ok(listener) => {
395                        tracing::info!(address = %self.address, "System status server rebound");
396                        self.listener = Some(listener);
397                    }
398                    Err(error) => {
399                        tracing::error!(
400                            address = %self.address,
401                            %error,
402                            retry_after = ?self.rebind_backoff,
403                            "System status server failed to rebind"
404                        );
405                    }
406                }
407                continue;
408            };
409
410            match listener.accept().await {
411                Ok(accepted) => return accepted,
412                // Connection errors do not invalidate the listener.
413                Err(error) if is_connection_error(&error) => {
414                    tracing::trace!(
415                        address = %self.address,
416                        %error,
417                        "System status connection failed before accept"
418                    );
419                }
420                // Resource exhaustion does not invalidate the listener.
421                Err(error) if is_resource_exhaustion_error(&error) => {
422                    tracing::error!(
423                        address = %self.address,
424                        %error,
425                        retry_after = ?self.rebind_backoff,
426                        "System status listener lacks resources; retrying the same socket"
427                    );
428                    tokio::time::sleep(self.rebind_backoff).await;
429                }
430                Err(error) => {
431                    tracing::error!(
432                        address = %self.address,
433                        %error,
434                        "System status listener stopped accepting; rebinding"
435                    );
436                    // Drop before rebinding or the address remains in use.
437                    self.listener = None;
438                }
439            }
440        }
441    }
442
443    fn local_addr(&self) -> io::Result<Self::Addr> {
444        Ok(self.address)
445    }
446}
447
448fn is_connection_error(error: &io::Error) -> bool {
449    if matches!(
450        error.kind(),
451        io::ErrorKind::ConnectionRefused
452            | io::ErrorKind::ConnectionAborted
453            | io::ErrorKind::ConnectionReset
454    ) {
455        return true;
456    }
457
458    // Linux accept(2) also reports pending network errors for the queued connection.
459    #[cfg(target_os = "linux")]
460    if let Some(code) = error.raw_os_error() {
461        return matches!(
462            code,
463            libc::ENETDOWN
464                | libc::EPROTO
465                | libc::ENOPROTOOPT
466                | libc::EHOSTDOWN
467                | libc::ENONET
468                | libc::EHOSTUNREACH
469                | libc::EOPNOTSUPP
470                | libc::ENETUNREACH
471        );
472    }
473
474    false
475}
476
477/// EMFILE, ENFILE, and ENOBUFS require raw errno checks because Rust has no distinct kinds.
478fn is_resource_exhaustion_error(error: &io::Error) -> bool {
479    if error.kind() == io::ErrorKind::OutOfMemory {
480        return true;
481    }
482
483    #[cfg(unix)]
484    {
485        if let Some(code) = error.raw_os_error() {
486            return matches!(code, libc::ENFILE | libc::EMFILE | libc::ENOBUFS);
487        }
488    }
489
490    false
491}
492
493/// Health handler with optional active health checking
494#[tracing::instrument(skip_all, level = "trace")]
495async fn health_handler(state: Arc<SystemStatusState>) -> impl IntoResponse {
496    // Get basic health status
497    let system_health = state.drt().system_health();
498    let system_health_lock = system_health.lock();
499    let (healthy, endpoints) = system_health_lock.get_health_status();
500    let uptime = Some(system_health_lock.uptime());
501    drop(system_health_lock);
502
503    let healthy_string = if healthy { "ready" } else { "notready" };
504    let status_code = if healthy {
505        StatusCode::OK
506    } else {
507        StatusCode::SERVICE_UNAVAILABLE
508    };
509
510    let response = json!({
511        "status": healthy_string,
512        "uptime": uptime,
513        "endpoints": endpoints,
514    });
515
516    tracing::trace!("Response {}", response.to_string());
517
518    (status_code, response.to_string())
519}
520
521/// Sidecar readiness is independent of engine health and model registration.
522async fn runtime_health_handler(state: Arc<SystemStatusState>) -> impl IntoResponse {
523    let ready = matches!(
524        tokio::time::timeout(Duration::from_secs(1), state.drt().check_dependencies()).await,
525        Ok(Ok(()))
526    );
527    let (code, status) = if ready {
528        (StatusCode::OK, "ready")
529    } else {
530        (StatusCode::SERVICE_UNAVAILABLE, "notready")
531    };
532    (code, Json(json!({ "status": status })))
533}
534
535/// Metrics handler with DistributedRuntime uptime
536#[tracing::instrument(skip_all, level = "trace")]
537async fn metrics_handler(state: Arc<SystemStatusState>) -> impl IntoResponse {
538    // Get all metrics from the DistributedRuntime.
539    // The uptime gauge is updated automatically via a PrometheusUpdateCallback
540    // registered in DistributedRuntime::new(), so it is always fresh before scrape.
541    //
542    // NOTE: We use a multi-registry model (e.g. one registry per endpoint) and merge at scrape time,
543    // so /metrics traverses registered child registries and produces a single combined output.
544    let registry = state.drt().get_metrics_registry().clone();
545    match render_scrape_at(state.last_scrape.clone(), registry, Instant::now()).await {
546        Ok(text) => (
547            StatusCode::OK,
548            [(
549                axum::http::header::CONTENT_TYPE,
550                "text/plain; charset=utf-8",
551            )],
552            text,
553        )
554            .into_response(),
555        Err(e) => {
556            tracing::error!("Failed to get metrics from registry: {e}");
557            (StatusCode::INTERNAL_SERVER_ERROR, "Failed to get metrics").into_response()
558        }
559    }
560}
561
562/// Render `/metrics` for a scrape that arrived at `requested_at`. A render
563/// that started collecting after the scrape arrived is reused; otherwise the
564/// scrape renders on the blocking pool. The owned guard moves into the
565/// closure, so a cancelled request cannot release the gate before its render
566/// finishes and let the next scrape queue inside the pool.
567async fn render_scrape_at(
568    last_scrape: Arc<tokio::sync::Mutex<LastScrape>>,
569    registry: crate::metrics::MetricsRegistry,
570    requested_at: Instant,
571) -> anyhow::Result<bytes::Bytes> {
572    let mut last = last_scrape.lock_owned().await;
573    if last.started_at.is_some_and(|at| at >= requested_at) {
574        return Ok(last.text.clone());
575    }
576    tokio::task::spawn_blocking(move || {
577        let started_at = Instant::now();
578        let text = bytes::Bytes::from(registry.prometheus_expfmt_combined()?);
579        *last = LastScrape {
580            started_at: Some(started_at),
581            text: text.clone(),
582        };
583        Ok(text)
584    })
585    .await
586    .map_err(|e| anyhow::anyhow!("metrics render task failed: {e}"))?
587}
588
589/// Metadata handler
590#[tracing::instrument(skip_all, level = "trace")]
591async fn metadata_handler(state: Arc<SystemStatusState>) -> impl IntoResponse {
592    // Check if discovery metadata is available
593    let metadata = match state.discovery_metadata() {
594        Some(metadata) => metadata,
595        None => {
596            tracing::debug!("Metadata endpoint called but no discovery metadata available");
597            return (
598                StatusCode::NOT_FOUND,
599                "Discovery metadata not available".to_string(),
600            )
601                .into_response();
602        }
603    };
604
605    // Read the metadata
606    let metadata_guard = metadata.read().await;
607
608    // Serialize to JSON
609    match serde_json::to_string(&*metadata_guard) {
610        Ok(json) => {
611            tracing::trace!("Returning metadata: {} bytes", json.len());
612            (StatusCode::OK, json).into_response()
613        }
614        Err(e) => {
615            tracing::error!("Failed to serialize metadata: {e}");
616            (
617                StatusCode::INTERNAL_SERVER_ERROR,
618                "Failed to serialize metadata".to_string(),
619            )
620                .into_response()
621        }
622    }
623}
624
625/// Handler for POST /v1/loras - Load a LoRA adapter
626#[tracing::instrument(skip_all, level = "debug")]
627async fn load_lora_handler(
628    State(state): State<Arc<SystemStatusState>>,
629    Json(request): Json<LoadLoraRequest>,
630) -> impl IntoResponse {
631    tracing::info!("Loading LoRA: {}", request.lora_name);
632
633    // Call the load_lora endpoint for each available backend
634    match call_lora_endpoint(
635        state.drt(),
636        "load_lora",
637        json!({
638            "lora_name": request.lora_name,
639            "source": {
640                "uri": request.source.uri
641            },
642        }),
643    )
644    .await
645    {
646        Ok(response) => {
647            if response.status == "error" {
648                tracing::error!(
649                    "Failed to load LoRA {}: {}",
650                    request.lora_name,
651                    response.message.as_deref().unwrap_or("Unknown error")
652                );
653                (StatusCode::INTERNAL_SERVER_ERROR, Json(response))
654            } else {
655                tracing::info!("LoRA loaded successfully: {}", request.lora_name);
656                (StatusCode::OK, Json(response))
657            }
658        }
659        Err(e) => {
660            tracing::error!("Failed to load LoRA {}: {}", request.lora_name, e);
661            (
662                StatusCode::INTERNAL_SERVER_ERROR,
663                Json(LoraResponse {
664                    status: "error".to_string(),
665                    message: Some(e.to_string()),
666                    lora_name: Some(request.lora_name),
667                    lora_id: None,
668                    loras: None,
669                    count: None,
670                }),
671            )
672        }
673    }
674}
675
676/// Handler for DELETE /v1/loras/*lora_name - Unload a LoRA adapter
677#[tracing::instrument(skip_all, level = "debug")]
678async fn unload_lora_handler(
679    State(state): State<Arc<SystemStatusState>>,
680    Path(lora_name): Path<String>,
681) -> impl IntoResponse {
682    // Strip the leading slash from the wildcard capture
683    let lora_name = lora_name
684        .strip_prefix('/')
685        .unwrap_or(&lora_name)
686        .to_string();
687    tracing::info!("Unloading LoRA: {lora_name}");
688
689    // Call the unload_lora endpoint for each available backend
690    match call_lora_endpoint(
691        state.drt(),
692        "unload_lora",
693        json!({
694            "lora_name": lora_name.clone(),
695        }),
696    )
697    .await
698    {
699        Ok(response) => {
700            if response.status == "error" {
701                tracing::error!(
702                    "Failed to unload LoRA {}: {}",
703                    lora_name,
704                    response.message.as_deref().unwrap_or("Unknown error")
705                );
706                (StatusCode::INTERNAL_SERVER_ERROR, Json(response))
707            } else {
708                tracing::info!("LoRA unloaded successfully: {lora_name}");
709                (StatusCode::OK, Json(response))
710            }
711        }
712        Err(e) => {
713            tracing::error!("Failed to unload LoRA {}: {}", lora_name, e);
714            (
715                StatusCode::INTERNAL_SERVER_ERROR,
716                Json(LoraResponse {
717                    status: "error".to_string(),
718                    message: Some(e.to_string()),
719                    lora_name: Some(lora_name),
720                    lora_id: None,
721                    loras: None,
722                    count: None,
723                }),
724            )
725        }
726    }
727}
728
729/// Handler for GET /v1/loras - List all LoRA adapters
730#[tracing::instrument(skip_all, level = "debug")]
731async fn list_loras_handler(State(state): State<Arc<SystemStatusState>>) -> impl IntoResponse {
732    tracing::info!("Listing all LoRAs");
733
734    // Call the list_loras endpoint for each available backend
735    match call_lora_endpoint(state.drt(), "list_loras", json!({})).await {
736        Ok(response) => {
737            tracing::info!("Successfully retrieved LoRA list");
738            (StatusCode::OK, Json(response))
739        }
740        Err(e) => {
741            tracing::error!("Failed to list LoRAs: {e}");
742            (
743                StatusCode::INTERNAL_SERVER_ERROR,
744                Json(LoraResponse {
745                    status: "error".to_string(),
746                    message: Some(e.to_string()),
747                    lora_name: None,
748                    lora_id: None,
749                    loras: None,
750                    count: None,
751                }),
752            )
753        }
754    }
755}
756
757/// `GET /v1/metadata/{namespace}/{component}/{endpoint}/{slug}/{suffix}/{filename}`
758/// — 404 on miss, 500 on read error, raw bytes on hit. Consumer blake3-verifies.
759async fn metadata_file_handler(
760    State(state): State<Arc<SystemStatusState>>,
761    Path((namespace, component, endpoint, model_slug, model_suffix, filename)): Path<(
762        String,
763        String,
764        String,
765        String,
766        String,
767        String,
768    )>,
769) -> impl IntoResponse {
770    let path = match state.drt().metadata_artifacts().get(
771        &namespace,
772        &component,
773        &endpoint,
774        &model_slug,
775        &model_suffix,
776        &filename,
777    ) {
778        Some(p) => p,
779        None => {
780            tracing::debug!(
781                namespace,
782                component,
783                endpoint,
784                model_slug,
785                model_suffix,
786                filename,
787                "metadata artifact not registered for self-host"
788            );
789            return (StatusCode::NOT_FOUND, "Not found").into_response();
790        }
791    };
792
793    match tokio::fs::read(&path).await {
794        Ok(bytes) => (StatusCode::OK, bytes).into_response(),
795        Err(err) => {
796            tracing::error!(
797                namespace,
798                component,
799                endpoint,
800                model_slug,
801                model_suffix,
802                filename,
803                path = %path.display(),
804                %err,
805                "failed to read self-hosted metadata file"
806            );
807            (StatusCode::INTERNAL_SERVER_ERROR, "Failed to read file").into_response()
808        }
809    }
810}
811
812/// Helper function to call a LoRA management endpoint for the local worker.
813///
814/// Resolution order (both are in-process, never network discovery):
815/// 1. The legacy local endpoint registry, populated by non-unified workers via
816///    `.register_local_engine()`.
817/// 2. The generic engine-route registry (`/engine/*`). Unified-backend workers
818///    advertise LoRA lifecycle ops (`load_lora`/`unload_lora`/`list_loras`) as
819///    engine *updates*, registered under `update/<name>`; this fallback maps the
820///    bare LoRA name onto that key so the legacy `/v1/loras` surface forwards to
821///    them (the `/v1/loras` compatibility shim).
822///
823/// Because legacy workers populate the local registry, they never reach the
824/// fallback — their `/v1/loras` behavior is unchanged. If neither registry
825/// holds the name, returns an explicit "LoRA management not available" error
826/// rather than an opaque "endpoint not found".
827async fn call_lora_endpoint(
828    drt: &crate::DistributedRuntime,
829    endpoint_name: &str,
830    request_body: serde_json::Value,
831) -> anyhow::Result<LoraResponse> {
832    use crate::engine::AsyncEngine;
833
834    tracing::debug!("Calling LoRA endpoint: '{endpoint_name}'");
835
836    // 1. Legacy local registry (in-process call only).
837    if let Some(engine) = drt.local_endpoint_registry().get(endpoint_name) {
838        tracing::debug!(
839            "Found endpoint '{}' in local registry, calling directly",
840            endpoint_name
841        );
842
843        let request = crate::pipeline::SingleIn::new(request_body);
844        let mut stream = engine.generate(request).await?;
845
846        if let Some(response) = stream.next().await {
847            let response_data = response.data.unwrap_or_default();
848            let lora_response = serde_json::from_value::<LoraResponse>(response_data.clone())
849                .unwrap_or_else(|_| parse_lora_response(&response_data));
850            return Ok(lora_response);
851        }
852
853        anyhow::bail!("No response received from endpoint '{}'", endpoint_name)
854    }
855
856    // 2. Unified-backend engine-update registry fallback. The unified Worker
857    //    registers LoRA ops as engine updates under `update/<name>`, so map the
858    //    bare LoRA endpoint name onto that namespaced key.
859    let update_key = format!("update/{endpoint_name}");
860    if let Some(callback) = drt.engine_routes().get(&update_key) {
861        tracing::debug!(
862            "Found '{}' in engine routes registry, invoking update callback",
863            update_key
864        );
865        let response_data = callback(request_body).await?;
866        let lora_response = serde_json::from_value::<LoraResponse>(response_data.clone())
867            .unwrap_or_else(|_| parse_lora_response(&response_data));
868        return Ok(lora_response);
869    }
870
871    anyhow::bail!(
872        "LoRA management not available: no '{}' handler is registered \
873         (neither a local LoRA endpoint nor an engine update). This worker \
874         either has LoRA disabled or its backend does not support LoRA \
875         management.",
876        endpoint_name
877    )
878}
879
880/// Helper to parse response data into LoraResponse
881fn parse_lora_response(response_data: &serde_json::Value) -> LoraResponse {
882    LoraResponse {
883        status: response_data
884            .get("status")
885            .and_then(|s| s.as_str())
886            .unwrap_or("success")
887            .to_string(),
888        message: response_data
889            .get("message")
890            .and_then(|m| m.as_str())
891            .map(|s| s.to_string()),
892        lora_name: response_data
893            .get("lora_name")
894            .and_then(|n| n.as_str())
895            .map(|s| s.to_string()),
896        lora_id: response_data.get("lora_id").and_then(|id| id.as_u64()),
897        loras: response_data.get("loras").cloned(),
898        count: response_data
899            .get("count")
900            .and_then(|c| c.as_u64())
901            .map(|c| c as usize),
902    }
903}
904
905/// Engine route handler for /engine/* routes
906///
907/// This handler looks up registered callbacks in the engine routes registry
908/// and invokes them with the request body, returning the response as JSON.
909#[tracing::instrument(skip_all, level = "trace", fields(path = %path))]
910async fn engine_route_handler(
911    state: Arc<SystemStatusState>,
912    Path(path): Path<String>,
913    method: axum::http::Method,
914    body: Bytes,
915) -> Response {
916    crate::engine_routes::dispatch(state.drt().engine_routes(), path, method, body).await
917}
918
919// Regular tests: cargo test system_status_server --lib
920#[cfg(test)]
921mod tests {
922    use super::*;
923    use crate::utils::ip_resolver::test_support::StubResolver;
924    use tokio::time::Duration;
925
926    /// Engine callback whose renders block until the test releases them, and
927    /// which reports each render start, so the tests never sleep-and-hope.
928    fn held_registry() -> (
929        crate::metrics::MetricsRegistry,
930        tokio::sync::mpsc::UnboundedReceiver<()>,
931        std::sync::mpsc::Sender<()>,
932    ) {
933        let registry = crate::metrics::MetricsRegistry::new();
934        let (started_tx, started_rx) = tokio::sync::mpsc::unbounded_channel();
935        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
936        let release_rx = std::sync::Mutex::new(release_rx);
937        registry.add_expfmt_callback(Arc::new(move || {
938            let _ = started_tx.send(());
939            release_rx.lock().unwrap().recv().expect("release");
940            Ok("engine_metric 1\n".to_string())
941        }));
942        (registry, started_rx, release_tx)
943    }
944
945    /// A scrape that arrives while a render is in flight waits on the runtime,
946    /// not in the blocking pool, and then renders once for every later arrival
947    /// to share; cancelling the active request does not release the gate.
948    #[test]
949    fn scrapes_queue_on_the_gate_and_share_the_next_render() {
950        let rt = tokio::runtime::Builder::new_multi_thread()
951            .worker_threads(2)
952            .max_blocking_threads(2)
953            .enable_all()
954            .build()
955            .expect("runtime");
956        rt.block_on(async {
957            let (registry, mut started, release) = held_registry();
958            let last = Arc::new(tokio::sync::Mutex::new(LastScrape::default()));
959            let scrape = |last: &Arc<tokio::sync::Mutex<LastScrape>>| {
960                let (last, registry) = (last.clone(), registry.clone());
961                tokio::spawn(async move { render_scrape_at(last, registry, Instant::now()).await })
962            };
963
964            // First scrape starts a render, then its request is cancelled.
965            let first = scrape(&last);
966            started.recv().await.expect("first render started");
967            first.abort();
968            let _ = first.await;
969
970            // Two scrapes arrive during that render. They must wait on the gate,
971            // leaving the pool's other thread free for unrelated work.
972            let second = scrape(&last);
973            let third = scrape(&last);
974            tokio::time::timeout(Duration::from_secs(5), tokio::task::spawn_blocking(|| ()))
975                .await
976                .expect("a waiting scrape occupied a blocking thread")
977                .expect("probe");
978
979            // Releasing the cancelled render lets the second scrape render; the
980            // third arrived before that render started and shares it.
981            release.send(()).unwrap();
982            started.recv().await.expect("second render started");
983            release.send(()).unwrap();
984            let second = second.await.expect("task").expect("render");
985            let third = third.await.expect("task").expect("render");
986            assert_eq!(second, third);
987            assert!(
988                std::str::from_utf8(&second)
989                    .unwrap()
990                    .contains("engine_metric 1")
991            );
992            assert!(
993                started.try_recv().is_err(),
994                "the third scrape must share the second render, not start its own"
995            );
996        });
997    }
998
999    #[test]
1000    fn advertised_address_stays_in_the_bound_family() {
1001        let mut resolver = StubResolver::not_found();
1002        resolver.interfaces = vec![
1003            ("lo", "127.0.0.1".parse().unwrap()),
1004            ("eth0", "2001:db8::20".parse().unwrap()),
1005        ];
1006
1007        let advertised = advertised_socket_addr("0.0.0.0:8080".parse().unwrap(), &resolver)
1008            .expect("wildcard advertisement should resolve");
1009
1010        assert_eq!(advertised, "127.0.0.1:8080".parse().unwrap());
1011    }
1012
1013    // This is a basic test to verify the HTTP server is working before testing other more complicated tests
1014    #[tokio::test]
1015    async fn test_http_server_lifecycle() {
1016        let cancel_token = CancellationToken::new();
1017        let cancel_token_for_server = cancel_token.clone();
1018
1019        // Test basic HTTP server lifecycle without DistributedRuntime
1020        let app = Router::new().route("/test", get(|| async { (StatusCode::OK, "test") }));
1021
1022        // start HTTP server
1023        let server_handle = tokio::spawn(async move {
1024            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1025            let _ = axum::serve(listener, app)
1026                .with_graceful_shutdown(cancel_token_for_server.cancelled_owned())
1027                .await;
1028        });
1029
1030        // server starts immediately, no need to wait
1031
1032        // cancel token
1033        cancel_token.cancel();
1034
1035        // wait for the server to shut down
1036        let result = tokio::time::timeout(Duration::from_secs(5), server_handle).await;
1037        assert!(
1038            result.is_ok(),
1039            "HTTP server should shut down when cancel token is cancelled"
1040        );
1041    }
1042
1043    #[cfg(unix)]
1044    #[tokio::test]
1045    async fn test_rebinding_listener_serves_again_after_listener_shutdown() {
1046        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1047        let address = listener.local_addr().unwrap();
1048
1049        let shutdown_result = socket2::SockRef::from(&listener).shutdown(std::net::Shutdown::Both);
1050
1051        let mut rebinding = RebindingTcpListener::new(listener, address, Duration::from_millis(10));
1052
1053        if let Err(error) = shutdown_result {
1054            eprintln!("skipping: this platform refused shutdown on a listening socket: {error}");
1055            return;
1056        }
1057
1058        let accepted = tokio::spawn(async move { rebinding.accept().await });
1059
1060        let mut accepted = accepted;
1061        let mut clients = Vec::new();
1062        let peer = tokio::time::timeout(Duration::from_secs(5), async {
1063            loop {
1064                let Ok(stream) = tokio::net::TcpStream::connect(address).await else {
1065                    tokio::time::sleep(Duration::from_millis(10)).await;
1066                    continue;
1067                };
1068                let client_addr = stream.local_addr().unwrap();
1069                clients.push((stream, client_addr));
1070                tokio::select! {
1071                    result = &mut accepted => {
1072                        let (_io, peer) = result.expect("accept task should not panic");
1073                        return peer;
1074                    }
1075                    _ = tokio::time::sleep(Duration::from_millis(50)) => {}
1076                }
1077            }
1078        })
1079        .await
1080        .expect("listener should rebind and accept connections again");
1081
1082        assert!(
1083            clients.iter().any(|(_, client_addr)| *client_addr == peer),
1084            "accepted connection should be one we opened"
1085        );
1086    }
1087
1088    #[cfg(unix)]
1089    #[tokio::test]
1090    async fn test_rebinding_listener_keeps_trying_after_a_rebind_fails() {
1091        let holder = TcpListener::bind("127.0.0.1:0").await.unwrap();
1092        let contested_address = holder.local_addr().unwrap();
1093
1094        let broken = TcpListener::bind("127.0.0.1:0").await.unwrap();
1095        let shutdown_result = socket2::SockRef::from(&broken).shutdown(std::net::Shutdown::Both);
1096
1097        let mut rebinding =
1098            RebindingTcpListener::new(broken, contested_address, Duration::from_millis(10));
1099
1100        if let Err(error) = shutdown_result {
1101            eprintln!("skipping: this platform refused shutdown on a listening socket: {error}");
1102            return;
1103        }
1104
1105        let accepted = tokio::spawn(async move { rebinding.accept().await });
1106
1107        tokio::time::sleep(Duration::from_millis(100)).await;
1108        drop(holder);
1109
1110        let client = tokio::time::timeout(Duration::from_secs(5), async {
1111            loop {
1112                if let Ok(stream) = tokio::net::TcpStream::connect(contested_address).await {
1113                    return stream;
1114                }
1115                tokio::time::sleep(Duration::from_millis(10)).await;
1116            }
1117        })
1118        .await
1119        .expect("listener should rebind once the address is free again");
1120
1121        let (_io, peer) = tokio::time::timeout(Duration::from_secs(5), accepted)
1122            .await
1123            .expect("accept should return once a later rebind succeeds")
1124            .expect("accept task should not panic");
1125
1126        assert_eq!(
1127            peer,
1128            client.local_addr().unwrap(),
1129            "accepted connection should be the one we opened"
1130        );
1131    }
1132
1133    #[cfg(unix)]
1134    #[test]
1135    fn test_resource_exhaustion_does_not_look_like_a_dead_listener() {
1136        for code in [libc::ENFILE, libc::ENOBUFS] {
1137            let error = io::Error::from_raw_os_error(code);
1138            assert!(
1139                is_resource_exhaustion_error(&error),
1140                "errno {code} should be treated as a process resource shortage, got {:?}",
1141                error.kind()
1142            );
1143            assert!(
1144                !is_connection_error(&error),
1145                "errno {code} is not a dead connection"
1146            );
1147        }
1148    }
1149
1150    #[cfg(target_os = "linux")]
1151    #[test]
1152    fn test_pending_network_errors_leave_the_listener_usable() {
1153        for code in [
1154            libc::ENETDOWN,
1155            libc::EPROTO,
1156            libc::ENOPROTOOPT,
1157            libc::EHOSTDOWN,
1158            libc::ENONET,
1159            libc::EHOSTUNREACH,
1160            libc::EOPNOTSUPP,
1161            libc::ENETUNREACH,
1162        ] {
1163            let error = io::Error::from_raw_os_error(code);
1164            assert!(
1165                is_connection_error(&error),
1166                "errno {code} should retry accept"
1167            );
1168        }
1169    }
1170
1171    #[tokio::test]
1172    async fn test_rebinding_listener_shutdown_interrupts_failed_rebinds() {
1173        let holder = TcpListener::bind("127.0.0.1:0").await.unwrap();
1174        let listener = RebindingTcpListener {
1175            address: holder.local_addr().unwrap(),
1176            listener: None,
1177            rebind_backoff: Duration::from_secs(60),
1178        };
1179        let cancel_token = CancellationToken::new();
1180        let observer = cancel_token.clone();
1181        let server = tokio::spawn(async move {
1182            axum::serve(listener, Router::new())
1183                .with_graceful_shutdown(observer.cancelled_owned())
1184                .await
1185                .unwrap();
1186        });
1187        tokio::time::sleep(Duration::from_millis(50)).await;
1188        assert!(
1189            !server.is_finished(),
1190            "server should keep retrying the held address"
1191        );
1192        cancel_token.cancel();
1193        tokio::time::timeout(Duration::from_secs(1), server)
1194            .await
1195            .expect("shutdown should interrupt the 60-second rebind backoff")
1196            .expect("server task should not panic");
1197    }
1198
1199    #[cfg(target_os = "linux")]
1200    #[tokio::test]
1201    async fn test_rebinding_listener_preserves_backlog_during_resource_exhaustion() {
1202        const CHILD_ENV: &str = "DYNAMO_TEST_LISTENER_EMFILE_CHILD";
1203        if std::env::var_os(CHILD_ENV).is_none() {
1204            // Descriptor limits are process-wide; isolate this test from sibling tests.
1205            let output = tokio::time::timeout(
1206                Duration::from_secs(15),
1207                tokio::process::Command::new(std::env::current_exe().unwrap())
1208                    .args([
1209                        "--exact",
1210                        "system_status_server::tests::test_rebinding_listener_preserves_backlog_during_resource_exhaustion",
1211                        "--nocapture",
1212                    ])
1213                    .env(CHILD_ENV, "1")
1214                    .kill_on_drop(true)
1215                    .output(),
1216            )
1217            .await
1218            .expect("descriptor-exhaustion child should finish promptly")
1219            .expect("test child should start");
1220            assert!(
1221                output.status.success(),
1222                "descriptor-exhaustion child failed:\n{}\n{}",
1223                String::from_utf8_lossy(&output.stdout),
1224                String::from_utf8_lossy(&output.stderr),
1225            );
1226            assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
1227            return;
1228        }
1229
1230        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1231        let address = listener.local_addr().unwrap();
1232        let client = tokio::net::TcpStream::connect(address).await.unwrap();
1233        let peer = client.local_addr().unwrap();
1234
1235        let mut limit = libc::rlimit {
1236            rlim_cur: 0,
1237            rlim_max: 0,
1238        };
1239        // SAFETY: limit is writable and correctly aligned. Only this child is affected.
1240        assert_eq!(
1241            unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) },
1242            0
1243        );
1244        limit.rlim_cur = limit.rlim_cur.min(96);
1245        // SAFETY: limit is initialized; the soft limit is lowered without changing the hard limit.
1246        assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);
1247
1248        let mut descriptors = Vec::new();
1249        loop {
1250            match std::fs::File::open("/dev/null") {
1251                Ok(file) => descriptors.push(file),
1252                Err(error) => {
1253                    assert_eq!(error.raw_os_error(), Some(libc::EMFILE));
1254                    break;
1255                }
1256            }
1257        }
1258        let error = listener.accept().await.unwrap_err();
1259        assert_eq!(error.raw_os_error(), Some(libc::EMFILE));
1260
1261        let backoff = Duration::from_millis(200);
1262        let mut rebinding = RebindingTcpListener::new(listener, address, backoff);
1263        let started = tokio::time::Instant::now();
1264        let accepted = rebinding.accept();
1265        tokio::pin!(accepted);
1266        assert!(
1267            tokio::time::timeout(Duration::from_millis(50), accepted.as_mut())
1268                .await
1269                .is_err(),
1270            "accept should wait during descriptor exhaustion"
1271        );
1272        drop(descriptors);
1273
1274        // A fresh bind rules out lingering descriptor pressure as the cause of AddrInUse.
1275        let _control = TcpListener::bind("127.0.0.1:0").await.unwrap();
1276        assert_eq!(
1277            TcpListener::bind(address).await.unwrap_err().kind(),
1278            io::ErrorKind::AddrInUse,
1279            "the original listening address should remain held"
1280        );
1281        let (_stream, accepted_peer) = tokio::time::timeout(Duration::from_secs(2), accepted)
1282            .await
1283            .expect("the queued connection should survive the shortage");
1284        assert!(
1285            started.elapsed() >= backoff,
1286            "accept should finish its resource-shortage backoff before retrying"
1287        );
1288        assert_eq!(accepted_peer, peer);
1289    }
1290}
1291
1292// Integration tests: cargo test system_status_server --lib --features integration
1293#[cfg(all(test, feature = "integration"))]
1294mod integration_tests {
1295    use super::*;
1296    use crate::config::environment_names::logging as env_logging;
1297    use crate::config::environment_names::runtime::canary as env_canary;
1298    use crate::distributed::distributed_test_utils::create_test_drt_async;
1299    use crate::metrics::MetricsHierarchy;
1300    use anyhow::Result;
1301    use rstest::rstest;
1302    use std::sync::Arc;
1303    use tokio::time::Duration;
1304
1305    #[tokio::test]
1306    async fn test_uptime_from_system_health() {
1307        // Test that uptime is available from SystemHealth
1308        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, None::<&str>)], async {
1309            let drt = create_test_drt_async().await;
1310
1311            // Get uptime from SystemHealth
1312            let uptime = drt.system_health().lock().uptime();
1313            // Uptime should exist (even if close to zero)
1314            assert!(uptime.as_nanos() > 0 || uptime.is_zero());
1315
1316            // Sleep briefly and check uptime increases
1317            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1318            let uptime_after = drt.system_health().lock().uptime();
1319            assert!(uptime_after > uptime);
1320        })
1321        .await;
1322    }
1323
1324    #[tokio::test]
1325    async fn test_runtime_metrics_initialization_and_namespace() {
1326        // Test that metrics have correct namespace
1327        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, None::<&str>)], async {
1328            let drt = create_test_drt_async().await;
1329            // SystemStatusState is already created in distributed.rs
1330            // so we don't need to create it again here
1331
1332            // The uptime_seconds metric should already be registered and available
1333            let response = drt.metrics().prometheus_expfmt().unwrap();
1334            println!("Full metrics response:\n{}", response);
1335
1336            // Check that uptime_seconds metric is present with correct namespace
1337            assert!(
1338                response.contains("# HELP dynamo_component_uptime_seconds"),
1339                "Should contain uptime_seconds help text"
1340            );
1341            assert!(
1342                response.contains("# TYPE dynamo_component_uptime_seconds gauge"),
1343                "Should contain uptime_seconds type"
1344            );
1345            assert!(
1346                response.contains("dynamo_component_uptime_seconds"),
1347                "Should contain uptime_seconds metric with correct namespace"
1348            );
1349        })
1350        .await;
1351    }
1352
1353    #[tokio::test]
1354    async fn test_uptime_gauge_updates() {
1355        // Test that the uptime gauge is properly updated and increases over time
1356        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, None::<&str>)], async {
1357            let drt = create_test_drt_async().await;
1358
1359            // Get initial uptime
1360            let initial_uptime = drt.system_health().lock().uptime();
1361
1362            // Update the gauge with initial value
1363            drt.system_health().lock().update_uptime_gauge();
1364
1365            // Sleep for 100ms
1366            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1367
1368            // Get uptime after sleep
1369            let uptime_after_sleep = drt.system_health().lock().uptime();
1370
1371            // Update the gauge again
1372            drt.system_health().lock().update_uptime_gauge();
1373
1374            // Verify uptime increased by at least 100ms
1375            let elapsed = uptime_after_sleep - initial_uptime;
1376            assert!(
1377                elapsed >= std::time::Duration::from_millis(100),
1378                "Uptime should have increased by at least 100ms after sleep, but only increased by {:?}",
1379                elapsed
1380            );
1381        })
1382        .await;
1383    }
1384
1385    #[tokio::test]
1386    async fn test_http_requests_fail_when_system_disabled() {
1387        // Test that system status server is not running when disabled
1388        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, None::<&str>)], async {
1389            let drt = create_test_drt_async().await;
1390
1391            // Verify that system status server info is None when disabled
1392            let system_info = drt.system_status_server_info();
1393            assert!(
1394                system_info.is_none(),
1395                "System status server should not be running when disabled"
1396            );
1397
1398            println!("✓ System status server correctly disabled when not enabled");
1399        })
1400        .await;
1401    }
1402
1403    /// This test verifies the health and liveness endpoints of the system status server.
1404    /// It checks that the endpoints respond with the correct HTTP status codes and bodies
1405    /// based on the initial health status and any custom endpoint paths provided via environment variables.
1406    /// The test is parameterized using multiple #[case] attributes to cover various scenarios,
1407    /// including different initial health states ("ready" and "notready"), default and custom endpoint paths,
1408    /// and expected response codes and bodies.
1409    #[rstest]
1410    #[case("ready", 200, "ready", None, None, 3)]
1411    #[case("notready", 503, "notready", None, None, 3)]
1412    #[case("ready", 200, "ready", Some("/custom/health"), Some("/custom/live"), 5)]
1413    #[case(
1414        "notready",
1415        503,
1416        "notready",
1417        Some("/custom/health"),
1418        Some("/custom/live"),
1419        5
1420    )]
1421    #[tokio::test]
1422    #[cfg(feature = "integration")]
1423    async fn test_health_endpoints(
1424        #[case] starting_health_status: &'static str,
1425        #[case] expected_status: u16,
1426        #[case] expected_body: &'static str,
1427        #[case] custom_health_path: Option<&'static str>,
1428        #[case] custom_live_path: Option<&'static str>,
1429        #[case] expected_num_tests: usize,
1430    ) {
1431        use std::sync::Arc;
1432        // use tokio::io::{AsyncReadExt, AsyncWriteExt};
1433        // use reqwest for HTTP requests
1434
1435        // Closure call is needed here to satisfy async_with_vars
1436
1437        crate::logging::init();
1438
1439        #[allow(clippy::redundant_closure_call)]
1440        temp_env::async_with_vars(
1441            [
1442                (env_system::DYN_SYSTEM_PORT, Some("0")),
1443                (
1444                    env_system::DYN_SYSTEM_STARTING_HEALTH_STATUS,
1445                    Some(starting_health_status),
1446                ),
1447                (env_system::DYN_SYSTEM_HEALTH_PATH, custom_health_path),
1448                (env_system::DYN_SYSTEM_LIVE_PATH, custom_live_path),
1449            ],
1450            (async || {
1451                let drt = Arc::new(create_test_drt_async().await);
1452
1453                // Get system status server info from DRT (instead of manually spawning)
1454                let system_info = drt
1455                    .system_status_server_info()
1456                    .expect("System status server should be started by DRT");
1457                let addr = system_info.socket_addr;
1458
1459                let client = reqwest::Client::new();
1460
1461                // Prepare test cases
1462                let mut test_cases = vec![];
1463                match custom_health_path {
1464                    None => {
1465                        // When using default paths, test the default paths
1466                        test_cases.push(("/health", expected_status, expected_body));
1467                    }
1468                    Some(chp) => {
1469                        // When using custom paths, default paths should not exist
1470                        test_cases.push(("/health", 404, "Route not found"));
1471                        test_cases.push((chp, expected_status, expected_body));
1472                    }
1473                }
1474                match custom_live_path {
1475                    None => {
1476                        // When using default paths, test the default paths
1477                        test_cases.push(("/live", expected_status, expected_body));
1478                    }
1479                    Some(clp) => {
1480                        // When using custom paths, default paths should not exist
1481                        test_cases.push(("/live", 404, "Route not found"));
1482                        test_cases.push((clp, expected_status, expected_body));
1483                    }
1484                }
1485                test_cases.push(("/someRandomPathNotFoundHere", 404, "Route not found"));
1486                assert_eq!(test_cases.len(), expected_num_tests);
1487
1488                for (path, expect_status, expect_body) in test_cases {
1489                    println!("[test] Sending request to {}", path);
1490                    let url = format!("http://{}{}", addr, path);
1491                    let response = client.get(&url).send().await.unwrap();
1492                    let status = response.status();
1493                    let body = response.text().await.unwrap();
1494                    println!(
1495                        "[test] Response for {}: status={}, body={:?}",
1496                        path, status, body
1497                    );
1498                    assert_eq!(
1499                        status, expect_status,
1500                        "Response: status={}, body={:?}",
1501                        status, body
1502                    );
1503                    assert!(
1504                        body.contains(expect_body),
1505                        "Response: status={}, body={:?}",
1506                        status,
1507                        body
1508                    );
1509                }
1510            })(),
1511        )
1512        .await;
1513    }
1514
1515    #[tokio::test]
1516    async fn test_health_endpoint_tracing() -> Result<()> {
1517        use std::sync::Arc;
1518
1519        // Closure call is needed here to satisfy async_with_vars
1520
1521        #[allow(clippy::redundant_closure_call)]
1522        let _ = temp_env::async_with_vars(
1523            [
1524                (env_system::DYN_SYSTEM_PORT, Some("0")),
1525                (env_system::DYN_SYSTEM_STARTING_HEALTH_STATUS, Some("ready")),
1526                (env_logging::DYN_LOGGING_JSONL, Some("1")),
1527                (env_logging::DYN_LOG, Some("trace")),
1528            ],
1529            (async || {
1530                // TODO Add proper testing for
1531                // trace id and parent id
1532
1533                crate::logging::init();
1534
1535                let drt = Arc::new(create_test_drt_async().await);
1536
1537                // Get system status server info from DRT (instead of manually spawning)
1538                let system_info = drt
1539                    .system_status_server_info()
1540                    .expect("System status server should be started by DRT");
1541                let addr = system_info.socket_addr;
1542                let client = reqwest::Client::new();
1543                for path in [("/health"), ("/live"), ("/someRandomPathNotFoundHere")] {
1544                    let traceparent_value =
1545                        "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
1546                    let tracestate_value = "vendor1=opaqueValue1,vendor2=opaqueValue2";
1547                    let mut headers = reqwest::header::HeaderMap::new();
1548                    headers.insert(
1549                        reqwest::header::HeaderName::from_static("traceparent"),
1550                        reqwest::header::HeaderValue::from_str(traceparent_value)?,
1551                    );
1552                    headers.insert(
1553                        reqwest::header::HeaderName::from_static("tracestate"),
1554                        reqwest::header::HeaderValue::from_str(tracestate_value)?,
1555                    );
1556                    let url = format!("http://{}{}", addr, path);
1557                    let response = client.get(&url).headers(headers).send().await.unwrap();
1558                    let status = response.status();
1559                    let body = response.text().await.unwrap();
1560                    tracing::info!(body = body, status = status.to_string());
1561                }
1562
1563                Ok::<(), anyhow::Error>(())
1564            })(),
1565        )
1566        .await;
1567        Ok(())
1568    }
1569
1570    #[tokio::test]
1571    async fn test_health_endpoint_with_changing_health_status() {
1572        // Test health endpoint starts in not ready status, then becomes ready
1573        // when endpoints are created (DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS=generate)
1574        const ENDPOINT_NAME: &str = "generate";
1575        const ENDPOINT_HEALTH_CONFIG: &str = "[\"generate\"]";
1576        temp_env::async_with_vars(
1577            [
1578                (env_system::DYN_SYSTEM_PORT, Some("0")),
1579                (env_system::DYN_SYSTEM_STARTING_HEALTH_STATUS, Some("notready")),
1580                (env_system::DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS, Some(ENDPOINT_HEALTH_CONFIG)),
1581            ],
1582            async {
1583                let drt = Arc::new(create_test_drt_async().await);
1584
1585                // Check if system status server was started
1586                let system_info_opt = drt.system_status_server_info();
1587
1588                // Ensure system status server was spawned by DRT
1589                assert!(
1590                    system_info_opt.is_some(),
1591                    "System status server was not spawned by DRT. Expected DRT to spawn server when DYN_SYSTEM_PORT is set to a positive value, but system_status_server_info() returned None. Environment: DYN_SYSTEM_PORT={:?}",
1592                    std::env::var(env_system::DYN_SYSTEM_PORT)
1593                );
1594
1595                // Get the system status server info from DRT - this should never fail now due to above check
1596                let system_info = system_info_opt.unwrap();
1597                let addr = system_info.socket_addr;
1598
1599                // Initially check health - should be not ready
1600                let client = reqwest::Client::new();
1601                let health_url = format!("http://{}/health", addr);
1602
1603                let response = client.get(&health_url).send().await.unwrap();
1604                let status = response.status();
1605                let body = response.text().await.unwrap();
1606
1607                // Health should be not ready (503) initially
1608                assert_eq!(status, 503, "Health should be 503 (not ready) initially, got: {}", status);
1609                assert!(body.contains("\"status\":\"notready\""), "Health should contain status notready");
1610
1611                // Now create a namespace, component, and endpoint to make the system healthy
1612                let namespace = drt.namespace("ns1234").unwrap();
1613                let component = namespace.component("comp1234").unwrap();
1614
1615                // Create a simple test handler
1616                use crate::pipeline::{async_trait, network::Ingress, AsyncEngine, AsyncEngineContextProvider, Error, ManyOut, SingleIn};
1617                use crate::protocols::annotated::Annotated;
1618
1619                struct TestHandler;
1620
1621                #[async_trait]
1622                impl AsyncEngine<SingleIn<String>, ManyOut<Annotated<String>>, anyhow::Error> for TestHandler {
1623                    async fn generate(&self, input: SingleIn<String>) -> anyhow::Result<ManyOut<Annotated<String>>> {
1624                        let (data, ctx) = input.into_parts();
1625                        let response = Annotated::from_data(format!("You responded: {}", data));
1626                        Ok(crate::pipeline::ResponseStream::new(
1627                            Box::pin(crate::stream::iter(vec![response])),
1628                            ctx.context()
1629                        ))
1630                    }
1631                }
1632
1633                // Create the ingress and start the endpoint service
1634                let ingress = Ingress::for_engine(std::sync::Arc::new(TestHandler)).unwrap();
1635
1636                // Start the service and endpoint with a health check payload
1637                // This will automatically register the endpoint for health monitoring
1638                tokio::spawn(async move {
1639                    let _ = component.endpoint(ENDPOINT_NAME)
1640                        .endpoint_builder()
1641                        .handler(ingress)
1642                        .health_check_payload(serde_json::json!({
1643                            "test": "health_check"
1644                        }))
1645                        .start()
1646                        .await;
1647                });
1648
1649                // Hit health endpoint 200 times to verify consistency
1650                let mut success_count = 0;
1651                let mut failures = Vec::new();
1652
1653                for i in 1..=200 {
1654                    let response = client.get(&health_url).send().await.unwrap();
1655                    let status = response.status();
1656                    let body = response.text().await.unwrap();
1657
1658                    if status == 200 && body.contains("\"status\":\"ready\"") {
1659                        success_count += 1;
1660                    } else {
1661                        failures.push((i, status.as_u16(), body.clone()));
1662                        if failures.len() <= 5 {  // Only log first 5 failures
1663                            tracing::warn!("Request {}: status={}, body={}", i, status, body);
1664                        }
1665                    }
1666                }
1667
1668                tracing::info!("Health endpoint test results: {success_count}/200 requests succeeded");
1669                if !failures.is_empty() {
1670                    tracing::warn!("Failed requests: {}", failures.len());
1671                }
1672
1673                // Expect at least 150 out of 200 requests to be successful
1674                assert!(success_count >= 150, "Expected at least 150 out of 200 requests to succeed, but only {} succeeded", success_count);
1675            },
1676        )
1677        .await;
1678    }
1679
1680    #[tokio::test]
1681    async fn test_spawn_system_status_server_endpoints() {
1682        // use reqwest for HTTP requests
1683        temp_env::async_with_vars(
1684            [
1685                (env_system::DYN_SYSTEM_PORT, Some("0")),
1686                (env_system::DYN_SYSTEM_STARTING_HEALTH_STATUS, Some("ready")),
1687            ],
1688            async {
1689                let drt = Arc::new(create_test_drt_async().await);
1690
1691                // Get system status server info from DRT (instead of manually spawning)
1692                let system_info = drt
1693                    .system_status_server_info()
1694                    .expect("System status server should be started by DRT");
1695                let addr = system_info.socket_addr;
1696                let client = reqwest::Client::new();
1697                for (path, expect_200, expect_body) in [
1698                    ("/health", true, "ready"),
1699                    ("/live", true, "ready"),
1700                    ("/someRandomPathNotFoundHere", false, "Route not found"),
1701                ] {
1702                    println!("[test] Sending request to {}", path);
1703                    let url = format!("http://{}{}", addr, path);
1704                    let response = client.get(&url).send().await.unwrap();
1705                    let status = response.status();
1706                    let body = response.text().await.unwrap();
1707                    println!(
1708                        "[test] Response for {}: status={}, body={:?}",
1709                        path, status, body
1710                    );
1711                    if expect_200 {
1712                        assert_eq!(status, 200, "Response: status={}, body={:?}", status, body);
1713                    } else {
1714                        assert_eq!(status, 404, "Response: status={}, body={:?}", status, body);
1715                    }
1716                    assert!(
1717                        body.contains(expect_body),
1718                        "Response: status={}, body={:?}",
1719                        status,
1720                        body
1721                    );
1722                }
1723                // DRT handles server cleanup automatically
1724            },
1725        )
1726        .await;
1727    }
1728
1729    #[tokio::test]
1730    async fn test_payloadless_endpoint_is_healthy_with_canary_enabled() {
1731        temp_env::async_with_vars(
1732            [
1733                (env_system::DYN_SYSTEM_PORT, Some("0")),
1734                (
1735                    env_system::DYN_SYSTEM_STARTING_HEALTH_STATUS,
1736                    Some("notready"),
1737                ),
1738                ("DYN_HEALTH_CHECK_ENABLED", Some("true")),
1739            ],
1740            async {
1741                let runtime = crate::Runtime::from_current().unwrap();
1742                let drt = Arc::new(
1743                    crate::DistributedRuntime::new(
1744                        runtime,
1745                        crate::distributed::DistributedConfig::process_local(),
1746                    )
1747                    .await
1748                    .unwrap(),
1749                );
1750                let addr = drt
1751                    .system_status_server_info()
1752                    .expect("System status server should be started")
1753                    .socket_addr;
1754
1755                use crate::pipeline::{
1756                    AsyncEngine, AsyncEngineContextProvider, Error, ManyOut, SingleIn, async_trait,
1757                    network::Ingress,
1758                };
1759                use crate::protocols::annotated::Annotated;
1760
1761                struct PayloadlessHandler;
1762
1763                #[async_trait]
1764                impl AsyncEngine<SingleIn<String>, ManyOut<Annotated<String>>, anyhow::Error>
1765                    for PayloadlessHandler
1766                {
1767                    async fn generate(
1768                        &self,
1769                        input: SingleIn<String>,
1770                    ) -> anyhow::Result<ManyOut<Annotated<String>>> {
1771                        let (data, ctx) = input.into_parts();
1772                        Ok(crate::pipeline::ResponseStream::new(
1773                            Box::pin(crate::stream::iter(vec![Annotated::from_data(data)])),
1774                            ctx.context(),
1775                        ))
1776                    }
1777                }
1778
1779                let namespace = drt.namespace("test").unwrap();
1780                let component = namespace.component("backend").unwrap();
1781                let ingress = Ingress::for_engine(Arc::new(PayloadlessHandler)).unwrap();
1782                tokio::spawn(async move {
1783                    // Unified decode workers deliberately follow this path: the
1784                    // endpoint is registered without a canary payload.
1785                    let _ = component
1786                        .endpoint("generate")
1787                        .endpoint_builder()
1788                        .handler(ingress)
1789                        .start()
1790                        .await;
1791                });
1792
1793                let client = reqwest::Client::new();
1794                for path in ["/health", "/live"] {
1795                    let url = format!("http://{addr}{path}");
1796                    let mut last_response = None;
1797                    for _ in 0..50 {
1798                        let response = client.get(&url).send().await.unwrap();
1799                        let status = response.status();
1800                        let body = response.text().await.unwrap();
1801                        if status == 200 && body.contains("\"status\":\"ready\"") {
1802                            last_response = Some((status, body));
1803                            break;
1804                        }
1805                        last_response = Some((status, body));
1806                        tokio::time::sleep(Duration::from_millis(20)).await;
1807                    }
1808                    let (status, body) = last_response.unwrap();
1809                    assert_eq!(status, 200, "{path} response: {body}");
1810                    assert!(
1811                        body.contains("\"status\":\"ready\""),
1812                        "{path} response: {body}"
1813                    );
1814                }
1815            },
1816        )
1817        .await;
1818    }
1819
1820    #[cfg(feature = "integration")]
1821    #[tokio::test]
1822    async fn test_health_check_with_payload_and_timeout() {
1823        // Test the complete health check flow with the new canary-based system:
1824        crate::logging::init();
1825
1826        temp_env::async_with_vars(
1827            [
1828                (env_system::DYN_SYSTEM_PORT, Some("0")),
1829                (
1830                    env_system::DYN_SYSTEM_STARTING_HEALTH_STATUS,
1831                    Some("notready"),
1832                ),
1833                (
1834                    env_system::DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS,
1835                    Some("[\"test.endpoint\"]"),
1836                ),
1837                // Enable health check with short intervals for testing
1838                ("DYN_HEALTH_CHECK_ENABLED", Some("true")),
1839                (env_canary::DYN_CANARY_WAIT_TIME, Some("1")), // Send canary after 1 second of inactivity
1840                ("DYN_HEALTH_CHECK_REQUEST_TIMEOUT", Some("1")), // Immediately timeout to mimic unresponsiveness
1841                ("RUST_LOG", Some("info")),                      // Enable logging for test
1842            ],
1843            async {
1844                let drt = Arc::new(create_test_drt_async().await);
1845
1846                // Get system status server info
1847                let system_info = drt
1848                    .system_status_server_info()
1849                    .expect("System status server should be started");
1850                let addr = system_info.socket_addr;
1851
1852                let client = reqwest::Client::new();
1853                let health_url = format!("http://{}/health", addr);
1854
1855                // Register an endpoint with health check payload
1856                let endpoint = "test.endpoint";
1857                let health_check_payload = serde_json::json!({
1858                    "prompt": "health check test",
1859                    "_health_check": true
1860                });
1861
1862                // Register the endpoint and its health check payload
1863                {
1864                    let system_health = drt.system_health();
1865                    let system_health_lock = system_health.lock();
1866                    system_health_lock.register_health_check_target(
1867                        endpoint,
1868                        crate::component::Instance {
1869                            component: "test_component".to_string(),
1870                            endpoint: "health".to_string(),
1871                            namespace: "test_namespace".to_string(),
1872                            instance_id: 1,
1873                            transport: crate::component::TransportType::Nats(endpoint.to_string()),
1874                            device_type: None,
1875                            request_plane_codec: None,
1876                        },
1877                        health_check_payload.clone(),
1878                    );
1879                }
1880
1881                // Check initial health - should be ready (default state)
1882                let response = client.get(&health_url).send().await.unwrap();
1883                let status = response.status();
1884                let body = response.text().await.unwrap();
1885                assert_eq!(status, 503, "Should be unhealthy initially (default state)");
1886                assert!(
1887                    body.contains("\"status\":\"notready\""),
1888                    "Should show notready status initially"
1889                );
1890
1891                // Set endpoint to healthy state
1892                drt.system_health()
1893                    .lock()
1894                    .set_endpoint_health_status(endpoint, HealthStatus::Ready);
1895
1896                // Check health again - should now be healthy
1897                let response = client.get(&health_url).send().await.unwrap();
1898                let status = response.status();
1899                let body = response.text().await.unwrap();
1900
1901                assert_eq!(status, 200, "Should be healthy due to recent response");
1902                assert!(
1903                    body.contains("\"status\":\"ready\""),
1904                    "Should show ready status after response"
1905                );
1906
1907                // Verify the endpoint status in SystemHealth directly
1908                let endpoint_status = drt
1909                    .system_health()
1910                    .lock()
1911                    .get_endpoint_health_status(endpoint);
1912                assert_eq!(
1913                    endpoint_status,
1914                    Some(HealthStatus::Ready),
1915                    "SystemHealth should show endpoint as Ready after response"
1916                );
1917            },
1918        )
1919        .await;
1920    }
1921
1922    /// `/v1/loras` compat shim: with the legacy local registry empty, a LoRA
1923    /// update registered in `engine_routes()` under `update/<name>` resolves via
1924    /// the fallback and its JSON response is parsed into a `LoraResponse`. This
1925    /// is the path unified-backend workers take for `/v1/loras`.
1926    #[tokio::test]
1927    async fn test_call_lora_endpoint_resolves_via_engine_routes() {
1928        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, None::<&str>)], async {
1929            let drt = create_test_drt_async().await;
1930
1931            let callback: crate::engine_routes::EngineRouteCallback = Arc::new(|_body| {
1932                Box::pin(async move {
1933                    Ok(serde_json::json!({
1934                        "status": "success",
1935                        "lora_name": "adapterA",
1936                        "lora_id": 42,
1937                    }))
1938                })
1939            });
1940            // Unified Worker registers LoRA ops under the `update/` namespace.
1941            drt.engine_routes().register("update/load_lora", callback);
1942
1943            // Local registry is empty, so resolution must fall through to
1944            // engine_routes.
1945            assert!(drt.local_endpoint_registry().get("load_lora").is_none());
1946
1947            let response = call_lora_endpoint(
1948                &drt,
1949                "load_lora",
1950                serde_json::json!({"lora_name": "adapterA"}),
1951            )
1952            .await
1953            .expect("engine_routes fallback should resolve the control");
1954
1955            assert_eq!(response.status, "success");
1956            assert_eq!(response.lora_name.as_deref(), Some("adapterA"));
1957            assert_eq!(response.lora_id, Some(42));
1958        })
1959        .await;
1960    }
1961
1962    /// When neither the local registry nor `engine_routes()` holds the name,
1963    /// the caller gets an explicit "LoRA management not available" error
1964    /// rather than an opaque "endpoint not found".
1965    #[tokio::test]
1966    async fn test_call_lora_endpoint_missing_returns_clean_error() {
1967        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, None::<&str>)], async {
1968            let drt = create_test_drt_async().await;
1969
1970            let err = call_lora_endpoint(&drt, "load_lora", serde_json::json!({}))
1971                .await
1972                .expect_err("missing handler must error");
1973
1974            assert!(
1975                err.to_string().contains("LoRA management not available"),
1976                "expected explicit unavailable message, got: {err}"
1977            );
1978        })
1979        .await;
1980    }
1981
1982    /// An update callback that returns `{"status":"error",...}` (rather than
1983    /// raising) surfaces as a `LoraResponse{status:"error"}`. The `/v1/loras`
1984    /// load/unload handlers map this to HTTP 500, preserving legacy semantics;
1985    /// the direct `/engine/*` route would instead return HTTP 200 + this JSON.
1986    #[tokio::test]
1987    async fn test_call_lora_endpoint_propagates_error_status() {
1988        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, None::<&str>)], async {
1989            let drt = create_test_drt_async().await;
1990
1991            let callback: crate::engine_routes::EngineRouteCallback = Arc::new(|_body| {
1992                Box::pin(async move {
1993                    Ok(serde_json::json!({
1994                        "status": "error",
1995                        "message": "adapter not found",
1996                    }))
1997                })
1998            });
1999            // Unified Worker registers LoRA ops under the `update/` namespace.
2000            drt.engine_routes().register("update/unload_lora", callback);
2001
2002            let response = call_lora_endpoint(&drt, "unload_lora", serde_json::json!({}))
2003                .await
2004                .expect("a non-raising callback returns Ok even on logical error");
2005
2006            assert_eq!(response.status, "error");
2007            assert_eq!(response.message.as_deref(), Some("adapter not found"));
2008        })
2009        .await;
2010    }
2011}