Skip to main content

dynamo_runtime/pipeline/network/egress/
push_router.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use super::{AsyncEngineContextProvider, ResponseStream};
5use crate::error::{BackendError, DynamoError, ErrorType, match_error_chain};
6use crate::pipeline::network::egress::route_span::{
7    get_route_trace_context, record_route_error, record_route_span_start, wrap_route_span,
8};
9use crate::{
10    component::{Client, DeviceType, Endpoint, Instance, RoutingInstances},
11    discovery::EndpointInstanceId,
12    dynamo_nvtx_range,
13    engine::{AsyncEngine, AsyncEngineContext, Data},
14    metrics::frontend_perf::{STAGE_DURATION_SECONDS, STAGE_ROUTE},
15    pipeline::{
16        AddressedPushRouter, AddressedRequest, Error, ManyIn, ManyOut, SingleIn, StreamingDispatch,
17        error::{PipelineError, PipelineErrorExt},
18    },
19    protocols::{EndpointId, maybe_error::MaybeError},
20    routing_policy::{
21        InstanceSelector, ModeSelectors, OccupancyReservation, RouteCandidate, RouteContext,
22        RouteDevice, RouteTarget, RoutingOccupancyState, get_or_create_routing_occupancy_state,
23    },
24    traits::DistributedRuntimeProvider,
25};
26use async_trait::async_trait;
27use futures::Stream;
28use serde::{Deserialize, Serialize};
29use std::{
30    collections::{HashMap, HashSet},
31    marker::PhantomData,
32    pin::Pin,
33    sync::{Arc, atomic::AtomicU64},
34    task::Poll,
35    time::Instant,
36};
37use tokio_stream::StreamExt;
38use tracing::Instrument;
39
40/// The stable reason of a worker's overload refusal.
41///
42/// Across the request plane a refusal keeps its semantic class and reason but
43/// decodes with the legacy type `ResourceExhausted`, which it shares with
44/// pool-wide exhaustion (`capacity.pool_exhausted`), so the reason, not the
45/// legacy type, identifies a worker-scoped overload.
46const WORKER_OVERLOADED_REASON: &str = "capacity.worker_overloaded";
47
48/// A worker's overload refusal, wherever it appears in an error chain.
49///
50/// A worker refusing a request it has no capacity for is backpressure from a
51/// healthy worker. The refusal reaches the router as the cause of a pre-stream
52/// `CannotConnect`, so only a walk of the whole chain finds it.
53fn worker_overload<'a>(err: &'a (dyn std::error::Error + 'static)) -> Option<&'a DynamoError> {
54    let mut current = Some(err);
55    while let Some(error) = current {
56        if let Some(error) = error.downcast_ref::<DynamoError>()
57            && error.class() == ErrorType::CapacityExhausted
58            && error.reason().as_str() == WORKER_OVERLOADED_REASON
59        {
60            return Some(error);
61        }
62        current = error.source();
63    }
64    None
65}
66
67/// Whether a worker's overload appears anywhere in an error chain: see
68/// [`worker_overload`].
69fn is_worker_overloaded(err: &(dyn std::error::Error + 'static)) -> bool {
70    worker_overload(err).is_some()
71}
72
73/// Check if an error chain indicates the worker should be reported as down.
74///
75/// Never for a chain that carries a worker's overload, whatever wraps it: see
76/// [`is_worker_overloaded`].
77fn is_inhibited(err: &(dyn std::error::Error + 'static)) -> bool {
78    const INHIBITED: &[ErrorType] = &[
79        ErrorType::CannotConnect,
80        ErrorType::Disconnected,
81        ErrorType::ConnectionTimeout,
82        ErrorType::ResponseTimeout,
83        ErrorType::Backend(BackendError::EngineShutdown),
84        // A stream that ends mid-generation means this worker dropped the
85        // request. Quarantine it, or a migration retry can reselect the same
86        // worker before discovery removal catches up.
87        ErrorType::Backend(BackendError::StreamIncomplete),
88        // The addressed server has no handler for this instance: discovery is
89        // stale or the worker is shutting down. Same reasoning as above.
90        ErrorType::WorkerUnavailable,
91    ];
92    // Pre-stream request rejections can carry an outer CannotConnect wrapper.
93    // A `Conflict` is a worker refusing a request id it is still serving.
94    !is_worker_overloaded(err)
95        && match_error_chain(
96            err,
97            INHIBITED,
98            &[
99                ErrorType::InvalidRequest,
100                ErrorType::InvalidArgument,
101                ErrorType::Backend(BackendError::InvalidArgument),
102                ErrorType::Conflict,
103            ],
104        )
105}
106
107/// Read the backend response inactivity timeout from the environment.
108/// Reuses `DYN_HTTP_BACKEND_STREAM_TIMEOUT_SECS` — the same env var
109/// as the HTTP-layer safety net in `disconnect.rs`.
110fn response_inactivity_timeout() -> Option<std::time::Duration> {
111    use crate::config::environment_names::llm::DYN_HTTP_BACKEND_STREAM_TIMEOUT_SECS;
112    std::env::var(DYN_HTTP_BACKEND_STREAM_TIMEOUT_SECS)
113        .ok()
114        .and_then(|s| s.parse::<u64>().ok())
115        .filter(|&secs| secs > 0)
116        .map(std::time::Duration::from_secs)
117}
118
119/// Read the response-stream establish timeout from the environment.
120fn response_stream_establish_timeout() -> Option<std::time::Duration> {
121    use crate::config::environment_names::response_plane::DYN_RESPONSE_STREAM_ESTABLISH_TIMEOUT_SECS;
122    std::env::var(DYN_RESPONSE_STREAM_ESTABLISH_TIMEOUT_SECS)
123        .ok()
124        .and_then(|s| s.parse::<u64>().ok())
125        .filter(|&secs| secs > 0)
126        .map(std::time::Duration::from_secs)
127}
128
129/// RAII handle for one in-flight unit of work charged against
130/// [`RoutingOccupancyState`]. The counter is incremented at construction; the
131/// matching decrement is emitted on drop (or by [`Self::into_tracked_stream`]).
132struct OccupancyPermit {
133    reservation: Option<OccupancyReservation>,
134}
135
136impl OccupancyPermit {
137    fn acquire(state: Arc<RoutingOccupancyState>, instance_id: u64) -> Self {
138        Self {
139            reservation: Some(state.reserve(instance_id)),
140        }
141    }
142
143    fn from_counter(
144        state: Arc<RoutingOccupancyState>,
145        instance_id: u64,
146        counter: Arc<AtomicU64>,
147    ) -> Self {
148        Self {
149            reservation: Some(OccupancyReservation::from_counter(
150                state,
151                instance_id,
152                counter,
153            )),
154        }
155    }
156
157    fn from_reservation(reservation: OccupancyReservation) -> Self {
158        Self {
159            reservation: Some(reservation),
160        }
161    }
162
163    fn retarget(&mut self, instance_id: u64) {
164        self.reservation
165            .as_mut()
166            .expect("occupancy permit must be armed before stream tracking")
167            .retarget(instance_id);
168    }
169
170    fn into_tracked_stream<U: Data + MaybeError>(mut self, stream: ManyOut<U>) -> ManyOut<U> {
171        let engine_ctx = stream.context();
172        ResponseStream::new(
173            Box::pin(OccupancyTrackedStream {
174                inner: stream,
175                reservation: self.reservation.take(),
176            }),
177            engine_ctx,
178        )
179    }
180}
181
182/// Trait for monitoring worker load and determining overload state.
183/// Implementations can define custom load metrics and overload thresholds.
184#[async_trait]
185pub trait WorkerLoadMonitor: Send + Sync {
186    /// Start background monitoring of worker load.
187    /// This should spawn background tasks that update the client's overloaded instances.
188    async fn start_monitoring(&self) -> anyhow::Result<()>;
189}
190
191/// Query interface for routing against multimodal embedding cache state.
192pub trait MultimodalCacheIndex: Send + Sync {
193    fn workers_with_cache_key_hits(&self, cache_keys: &[String]) -> Vec<(u64, usize)>;
194    fn remove_worker(&self, worker_id: u64);
195}
196
197pub type MultimodalCacheKeyExtractor<T> = Arc<dyn Fn(&T) -> Vec<String> + Send + Sync>;
198
199#[derive(Clone)]
200pub struct PushRouter<T, U>
201where
202    T: Data + Serialize,
203    U: Data + for<'de> Deserialize<'de>,
204{
205    // TODO: This shouldn't be pub, but lib/bindings/python/rust/lib.rs exposes it.
206    /// The Client is how we gather remote endpoint information from etcd.
207    pub client: Client,
208
209    /// How we choose which instance to send traffic to.
210    ///
211    /// Setting this to KV means we never intend to call `generate` on this PushRouter. We are
212    /// not using it as an AsyncEngine.
213    /// Instead we will decide whether to call random/round_robin/direct ourselves and call them directly.
214    /// dynamo-llm's KV Routing does this.
215    router_mode: RouterMode,
216
217    /// Instance selectors for the modes this router picks by: the configured mode, plus
218    /// round-robin and random, which [`Self::round_robin`] and [`Self::random`] use whatever
219    /// the mode. Resolved once at construction from [`PushRouterOptions::selectors`].
220    selectors: Vec<(RouterMode, Arc<dyn InstanceSelector>)>,
221
222    /// The final hop: after selecting an instance, `PushRouter` hands it to this
223    /// `StreamingDispatch` (the request-plane `AddressedPushRouter` by default).
224    /// A trait object so an alternate transport can swap it out.
225    addressed: Arc<dyn StreamingDispatch<T, U>>,
226
227    /// When false, `generate_with_fault_detection` skips fault detection logic:
228    /// it won't call `report_instance_down` on errors, and it uses the raw discovery
229    /// instance list instead of the filtered avail list. Use for recovery/query paths
230    /// where transient failures are expected.
231    fault_detection_enabled: bool,
232
233    /// Cached response inactivity timeout. Read once at construction from
234    /// [`environment_names::llm::DYN_HTTP_BACKEND_STREAM_TIMEOUT_SECS`](crate::config::environment_names::llm::DYN_HTTP_BACKEND_STREAM_TIMEOUT_SECS) to avoid a syscall per request.
235    response_timeout: Option<std::time::Duration>,
236
237    /// Cached bound on the wait for a worker's response stream after the worker
238    /// ACKs a unary request. Read once at construction from
239    /// [`environment_names::response_plane::DYN_RESPONSE_STREAM_ESTABLISH_TIMEOUT_SECS`](crate::config::environment_names::response_plane::DYN_RESPONSE_STREAM_ESTABLISH_TIMEOUT_SECS).
240    /// Applied only when fault detection is enabled.
241    establish_timeout: Option<std::time::Duration>,
242
243    /// Shared request occupancy state, present when the mode or a selector reads in-flight counts.
244    occupancy_state: Option<Arc<RoutingOccupancyState>>,
245
246    /// Optional cache index for direct multimodal embedding cache lookups.
247    /// Currently consumed by `RouterMode::DeviceAwareWeighted`.
248    multimodal_cache_indexer: Option<Arc<dyn MultimodalCacheIndex>>,
249
250    /// Optional typed request extractor for multimodal embedding cache keys.
251    multimodal_cache_key_extractor: Option<MultimodalCacheKeyExtractor<T>>,
252
253    /// An internal Rust type. This says that PushRouter is generic over the T and U types,
254    /// which are the input and output types of it's `generate` function. It allows the
255    /// compiler to specialize us at compile time.
256    _phantom: PhantomData<(T, U)>,
257}
258
259#[derive(Default, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
260#[serde(rename_all = "snake_case")]
261pub enum RouterMode {
262    #[default]
263    RoundRobin,
264    Random,
265    /// `--router-mode power-of-two`, removed in v1.7. Cards from v1.5 and v1.6 workers can still
266    /// carry it, so it stays decodable; building a router with it fails.
267    // TODO(v1.9): Remove when v1.6 falls outside the N-2 compatibility window.
268    PowerOfTwoChoices,
269    KV,
270    Direct,
271    LeastLoaded,
272    /// Device-aware weighted routing for heterogeneous workers.
273    DeviceAwareWeighted,
274}
275
276#[derive(Clone, Copy)]
277enum TransportFallback<'a> {
278    Allow,
279    Deny,
280    Within(&'a HashSet<u64>),
281}
282
283#[derive(Clone, Copy)]
284enum OverloadCheck {
285    Required,
286    AlreadyAdmitted,
287}
288
289struct DeviceAwareCandidates {
290    candidates: Vec<RouteCandidate>,
291    context: RouteContext,
292    embedding_cache_hit: bool,
293    request_cache_keys: usize,
294}
295
296/// A DeviceAware policy decision whose optional occupancy booking is owned by
297/// the caller's request lifecycle.
298pub struct DeviceAwareSelection {
299    worker_id: u64,
300    candidate_count: usize,
301    load: u64,
302    is_cpu: bool,
303    embedding_cache_hit: bool,
304    request_cache_keys: usize,
305    reservation: Option<OccupancyReservation>,
306}
307
308impl DeviceAwareSelection {
309    pub fn worker_id(&self) -> u64 {
310        self.worker_id
311    }
312
313    pub fn candidate_count(&self) -> usize {
314        self.candidate_count
315    }
316
317    pub fn load(&self) -> u64 {
318        self.load
319    }
320
321    pub fn is_cpu(&self) -> bool {
322        self.is_cpu
323    }
324
325    pub fn embedding_cache_hit(&self) -> bool {
326        self.embedding_cache_hit
327    }
328
329    pub fn request_cache_keys(&self) -> usize {
330        self.request_cache_keys
331    }
332
333    pub fn into_reservation(self) -> Option<OccupancyReservation> {
334        self.reservation
335    }
336}
337
338impl RouterMode {
339    pub const fn telemetry_label(self) -> &'static str {
340        match self {
341            Self::RoundRobin => "round-robin",
342            Self::Random => "random",
343            Self::PowerOfTwoChoices => "power-of-two-choices",
344            Self::KV => "kv",
345            Self::Direct => "direct",
346            Self::LeastLoaded => "least-loaded",
347            Self::DeviceAwareWeighted => "device-aware-weighted",
348        }
349    }
350
351    pub fn is_kv_routing(&self) -> bool {
352        *self == RouterMode::KV
353    }
354
355    pub fn is_direct_routing(&self) -> bool {
356        *self == RouterMode::Direct
357    }
358
359    /// Whether this mode admits requests against host-owned occupancy counters.
360    pub const fn requires_occupancy(self) -> bool {
361        matches!(self, Self::LeastLoaded | Self::DeviceAwareWeighted)
362    }
363
364    /// Whether this mode picks with an [`InstanceSelector`] passed in
365    /// [`PushRouterOptions::selectors`].
366    pub const fn picks_with_selector(self) -> bool {
367        matches!(self, Self::RoundRobin | Self::Random | Self::LeastLoaded)
368    }
369}
370
371/// The selectors a router keeps: its configured mode's, required when that mode picks with
372/// one, and round-robin's and random's when the caller provides them.
373fn resolve_selectors(
374    router_mode: RouterMode,
375    selectors: Option<&ModeSelectors>,
376) -> anyhow::Result<Vec<(RouterMode, Arc<dyn InstanceSelector>)>> {
377    // TODO(v1.9): Remove with the `PowerOfTwoChoices` wire value.
378    anyhow::ensure!(
379        router_mode != RouterMode::PowerOfTwoChoices,
380        "the power-of-two router mode was removed in Dynamo v1.7; use another router mode"
381    );
382    let Some(selectors) = selectors else {
383        anyhow::ensure!(
384            !router_mode.picks_with_selector(),
385            "{router_mode:?} routing needs instance selectors; pass PushRouterOptions::selectors"
386        );
387        return Ok(Vec::new());
388    };
389    let mut resolved = Vec::with_capacity(3);
390    if router_mode.picks_with_selector() {
391        let selector = selectors(router_mode)
392            .ok_or_else(|| anyhow::anyhow!("no instance selector for {router_mode:?} routing"))?;
393        resolved.push((router_mode, selector));
394    }
395    for mode in [RouterMode::RoundRobin, RouterMode::Random] {
396        if mode != router_mode
397            && let Some(selector) = selectors(mode)
398        {
399            resolved.push((mode, selector));
400        }
401    }
402    Ok(resolved)
403}
404
405/// One instance picked by an [`InstanceSelector`], booked when the selector reads load.
406struct SelectedInstance {
407    instance_id: u64,
408    candidate_count: usize,
409    load: Option<u64>,
410    permit: Option<OccupancyPermit>,
411}
412
413/// At most one `list_and_watch` per endpoint, across all `PushRouter`
414/// instances. Entry removed on watcher exit so a later router can re-arm.
415static ENDPOINT_WATCHER_ACTIVE: std::sync::OnceLock<dashmap::DashMap<EndpointId, ()>> =
416    std::sync::OnceLock::new();
417
418#[derive(Clone, Debug, Eq, Hash, PartialEq)]
419struct RuntimeEndpointId {
420    connection_id: u64,
421    endpoint_id: EndpointId,
422}
423
424impl RuntimeEndpointId {
425    fn for_endpoint(endpoint: &Endpoint) -> Self {
426        Self {
427            connection_id: endpoint.drt().connection_id(),
428            endpoint_id: endpoint.id(),
429        }
430    }
431}
432
433/// At most one multimodal cache cleanup watcher per runtime endpoint.
434static ENDPOINT_CACHE_INDEXER_WATCHER_ACTIVE: std::sync::OnceLock<
435    dashmap::DashMap<RuntimeEndpointId, ()>,
436> = std::sync::OnceLock::new();
437
438/// Watch discovery for instance removals and cancel pending response-stream
439/// registrations on the removed instance, unblocking queued requests with
440/// a migratable `Disconnected` error. Uses raw `list_and_watch` events
441/// (not a coalesced snapshot diff) so a rapid remove→re-add of the same
442/// identity is not silently swallowed. Keyed by full `EndpointInstanceId`.
443fn spawn_instance_removal_watcher<T, U>(
444    endpoint: Endpoint,
445    dispatch: Arc<dyn StreamingDispatch<T, U>>,
446    cancel_token: tokio_util::sync::CancellationToken,
447) where
448    T: Data + Serialize + 'static,
449    U: Data + for<'de> Deserialize<'de> + MaybeError + 'static,
450{
451    use crate::discovery::{
452        DiscoveryEvent, DiscoveryInstance, DiscoveryInstanceId, DiscoveryQuery,
453    };
454    use tokio_stream::StreamExt as _;
455
456    // One watcher per endpoint: if one is already running, skip.
457    let guard = ENDPOINT_WATCHER_ACTIVE.get_or_init(dashmap::DashMap::new);
458    let endpoint_id = endpoint.id();
459    if guard.insert(endpoint_id.clone(), ()).is_some() {
460        tracing::debug!(
461            ?endpoint_id,
462            "Instance removal watcher already running for this endpoint, skipping"
463        );
464        return;
465    }
466
467    let endpoint_name = endpoint.name().to_string();
468
469    tokio::spawn(async move {
470        // Release on every exit path (including panic); a leaked entry
471        // silently disables removal cancellation until process restart.
472        struct GuardRelease(EndpointId);
473        impl Drop for GuardRelease {
474            fn drop(&mut self) {
475                if let Some(map) = ENDPOINT_WATCHER_ACTIVE.get() {
476                    map.remove(&self.0);
477                }
478            }
479        }
480        let _release = GuardRelease(endpoint_id);
481
482        let namespace = endpoint.component().namespace().name();
483        let component = endpoint.component().name().to_string();
484
485        // Reconnect on transient discovery failure; cancel-aware backoff.
486        const RECONNECT_BACKOFF: std::time::Duration = std::time::Duration::from_secs(5);
487        'reconnect: loop {
488            let query = DiscoveryQuery::Endpoint {
489                namespace: namespace.clone(),
490                component: component.clone(),
491                endpoint: endpoint_name.clone(),
492            };
493
494            let mut stream = match endpoint.drt().discovery().list_and_watch(query, None).await {
495                Ok(s) => s,
496                Err(e) => {
497                    tracing::warn!(
498                        endpoint = %endpoint_name,
499                        "Failed to start instance removal watcher (will retry): {e}"
500                    );
501                    tokio::select! {
502                        _ = tokio::time::sleep(RECONNECT_BACKOFF) => continue 'reconnect,
503                        _ = cancel_token.cancelled() => break 'reconnect,
504                    }
505                }
506            };
507
508            loop {
509                tokio::select! {
510                    event = stream.next() => {
511                        match event {
512                            Some(Ok(DiscoveryEvent::Removed(id))) => {
513                                if let DiscoveryInstanceId::Endpoint(eid) = &id {
514                                    dispatch.on_instance_removed(eid).await;
515                                }
516                            }
517                            Some(Ok(DiscoveryEvent::Added(DiscoveryInstance::Endpoint(inst)))) => {
518                                let eid: EndpointInstanceId = inst.endpoint_instance_id();
519                                dispatch.on_instance_added(&eid).await;
520                            }
521                            Some(Ok(DiscoveryEvent::Added(_)))
522                            | Some(Ok(DiscoveryEvent::ModelTaintsUpdated(_)))
523                            | Some(Ok(DiscoveryEvent::Resync(_))) => {}
524                            Some(Err(e)) => {
525                                tracing::warn!(
526                                    endpoint = %endpoint_name,
527                                    "Instance removal watcher stream error: {e}"
528                                );
529                            }
530                            None => {
531                                tracing::warn!(
532                                    endpoint = %endpoint_name,
533                                    "Instance removal watcher stream ended; reconnecting"
534                                );
535                                continue 'reconnect;
536                            }
537                        }
538                    }
539                    _ = cancel_token.cancelled() => {
540                        break 'reconnect;
541                    }
542                }
543            }
544        }
545
546        tracing::debug!(endpoint = %endpoint_name, "Instance removal watcher exiting");
547    });
548}
549
550/// Watch discovery removals for cache-aware routers and drop stale worker cache entries.
551fn spawn_multimodal_cache_cleanup_watcher(
552    endpoint: Endpoint,
553    indexer: Arc<dyn MultimodalCacheIndex>,
554    cancel_token: tokio_util::sync::CancellationToken,
555) {
556    use crate::discovery::{DiscoveryEvent, DiscoveryInstanceId, DiscoveryQuery};
557    use tokio_stream::StreamExt as _;
558
559    let guard = ENDPOINT_CACHE_INDEXER_WATCHER_ACTIVE.get_or_init(dashmap::DashMap::new);
560    let watcher_id = RuntimeEndpointId::for_endpoint(&endpoint);
561    if guard.insert(watcher_id.clone(), ()).is_some() {
562        tracing::debug!(
563            connection_id = watcher_id.connection_id,
564            ?watcher_id.endpoint_id,
565            "Multimodal cache cleanup watcher already running for this runtime endpoint, skipping"
566        );
567        return;
568    }
569
570    let endpoint_name = endpoint.name().to_string();
571    let namespace = endpoint.component().namespace().name();
572    let component = endpoint.component().name().to_string();
573
574    tokio::spawn(async move {
575        struct GuardRelease(RuntimeEndpointId);
576        impl Drop for GuardRelease {
577            fn drop(&mut self) {
578                if let Some(map) = ENDPOINT_CACHE_INDEXER_WATCHER_ACTIVE.get() {
579                    map.remove(&self.0);
580                }
581            }
582        }
583        let _release = GuardRelease(watcher_id);
584
585        const RECONNECT_BACKOFF: std::time::Duration = std::time::Duration::from_secs(5);
586        'reconnect: loop {
587            let query = DiscoveryQuery::Endpoint {
588                namespace: namespace.clone(),
589                component: component.clone(),
590                endpoint: endpoint_name.clone(),
591            };
592
593            let mut stream = match endpoint.drt().discovery().list_and_watch(query, None).await {
594                Ok(stream) => stream,
595                Err(error) => {
596                    tracing::warn!(
597                        endpoint = %endpoint_name,
598                        "Failed to start multimodal cache cleanup watcher (will retry): {error}"
599                    );
600                    tokio::select! {
601                        _ = tokio::time::sleep(RECONNECT_BACKOFF) => continue 'reconnect,
602                        _ = cancel_token.cancelled() => break 'reconnect,
603                    }
604                }
605            };
606
607            loop {
608                tokio::select! {
609                    event = stream.next() => {
610                        match event {
611                            Some(Ok(DiscoveryEvent::Removed(DiscoveryInstanceId::Endpoint(eid)))) => {
612                                indexer.remove_worker(eid.instance_id);
613                            }
614                            Some(Ok(DiscoveryEvent::Added(_)))
615                            | Some(Ok(DiscoveryEvent::ModelTaintsUpdated(_)))
616                            | Some(Ok(DiscoveryEvent::Removed(_)))
617                            | Some(Ok(DiscoveryEvent::Resync(_))) => {}
618                            Some(Err(error)) => {
619                                tracing::warn!(
620                                    endpoint = %endpoint_name,
621                                    "Multimodal cache cleanup watcher stream error: {error}"
622                                );
623                                continue 'reconnect;
624                            }
625                            None => {
626                                tracing::warn!(
627                                    endpoint = %endpoint_name,
628                                    "Multimodal cache cleanup watcher stream ended; reconnecting"
629                                );
630                                continue 'reconnect;
631                            }
632                        }
633                    }
634                    _ = cancel_token.cancelled() => break 'reconnect,
635                }
636            }
637        }
638
639        tracing::debug!(endpoint = %endpoint_name, "Multimodal cache cleanup watcher exiting");
640    });
641}
642
643async fn addressed_router(endpoint: &Endpoint) -> anyhow::Result<Arc<AddressedPushRouter>> {
644    AddressedPushRouter::from_runtime_provider(endpoint).await
645}
646
647/// Optional capabilities of a [`PushRouter`], for [`PushRouter::from_client_with_options`].
648///
649/// Every named constructor on [`PushRouter`] is a shorthand for one of these.
650pub struct PushRouterOptions<T, U> {
651    /// Durable overload detection, driven through `client.set_overloaded_instances(...)`.
652    pub worker_monitor: Option<Arc<dyn WorkerLoadMonitor>>,
653    /// Multimodal embedding-cache state for `RouterMode::DeviceAwareWeighted`.
654    pub multimodal_cache_indexer: Option<Arc<dyn MultimodalCacheIndex>>,
655    pub multimodal_cache_key_extractor: Option<MultimodalCacheKeyExtractor<T>>,
656    /// A caller-supplied final hop in place of the request plane. Its `ErrorType`
657    /// mapping drives report-down, overload and migration as usual.
658    pub dispatch: Option<Arc<dyn StreamingDispatch<T, U>>>,
659    /// Report transient worker errors to discovery (`report_instance_down`) and
660    /// route `direct()` through the filtered available list. Off for recovery and
661    /// query paths that must reach a worker regardless of its health.
662    pub fault_detection: bool,
663    /// Instance selectors for round-robin, random and least-loaded. Required
664    /// when the router's mode is one of them; also backs [`PushRouter::round_robin`] and
665    /// [`PushRouter::random`] on routers of any mode.
666    pub selectors: Option<ModeSelectors>,
667}
668
669impl<T, U> Default for PushRouterOptions<T, U> {
670    fn default() -> Self {
671        Self {
672            worker_monitor: None,
673            multimodal_cache_indexer: None,
674            multimodal_cache_key_extractor: None,
675            dispatch: None,
676            fault_detection: true,
677            selectors: None,
678        }
679    }
680}
681
682impl<T, U> PushRouter<T, U>
683where
684    T: Data + Serialize,
685    U: Data + for<'de> Deserialize<'de> + MaybeError,
686{
687    pub fn router_mode(&self) -> RouterMode {
688        self.router_mode
689    }
690
691    /// Create a new PushRouter without a worker load monitor (no overload detection)
692    pub async fn from_client(client: Client, router_mode: RouterMode) -> anyhow::Result<Self> {
693        Self::from_client_with_options(client, router_mode, PushRouterOptions::default()).await
694    }
695
696    /// Create a new PushRouter with fault detection disabled.
697    ///
698    /// Unlike `from_client`, this router will not call `report_instance_down` on
699    /// transient errors, and `direct()` uses the raw discovery instance list instead
700    /// of the filtered avail list. Use for recovery/query paths.
701    pub async fn from_client_no_fault_detection(
702        client: Client,
703        router_mode: RouterMode,
704    ) -> anyhow::Result<Self> {
705        Self::from_client_with_options(
706            client,
707            router_mode,
708            PushRouterOptions {
709                fault_detection: false,
710                ..PushRouterOptions::default()
711            },
712        )
713        .await
714    }
715
716    /// Create a new PushRouter with an optional worker load monitor.
717    ///
718    /// The rejection path is gated by `fault_detection_enabled` (true here);
719    /// durable overload detection is driven by the monitor through
720    /// `client.set_overloaded_instances(...)`. Worker responses can also create
721    /// bounded request-path overload leases.
722    pub async fn from_client_with_monitor(
723        client: Client,
724        router_mode: RouterMode,
725        worker_monitor: Option<Arc<dyn WorkerLoadMonitor>>,
726    ) -> anyhow::Result<Self> {
727        Self::from_client_with_options(
728            client,
729            router_mode,
730            PushRouterOptions {
731                worker_monitor,
732                ..PushRouterOptions::default()
733            },
734        )
735        .await
736    }
737
738    /// Create a new PushRouter from `client` with the given optional capabilities.
739    /// A caller-supplied `dispatch` replaces the request plane as the final hop;
740    /// fault detection stays on, so its `ErrorType` mapping drives report-down,
741    /// overload and migration as usual.
742    pub async fn from_client_with_options(
743        client: Client,
744        router_mode: RouterMode,
745        options: PushRouterOptions<T, U>,
746    ) -> anyhow::Result<Self> {
747        let PushRouterOptions {
748            worker_monitor,
749            multimodal_cache_indexer,
750            multimodal_cache_key_extractor,
751            dispatch,
752            fault_detection,
753            selectors,
754        } = options;
755        let selectors = resolve_selectors(router_mode, selectors.as_ref())?;
756
757        // Type-erase to the seam so discovery-removal cleanup runs through it.
758        let addressed: Arc<dyn StreamingDispatch<T, U>> = match dispatch {
759            Some(dispatch) => dispatch,
760            None => addressed_router(&client.endpoint).await?,
761        };
762
763        // Start worker monitor if provided and in dynamic mode
764        if let Some(monitor) = worker_monitor.as_ref() {
765            monitor.start_monitoring().await?;
766        }
767
768        let occupancy_state = if router_mode.requires_occupancy()
769            || selectors
770                .iter()
771                .any(|(_, selector)| selector.reads_active_requests())
772        {
773            Some(get_or_create_routing_occupancy_state(&client.endpoint).await)
774        } else {
775            None
776        };
777
778        spawn_instance_removal_watcher(
779            client.endpoint.clone(),
780            addressed.clone(),
781            client.endpoint.drt().primary_token(),
782        );
783
784        // Drop stale cache-index entries when workers leave discovery.
785        if let Some(indexer) = multimodal_cache_indexer.clone() {
786            spawn_multimodal_cache_cleanup_watcher(
787                client.endpoint.clone(),
788                indexer,
789                client.endpoint.drt().primary_token(),
790            );
791        }
792        Ok(PushRouter {
793            client,
794            addressed,
795            router_mode,
796            selectors,
797            fault_detection_enabled: fault_detection,
798            response_timeout: response_inactivity_timeout(),
799            establish_timeout: response_stream_establish_timeout(),
800            occupancy_state,
801            multimodal_cache_indexer,
802            multimodal_cache_key_extractor,
803            _phantom: PhantomData,
804        })
805    }
806
807    /// `ResourceExhausted` when workers are routable but all overloaded;
808    /// `Unavailable` when no routable workers exist.
809    fn empty_free_pool_error(&self, routing_instances: &RoutingInstances) -> anyhow::Error {
810        if !routing_instances.routable_ids().is_empty() {
811            let cause = PipelineError::ServiceOverloaded(
812                "All workers are busy, please retry later".to_string(),
813            );
814            return DynamoError::builder()
815                .error_type(ErrorType::ResourceExhausted)
816                .message("All workers are busy, please retry later")
817                .cause(cause)
818                .build()
819                .into();
820        }
821        DynamoError::builder()
822            .error_type(ErrorType::Unavailable)
823            .message(format!(
824                "No workers available for endpoint {}",
825                self.client.endpoint.id()
826            ))
827            .build()
828            .into()
829    }
830
831    fn selector(&self, mode: RouterMode) -> anyhow::Result<&dyn InstanceSelector> {
832        self.selectors
833            .iter()
834            .find(|(selector_mode, _)| *selector_mode == mode)
835            .map(|(_, selector)| selector.as_ref())
836            .ok_or_else(|| {
837                anyhow::anyhow!(
838                    "no instance selector for {mode:?} routing on endpoint {}",
839                    self.client.endpoint.id()
840                )
841            })
842    }
843
844    /// Pick a free instance by `mode`. A selector that reads in-flight counts picks under
845    /// the admission lock, and the pick is booked before the lock is released.
846    fn select_by(&self, mode: RouterMode) -> anyhow::Result<SelectedInstance> {
847        let selector = self.selector(mode)?;
848        let routing_instances = self.client.routing_instances();
849        let candidates = routing_instances.free_ids();
850        if candidates.is_empty() {
851            return Err(self.empty_free_pool_error(&routing_instances));
852        }
853        if !selector.reads_active_requests() {
854            let instance_id = selector
855                .select_instance(candidates, &|_| 0, false)
856                .ok_or_else(|| self.empty_free_pool_error(&routing_instances))?;
857            return Ok(SelectedInstance {
858                instance_id,
859                candidate_count: candidates.len(),
860                load: None,
861                permit: None,
862            });
863        }
864        let state = self.occupancy_state()?;
865        let selection = state.select_and_reserve_with(candidates, |active_requests| {
866            selector
867                .select_instance(candidates, active_requests, false)
868                .ok_or_else(|| self.empty_free_pool_error(&routing_instances))
869        })?;
870        Ok(SelectedInstance {
871            instance_id: selection.worker_id(),
872            candidate_count: selection.candidate_count(),
873            load: Some(selection.load()),
874            permit: Some(OccupancyPermit::from_reservation(
875                selection.into_reservation(),
876            )),
877        })
878    }
879
880    /// Snapshot workers currently eligible for a new routing decision.
881    ///
882    /// Selection stays outside `PushRouter`; this is the discovery/admission
883    /// boundary used by routing hosts that own their policy lifecycle.
884    pub fn selectable_worker_ids(&self) -> anyhow::Result<Vec<u64>> {
885        self.with_selectable_worker_ids(<[u64]>::to_vec)
886    }
887
888    /// Borrow workers currently eligible for a new routing decision.
889    pub fn with_selectable_worker_ids<R>(
890        &self,
891        select: impl FnOnce(&[u64]) -> R,
892    ) -> anyhow::Result<R> {
893        let routing_instances = self.client.routing_instances();
894        if routing_instances.free_ids().is_empty() {
895            return Err(self.empty_free_pool_error(&routing_instances));
896        }
897        Ok(select(routing_instances.free_ids()))
898    }
899
900    /// Shared O(1) occupancy capability for load-aware routing hosts.
901    pub fn routing_occupancy_state(&self) -> Option<Arc<RoutingOccupancyState>> {
902        self.occupancy_state.clone()
903    }
904
905    /// Select a DeviceAware worker while leaving request-lifecycle cleanup to
906    /// the routing host. Request and device metadata is prepared before the
907    /// occupancy admission lock is acquired.
908    pub fn select_device_aware_and_reserve(
909        &self,
910        request: &T,
911        pinned_worker: Option<u64>,
912    ) -> anyhow::Result<DeviceAwareSelection> {
913        anyhow::ensure!(
914            self.router_mode == RouterMode::DeviceAwareWeighted,
915            "{:?} routing is not DeviceAwareWeighted",
916            self.router_mode
917        );
918
919        let state = self.occupancy_state()?;
920        if let Some(worker_id) = pinned_worker {
921            self.ensure_routable(worker_id)?;
922            let selection = self.device_aware_candidates(request, &[worker_id]);
923            let is_cpu = selection
924                .candidates
925                .first()
926                .is_some_and(|candidate| candidate.device == RouteDevice::Cpu);
927            let reservation = state.reserve(worker_id);
928            let load = reservation.load();
929            return Ok(DeviceAwareSelection {
930                worker_id,
931                candidate_count: 1,
932                load,
933                is_cpu,
934                embedding_cache_hit: selection.embedding_cache_hit,
935                request_cache_keys: selection.request_cache_keys,
936                reservation: Some(reservation),
937            });
938        }
939
940        let routing_instances = self.client.routing_instances();
941        let instance_ids = routing_instances.free_ids();
942        if instance_ids.is_empty() {
943            return Err(self.empty_free_pool_error(&routing_instances));
944        }
945        let selection = self.device_aware_candidates(request, instance_ids);
946        let (decision, counter) = state
947            .select_and_admit_device_aware(&selection.candidates, selection.context)
948            .ok_or_else(|| self.empty_free_pool_error(&routing_instances))?;
949        let worker_id = decision.target.worker_id;
950        let is_cpu = selection.candidates.iter().any(|candidate| {
951            candidate.target.worker_id == worker_id && candidate.device == RouteDevice::Cpu
952        });
953        let reservation = counter
954            .map(|counter| OccupancyReservation::from_counter(state.clone(), worker_id, counter));
955
956        Ok(DeviceAwareSelection {
957            worker_id,
958            candidate_count: selection.candidates.len(),
959            load: state.load(worker_id),
960            is_cpu,
961            embedding_cache_hit: selection.embedding_cache_hit,
962            request_cache_keys: selection.request_cache_keys,
963            reservation,
964        })
965    }
966
967    /// Reject an exact target that local fault detection has removed from routing.
968    pub fn ensure_routable(&self, instance_id: u64) -> anyhow::Result<()> {
969        if self
970            .client
971            .routing_instances()
972            .routable_ids()
973            .contains(&instance_id)
974        {
975            return Ok(());
976        }
977        anyhow::bail!(
978            "instance_id={instance_id} not found for endpoint {}",
979            self.client.endpoint.id()
980        )
981    }
982
983    fn ensure_discovered_for_dispatch(&self, instance_id: u64) -> anyhow::Result<()> {
984        if self.client.is_instance_live(instance_id) {
985            return Ok(());
986        }
987        Err(DynamoError::builder()
988            .error_type(ErrorType::CannotConnect)
989            .message(format!(
990                "instance_id={instance_id} not found for endpoint {}",
991                self.client.endpoint.id()
992            ))
993            .build()
994            .into())
995    }
996
997    /// Issue a request to the next instance in round-robin order.
998    pub async fn round_robin(&self, request: SingleIn<T>) -> anyhow::Result<ManyOut<U>> {
999        self.dispatch_by(RouterMode::RoundRobin, request).await
1000    }
1001
1002    /// Issue a request to a random instance.
1003    pub async fn random(&self, request: SingleIn<T>) -> anyhow::Result<ManyOut<U>> {
1004        self.dispatch_by(RouterMode::Random, request).await
1005    }
1006
1007    /// Issue a request to the instance with the fewest requests in flight.
1008    pub async fn least_loaded(&self, request: SingleIn<T>) -> anyhow::Result<ManyOut<U>> {
1009        self.dispatch_by(RouterMode::LeastLoaded, request).await
1010    }
1011
1012    async fn dispatch_by(
1013        &self,
1014        mode: RouterMode,
1015        request: SingleIn<T>,
1016    ) -> anyhow::Result<ManyOut<U>> {
1017        self.select_and_dispatch_by(mode, request, |_, _| Ok(()))
1018            .await
1019            .map(|(_, stream)| stream)
1020    }
1021
1022    /// Pick an instance by `mode`, prepare the request for the instance that survives
1023    /// transport resolution, then dispatch with normal fallback behavior.
1024    async fn select_and_dispatch_by<M, F>(
1025        &self,
1026        mode: RouterMode,
1027        request: SingleIn<T>,
1028        prepare: F,
1029    ) -> anyhow::Result<(M, ManyOut<U>)>
1030    where
1031        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1032    {
1033        let selected = self.select_by(mode)?;
1034        tracing::info!(
1035            router_mode = mode.telemetry_label(),
1036            worker_id = selected.instance_id,
1037            candidate_count = selected.candidate_count,
1038            load = selected.load,
1039            "Selected worker"
1040        );
1041        self.dispatch_selected(selected.instance_id, request, selected.permit, prepare)
1042            .await
1043    }
1044
1045    /// Issue a request to exactly one endpoint without transport fallback.
1046    pub async fn direct(
1047        &self,
1048        request: SingleIn<T>,
1049        instance_id: u64,
1050    ) -> anyhow::Result<ManyOut<U>> {
1051        tracing::info!(
1052            router_mode = "direct",
1053            worker_id = instance_id,
1054            "Selected worker"
1055        );
1056        self.generate_with_fault_detection(instance_id, request, TransportFallback::Deny)
1057            .await
1058    }
1059
1060    /// Dispatch to a selected endpoint with transport fallback.
1061    ///
1062    /// Unlike [`Self::direct`], if the selected instance disappears between selection and
1063    /// dispatch, this method may reselect another worker. When `allowed_fallback` is `Some`,
1064    /// reselection is constrained to that set; callers that pre-narrowed the candidates (e.g.
1065    /// LoRA replica-set filtering) use it to prevent fallback to an arbitrary worker.
1066    pub async fn direct_within(
1067        &self,
1068        request: SingleIn<T>,
1069        instance_id: u64,
1070        allowed_fallback: Option<&HashSet<u64>>,
1071    ) -> anyhow::Result<ManyOut<U>> {
1072        self.direct_within_prepared(request, instance_id, allowed_fallback, |_, _| Ok(()))
1073            .await
1074            .map(|(_, stream)| stream)
1075    }
1076
1077    /// Like [`Self::direct_within`], but prepares the request after transport resolution and
1078    /// returns the preparation metadata alongside the response stream.
1079    pub async fn direct_within_prepared<M, F>(
1080        &self,
1081        request: SingleIn<T>,
1082        instance_id: u64,
1083        allowed_fallback: Option<&HashSet<u64>>,
1084        prepare: F,
1085    ) -> anyhow::Result<(M, ManyOut<U>)>
1086    where
1087        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1088    {
1089        let fallback = allowed_fallback
1090            .map(TransportFallback::Within)
1091            .unwrap_or(TransportFallback::Allow);
1092        self.direct_prepared_with_fallback(instance_id, request, fallback, prepare)
1093            .await
1094    }
1095
1096    /// Dispatch a worker already selected by a routing host.
1097    ///
1098    /// `PushRouter` may still resolve transport fallback if the selected worker
1099    /// disappears before dispatch. The callback receives that final worker so
1100    /// the caller can retarget its own reservation and telemetry.
1101    pub async fn dispatch_preselected_prepared<M, F>(
1102        &self,
1103        request: SingleIn<T>,
1104        instance_id: u64,
1105        prepare: F,
1106    ) -> anyhow::Result<(M, ManyOut<U>)>
1107    where
1108        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1109    {
1110        self.dispatch_preselected_with_fallback(
1111            instance_id,
1112            request,
1113            TransportFallback::Allow,
1114            prepare,
1115        )
1116        .await
1117    }
1118
1119    async fn direct_prepared_with_fallback<M, F>(
1120        &self,
1121        instance_id: u64,
1122        request: SingleIn<T>,
1123        fallback: TransportFallback<'_>,
1124        prepare: F,
1125    ) -> anyhow::Result<(M, ManyOut<U>)>
1126    where
1127        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1128    {
1129        // Fallback resolution owns the unavailable-target decision. Allowing it
1130        // to see a worker already absent from discovery preserves Direct's
1131        // historical standalone fallback; `Deny` remains exact-target behavior.
1132        let selected_is_discovered = self.client.is_instance_live(instance_id);
1133        if !selected_is_discovered {
1134            let fallback_is_available = self
1135                .client
1136                .routing_instances()
1137                .free_ids()
1138                .iter()
1139                .copied()
1140                .any(|candidate| {
1141                    candidate != instance_id
1142                        && match fallback {
1143                            TransportFallback::Allow => true,
1144                            TransportFallback::Deny => false,
1145                            TransportFallback::Within(allowed) => allowed.contains(&candidate),
1146                        }
1147                });
1148            if !fallback_is_available {
1149                self.ensure_discovered_for_dispatch(instance_id)?;
1150            }
1151        }
1152        let ((metadata, resolved_instance_id), response_stream) = self
1153            .generate_with_fault_detection_prepared(
1154                instance_id,
1155                request,
1156                fallback,
1157                |request, resolved_instance_id| {
1158                    prepare(request, resolved_instance_id)
1159                        .map(|metadata| (metadata, resolved_instance_id))
1160                },
1161            )
1162            .await?;
1163        tracing::info!(
1164            router_mode = self.router_mode.telemetry_label(),
1165            worker_id = resolved_instance_id,
1166            "Selected worker"
1167        );
1168        Ok((metadata, response_stream))
1169    }
1170
1171    async fn dispatch_preselected_with_fallback<M, F>(
1172        &self,
1173        instance_id: u64,
1174        request: SingleIn<T>,
1175        fallback: TransportFallback<'_>,
1176        prepare: F,
1177    ) -> anyhow::Result<(M, ManyOut<U>)>
1178    where
1179        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1180    {
1181        // Fallback-enabled dispatch still honors a selected worker while it remains in
1182        // discovery. Local inhibition only filters worker selection owned by this router;
1183        // fallback is considered only if the selected worker disappears after this check.
1184        self.ensure_discovered_for_dispatch(instance_id)?;
1185
1186        self.generate_with_fault_detection_prepared(instance_id, request, fallback, prepare)
1187            .await
1188    }
1189
1190    /// Dispatch to exactly one worker without transport fallback.
1191    ///
1192    /// The worker is revalidated against the latest discovery and overload
1193    /// state immediately before dispatch.
1194    pub async fn dispatch_exact(
1195        &self,
1196        request: SingleIn<T>,
1197        instance_id: u64,
1198    ) -> anyhow::Result<ManyOut<U>> {
1199        self.generate_with_fault_detection(instance_id, request, TransportFallback::Deny)
1200            .await
1201    }
1202
1203    /// Dispatch exactly to a worker whose KV selection step already performed
1204    /// overload admission.
1205    ///
1206    /// Discovery and fault detection are still enforced. The shared client
1207    /// overload state is not rechecked because admission may synchronously
1208    /// publish this request's own load before dispatch begins.
1209    pub async fn dispatch_kv_admitted(
1210        &self,
1211        request: SingleIn<T>,
1212        instance_id: u64,
1213    ) -> anyhow::Result<ManyOut<U>> {
1214        if !self.router_mode.is_kv_routing() {
1215            anyhow::bail!("admitted dispatch is only valid in KV routing mode");
1216        }
1217        self.generate_with_fault_detection_inner(
1218            instance_id,
1219            request,
1220            TransportFallback::Deny,
1221            OverloadCheck::AlreadyAdmitted,
1222        )
1223        .await
1224    }
1225
1226    /// Select and book one worker, prepare the request for that exact worker,
1227    /// then dispatch without reselection or transport fallback.
1228    pub async fn select_and_dispatch_exact<M, F>(
1229        &self,
1230        mut request: SingleIn<T>,
1231        pinned_worker: Option<u64>,
1232        prepare: F,
1233    ) -> anyhow::Result<(M, ManyOut<U>)>
1234    where
1235        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1236    {
1237        let (instance_id, permit) = self
1238            .select_exact_target(request.content(), pinned_worker)
1239            .await?;
1240        let metadata = prepare(&mut request, instance_id)?;
1241        let stream = self.dispatch_exact(request, instance_id).await?;
1242        let stream = match permit {
1243            Some(permit) => permit.into_tracked_stream(stream),
1244            None => stream,
1245        };
1246        Ok((metadata, stream))
1247    }
1248
1249    /// Select a worker using the configured routing mode, prepare the request with the worker
1250    /// that survives transport resolution, then dispatch with normal fallback behavior.
1251    pub async fn select_and_dispatch<M, F>(
1252        &self,
1253        request: SingleIn<T>,
1254        prepare: F,
1255    ) -> anyhow::Result<(M, ManyOut<U>)>
1256    where
1257        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1258    {
1259        match self.router_mode {
1260            RouterMode::DeviceAwareWeighted => {
1261                self.device_aware_weighted_prepared(request, prepare).await
1262            }
1263            RouterMode::KV => anyhow::bail!("KV routing should not call select_and_dispatch"),
1264            RouterMode::Direct => anyhow::bail!(
1265                "Direct routing should use direct_within_prepared instead of select_and_dispatch"
1266            ),
1267            mode => self.select_and_dispatch_by(mode, request, prepare).await,
1268        }
1269    }
1270
1271    async fn dispatch_selected<M, F>(
1272        &self,
1273        instance_id: u64,
1274        request: SingleIn<T>,
1275        mut permit: Option<OccupancyPermit>,
1276        prepare: F,
1277    ) -> anyhow::Result<(M, ManyOut<U>)>
1278    where
1279        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1280    {
1281        let (metadata, stream) = self
1282            .generate_with_fault_detection_prepared(
1283                instance_id,
1284                request,
1285                TransportFallback::Allow,
1286                |request, resolved_instance_id| {
1287                    if let Some(permit) = permit.as_mut() {
1288                        permit.retarget(resolved_instance_id);
1289                    }
1290                    prepare(request, resolved_instance_id)
1291                },
1292            )
1293            .await?;
1294        let stream = match permit {
1295            Some(permit) => permit.into_tracked_stream(stream),
1296            None => stream,
1297        };
1298        Ok((metadata, stream))
1299    }
1300
1301    /// Issue a request using device-aware weighted routing.
1302    ///
1303    /// Instances are partitioned by device type (CPU vs non-CPU), then the router
1304    /// applies a budget policy and selects the least-loaded instance within the
1305    /// chosen group.
1306    ///
1307    /// If only one device class exists (all CPU or all non-CPU), this naturally
1308    /// degenerates to least-loaded routing over the available instances.
1309    pub async fn device_aware_weighted(&self, request: SingleIn<T>) -> anyhow::Result<ManyOut<U>> {
1310        self.device_aware_weighted_prepared(request, |_, _| Ok(()))
1311            .await
1312            .map(|(_, stream)| stream)
1313    }
1314
1315    async fn device_aware_weighted_prepared<M, F>(
1316        &self,
1317        request: SingleIn<T>,
1318        prepare: F,
1319    ) -> anyhow::Result<(M, ManyOut<U>)>
1320    where
1321        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1322    {
1323        let state = self.occupancy_state()?;
1324        let routing_instances = self.client.routing_instances();
1325        let instance_ids = routing_instances.free_ids();
1326
1327        if instance_ids.is_empty() {
1328            return Err(self.empty_free_pool_error(&routing_instances));
1329        }
1330
1331        // Apply a unified policy for all endpoints.
1332        let endpoint_id = self.client.endpoint.id();
1333
1334        let selection = self.device_aware_candidates(request.content(), instance_ids);
1335
1336        // Only full cache hits bypass weighted accounting; partial hits still follow the
1337        // device-aware ratio because some image encoding remains for this request.
1338        let (decision, counter) = state
1339            .select_and_admit_device_aware(&selection.candidates, selection.context)
1340            .ok_or_else(|| self.empty_free_pool_error(&routing_instances))?;
1341        let instance_id = decision.target.worker_id;
1342        let permit = counter
1343            .map(|counter| OccupancyPermit::from_counter(state.clone(), instance_id, counter));
1344        let is_cpu = selection.candidates.iter().any(|candidate| {
1345            candidate.target.worker_id == instance_id && candidate.device == RouteDevice::Cpu
1346        });
1347        tracing::info!(
1348            router_mode = "device-aware-weighted",
1349            worker_id = instance_id,
1350            candidate_count = selection.candidates.len(),
1351            load = state.load(instance_id),
1352            endpoint = %endpoint_id,
1353            is_cpu,
1354            embedding_cache_hit = selection.embedding_cache_hit,
1355            request_cache_keys = selection.request_cache_keys,
1356            "Selected worker"
1357        );
1358
1359        self.dispatch_selected(instance_id, request, permit, prepare)
1360            .await
1361    }
1362
1363    fn device_aware_candidates(&self, request: &T, instance_ids: &[u64]) -> DeviceAwareCandidates {
1364        let device_type_map = self
1365            .client
1366            .instances()
1367            .iter()
1368            .map(|instance| {
1369                let device = if matches!(instance.device_type, Some(DeviceType::Cpu)) {
1370                    RouteDevice::Cpu
1371                } else {
1372                    RouteDevice::Accelerator
1373                };
1374                (instance.instance_id, device)
1375            })
1376            .collect::<HashMap<_, _>>();
1377        let cuda_to_cpu_ratio = std::env::var("DYN_ENCODER_CUDA_TO_CPU_RATIO")
1378            .ok()
1379            .and_then(|value| value.parse::<usize>().ok())
1380            .filter(|value| *value >= 1)
1381            .unwrap_or(8);
1382
1383        let (request_cache_keys, cache_matched_candidates) =
1384            if let (Some(indexer), Some(extractor)) = (
1385                self.multimodal_cache_indexer.as_ref(),
1386                self.multimodal_cache_key_extractor.as_ref(),
1387            ) {
1388                let request_cache_keys = extractor(request);
1389                let matched = if request_cache_keys.is_empty() {
1390                    Vec::new()
1391                } else {
1392                    let mut matched = indexer.workers_with_cache_key_hits(&request_cache_keys);
1393                    matched.retain(|(id, _)| instance_ids.contains(id));
1394                    matched
1395                };
1396                (request_cache_keys, matched)
1397            } else {
1398                (Vec::new(), Vec::new())
1399            };
1400
1401        let embedding_cache_hit = !cache_matched_candidates.is_empty();
1402        let cache_hits = cache_matched_candidates
1403            .into_iter()
1404            .collect::<HashMap<_, _>>();
1405        let request_cache_key_count = request_cache_keys
1406            .iter()
1407            .collect::<std::collections::HashSet<_>>()
1408            .len();
1409        let candidates = instance_ids
1410            .iter()
1411            .map(|worker_id| RouteCandidate {
1412                target: RouteTarget::worker(*worker_id),
1413                device: device_type_map.get(worker_id).copied().unwrap_or_default(),
1414                cache_hits: cache_hits.get(worker_id).copied().unwrap_or_default(),
1415            })
1416            .collect::<Vec<_>>();
1417
1418        DeviceAwareCandidates {
1419            candidates,
1420            context: RouteContext {
1421                required_cache_hits: request_cache_key_count,
1422                non_cpu_to_cpu_ratio: cuda_to_cpu_ratio,
1423            },
1424            embedding_cache_hit,
1425            request_cache_keys: request_cache_keys.len(),
1426        }
1427    }
1428
1429    /// Select the next worker according to the routing mode.
1430    /// Increments round-robin counter if applicable.
1431    /// Returns None for modes that require request lifecycle tracking or explicit routing hints.
1432    pub fn select_next_worker(&self) -> Option<u64> {
1433        match self.router_mode {
1434            RouterMode::KV => {
1435                panic!(
1436                    "select_next_worker should not be called for {:?} routing mode",
1437                    self.router_mode
1438                )
1439            }
1440            RouterMode::Direct | RouterMode::DeviceAwareWeighted => None,
1441            mode => {
1442                let selector = self.selector(mode).ok()?;
1443                if selector.reads_active_requests() {
1444                    return None;
1445                }
1446                let routing_instances = self.client.routing_instances();
1447                let instance_ids = routing_instances.free_ids();
1448                if instance_ids.is_empty() {
1449                    return None;
1450                }
1451                selector.select_instance(instance_ids, &|_| 0, false)
1452            }
1453        }
1454    }
1455
1456    /// Peek the next worker according to the routing mode without incrementing the counter.
1457    /// Useful for checking if a worker is suitable before committing to it.
1458    ///
1459    /// `None` for [`RouterMode::Direct`] (caller-supplied routing); panics for
1460    /// [`RouterMode::KV`], which selects via `kv_chooser::find_best_match`.
1461    pub fn peek_next_worker(&self) -> Option<u64> {
1462        // Select among free (admission-eligible) workers — see select_next_worker
1463        // for the per-mode selection rationale.
1464        let routing_instances = self.client.routing_instances();
1465        let instance_ids = routing_instances.free_ids();
1466        if instance_ids.is_empty() {
1467            return None;
1468        }
1469
1470        match self.router_mode {
1471            RouterMode::DeviceAwareWeighted => {
1472                let state = self.occupancy_state.as_deref()?;
1473                let device_type_map: HashMap<u64, Option<DeviceType>> = self
1474                    .client
1475                    .instances()
1476                    .iter()
1477                    .map(|instance| (instance.instance_id, instance.device_type.clone()))
1478                    .collect();
1479                let cuda_to_cpu_ratio = std::env::var("DYN_ENCODER_CUDA_TO_CPU_RATIO")
1480                    .ok()
1481                    .and_then(|value| value.parse::<usize>().ok())
1482                    .filter(|value| *value >= 1)
1483                    .unwrap_or(8);
1484                let candidates = instance_ids
1485                    .iter()
1486                    .map(|worker_id| RouteCandidate {
1487                        target: RouteTarget::worker(*worker_id),
1488                        device: if matches!(
1489                            device_type_map.get(worker_id),
1490                            Some(Some(DeviceType::Cpu))
1491                        ) {
1492                            RouteDevice::Cpu
1493                        } else {
1494                            RouteDevice::Accelerator
1495                        },
1496                        cache_hits: 0,
1497                    })
1498                    .collect::<Vec<_>>();
1499                state
1500                    .peek_device_aware(
1501                        &candidates,
1502                        RouteContext {
1503                            required_cache_hits: 0,
1504                            non_cpu_to_cpu_ratio: cuda_to_cpu_ratio,
1505                        },
1506                    )
1507                    .map(|decision| decision.target.worker_id)
1508            }
1509            RouterMode::Direct => None,
1510            RouterMode::KV => {
1511                panic!(
1512                    "peek_next_worker should not be called for {:?} routing mode",
1513                    self.router_mode
1514                )
1515            }
1516            mode => {
1517                let selector = self.selector(mode).ok()?;
1518                if selector.reads_active_requests() {
1519                    let state = self.occupancy_state.as_deref()?;
1520                    selector.select_instance(instance_ids, &|id| state.load(id), true)
1521                } else {
1522                    selector.select_instance(instance_ids, &|_| 0, true)
1523                }
1524            }
1525        }
1526    }
1527
1528    #[cfg(any(test, feature = "testing"))]
1529    #[doc(hidden)]
1530    pub fn occupancy_for_test(&self, worker_id: u64) -> u64 {
1531        self.occupancy_state
1532            .as_deref()
1533            .map(|state| state.load(worker_id))
1534            .unwrap_or(0)
1535    }
1536
1537    async fn select_exact_target(
1538        &self,
1539        request: &T,
1540        pinned_worker: Option<u64>,
1541    ) -> anyhow::Result<(u64, Option<OccupancyPermit>)> {
1542        if let Some(instance_id) = pinned_worker {
1543            let routing_instances = self.client.routing_instances();
1544            if !routing_instances.routable_ids().contains(&instance_id) {
1545                return Err(anyhow::anyhow!(
1546                    "instance_id={instance_id} not found for endpoint {}",
1547                    self.client.endpoint.id()
1548                ));
1549            }
1550            let permit = self
1551                .occupancy_state
1552                .clone()
1553                .map(|state| OccupancyPermit::acquire(state, instance_id));
1554            return Ok((instance_id, permit));
1555        }
1556
1557        match self.router_mode {
1558            RouterMode::DeviceAwareWeighted => {
1559                let state = self.occupancy_state()?;
1560                let routing_instances = self.client.routing_instances();
1561                let instance_ids = routing_instances.free_ids();
1562                if instance_ids.is_empty() {
1563                    return Err(self.empty_free_pool_error(&routing_instances));
1564                }
1565                let selection = self.device_aware_candidates(request, instance_ids);
1566                let (decision, counter) = state
1567                    .select_and_admit_device_aware(&selection.candidates, selection.context)
1568                    .ok_or_else(|| self.empty_free_pool_error(&routing_instances))?;
1569                let instance_id = decision.target.worker_id;
1570                let permit = counter
1571                    .map(|counter| OccupancyPermit::from_counter(state, instance_id, counter));
1572                Ok((instance_id, permit))
1573            }
1574            RouterMode::Direct => Err(anyhow::anyhow!(
1575                "Worker ID required for exact dispatch in Direct routing mode"
1576            )),
1577            RouterMode::KV => Err(anyhow::anyhow!(
1578                "select_and_dispatch_exact cannot select workers in KV routing mode"
1579            )),
1580            mode => self
1581                .select_by(mode)
1582                .map(|selected| (selected.instance_id, selected.permit)),
1583        }
1584    }
1585
1586    fn occupancy_state(&self) -> anyhow::Result<Arc<RoutingOccupancyState>> {
1587        self.occupancy_state.clone().ok_or_else(|| {
1588            anyhow::anyhow!(
1589                "routing occupancy state not initialized for endpoint {}",
1590                self.client.endpoint.id()
1591            )
1592        })
1593    }
1594
1595    /*
1596    pub async fn r#static(&self, request: SingleIn<T>) -> anyhow::Result<ManyOut<U>> {
1597        let subject = self.client.endpoint.subject();
1598        tracing::debug!("static got subject: {subject}");
1599        let request = request.map(|req| AddressedRequest::new(req, subject));
1600        tracing::debug!("router generate");
1601        self.addressed.generate(request).await
1602    }
1603    */
1604
1605    async fn generate_with_fault_detection(
1606        &self,
1607        instance_id: u64,
1608        request: SingleIn<T>,
1609        fallback: TransportFallback<'_>,
1610    ) -> anyhow::Result<ManyOut<U>> {
1611        self.generate_with_fault_detection_inner(
1612            instance_id,
1613            request,
1614            fallback,
1615            OverloadCheck::Required,
1616        )
1617        .await
1618    }
1619
1620    async fn generate_with_fault_detection_inner(
1621        &self,
1622        instance_id: u64,
1623        request: SingleIn<T>,
1624        fallback: TransportFallback<'_>,
1625        overload_check: OverloadCheck,
1626    ) -> anyhow::Result<ManyOut<U>> {
1627        self.generate_with_fault_detection_prepared_inner(
1628            instance_id,
1629            request,
1630            fallback,
1631            overload_check,
1632            |_, _| Ok(()),
1633        )
1634        .await
1635        .map(|(_, stream)| stream)
1636    }
1637
1638    async fn generate_with_fault_detection_prepared<M, F>(
1639        &self,
1640        instance_id: u64,
1641        request: SingleIn<T>,
1642        fallback: TransportFallback<'_>,
1643        prepare: F,
1644    ) -> anyhow::Result<(M, ManyOut<U>)>
1645    where
1646        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1647    {
1648        self.generate_with_fault_detection_prepared_inner(
1649            instance_id,
1650            request,
1651            fallback,
1652            OverloadCheck::Required,
1653            prepare,
1654        )
1655        .await
1656    }
1657
1658    async fn generate_with_fault_detection_prepared_inner<M, F>(
1659        &self,
1660        instance_id: u64,
1661        mut request: SingleIn<T>,
1662        fallback: TransportFallback<'_>,
1663        overload_check: OverloadCheck,
1664        prepare: F,
1665    ) -> anyhow::Result<(M, ManyOut<U>)>
1666    where
1667        F: FnOnce(&mut T, u64) -> anyhow::Result<M>,
1668    {
1669        let route_start = Instant::now();
1670        let request_id = request.id().to_string();
1671        let route_trace_context = get_route_trace_context(&request);
1672        let route_span = if matches!(self.router_mode, RouterMode::KV) {
1673            tracing::Span::none()
1674        } else {
1675            tracing::info_span!(
1676                target: "request_span",
1677                "router.route_request",
1678                otel.kind = "client",
1679                request_id = %request_id,
1680                worker_id = tracing::field::Empty,
1681                router_mode = ?self.router_mode,
1682                "request.attempt" = tracing::field::Empty,
1683                "request.outcome" = tracing::field::Empty,
1684                "migration.is_retry" = tracing::field::Empty,
1685                "migration.reason" = tracing::field::Empty,
1686                "migration.from_worker_id" = tracing::field::Empty,
1687                "migration.tokens_completed" = tracing::field::Empty,
1688                "cancellation.signal" = tracing::field::Empty,
1689                "error.type" = tracing::field::Empty,
1690                otel.status_code = tracing::field::Empty,
1691                otel.status_description = tracing::field::Empty,
1692            )
1693        };
1694        let (instance_id, address, transport_kind, instance) = match self
1695            .resolve_transport(instance_id, fallback)
1696        {
1697            Ok(resolved) => resolved,
1698            Err(error) => {
1699                record_route_span_start(&route_span, route_trace_context.as_deref(), instance_id);
1700                record_route_error(&route_span, error.as_ref());
1701                return Err(error);
1702            }
1703        };
1704        record_route_span_start(&route_span, route_trace_context.as_deref(), instance_id);
1705        if matches!(overload_check, OverloadCheck::Required)
1706            && let Err(error) = self.check_workers_available(instance_id, &request_id)
1707        {
1708            record_route_error(&route_span, error.as_ref());
1709            return Err(error);
1710        }
1711
1712        let metadata = match prepare(&mut request, instance_id) {
1713            Ok(metadata) => metadata,
1714            Err(error) => {
1715                record_route_error(&route_span, error.as_ref());
1716                return Err(error);
1717            }
1718        };
1719        let establish_timeout = self
1720            .establish_timeout
1721            .filter(|_| self.fault_detection_enabled);
1722        let request = request.map(|req| {
1723            AddressedRequest::with_instance(req, address, instance)
1724                .with_establish_timeout(establish_timeout)
1725        });
1726
1727        STAGE_DURATION_SECONDS
1728            .with_label_values(&[STAGE_ROUTE])
1729            .observe(route_start.elapsed().as_secs_f64());
1730
1731        let _nvtx_transport = dynamo_nvtx_range!(transport_kind);
1732        let stream = self
1733            .addressed
1734            .generate(request)
1735            .instrument(route_span.clone())
1736            .await;
1737        let stream = self.wrap_with_fault_detection(stream, instance_id, route_span)?;
1738        Ok((metadata, stream))
1739    }
1740
1741    /// Reject early if the selected worker is overloaded and fault detection
1742    /// is enabled. The request_id is only used for the debug-level "checked
1743    /// worker overload state" trace; pass an empty string from callers that
1744    /// don't have one handy.
1745    fn check_workers_available(&self, instance_id: u64, request_id: &str) -> anyhow::Result<()> {
1746        if !self.fault_detection_enabled {
1747            return Ok(());
1748        }
1749        let routing_instances = self.client.routing_instances();
1750        let selected_worker_overloaded = routing_instances.is_overloaded(instance_id);
1751        let counts = routing_instances.counts();
1752        if tracing::enabled!(tracing::Level::DEBUG) {
1753            tracing::debug!(
1754                request_id,
1755                instance_id,
1756                router_mode = ?self.router_mode,
1757                free_workers = counts.free,
1758                overloaded_workers = counts.overloaded,
1759                total_workers = counts.discovered,
1760                selected_worker_overloaded,
1761                "checked worker overload state"
1762            );
1763        }
1764        if !selected_worker_overloaded {
1765            return Ok(());
1766        }
1767        tracing::warn!(
1768            instance_id,
1769            overloaded_workers = counts.overloaded,
1770            total_workers = counts.discovered,
1771            "Rejecting request: selected worker is overloaded"
1772        );
1773        let cause = PipelineError::ServiceOverloaded(
1774            "Selected worker is overloaded, please retry later".into(),
1775        );
1776        Err(DynamoError::builder()
1777            .error_type(ErrorType::WorkerOverloaded)
1778            .message("Selected worker is overloaded, please retry later")
1779            .cause(cause)
1780            .build()
1781            .into())
1782    }
1783
1784    /// Resolve `(instance_id, address, transport_kind_label, Instance)` for
1785    /// the selected worker. If that worker has disappeared, apply the caller's
1786    /// fallback policy. `CannotConnect` is returned when fallback is forbidden
1787    /// or when a selected fallback disappears before its transport can be
1788    /// resolved.
1789    fn resolve_transport(
1790        &self,
1791        instance_id: u64,
1792        fallback: TransportFallback<'_>,
1793    ) -> anyhow::Result<(u64, String, &'static str, Instance)> {
1794        use crate::component::TransportType;
1795
1796        let lookup = |id: u64| {
1797            self.client.instance_by_id(id).map(|instance| {
1798                let (addr, kind) = match &instance.transport {
1799                    TransportType::Tcp(tcp_endpoint) => {
1800                        (tcp_endpoint.clone(), "transport.tcp.request")
1801                    }
1802                    TransportType::Nats(subject) => (subject.clone(), "transport.nats.request"),
1803                };
1804                (addr, kind, instance)
1805            })
1806        };
1807
1808        if let Some((addr, kind, inst)) = lookup(instance_id) {
1809            return Ok((instance_id, addr, kind, inst));
1810        }
1811        let allowed_fallback = match fallback {
1812            TransportFallback::Allow => None,
1813            TransportFallback::Deny => {
1814                return Err(DynamoError::builder()
1815                    .error_type(ErrorType::CannotConnect)
1816                    .message(format!(
1817                        "instance_id={instance_id} not found for endpoint {}",
1818                        self.client.endpoint.id()
1819                    ))
1820                    .build()
1821                    .into());
1822            }
1823            TransportFallback::Within(allowed) => Some(allowed),
1824        };
1825
1826        let routing_instances = self.client.routing_instances();
1827        let fallback_id = routing_instances.free_ids().iter().copied().find(|&id| {
1828            id != instance_id && allowed_fallback.is_none_or(|allowed| allowed.contains(&id))
1829        });
1830        match fallback_id {
1831            Some(id) => {
1832                tracing::warn!(
1833                    original_instance = instance_id,
1834                    fallback_instance = id,
1835                    "Instance disappeared during routing, reselecting"
1836                );
1837                let (addr, kind, inst) = lookup(id).ok_or_else(|| {
1838                    DynamoError::builder()
1839                        .error_type(ErrorType::CannotConnect)
1840                        .message(format!(
1841                            "Fallback instance {} also not found for endpoint {}",
1842                            id,
1843                            self.client.endpoint.id()
1844                        ))
1845                        .build()
1846                })?;
1847                Ok((id, addr, kind, inst))
1848            }
1849            // The selected instance vanished from discovery and no permitted
1850            // fallback is free. Typed rather than a bare `anyhow!` so
1851            // `error_type_from_chain` (route spans) and the frontend's status
1852            // mapping see a real category instead of `unknown`/500.
1853            //
1854            // Uniformly `Unavailable`, not a pool-state split: reaching here
1855            // means *this request's* worker is gone, which is a discovery fact,
1856            // and `transport_resolution_precedes_stale_overload_check` requires
1857            // that a vanished instance is never redressed as overload. Nor
1858            // `CannotConnect`, which stays the signature of exact dispatch
1859            // (`TransportFallback::Deny`) and must remain distinguishable from a
1860            // fallback-enabled failure.
1861            None => Err(DynamoError::builder()
1862                .error_type(ErrorType::Unavailable)
1863                .message(format!(
1864                    "Instance {} not found and no other instances available for endpoint {}",
1865                    instance_id,
1866                    self.client.endpoint.id()
1867                ))
1868                .build()
1869                .into()),
1870        }
1871    }
1872
1873    /// Wrap a dispatched stream with fault detection + inactivity timeout.
1874    /// `is_inhibited` errors trigger `report_instance_down`; the timeout
1875    /// (driven by `DYN_HTTP_BACKEND_STREAM_TIMEOUT_SECS`) yields a synthetic
1876    /// `ResponseTimeout` and quarantines the worker.
1877    fn wrap_with_fault_detection(
1878        &self,
1879        stream: anyhow::Result<ManyOut<U>>,
1880        instance_id: u64,
1881        route_span: tracing::Span,
1882    ) -> anyhow::Result<ManyOut<U>> {
1883        let stream = match stream {
1884            Ok(stream) => stream,
1885            Err(err) => {
1886                record_route_error(&route_span, err.as_ref());
1887                if self.fault_detection_enabled {
1888                    // Overload first: a worker's refusal arrives as the cause
1889                    // of a pre-stream `CannotConnect`, which on its own would
1890                    // report a healthy worker down.
1891                    if let Some(refusal) = worker_overload(err.as_ref()) {
1892                        match refusal.error_type() {
1893                            // Backpressure from one DP rank. The worker's other
1894                            // ranks may still have room, which a lease on the
1895                            // whole worker would withhold.
1896                            ErrorType::WorkerRankOverloaded(dp_rank) => tracing::debug!(
1897                                "Leaving instance {instance_id} routable: its overload is limited to DP rank {dp_rank}: {err}"
1898                            ),
1899                            _ if self.router_mode.is_direct_routing() => tracing::debug!(
1900                                "Leaving instance {instance_id} routable in direct mode; its refusal goes back to the caller: {err}"
1901                            ),
1902                            // Backpressure: the worker said "my queue is full,
1903                            // retry later". A bounded lease prevents an immediate
1904                            // retry loop. Fresh monitor data clears the lease early.
1905                            // Lease expiry permits a recovery probe when load events
1906                            // remain unchanged. This is not a fault quarantine.
1907                            _ => {
1908                                tracing::debug!(
1909                                    "Marking instance {instance_id} overloaded due to backpressure: {err}"
1910                                );
1911                                self.client.mark_overloaded_immediate(instance_id);
1912                            }
1913                        }
1914                    } else if is_inhibited(err.as_ref()) {
1915                        tracing::debug!(
1916                            "Reporting instance {instance_id} down due to error: {err}"
1917                        );
1918                        self.client.report_instance_down(instance_id);
1919                    }
1920                }
1921                return Err(err);
1922            }
1923        };
1924
1925        if !self.fault_detection_enabled {
1926            return Ok(wrap_route_span(stream, route_span));
1927        }
1928
1929        let engine_ctx = stream.context();
1930        let client = self.client.clone();
1931        let client_for_timeout = self.client.clone();
1932        let stream = stream.map(move |res| {
1933            if let Some(err) = res.err()
1934                && is_inhibited(&err)
1935            {
1936                tracing::debug!(
1937                    "Reporting instance {instance_id} down due to migratable error: {err}"
1938                );
1939                client.report_instance_down(instance_id);
1940            }
1941            res
1942        });
1943
1944        let stream: Pin<Box<dyn Stream<Item = U> + Send>> =
1945            if let Some(timeout) = self.response_timeout {
1946                Box::pin(async_stream::stream! {
1947                    let mut inner = Box::pin(stream);
1948                    loop {
1949                        tokio::select! {
1950                            biased;
1951                            item = inner.next() => {
1952                                match item {
1953                                    Some(item) => yield item,
1954                                    None => break,
1955                                }
1956                            }
1957                            _ = tokio::time::sleep(timeout) => {
1958                                tracing::warn!(
1959                                    instance_id,
1960                                    timeout_secs = timeout.as_secs(),
1961                                    "backend response inactivity timeout — quarantining worker"
1962                                );
1963                                client_for_timeout.report_instance_down(instance_id);
1964                                yield U::from_err(
1965                                    crate::error::DynamoError::builder()
1966                                        .error_type(crate::error::ErrorType::ResponseTimeout)
1967                                        .message("backend response inactivity timeout")
1968                                        .build()
1969                                );
1970                                break;
1971                            }
1972                        }
1973                    }
1974                })
1975            } else {
1976                Box::pin(stream)
1977            };
1978
1979        Ok(wrap_route_span(
1980            ResponseStream::new(stream, engine_ctx),
1981            route_span,
1982        ))
1983    }
1984}
1985
1986#[async_trait]
1987impl<T, U> AsyncEngine<SingleIn<T>, ManyOut<U>, Error> for PushRouter<T, U>
1988where
1989    T: Data + Serialize,
1990    U: Data + for<'de> Deserialize<'de> + MaybeError,
1991{
1992    async fn generate(&self, request: SingleIn<T>) -> Result<ManyOut<U>, Error> {
1993        match self.router_mode {
1994            RouterMode::KV => {
1995                anyhow::bail!("KV routing should not call generate on PushRouter");
1996            }
1997            RouterMode::Direct => {
1998                anyhow::bail!(
1999                    "Direct routing should not call generate on PushRouter directly; use RoutingHost"
2000                );
2001            }
2002            RouterMode::DeviceAwareWeighted => self.device_aware_weighted(request).await,
2003            mode => self.dispatch_by(mode, request).await,
2004        }
2005    }
2006}
2007
2008impl<T, U> PushRouter<T, U>
2009where
2010    T: Data + Serialize,
2011    U: Data + for<'de> Deserialize<'de> + MaybeError,
2012{
2013    /// Bidirectional sibling of [`Self::generate_with_fault_detection`].
2014    async fn bidirectional_dispatch(
2015        &self,
2016        instance_id: u64,
2017        input: ManyIn<T>,
2018    ) -> anyhow::Result<ManyOut<U>> {
2019        let route_start = Instant::now();
2020        let request_id = input.context().id().to_string();
2021        let route_trace_context = get_route_trace_context(&input);
2022        let route_span = tracing::info_span!(
2023            target: "request_span",
2024            "router.route_request_bidirectional",
2025            otel.kind = "client",
2026            request_id = %request_id,
2027            worker_id = tracing::field::Empty,
2028            router_mode = ?self.router_mode,
2029            "request.attempt" = tracing::field::Empty,
2030            "request.outcome" = tracing::field::Empty,
2031            "migration.is_retry" = tracing::field::Empty,
2032            "migration.reason" = tracing::field::Empty,
2033            "migration.from_worker_id" = tracing::field::Empty,
2034            "migration.tokens_completed" = tracing::field::Empty,
2035            "cancellation.signal" = tracing::field::Empty,
2036            "error.type" = tracing::field::Empty,
2037            otel.status_code = tracing::field::Empty,
2038            otel.status_description = tracing::field::Empty,
2039        );
2040
2041        let (instance_id, address, transport_kind, instance) = match self
2042            .resolve_transport(instance_id, TransportFallback::Allow)
2043        {
2044            Ok(resolved) => resolved,
2045            Err(error) => {
2046                record_route_span_start(&route_span, route_trace_context.as_deref(), instance_id);
2047                record_route_error(&route_span, error.as_ref());
2048                return Err(error);
2049            }
2050        };
2051        record_route_span_start(&route_span, route_trace_context.as_deref(), instance_id);
2052        if let Err(error) = self.check_workers_available(instance_id, &request_id) {
2053            record_route_error(&route_span, error.as_ref());
2054            return Err(error);
2055        }
2056
2057        STAGE_DURATION_SECONDS
2058            .with_label_values(&[STAGE_ROUTE])
2059            .observe(route_start.elapsed().as_secs_f64());
2060
2061        let _nvtx_transport = dynamo_nvtx_range!(transport_kind);
2062        let stream: anyhow::Result<ManyOut<U>> = self
2063            .addressed
2064            .generate_bidirectional(instance, address, input)
2065            .instrument(route_span.clone())
2066            .await;
2067        self.wrap_with_fault_detection(stream, instance_id, route_span)
2068    }
2069}
2070
2071/// Bidirectional `AsyncEngine` impl for streaming-input workloads (e.g. the
2072/// OpenAI Realtime API). Reserves a sticky worker up front — before any
2073/// inbound frame is observed — and binds the whole input stream to that
2074/// worker. KV and Direct modes inherit the same `bail!` invariants as the
2075/// unary impl.
2076///
2077/// **Reserve-before-observe rationale.** The router-mode strategies
2078/// (`RoundRobin`, `Random`, `LeastLoaded`, `DeviceAwareWeighted`) don't depend on frame contents, so selection
2079/// runs immediately and connection setup proceeds in parallel with the
2080/// client producing its first frame. A client that connects but never
2081/// sends one still releases the slot via the response-stream-drop path;
2082/// the dispatch-side `cancel_both` cleanup covers the early-bail case.
2083#[async_trait]
2084impl<T, U> AsyncEngine<ManyIn<T>, ManyOut<U>, Error> for PushRouter<T, U>
2085where
2086    T: Data + Serialize,
2087    U: Data + for<'de> Deserialize<'de> + MaybeError,
2088{
2089    async fn generate(&self, input: ManyIn<T>) -> Result<ManyOut<U>, Error> {
2090        match self.router_mode {
2091            RouterMode::KV => {
2092                anyhow::bail!("KV routing should not call generate on PushRouter");
2093            }
2094            RouterMode::Direct => {
2095                anyhow::bail!(
2096                    "Direct routing should not call generate on PushRouter directly; use RoutingHost"
2097                );
2098            }
2099            // These modes drive `select_next_worker()` to `None` — they rely on
2100            // the occupancy/load-aware selection the bidirectional path does not
2101            // wire yet, which would otherwise surface as a misleading "no
2102            // instances available" error below. Reject them explicitly until
2103            // bidirectional support lands; tracked in
2104            // https://github.com/ai-dynamo/dynamo/issues/10320.
2105            RouterMode::PowerOfTwoChoices
2106            | RouterMode::LeastLoaded
2107            | RouterMode::DeviceAwareWeighted => {
2108                anyhow::bail!(
2109                    "{:?} routing is not yet supported for bidirectional dispatch",
2110                    self.router_mode
2111                );
2112            }
2113            RouterMode::RoundRobin | RouterMode::Random => {}
2114        }
2115
2116        let instance_id = self
2117            .select_next_worker()
2118            .ok_or_else(|| anyhow::anyhow!("no instances available for bidirectional routing"))?;
2119
2120        self.bidirectional_dispatch(instance_id, input).await
2121    }
2122}
2123
2124struct OccupancyTrackedStream<U: Data + MaybeError> {
2125    inner: ManyOut<U>,
2126    reservation: Option<OccupancyReservation>,
2127}
2128
2129impl<U: Data + MaybeError> OccupancyTrackedStream<U> {
2130    fn release(&mut self) {
2131        drop(self.reservation.take());
2132    }
2133}
2134
2135impl<U: Data + MaybeError> Drop for OccupancyTrackedStream<U> {
2136    fn drop(&mut self) {
2137        self.release();
2138    }
2139}
2140
2141impl<U: Data + MaybeError> std::fmt::Debug for OccupancyTrackedStream<U> {
2142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2143        f.debug_struct("OccupancyTrackedStream")
2144            .field(
2145                "instance_id",
2146                &self
2147                    .reservation
2148                    .as_ref()
2149                    .map(OccupancyReservation::worker_id),
2150            )
2151            .finish()
2152    }
2153}
2154
2155impl<U: Data + MaybeError> Stream for OccupancyTrackedStream<U> {
2156    type Item = U;
2157
2158    fn poll_next(
2159        mut self: Pin<&mut Self>,
2160        cx: &mut std::task::Context<'_>,
2161    ) -> Poll<Option<Self::Item>> {
2162        let poll = self.inner.as_mut().poll_next(cx);
2163        if matches!(&poll, Poll::Ready(None))
2164            || matches!(&poll, Poll::Ready(Some(item)) if item.err().is_some())
2165        {
2166            self.release();
2167        }
2168        poll
2169    }
2170}
2171
2172impl<U: Data + MaybeError> AsyncEngineContextProvider for OccupancyTrackedStream<U> {
2173    fn context(&self) -> Arc<dyn AsyncEngineContext> {
2174        self.inner.context()
2175    }
2176}
2177
2178impl<U: Data + MaybeError> crate::engine::AsyncEngineStream<U> for OccupancyTrackedStream<U> {}
2179
2180#[cfg(test)]
2181mod tests {
2182    use super::*;
2183    use std::sync::atomic::{AtomicUsize, Ordering};
2184
2185    use crate::{
2186        DistributedRuntime, Runtime,
2187        distributed::DistributedConfig,
2188        error::DynamoError,
2189        pipeline::{
2190            RequestStream, ResponseStream,
2191            context::{Context, Controller},
2192            network::egress::route_span,
2193        },
2194    };
2195    use serde::{Deserialize, Serialize};
2196
2197    /// A stand-in for the router-mode plugins, which own and test the real algorithms. It
2198    /// rotates through the instances, or takes the least loaded (first on ties) when it reads
2199    /// load, so these tests exercise transport, occupancy and fallback.
2200    struct TestSelector {
2201        reads_load: bool,
2202        cursor: AtomicUsize,
2203    }
2204
2205    impl TestSelector {
2206        fn new(reads_load: bool) -> Self {
2207            Self {
2208                reads_load,
2209                cursor: AtomicUsize::new(0),
2210            }
2211        }
2212    }
2213
2214    impl InstanceSelector for TestSelector {
2215        fn reads_active_requests(&self) -> bool {
2216            self.reads_load
2217        }
2218
2219        fn select_instance(
2220            &self,
2221            instance_ids: &[u64],
2222            active_requests: &dyn Fn(u64) -> u64,
2223            preview: bool,
2224        ) -> Option<u64> {
2225            if self.reads_load {
2226                return instance_ids
2227                    .iter()
2228                    .copied()
2229                    .min_by_key(|id| active_requests(*id));
2230            }
2231            let cursor = if preview {
2232                self.cursor.load(Ordering::Relaxed)
2233            } else {
2234                self.cursor.fetch_add(1, Ordering::Relaxed)
2235            };
2236            instance_ids.get(cursor % instance_ids.len()).copied()
2237        }
2238    }
2239
2240    fn test_selectors() -> ModeSelectors {
2241        Arc::new(|mode| {
2242            mode.picks_with_selector().then(|| {
2243                Arc::new(TestSelector::new(mode.requires_occupancy())) as Arc<dyn InstanceSelector>
2244            })
2245        })
2246    }
2247
2248    impl<T, U> PushRouter<T, U>
2249    where
2250        T: Data + Serialize,
2251        U: Data + for<'de> Deserialize<'de> + MaybeError,
2252    {
2253        async fn for_test(client: Client, router_mode: RouterMode) -> anyhow::Result<Self> {
2254            Self::from_client_with_options(
2255                client,
2256                router_mode,
2257                PushRouterOptions {
2258                    selectors: Some(test_selectors()),
2259                    ..PushRouterOptions::default()
2260                },
2261            )
2262            .await
2263        }
2264    }
2265
2266    #[derive(Clone, Debug, Deserialize, Serialize)]
2267    struct TestResponse {
2268        error: Option<DynamoError>,
2269    }
2270
2271    impl MaybeError for TestResponse {
2272        fn from_err(err: impl std::error::Error + 'static) -> Self {
2273            Self {
2274                error: Some(DynamoError::from(
2275                    Box::new(err) as Box<dyn std::error::Error + 'static>
2276                )),
2277            }
2278        }
2279
2280        fn err(&self) -> Option<DynamoError> {
2281            self.error.clone()
2282        }
2283    }
2284
2285    fn assert_cannot_connect(error: &anyhow::Error) {
2286        assert!(
2287            match_error_chain(error.as_ref(), &[ErrorType::CannotConnect], &[]),
2288            "expected CannotConnect error, got: {error}"
2289        );
2290        assert!(
2291            !match_error_chain(error.as_ref(), &[ErrorType::ResourceExhausted], &[]),
2292            "CannotConnect failure must not be masked as ResourceExhausted: {error}"
2293        );
2294    }
2295
2296    fn assert_not_cannot_connect(error: &anyhow::Error) {
2297        assert!(
2298            !match_error_chain(error.as_ref(), &[ErrorType::CannotConnect], &[]),
2299            "fallback-enabled failure must preserve its existing error semantics: {error}"
2300        );
2301    }
2302
2303    /// The no-permitted-fallback path must carry a typed `Unavailable`, not a
2304    /// bare `anyhow!`. Asserted through `error_type_from_chain` because that is
2305    /// what route spans and the frontend's 503 mapping actually call: an
2306    /// untyped error classifies as `Unknown` there and is exported as
2307    /// `error.type=unknown` / HTTP 500.
2308    fn assert_unavailable(error: &anyhow::Error) {
2309        assert_eq!(
2310            route_span::error_type_from_chain(error.as_ref()),
2311            ErrorType::Unavailable,
2312            "no-permitted-fallback failure must be typed Unavailable, got: {error}"
2313        );
2314        assert_not_cannot_connect(error);
2315    }
2316
2317    struct StaticMultimodalCacheIndex {
2318        worker_id: u64,
2319    }
2320
2321    impl MultimodalCacheIndex for StaticMultimodalCacheIndex {
2322        fn workers_with_cache_key_hits(&self, cache_keys: &[String]) -> Vec<(u64, usize)> {
2323            vec![(self.worker_id, cache_keys.len())]
2324        }
2325
2326        fn remove_worker(&self, _worker_id: u64) {}
2327    }
2328
2329    #[test]
2330    fn router_mode_telemetry_labels_are_stable() {
2331        assert_eq!(RouterMode::RoundRobin.telemetry_label(), "round-robin");
2332        assert_eq!(RouterMode::Random.telemetry_label(), "random");
2333        assert_eq!(
2334            RouterMode::PowerOfTwoChoices.telemetry_label(),
2335            "power-of-two-choices"
2336        );
2337        assert_eq!(RouterMode::KV.telemetry_label(), "kv");
2338        assert_eq!(RouterMode::Direct.telemetry_label(), "direct");
2339        assert_eq!(RouterMode::LeastLoaded.telemetry_label(), "least-loaded");
2340        assert_eq!(
2341            RouterMode::DeviceAwareWeighted.telemetry_label(),
2342            "device-aware-weighted"
2343        );
2344    }
2345
2346    #[test]
2347    fn selectors_resolve_once_per_mode_and_are_required_for_picking_modes() {
2348        let modes = |resolved: Vec<(RouterMode, Arc<dyn InstanceSelector>)>| {
2349            resolved
2350                .into_iter()
2351                .map(|(mode, _)| mode)
2352                .collect::<Vec<_>>()
2353        };
2354        let selectors = test_selectors();
2355        assert_eq!(
2356            modes(resolve_selectors(RouterMode::KV, Some(&selectors)).unwrap()),
2357            [RouterMode::RoundRobin, RouterMode::Random]
2358        );
2359        assert_eq!(
2360            modes(resolve_selectors(RouterMode::RoundRobin, Some(&selectors)).unwrap()),
2361            [RouterMode::RoundRobin, RouterMode::Random]
2362        );
2363        assert_eq!(
2364            modes(resolve_selectors(RouterMode::LeastLoaded, Some(&selectors)).unwrap()),
2365            [
2366                RouterMode::LeastLoaded,
2367                RouterMode::RoundRobin,
2368                RouterMode::Random
2369            ]
2370        );
2371        assert!(
2372            resolve_selectors(RouterMode::Direct, None)
2373                .unwrap()
2374                .is_empty()
2375        );
2376        assert!(resolve_selectors(RouterMode::RoundRobin, None).is_err());
2377    }
2378
2379    #[test]
2380    fn occupancy_permit_decrements_before_stream_creation() {
2381        let state = Arc::new(RoutingOccupancyState::default());
2382        let counter = state.increment(42);
2383        let permit = OccupancyPermit::from_counter(state.clone(), 42, counter);
2384        assert_eq!(state.load(42), 1);
2385        drop(permit);
2386        assert_eq!(state.load(42), 0);
2387    }
2388
2389    #[test]
2390    fn occupancy_tracked_stream_decrements_on_drop() {
2391        let state = Arc::new(RoutingOccupancyState::default());
2392        let counter = state.increment(7);
2393        let permit = OccupancyPermit::from_counter(state.clone(), 7, counter);
2394        let ctx: Arc<dyn AsyncEngineContext> = Arc::new(Controller::default());
2395        let stream = permit.into_tracked_stream(ResponseStream::new(
2396            Box::pin(tokio_stream::iter(vec![TestResponse { error: None }])),
2397            ctx,
2398        ));
2399        assert_eq!(state.load(7), 1);
2400        drop(stream);
2401        assert_eq!(state.load(7), 0);
2402    }
2403
2404    #[tokio::test]
2405    async fn occupancy_tracked_stream_decrements_on_completion() {
2406        let state = Arc::new(RoutingOccupancyState::default());
2407        let counter = state.increment(7);
2408        let permit = OccupancyPermit::from_counter(state.clone(), 7, counter);
2409        let ctx: Arc<dyn AsyncEngineContext> = Arc::new(Controller::default());
2410        let mut stream = permit.into_tracked_stream(ResponseStream::new(
2411            Box::pin(tokio_stream::iter(vec![TestResponse { error: None }])),
2412            ctx,
2413        ));
2414
2415        assert!(stream.next().await.unwrap().err().is_none());
2416        assert_eq!(state.load(7), 1);
2417        assert!(stream.next().await.is_none());
2418        assert_eq!(state.load(7), 0);
2419        drop(stream);
2420        assert_eq!(state.load(7), 0, "drop must not release twice after EOF");
2421    }
2422
2423    #[tokio::test]
2424    async fn occupancy_tracked_stream_releases_before_yielding_error() {
2425        let state = Arc::new(RoutingOccupancyState::default());
2426        let counter = state.increment(7);
2427        let permit = OccupancyPermit::from_counter(state.clone(), 7, counter);
2428        let ctx: Arc<dyn AsyncEngineContext> = Arc::new(Controller::default());
2429        let error = DynamoError::builder()
2430            .error_type(ErrorType::WorkerOverloaded)
2431            .message("worker queue full")
2432            .build();
2433        let mut stream = permit.into_tracked_stream(ResponseStream::new(
2434            Box::pin(tokio_stream::iter(vec![TestResponse {
2435                error: Some(error),
2436            }])),
2437            ctx,
2438        ));
2439
2440        let response = stream.next().await.expect("error response");
2441        assert!(response.err().is_some());
2442        assert_eq!(
2443            state.load(7),
2444            0,
2445            "occupancy must be released before retry observes the error"
2446        );
2447    }
2448
2449    #[test]
2450    fn same_id_readd_keeps_existing_permit_accounting() {
2451        let state = Arc::new(RoutingOccupancyState::default());
2452        state.retain(&[7]);
2453        let old_counter = state.increment(7);
2454        let old_permit = OccupancyPermit::from_counter(state.clone(), 7, old_counter);
2455
2456        state.retain(&[]);
2457        assert_eq!(state.load(7), 1);
2458        state.retain(&[7]);
2459        let new_permit = OccupancyPermit::acquire(state.clone(), 7);
2460        assert_eq!(state.load(7), 2);
2461
2462        drop(old_permit);
2463        assert_eq!(
2464            state.load(7),
2465            1,
2466            "re-added worker must retain the still-live request"
2467        );
2468        drop(new_permit);
2469        assert_eq!(state.load(7), 0);
2470    }
2471
2472    /// A mid-generation stream end means the worker dropped the request, so it
2473    /// must quarantine — otherwise a migration retry can reselect the same
2474    /// worker before discovery removal catches up.
2475    ///
2476    /// This pins `is_inhibited` against the migration layer's migratable set:
2477    /// a worker fault that is migratable must also inhibit, or migration
2478    /// bounces off the same dead worker.
2479    #[test]
2480    fn stream_incomplete_quarantines_the_worker() {
2481        let err = DynamoError::builder()
2482            .error_type(ErrorType::Backend(BackendError::StreamIncomplete))
2483            .message("stream ended before generation completed")
2484            .build();
2485        assert!(
2486            is_inhibited(&err),
2487            "StreamIncomplete must inhibit; it is migratable, so leaving it out \
2488             lets a retry reselect the failed worker"
2489        );
2490
2491        let cancelled = DynamoError::builder()
2492            .error_type(ErrorType::Cancelled)
2493            .message("client went away")
2494            .build();
2495        assert!(
2496            !is_inhibited(&cancelled),
2497            "client cancellation is not a worker fault"
2498        );
2499    }
2500
2501    #[test]
2502    fn worker_unavailable_quarantines_the_worker() {
2503        let err = DynamoError::builder()
2504            .error_type(ErrorType::WorkerUnavailable)
2505            .message("Server unavailable: unknown endpoint a/generate")
2506            .build();
2507        assert!(is_inhibited(&err));
2508    }
2509
2510    /// A worker's admission refusal as the gate raises it, in process: for
2511    /// the whole worker, or for DP rank `dp_rank` alone.
2512    fn refusal(dp_rank: Option<u32>) -> DynamoError {
2513        DynamoError::builder()
2514            .error_type(
2515                dp_rank.map_or(ErrorType::WorkerOverloaded, ErrorType::WorkerRankOverloaded),
2516            )
2517            .message("Server overloaded: worker at capacity")
2518            .build()
2519    }
2520
2521    /// The same refusal as the request plane delivers it: carried as JSON in
2522    /// the response prologue, then made the cause of a pre-stream
2523    /// `CannotConnect`.
2524    fn admission_refusal(dp_rank: Option<u32>) -> DynamoError {
2525        use crate::pipeline::network::{ResponseStreamPrologue, StreamPrologueError};
2526
2527        let prologue = ResponseStreamPrologue {
2528            error: Some("Server overloaded: worker at capacity".to_string()),
2529            typed_error: Some(refusal(dp_rank)),
2530        };
2531        let delivered: ResponseStreamPrologue =
2532            serde_json::from_slice(&serde_json::to_vec(&prologue).unwrap()).unwrap();
2533        crate::pipeline::network::egress::addressed_router::pre_stream_failure_error(
2534            StreamPrologueError::new(
2535                "Server overloaded: worker at capacity",
2536                delivered
2537                    .typed_error
2538                    .expect("the prologue keeps the typed refusal"),
2539            ),
2540        )
2541    }
2542
2543    /// The overload is found through the `CannotConnect` that wraps it — by
2544    /// its reason, since the wire decodes its legacy type as the pool-wide
2545    /// `ResourceExhausted` — and it never inhibits the worker, whether it
2546    /// applies to the whole worker or names one DP rank, which it keeps.
2547    /// Pool-wide exhaustion is not a worker's refusal, and a `CannotConnect`
2548    /// without one is still a connection fault.
2549    #[test]
2550    fn a_wrapped_overload_is_backpressure_not_a_fault() {
2551        let delivered = admission_refusal(None);
2552        assert_eq!(
2553            delivered.error_type(),
2554            ErrorType::CannotConnect,
2555            "the outer type is unchanged"
2556        );
2557        let cause = std::error::Error::source(&delivered)
2558            .and_then(|source| source.downcast_ref::<DynamoError>())
2559            .expect("the worker's refusal is the cause");
2560        assert_eq!(cause.error_type(), ErrorType::ResourceExhausted);
2561        assert_eq!(cause.reason().as_str(), WORKER_OVERLOADED_REASON);
2562        assert!(is_worker_overloaded(&delivered));
2563        assert!(!is_inhibited(&delivered));
2564
2565        let rank = admission_refusal(Some(4));
2566        assert_eq!(rank.error_type(), ErrorType::CannotConnect);
2567        assert!(!is_inhibited(&rank));
2568        assert_eq!(
2569            worker_overload(&rank).unwrap().error_type(),
2570            ErrorType::WorkerRankOverloaded(4)
2571        );
2572
2573        let local = refusal(None);
2574        assert_eq!(local.reason().as_str(), WORKER_OVERLOADED_REASON);
2575        assert!(is_worker_overloaded(&local));
2576        assert!(!is_inhibited(&local));
2577
2578        let pool_exhausted = DynamoError::builder()
2579            .error_type(ErrorType::ResourceExhausted)
2580            .message("All workers are busy, please retry later")
2581            .build();
2582        assert!(!is_worker_overloaded(&pool_exhausted));
2583
2584        let connection_failure = DynamoError::builder()
2585            .error_type(ErrorType::CannotConnect)
2586            .message("connection refused")
2587            .build();
2588        assert!(!is_worker_overloaded(&connection_failure));
2589        assert!(is_inhibited(&connection_failure));
2590    }
2591
2592    /// Through the router's own fault detection, on one client: a refusal
2593    /// that names one DP rank leaves the worker selectable for its other work,
2594    /// while a whole-worker refusal — as an older worker's, which names none,
2595    /// also is — marks it overloaded, except in direct mode. Time is held still
2596    /// throughout, so no lease can lapse between a refusal and the check after
2597    /// it. Neither reports the worker down; a real connection failure still does.
2598    #[tokio::test]
2599    async fn fault_detection_marks_only_a_whole_worker_refusal_overloaded_and_never_down() {
2600        const TEST_RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(3600);
2601
2602        let rt = Runtime::from_current().unwrap();
2603        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2604            .await
2605            .unwrap();
2606        let endpoint = drt
2607            .namespace("test_admission_refusal_fault_detection".to_string())
2608            .unwrap()
2609            .component("test_component".to_string())
2610            .unwrap()
2611            .endpoint("test_endpoint".to_string());
2612        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
2613            .await
2614            .unwrap();
2615        endpoint.register_endpoint_instance().await.unwrap();
2616        let instance_id = client.wait_for_instances().await.unwrap()[0].id();
2617        assert!(poll_until(|| client.instance_ids_avail().contains(&instance_id)).await);
2618        let router =
2619            PushRouter::<u64, TestResponse>::for_test(client.clone(), RouterMode::RoundRobin)
2620                .await
2621                .unwrap();
2622        let direct =
2623            PushRouter::<u64, TestResponse>::from_client(client.clone(), RouterMode::Direct)
2624                .await
2625                .unwrap();
2626
2627        let refuse = |router: &PushRouter<u64, TestResponse>, dp_rank: Option<u32>| {
2628            let error = router
2629                .wrap_with_fault_detection(
2630                    Err(admission_refusal(dp_rank).into()),
2631                    instance_id,
2632                    tracing::Span::none(),
2633                )
2634                .expect_err("the refusal propagates");
2635            assert!(
2636                is_worker_overloaded(error.as_ref()),
2637                "the overload survives for the frontend to map"
2638            );
2639        };
2640        let overloaded = || {
2641            client
2642                .overloaded_instance_ids()
2643                .is_some_and(|overloaded| overloaded.contains(&instance_id))
2644        };
2645
2646        tokio::time::pause();
2647        refuse(&direct, None);
2648        assert!(!overloaded(), "a refusal in direct mode marks nothing");
2649        refuse(&router, Some(4));
2650        assert!(!overloaded(), "a refusal for one rank marks nothing");
2651        assert!(
2652            router
2653                .check_workers_available(instance_id, "sibling")
2654                .is_ok(),
2655            "so the same router still dispatches the worker's other work"
2656        );
2657        refuse(&router, None);
2658        assert!(overloaded(), "a whole-worker refusal marks it overloaded");
2659        assert!(
2660            router.check_workers_available(instance_id, "next").is_err(),
2661            "so the same router holds new work for it back"
2662        );
2663        tokio::time::resume();
2664        assert!(
2665            client.instance_ids_avail().contains(&instance_id),
2666            "a refusing worker is never reported down"
2667        );
2668
2669        let connection_failure = DynamoError::builder()
2670            .error_type(ErrorType::CannotConnect)
2671            .message("connection refused")
2672            .build();
2673        let _ = router.wrap_with_fault_detection(
2674            Err(connection_failure.into()),
2675            instance_id,
2676            tracing::Span::none(),
2677        );
2678        assert!(
2679            !client.instance_ids_avail().contains(&instance_id),
2680            "a real connection failure still reports the worker down"
2681        );
2682
2683        rt.shutdown();
2684    }
2685
2686    #[test]
2687    fn pre_stream_invalid_request_does_not_quarantine_healthy_worker() {
2688        use crate::pipeline::network::{
2689            StreamPrologueError, egress::addressed_router::pre_stream_failure_error,
2690        };
2691
2692        for (error_type, is_worker_fault) in [
2693            (ErrorType::InvalidRequest, false),
2694            (ErrorType::InvalidArgument, false),
2695            (ErrorType::Backend(BackendError::InvalidArgument), false),
2696            (ErrorType::Conflict, false),
2697            (ErrorType::CannotConnect, true),
2698            (ErrorType::Unavailable, true),
2699        ] {
2700            let rejection = DynamoError::builder()
2701                .error_type(error_type)
2702                .message("native request failed")
2703                .build();
2704            let error =
2705                pre_stream_failure_error(StreamPrologueError::new("Generate Error", rejection));
2706            assert_eq!(is_inhibited(&error), is_worker_fault, "{error_type:?}");
2707        }
2708    }
2709
2710    #[test]
2711    fn occupancy_permits_track_inflight_counts_with_shared_tracker() {
2712        let state = Arc::new(RoutingOccupancyState::default());
2713        let mut permits = Vec::new();
2714        for selected in [1, 2, 1, 2, 1] {
2715            permits.push(OccupancyPermit::acquire(state.clone(), selected));
2716        }
2717
2718        let total = state.load(1) + state.load(2);
2719        assert_eq!(total, 5, "5 in-flight requests should be tracked");
2720
2721        drop(permits);
2722        let total = state.load(1) + state.load(2);
2723        assert_eq!(total, 0, "All guards dropped, counts should be 0");
2724    }
2725
2726    #[tokio::test]
2727    async fn load_reading_selection_books_its_pick_until_the_permit_drops() {
2728        let state = Arc::new(RoutingOccupancyState::default());
2729        state.increment(1);
2730        state.increment(1);
2731        state.increment(2);
2732
2733        let selector = TestSelector::new(true);
2734        let selection = state
2735            .select_and_reserve_with(&[1, 2, 3], |active_requests| {
2736                selector
2737                    .select_instance(&[1, 2, 3], active_requests, false)
2738                    .ok_or(())
2739            })
2740            .unwrap();
2741        let selected = selection.worker_id();
2742        assert_eq!(selected, 3);
2743
2744        let permit = OccupancyPermit::from_reservation(selection.into_reservation());
2745        assert_eq!(state.load(selected), 1);
2746        drop(permit);
2747        assert_eq!(state.load(selected), 0);
2748    }
2749
2750    #[tokio::test]
2751    async fn bidirectional_generate_bails_with_no_instances() {
2752        let rt = Runtime::from_current().unwrap();
2753        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2754            .await
2755            .unwrap();
2756        let ns = drt.namespace("test_bidi_no_instances".to_string()).unwrap();
2757        let component = ns.component("test_component".to_string()).unwrap();
2758        let endpoint = component.endpoint("test_endpoint".to_string());
2759        let client = endpoint.client().await.unwrap();
2760
2761        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::RoundRobin)
2762            .await
2763            .unwrap();
2764
2765        let input: ManyIn<u64> =
2766            Context::new(RequestStream::new(Box::pin(tokio_stream::iter(vec![
2767                1u64, 2u64,
2768            ]))));
2769        let result = router.generate(input).await;
2770        assert!(
2771            result.is_err(),
2772            "bidirectional generate must bail when no instances are registered"
2773        );
2774
2775        rt.shutdown();
2776    }
2777
2778    #[tokio::test]
2779    async fn bidirectional_generate_bails_for_kv_router_mode() {
2780        let rt = Runtime::from_current().unwrap();
2781        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2782            .await
2783            .unwrap();
2784        let ns = drt.namespace("test_bidi_kv_mode".to_string()).unwrap();
2785        let component = ns.component("test_component".to_string()).unwrap();
2786        let endpoint = component.endpoint("test_endpoint".to_string());
2787        let client = endpoint.client().await.unwrap();
2788
2789        let router = PushRouter::<u64, TestResponse>::from_client(client, RouterMode::KV)
2790            .await
2791            .unwrap();
2792
2793        let input: ManyIn<u64> =
2794            Context::new(RequestStream::new(Box::pin(tokio_stream::iter(vec![1u64]))));
2795        let result = router.generate(input).await;
2796        assert!(
2797            result.is_err(),
2798            "bidirectional generate must bail for RouterMode::KV"
2799        );
2800        let err_msg = format!("{:?}", result.unwrap_err());
2801        assert!(
2802            err_msg.contains("KV") || err_msg.contains("kv"),
2803            "error should mention KV: got {err_msg}"
2804        );
2805
2806        rt.shutdown();
2807    }
2808
2809    #[tokio::test]
2810    async fn bidirectional_generate_bails_for_direct_router_mode() {
2811        let rt = Runtime::from_current().unwrap();
2812        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2813            .await
2814            .unwrap();
2815        let ns = drt.namespace("test_bidi_direct_mode".to_string()).unwrap();
2816        let component = ns.component("test_component".to_string()).unwrap();
2817        let endpoint = component.endpoint("test_endpoint".to_string());
2818        let client = endpoint.client().await.unwrap();
2819
2820        let router = PushRouter::<u64, TestResponse>::from_client(client, RouterMode::Direct)
2821            .await
2822            .unwrap();
2823
2824        let input: ManyIn<u64> =
2825            Context::new(RequestStream::new(Box::pin(tokio_stream::iter(vec![1u64]))));
2826        let result = router.generate(input).await;
2827        assert!(
2828            result.is_err(),
2829            "bidirectional generate must bail for RouterMode::Direct"
2830        );
2831        let err_msg = format!("{:?}", result.unwrap_err());
2832        assert!(
2833            err_msg.contains("Direct") || err_msg.contains("direct"),
2834            "error should mention Direct: got {err_msg}"
2835        );
2836
2837        rt.shutdown();
2838    }
2839
2840    #[tokio::test]
2841    async fn bidirectional_generate_rejects_unsupported_load_aware_modes() {
2842        let rt = Runtime::from_current().unwrap();
2843        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2844            .await
2845            .unwrap();
2846        let ns = drt.namespace("test_bidi_load_aware".to_string()).unwrap();
2847        let component = ns.component("test_component".to_string()).unwrap();
2848
2849        for mode in [RouterMode::LeastLoaded, RouterMode::DeviceAwareWeighted] {
2850            let endpoint = component.endpoint("test_endpoint".to_string());
2851            let client = endpoint.client().await.unwrap();
2852            let router = PushRouter::<u64, TestResponse>::for_test(client, mode)
2853                .await
2854                .unwrap();
2855
2856            let input: ManyIn<u64> =
2857                Context::new(RequestStream::new(Box::pin(tokio_stream::iter(vec![1u64]))));
2858            let result = router.generate(input).await;
2859            assert!(
2860                result.is_err(),
2861                "bidirectional generate must reject {mode:?} (not yet supported)"
2862            );
2863            let err_msg = format!("{:?}", result.unwrap_err());
2864            assert!(
2865                err_msg.contains("not yet supported for bidirectional dispatch"),
2866                "error should explain the mode is unsupported, not 'no instances': got {err_msg}"
2867            );
2868        }
2869
2870        rt.shutdown();
2871    }
2872
2873    #[tokio::test]
2874    async fn least_loaded_peek_returns_available_worker_select_stays_none() {
2875        let rt = Runtime::from_current().unwrap();
2876        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2877            .await
2878            .unwrap();
2879        let ns = drt
2880            .namespace("test_least_loaded_router".to_string())
2881            .unwrap();
2882        let component = ns.component("test_component".to_string()).unwrap();
2883        let endpoint = component.endpoint("test_endpoint".to_string());
2884        let client = endpoint.client().await.unwrap();
2885
2886        endpoint.register_endpoint_instance().await.unwrap();
2887        client.wait_for_instances().await.unwrap();
2888
2889        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::LeastLoaded)
2890            .await
2891            .unwrap();
2892
2893        // LeastLoaded selection tracks request occupancy, so the advisory API is
2894        // separate from select_next_worker().
2895        assert_eq!(router.select_next_worker(), None);
2896        assert!(
2897            router.peek_next_worker().is_some(),
2898            "LeastLoaded peek must return the available worker for disagg bootstrap"
2899        );
2900
2901        rt.shutdown();
2902    }
2903
2904    #[tokio::test]
2905    async fn exact_selection_releases_occupancy_when_preparation_fails() {
2906        let rt = Runtime::from_current().unwrap();
2907        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2908            .await
2909            .unwrap();
2910        let ns = drt
2911            .namespace("test_exact_prepare_failure".to_string())
2912            .unwrap();
2913        let component = ns.component("test_component".to_string()).unwrap();
2914        let endpoint = component.endpoint("test_endpoint".to_string());
2915        let client = endpoint.client().await.unwrap();
2916        endpoint.register_endpoint_instance().await.unwrap();
2917        let worker_id = client.wait_for_instances().await.unwrap()[0].id();
2918
2919        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::LeastLoaded)
2920            .await
2921            .unwrap();
2922        let state = router.occupancy_state.clone().unwrap();
2923        let result = router
2924            .select_and_dispatch_exact(SingleIn::new(42), None, |_, _| {
2925                Err::<(), _>(anyhow::anyhow!("metadata preparation failed"))
2926            })
2927            .await;
2928
2929        assert!(result.is_err());
2930        assert_eq!(
2931            state.load(worker_id),
2932            0,
2933            "preparation failure must release the selected worker"
2934        );
2935        rt.shutdown();
2936    }
2937
2938    #[tokio::test]
2939    async fn exact_dispatch_revalidates_overload_after_preparation() {
2940        let rt = Runtime::from_current().unwrap();
2941        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2942            .await
2943            .unwrap();
2944        let ns = drt
2945            .namespace("test_exact_overload_revalidation".to_string())
2946            .unwrap();
2947        let component = ns.component("test_component".to_string()).unwrap();
2948        let endpoint = component.endpoint("test_endpoint".to_string());
2949        let client = endpoint.client().await.unwrap();
2950        endpoint.register_endpoint_instance().await.unwrap();
2951        let worker_id = client.wait_for_instances().await.unwrap()[0].id();
2952
2953        let router =
2954            PushRouter::<u64, TestResponse>::for_test(client.clone(), RouterMode::LeastLoaded)
2955                .await
2956                .unwrap();
2957        let state = router.occupancy_state.clone().unwrap();
2958        let result = router
2959            .select_and_dispatch_exact(SingleIn::new(42), Some(worker_id), |_, worker_id| {
2960                client.set_overloaded_instances(&[worker_id]);
2961                Ok(())
2962            })
2963            .await;
2964
2965        assert!(result.is_err());
2966        assert_eq!(
2967            state.load(worker_id),
2968            0,
2969            "validation failure must release the selected worker"
2970        );
2971        rt.shutdown();
2972    }
2973
2974    #[tokio::test]
2975    async fn transport_resolution_precedes_stale_overload_check() {
2976        let rt = Runtime::from_current().unwrap();
2977        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2978            .await
2979            .unwrap();
2980        let endpoint = drt
2981            .namespace("test_transport_precedes_stale_overload".to_string())
2982            .unwrap()
2983            .component("test_component".to_string())
2984            .unwrap()
2985            .endpoint("test_endpoint".to_string());
2986        let client = endpoint.client().await.unwrap();
2987        let stale_id = 99999;
2988        client.override_instance_avail(vec![stale_id]);
2989        client.set_overloaded_instances(&[stale_id]);
2990        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::RoundRobin)
2991            .await
2992            .unwrap();
2993
2994        let unary_error = router
2995            .direct(SingleIn::new(42), stale_id)
2996            .await
2997            .unwrap_err();
2998        assert_cannot_connect(&unary_error);
2999
3000        let input: ManyIn<u64> =
3001            Context::new(RequestStream::new(Box::pin(tokio_stream::iter(vec![1u64]))));
3002        let bidirectional_error = router
3003            .bidirectional_dispatch(stale_id, input)
3004            .await
3005            .unwrap_err();
3006        assert_not_cannot_connect(&bidirectional_error);
3007        assert!(
3008            !match_error_chain(
3009                bidirectional_error.as_ref(),
3010                &[ErrorType::ResourceExhausted],
3011                &[]
3012            ),
3013            "transport resolution must precede the stale overload check: {bidirectional_error}"
3014        );
3015
3016        rt.shutdown();
3017    }
3018
3019    #[tokio::test]
3020    async fn selected_overloaded_worker_is_rejected_before_dispatch() {
3021        const TEST_RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);
3022
3023        let rt = Runtime::from_current().unwrap();
3024        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3025            .await
3026            .unwrap();
3027        let ns = drt
3028            .namespace("test_selected_overloaded_worker_rejected".to_string())
3029            .unwrap();
3030        let component = ns.component("test_component".to_string()).unwrap();
3031        let endpoint = component.endpoint("test_endpoint".to_string());
3032        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
3033            .await
3034            .unwrap();
3035
3036        endpoint.register_endpoint_instance().await.unwrap();
3037        let instances = client.wait_for_instances().await.unwrap();
3038        let worker_id = instances[0].id();
3039
3040        for _ in 0..10 {
3041            if client.instance_ids_avail().contains(&worker_id) {
3042                break;
3043            }
3044            tokio::time::sleep(TEST_RECONCILE_INTERVAL).await;
3045        }
3046        assert!(
3047            client.instance_ids_avail().contains(&worker_id),
3048            "worker should be routable before marking it overloaded"
3049        );
3050
3051        client.set_overloaded_instances(&[worker_id]);
3052        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::RoundRobin)
3053            .await
3054            .unwrap();
3055
3056        let result = router.generate(SingleIn::new(42u64)).await;
3057        assert!(result.is_err());
3058        let msg = format!("{}", result.unwrap_err());
3059        // With pre-selection filtering on free_ids, the single-overloaded-worker
3060        // case is now caught before selection rather than after — the chosen
3061        // worker is never overloaded because the candidate pool excludes it.
3062        // The post-selection check in route() remains as a race-condition
3063        // backstop.
3064        assert!(
3065            msg.contains("All workers are busy"),
3066            "expected empty-free-pool rejection, got: {msg}"
3067        );
3068
3069        rt.shutdown();
3070    }
3071
3072    #[tokio::test]
3073    async fn direct_within_rejects_overloaded_constrained_target() {
3074        const TEST_RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(3600);
3075
3076        let rt = Runtime::from_current().unwrap();
3077        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3078            .await
3079            .unwrap();
3080        let ns = drt
3081            .namespace("test_direct_within_overload_rejection".to_string())
3082            .unwrap();
3083        let component = ns.component("test_component".to_string()).unwrap();
3084        let endpoint = component.endpoint("test_endpoint".to_string());
3085        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
3086            .await
3087            .unwrap();
3088
3089        endpoint.register_endpoint_instance().await.unwrap();
3090        let worker_id = client.wait_for_instances().await.unwrap()[0].id();
3091        client.set_overloaded_instances(&[worker_id]);
3092
3093        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::RoundRobin)
3094            .await
3095            .unwrap();
3096        let allowed = HashSet::from([worker_id]);
3097        let error = router
3098            .direct_within(SingleIn::new(42), worker_id, Some(&allowed))
3099            .await
3100            .unwrap_err();
3101
3102        // A *selected* worker being overloaded is single-worker overload, distinct
3103        // from pool-wide exhaustion: migration may retry elsewhere. Previously
3104        // both collapsed to ResourceExhausted, which blocked that retry.
3105        assert!(match_error_chain(
3106            error.as_ref(),
3107            &[ErrorType::WorkerOverloaded],
3108            &[]
3109        ));
3110        assert!(
3111            error.to_string().contains("Selected worker is overloaded"),
3112            "expected overload rejection, got: {error}"
3113        );
3114
3115        rt.shutdown();
3116    }
3117
3118    #[tokio::test]
3119    async fn no_workers_is_reported_as_unavailable() {
3120        let rt = Runtime::from_current().unwrap();
3121        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3122            .await
3123            .unwrap();
3124        let ns = drt
3125            .namespace("test_no_workers_unavailable".to_string())
3126            .unwrap();
3127        let component = ns.component("test_component".to_string()).unwrap();
3128        let endpoint = component.endpoint("test_endpoint".to_string());
3129        let client = endpoint.client().await.unwrap();
3130        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::RoundRobin)
3131            .await
3132            .unwrap();
3133
3134        let error = router.generate(SingleIn::new(42)).await.unwrap_err();
3135        assert!(match_error_chain(
3136            error.as_ref(),
3137            &[ErrorType::Unavailable],
3138            &[]
3139        ));
3140
3141        rt.shutdown();
3142    }
3143
3144    #[tokio::test]
3145    async fn round_robin_excludes_overloaded_workers_from_candidates() {
3146        // Long reconcile interval so the synthetic override below survives
3147        // the test. We still register a real endpoint instance up front so
3148        // the initial reconcile (which fires immediately when the monitor
3149        // task spawns) settles on a non-empty source — without that, the
3150        // first reconcile would clobber the override before it takes effect.
3151        const TEST_RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(3600);
3152
3153        let rt = Runtime::from_current().unwrap();
3154        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3155            .await
3156            .unwrap();
3157        let ns = drt
3158            .namespace("test_round_robin_excludes_overloaded".to_string())
3159            .unwrap();
3160        let component = ns.component("test_component".to_string()).unwrap();
3161        let endpoint = component.endpoint("test_endpoint".to_string());
3162        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
3163            .await
3164            .unwrap();
3165
3166        endpoint.register_endpoint_instance().await.unwrap();
3167        let instances = client.wait_for_instances().await.unwrap();
3168        let real_id = instances[0].id();
3169        for _ in 0..50 {
3170            if client.instance_ids_avail().contains(&real_id) {
3171                break;
3172            }
3173            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3174        }
3175
3176        // Now override with two synthetic IDs and mark one overloaded.
3177        // round_robin must never select the overloaded one — that's the
3178        // whole point of selecting from free_ids instead of routable_ids.
3179        // The post-selection overload check in route() would otherwise return 529
3180        // one of N requests on each pass, which is the bug this PR closes
3181        // for non-KV selectors.
3182        client.override_instance_avail(vec![1, 2]);
3183        client.set_overloaded_instances(&[1]);
3184
3185        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::RoundRobin)
3186            .await
3187            .unwrap();
3188
3189        // Round-robin over N requests should land on worker 2 every time.
3190        // We use peek_next_worker for a side-effect-free probe.
3191        for _ in 0..6 {
3192            let selected = router
3193                .peek_next_worker()
3194                .expect("peek should succeed with a free worker");
3195            assert_eq!(
3196                selected, 2,
3197                "overloaded worker 1 must not appear in the candidate set"
3198            );
3199        }
3200
3201        rt.shutdown();
3202    }
3203
3204    #[tokio::test]
3205    async fn device_aware_weighted_peek_returns_available_worker_select_stays_none() {
3206        let rt = Runtime::from_current().unwrap();
3207        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3208            .await
3209            .unwrap();
3210        let ns = drt
3211            .namespace("test_device_aware_router".to_string())
3212            .unwrap();
3213        let component = ns.component("test_component".to_string()).unwrap();
3214        let endpoint = component.endpoint("test_endpoint".to_string());
3215        let client = endpoint.client().await.unwrap();
3216
3217        endpoint.register_endpoint_instance().await.unwrap();
3218        client.wait_for_instances().await.unwrap();
3219
3220        let router =
3221            PushRouter::<u64, TestResponse>::from_client(client, RouterMode::DeviceAwareWeighted)
3222                .await
3223                .unwrap();
3224
3225        // DeviceAwareWeighted degenerates to least-loaded for peek (device-class
3226        // partitioning happens at dispatch); select_next_worker stays None.
3227        assert_eq!(router.select_next_worker(), None);
3228        assert!(
3229            router.peek_next_worker().is_some(),
3230            "DeviceAwareWeighted peek must return the available worker for disagg bootstrap"
3231        );
3232
3233        rt.shutdown();
3234    }
3235
3236    #[tokio::test]
3237    async fn device_aware_exact_selection_preserves_full_multimodal_cache_hit() {
3238        let rt = Runtime::from_current().unwrap();
3239        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3240            .await
3241            .unwrap();
3242        let ns = drt
3243            .namespace("test_device_aware_affinity_cache".to_string())
3244            .unwrap();
3245        let component = ns.component("test_component".to_string()).unwrap();
3246        let endpoint = component.endpoint("test_endpoint".to_string());
3247        let client = endpoint.client().await.unwrap();
3248        endpoint.register_endpoint_instance().await.unwrap();
3249        let cache_worker = client.wait_for_instances().await.unwrap()[0].id();
3250
3251        let router = PushRouter::<u64, TestResponse>::from_client_with_options(
3252            client,
3253            RouterMode::DeviceAwareWeighted,
3254            PushRouterOptions {
3255                multimodal_cache_indexer: Some(Arc::new(StaticMultimodalCacheIndex {
3256                    worker_id: cache_worker,
3257                })),
3258                multimodal_cache_key_extractor: Some(Arc::new(|_| vec!["image-key".to_string()])),
3259                ..PushRouterOptions::default()
3260            },
3261        )
3262        .await
3263        .unwrap();
3264
3265        let selection = router.select_device_aware_and_reserve(&42, None).unwrap();
3266        assert_eq!(selection.worker_id(), cache_worker);
3267        assert!(
3268            selection.into_reservation().is_none(),
3269            "full cache hits bypass occupancy charging"
3270        );
3271
3272        rt.shutdown();
3273    }
3274
3275    /// Direct dispatch honors an upstream-selected worker even after local inhibition.
3276    #[tokio::test]
3277    async fn direct_dispatch_ignores_local_inhibition() {
3278        let rt = Runtime::from_current().unwrap();
3279        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3280            .await
3281            .unwrap();
3282        let ns = drt
3283            .namespace("test_direct_bypasses_inhibition".to_string())
3284            .unwrap();
3285        let component = ns.component("test_component".to_string()).unwrap();
3286        let endpoint = component.endpoint("test_endpoint".to_string());
3287        let client = endpoint.client().await.unwrap();
3288        endpoint.register_endpoint_instance().await.unwrap();
3289        let instance_id = client.wait_for_instances().await.unwrap()[0].id();
3290
3291        // KV routing selects upstream and dispatches through PushRouter::direct.
3292        let router = PushRouter::<u64, TestResponse>::from_client(client.clone(), RouterMode::KV)
3293            .await
3294            .unwrap();
3295
3296        client.report_instance_down(instance_id);
3297        assert!(
3298            !client.instance_ids_avail().contains(&instance_id),
3299            "precondition: worker should be locally inhibited"
3300        );
3301
3302        let result = router
3303            .direct_within_prepared(
3304                SingleIn::new(42),
3305                instance_id,
3306                None,
3307                |_, selected_instance_id| {
3308                    assert_eq!(selected_instance_id, instance_id);
3309                    Err::<(), _>(anyhow::anyhow!("direct prepare sentinel"))
3310                },
3311            )
3312            .await;
3313        let error = match result {
3314            Ok(_) => panic!("direct dispatch should reach request preparation"),
3315            Err(error) => error,
3316        };
3317        assert_eq!(error.to_string(), "direct prepare sentinel");
3318
3319        let missing_instance_id = instance_id.wrapping_add(1);
3320        let result = router
3321            .direct_within_prepared(SingleIn::new(42), missing_instance_id, None, |_, _| {
3322                Ok::<(), anyhow::Error>(())
3323            })
3324            .await;
3325        let error = match result {
3326            Ok(_) => panic!("direct dispatch should reject a worker absent from discovery"),
3327            Err(error) => error,
3328        };
3329        assert!(
3330            error
3331                .to_string()
3332                .contains(&format!("instance_id={missing_instance_id} not found")),
3333            "unexpected missing-worker error: {error}"
3334        );
3335
3336        rt.shutdown();
3337    }
3338
3339    /// When the router selects an instance that has deregistered between selection
3340    /// and transport resolution, it should fall back to another available instance
3341    /// rather than returning a 500 error.
3342    #[tokio::test]
3343    async fn transport_resolution_falls_back_when_selected_instance_disappears() {
3344        let rt = Runtime::from_current().unwrap();
3345        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3346            .await
3347            .unwrap();
3348        let ns = drt
3349            .namespace("test_transport_fallback".to_string())
3350            .unwrap();
3351        let component = ns.component("test_component".to_string()).unwrap();
3352        let endpoint = component.endpoint("test_endpoint".to_string());
3353        let client = endpoint.client().await.unwrap();
3354
3355        // Register one real instance so it appears in instance_source.
3356        endpoint.register_endpoint_instance().await.unwrap();
3357        client.wait_for_instances().await.unwrap();
3358
3359        let real_id = client.instance_ids()[0];
3360
3361        // Inject a stale ID into instance_avail that does NOT exist in
3362        // instance_source. This simulates the race window where an instance
3363        // deregistered after selection but before transport resolution.
3364        let stale_id = real_id + 1000;
3365        client.override_instance_avail(vec![stale_id, real_id]);
3366
3367        let router =
3368            PushRouter::<u64, TestResponse>::for_test(client.clone(), RouterMode::RoundRobin)
3369                .await
3370                .unwrap();
3371
3372        // Exercise transport resolution directly. Sending a request to this
3373        // registration would wait forever because the test intentionally has
3374        // no worker handler.
3375        let (resolved_id, _, _, _) = router
3376            .resolve_transport(stale_id, TransportFallback::Allow)
3377            .expect("normal routing should fall back from a stale worker");
3378        assert_eq!(resolved_id, real_id);
3379
3380        rt.shutdown();
3381    }
3382
3383    #[tokio::test]
3384    async fn prepared_dispatch_observes_worker_after_transport_fallback() {
3385        let rt = Runtime::from_current().unwrap();
3386        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3387            .await
3388            .unwrap();
3389        let endpoint = drt
3390            .namespace("test_prepared_transport_fallback".to_string())
3391            .unwrap()
3392            .component("test_component".to_string())
3393            .unwrap()
3394            .endpoint("test_endpoint".to_string());
3395        let client = endpoint.client().await.unwrap();
3396        endpoint.register_endpoint_instance().await.unwrap();
3397        let real_id = client.wait_for_instances().await.unwrap()[0].id();
3398        let stale_id = real_id.wrapping_add(1);
3399        client.override_instance_avail(vec![stale_id, real_id]);
3400        let router = PushRouter::<u64, TestResponse>::for_test(client, RouterMode::LeastLoaded)
3401            .await
3402            .unwrap();
3403        let state = router.occupancy_state.clone().unwrap();
3404        state.increment(real_id);
3405        let state_for_prepare = state.clone();
3406        let observed = Arc::new(AtomicU64::new(0));
3407        let observed_for_prepare = observed.clone();
3408
3409        let _ = tokio::time::timeout(
3410            std::time::Duration::from_millis(100),
3411            router.select_and_dispatch(SingleIn::new(42), move |_, worker_id| {
3412                assert_eq!(state_for_prepare.load(stale_id), 0);
3413                assert_eq!(state_for_prepare.load(worker_id), 2);
3414                observed_for_prepare.store(worker_id, Ordering::Relaxed);
3415                Ok(())
3416            }),
3417        )
3418        .await;
3419
3420        assert_eq!(observed.load(Ordering::Relaxed), real_id);
3421        assert_eq!(state.load(real_id), 1);
3422        state.decrement(real_id);
3423        rt.shutdown();
3424    }
3425
3426    /// When no instances are available at all (both primary and fallback),
3427    /// the router should return a clear error.
3428    #[tokio::test]
3429    async fn transport_resolution_errors_when_no_instances_available() {
3430        let rt = Runtime::from_current().unwrap();
3431        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3432            .await
3433            .unwrap();
3434        let ns = drt
3435            .namespace("test_transport_no_fallback".to_string())
3436            .unwrap();
3437        let component = ns.component("test_component".to_string()).unwrap();
3438        let endpoint = component.endpoint("test_endpoint".to_string());
3439        // Freeze `monitor_instance_source` before staging routing state. That
3440        // task reconciles `routable_ids` back to the real discovered set on
3441        // every discovery change *and* every `reconcile_interval` (5s by
3442        // default), so it silently undoes `override_instance_avail` mid-test.
3443        // Cancelling before registration means the only writer left is this
3444        // test. Safe because `wait_for_instances` reads `instance_source`
3445        // directly rather than the reconciled routing snapshot.
3446        let monitor = tokio_util::sync::CancellationToken::new();
3447        let client = endpoint
3448            .client_with_cancellation(monitor.clone())
3449            .await
3450            .unwrap();
3451        monitor.cancel();
3452
3453        // Register an instance so we can create the router (needs transport setup).
3454        endpoint.register_endpoint_instance().await.unwrap();
3455        client.wait_for_instances().await.unwrap();
3456
3457        let router =
3458            PushRouter::<u64, TestResponse>::for_test(client.clone(), RouterMode::RoundRobin)
3459                .await
3460                .unwrap();
3461
3462        // Override avail to contain only a stale ID with no real backing
3463        // instance AND no other available fallback.
3464        let stale_id = 99999;
3465        client.override_instance_avail(vec![stale_id]);
3466
3467        let request = SingleIn::new(42u64);
3468        let result = router.generate(request).await;
3469
3470        assert!(result.is_err());
3471        let error = result.unwrap_err();
3472        assert_unavailable(&error);
3473        let msg = error.to_string();
3474        assert!(
3475            msg.contains("not found") && msg.contains("no other instances available"),
3476            "Expected clear error about missing instance with no fallback, got: {msg}"
3477        );
3478
3479        rt.shutdown();
3480    }
3481
3482    #[tokio::test]
3483    async fn transport_resolution_honors_fallback_policy() {
3484        let rt = Runtime::from_current().unwrap();
3485        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3486            .await
3487            .unwrap();
3488        let ns = drt
3489            .namespace("test_exact_transport_no_fallback".to_string())
3490            .unwrap();
3491        let component = ns.component("test_component".to_string()).unwrap();
3492        let endpoint = component.endpoint("test_endpoint".to_string());
3493        // Freeze `monitor_instance_source` before staging routing state. That
3494        // task reconciles `routable_ids` back to the real discovered set on
3495        // every discovery change *and* every `reconcile_interval` (5s by
3496        // default), so it silently undoes `override_instance_avail` mid-test.
3497        // Cancelling before registration means the only writer left is this
3498        // test. Safe because `wait_for_instances` reads `instance_source`
3499        // directly rather than the reconciled routing snapshot.
3500        let monitor = tokio_util::sync::CancellationToken::new();
3501        let client = endpoint
3502            .client_with_cancellation(monitor.clone())
3503            .await
3504            .unwrap();
3505        monitor.cancel();
3506        endpoint.register_endpoint_instance().await.unwrap();
3507        let instances = client.wait_for_instances().await.unwrap();
3508        let real_id = instances[0].id();
3509
3510        let router =
3511            PushRouter::<u64, TestResponse>::for_test(client.clone(), RouterMode::RoundRobin)
3512                .await
3513                .unwrap();
3514        let stale_id = real_id.wrapping_add(1);
3515        client.override_instance_avail(vec![stale_id, real_id]);
3516
3517        assert!(
3518            router
3519                .resolve_transport(stale_id, TransportFallback::Allow)
3520                .is_ok(),
3521            "normal dispatch should preserve transport fallback"
3522        );
3523        let allowed = HashSet::from([real_id]);
3524        assert!(
3525            router
3526                .resolve_transport(stale_id, TransportFallback::Within(&allowed))
3527                .is_ok(),
3528            "constrained dispatch should fall back within the allowed worker set"
3529        );
3530        let disallowed = HashSet::new();
3531        let disallowed_error = router
3532            .resolve_transport(stale_id, TransportFallback::Within(&disallowed))
3533            .unwrap_err();
3534        assert_unavailable(&disallowed_error);
3535
3536        let exact_error = router
3537            .resolve_transport(stale_id, TransportFallback::Deny)
3538            .unwrap_err();
3539        assert_cannot_connect(&exact_error);
3540
3541        let second_stale_id = stale_id.wrapping_add(1);
3542        client.override_instance_avail(vec![stale_id, second_stale_id]);
3543        let stale_fallback_error = router
3544            .resolve_transport(stale_id, TransportFallback::Allow)
3545            .unwrap_err();
3546        assert_cannot_connect(&stale_fallback_error);
3547        assert!(
3548            stale_fallback_error
3549                .to_string()
3550                .contains("Fallback instance"),
3551            "expected fallback lookup failure, got: {stale_fallback_error}"
3552        );
3553        rt.shutdown();
3554    }
3555
3556    /// The watcher dedup guard must be released even if the spawned task panics.
3557    /// Without this, a panic anywhere in the watcher body would leave a stale
3558    /// `ENDPOINT_WATCHER_ACTIVE` entry, silently disabling orphaned-pending-
3559    /// request cancellation for that endpoint until process restart.
3560    ///
3561    /// We exercise the Drop-guard pattern directly against the same static
3562    /// rather than driving `spawn_instance_removal_watcher` end-to-end (which
3563    /// would require staging a panicking discovery stream). The test mirrors
3564    /// the production code's GuardRelease shape; if the production code stops
3565    /// using a Drop guard, the integration would regress and the existing
3566    /// orphan-cancellation tests would fail.
3567    #[tokio::test]
3568    async fn watcher_dedup_guard_released_on_panic() {
3569        let endpoint_id = EndpointId {
3570            namespace: "panic-test-ns".to_string(),
3571            component: "panic-test-comp".to_string(),
3572            name: "panic-test-endpoint".to_string(),
3573        };
3574
3575        // Mimic the production code's pre-spawn dedup insert.
3576        let map = ENDPOINT_WATCHER_ACTIVE.get_or_init(dashmap::DashMap::new);
3577        map.insert(endpoint_id.clone(), ());
3578
3579        let endpoint_id_clone = endpoint_id.clone();
3580        let join = tokio::spawn(async move {
3581            // Same shape as in spawn_instance_removal_watcher.
3582            struct GuardRelease(EndpointId);
3583            impl Drop for GuardRelease {
3584                fn drop(&mut self) {
3585                    if let Some(map) = ENDPOINT_WATCHER_ACTIVE.get() {
3586                        map.remove(&self.0);
3587                    }
3588                }
3589            }
3590            let _release = GuardRelease(endpoint_id_clone);
3591            panic!("simulated watcher-task panic");
3592        });
3593
3594        let result = join.await;
3595        assert!(result.is_err() && result.unwrap_err().is_panic());
3596        assert!(
3597            !map.contains_key(&endpoint_id),
3598            "Drop guard must release the dedup entry even on panic"
3599        );
3600    }
3601
3602    /// Normal-exit path: the Drop guard releases the entry when the task
3603    /// finishes without panicking. This is the everyday case (cancel_token
3604    /// fires or discovery stream closes).
3605    #[tokio::test]
3606    async fn watcher_dedup_guard_released_on_normal_exit() {
3607        let endpoint_id = EndpointId {
3608            namespace: "normal-test-ns".to_string(),
3609            component: "normal-test-comp".to_string(),
3610            name: "normal-test-endpoint".to_string(),
3611        };
3612
3613        let map = ENDPOINT_WATCHER_ACTIVE.get_or_init(dashmap::DashMap::new);
3614        map.insert(endpoint_id.clone(), ());
3615
3616        let endpoint_id_clone = endpoint_id.clone();
3617        tokio::spawn(async move {
3618            struct GuardRelease(EndpointId);
3619            impl Drop for GuardRelease {
3620                fn drop(&mut self) {
3621                    if let Some(map) = ENDPOINT_WATCHER_ACTIVE.get() {
3622                        map.remove(&self.0);
3623                    }
3624                }
3625            }
3626            let _release = GuardRelease(endpoint_id_clone);
3627            // task body returns normally
3628        })
3629        .await
3630        .unwrap();
3631
3632        assert!(!map.contains_key(&endpoint_id));
3633    }
3634
3635    #[tokio::test]
3636    async fn cache_cleanup_watcher_identity_includes_runtime() {
3637        let runtime = Runtime::from_current().unwrap();
3638        let first = DistributedRuntime::new(runtime.clone(), DistributedConfig::process_local())
3639            .await
3640            .unwrap();
3641        let second = DistributedRuntime::new(runtime.clone(), DistributedConfig::process_local())
3642            .await
3643            .unwrap();
3644        let endpoint = |distributed: &DistributedRuntime| {
3645            distributed
3646                .namespace("cache-watcher-identity".to_string())
3647                .unwrap()
3648                .component("workers".to_string())
3649                .unwrap()
3650                .endpoint("generate".to_string())
3651        };
3652        let first = RuntimeEndpointId::for_endpoint(&endpoint(&first));
3653        let second = RuntimeEndpointId::for_endpoint(&endpoint(&second));
3654
3655        assert_eq!(first.endpoint_id, second.endpoint_id);
3656        assert_ne!(first.connection_id, second.connection_id);
3657        assert_ne!(first, second);
3658
3659        runtime.shutdown();
3660    }
3661
3662    /// A `StreamingDispatch` that records what the router hands the seam, so the
3663    /// test can assert a *caller-supplied* dispatch (not just the default
3664    /// `AddressedPushRouter`) receives the selected address/instance and the
3665    /// discovery lifecycle events.
3666    #[derive(Default)]
3667    struct RecordingDispatch {
3668        unary: std::sync::Mutex<Vec<(u64, String, Option<u64>)>>,
3669        bidi: std::sync::Mutex<Vec<(String, u64)>>,
3670        added: std::sync::Mutex<Vec<u64>>,
3671        removed: std::sync::Mutex<Vec<u64>>,
3672    }
3673
3674    impl RecordingDispatch {
3675        fn canned_stream() -> ManyOut<TestResponse> {
3676            let ctx: Arc<dyn AsyncEngineContext> = Arc::new(Controller::default());
3677            ResponseStream::new(
3678                Box::pin(tokio_stream::iter(vec![TestResponse { error: None }])),
3679                ctx,
3680            )
3681        }
3682    }
3683
3684    #[async_trait::async_trait]
3685    impl StreamingDispatch<u64, TestResponse> for RecordingDispatch {
3686        async fn generate(
3687            &self,
3688            request: SingleIn<AddressedRequest<u64>>,
3689        ) -> Result<ManyOut<TestResponse>, Error> {
3690            let (addressed, _ctx) = request.transfer(());
3691            let (payload, address, instance) = addressed.into_parts();
3692            self.unary
3693                .lock()
3694                .unwrap()
3695                .push((payload, address, instance.map(|i| i.id())));
3696            Ok(Self::canned_stream())
3697        }
3698
3699        async fn generate_bidirectional(
3700            &self,
3701            instance: Instance,
3702            address: String,
3703            _input: ManyIn<u64>,
3704        ) -> Result<ManyOut<TestResponse>, Error> {
3705            self.bidi.lock().unwrap().push((address, instance.id()));
3706            Ok(Self::canned_stream())
3707        }
3708
3709        async fn on_instance_removed(&self, id: &EndpointInstanceId) {
3710            self.removed.lock().unwrap().push(id.instance_id);
3711        }
3712
3713        async fn on_instance_added(&self, id: &EndpointInstanceId) {
3714            self.added.lock().unwrap().push(id.instance_id);
3715        }
3716    }
3717
3718    /// The transport seam must deliver to a caller-supplied `StreamingDispatch`:
3719    /// unary and bidirectional requests arrive with the selected address and
3720    /// instance, and discovery removal/re-addition reach its lifecycle hooks.
3721    #[tokio::test]
3722    async fn from_client_with_dispatch_delivers_requests_and_lifecycle() {
3723        let rt = Runtime::from_current().unwrap();
3724        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3725            .await
3726            .unwrap();
3727        let endpoint = drt
3728            .namespace("test_dispatch_seam".to_string())
3729            .unwrap()
3730            .component("test_component".to_string())
3731            .unwrap()
3732            .endpoint("test_endpoint".to_string());
3733        let client = endpoint.client().await.unwrap();
3734
3735        endpoint.register_endpoint_instance().await.unwrap();
3736        let instance_id = client.wait_for_instances().await.unwrap()[0].id();
3737
3738        let dispatch = Arc::new(RecordingDispatch::default());
3739        let router = PushRouter::<u64, TestResponse>::from_client_with_options(
3740            client.clone(),
3741            RouterMode::RoundRobin,
3742            PushRouterOptions {
3743                selectors: Some(test_selectors()),
3744                dispatch: Some(dispatch.clone()),
3745                ..PushRouterOptions::default()
3746            },
3747        )
3748        .await
3749        .unwrap();
3750
3751        // Unary hop reaches the supplied dispatch with the selected worker.
3752        let mut stream = router.generate(SingleIn::new(42u64)).await.unwrap();
3753        while stream.next().await.is_some() {}
3754        {
3755            let unary = dispatch.unary.lock().unwrap();
3756            assert_eq!(unary.len(), 1, "one unary dispatch expected");
3757            let (payload, address, dispatched) = &unary[0];
3758            assert_eq!(*payload, 42);
3759            assert_eq!(*dispatched, Some(instance_id));
3760            assert!(!address.is_empty(), "selected transport address expected");
3761        }
3762
3763        // Bidirectional hop reaches the supplied dispatch with the same worker.
3764        let input: ManyIn<u64> =
3765            Context::new(RequestStream::new(Box::pin(tokio_stream::iter(vec![
3766                1u64, 2u64,
3767            ]))));
3768        let mut stream = router.generate(input).await.unwrap();
3769        while stream.next().await.is_some() {}
3770        {
3771            let bidi = dispatch.bidi.lock().unwrap();
3772            assert_eq!(bidi.len(), 1, "one bidirectional dispatch expected");
3773            assert_eq!(bidi[0].1, instance_id);
3774            assert!(!bidi[0].0.is_empty());
3775        }
3776
3777        // Gate on the initial-snapshot add before mutating discovery: this both
3778        // asserts on_instance_added is delivered and guarantees the watcher is
3779        // subscribed, so the removal broadcast can't race ahead of it.
3780        assert!(
3781            poll_until(|| dispatch.added.lock().unwrap().contains(&instance_id)).await,
3782            "on_instance_added (initial snapshot) not delivered to the supplied dispatch"
3783        );
3784
3785        endpoint.unregister_endpoint_instance().await.unwrap();
3786        assert!(
3787            poll_until(|| dispatch.removed.lock().unwrap().contains(&instance_id)).await,
3788            "on_instance_removed not delivered to the supplied dispatch"
3789        );
3790
3791        // A fresh add after re-registration must also reach the hook.
3792        let adds_before = dispatch.added.lock().unwrap().len();
3793        endpoint.register_endpoint_instance().await.unwrap();
3794        assert!(
3795            poll_until(|| dispatch.added.lock().unwrap().len() > adds_before).await,
3796            "on_instance_added (re-registration) not delivered to the supplied dispatch"
3797        );
3798
3799        rt.shutdown();
3800    }
3801
3802    #[tokio::test]
3803    async fn admitted_dispatch_does_not_reject_the_load_it_just_booked() {
3804        const TEST_RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(3600);
3805
3806        let rt = Runtime::from_current().unwrap();
3807        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3808            .await
3809            .unwrap();
3810        let endpoint = drt
3811            .namespace("test_admitted_dispatch".to_string())
3812            .unwrap()
3813            .component("test_component".to_string())
3814            .unwrap()
3815            .endpoint("test_endpoint".to_string());
3816        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
3817            .await
3818            .unwrap();
3819
3820        endpoint.register_endpoint_instance().await.unwrap();
3821        let instance_id = client.wait_for_instances().await.unwrap()[0].id();
3822        for _ in 0..50 {
3823            if client.instance_ids_avail().contains(&instance_id) {
3824                break;
3825            }
3826            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3827        }
3828        assert!(client.instance_ids_avail().contains(&instance_id));
3829        let dispatch = Arc::new(RecordingDispatch::default());
3830        let router = PushRouter::<u64, TestResponse>::from_client_with_options(
3831            client.clone(),
3832            RouterMode::KV,
3833            PushRouterOptions {
3834                dispatch: Some(dispatch.clone()),
3835                ..PushRouterOptions::default()
3836            },
3837        )
3838        .await
3839        .unwrap();
3840
3841        client.set_overloaded_instances(&[instance_id]);
3842        let error = router
3843            .dispatch_exact(SingleIn::new(41), instance_id)
3844            .await
3845            .unwrap_err();
3846        assert!(match_error_chain(
3847            error.as_ref(),
3848            &[ErrorType::WorkerOverloaded],
3849            &[]
3850        ));
3851        assert!(dispatch.unary.lock().unwrap().is_empty());
3852
3853        let mut stream = router
3854            .dispatch_kv_admitted(SingleIn::new(42), instance_id)
3855            .await
3856            .unwrap();
3857        while stream.next().await.is_some() {}
3858        let unary = dispatch.unary.lock().unwrap();
3859        assert_eq!(unary.len(), 1);
3860        assert_eq!(unary[0].0, 42);
3861        assert!(!unary[0].1.is_empty());
3862        assert_eq!(unary[0].2, Some(instance_id));
3863        drop(unary);
3864
3865        rt.shutdown();
3866    }
3867
3868    /// Records the establish timeout each unary dispatch carries.
3869    #[derive(Default)]
3870    struct DeadlineRecordingDispatch {
3871        seen: std::sync::Mutex<Vec<Option<std::time::Duration>>>,
3872    }
3873
3874    #[async_trait::async_trait]
3875    impl StreamingDispatch<u64, TestResponse> for DeadlineRecordingDispatch {
3876        async fn generate(
3877            &self,
3878            request: SingleIn<AddressedRequest<u64>>,
3879        ) -> Result<ManyOut<TestResponse>, Error> {
3880            self.seen
3881                .lock()
3882                .unwrap()
3883                .push(request.content().establish_timeout());
3884            Ok(RecordingDispatch::canned_stream())
3885        }
3886
3887        async fn generate_bidirectional(
3888            &self,
3889            _instance: Instance,
3890            _address: String,
3891            _input: ManyIn<u64>,
3892        ) -> Result<ManyOut<TestResponse>, Error> {
3893            Ok(RecordingDispatch::canned_stream())
3894        }
3895    }
3896
3897    async fn establish_timeout_seen_by_dispatch(
3898        namespace: &str,
3899        fault_detection_enabled: bool,
3900    ) -> Option<std::time::Duration> {
3901        let rt = Runtime::from_current().unwrap();
3902        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3903            .await
3904            .unwrap();
3905        let endpoint = drt
3906            .namespace(namespace.to_string())
3907            .unwrap()
3908            .component("test_component".to_string())
3909            .unwrap()
3910            .endpoint("test_endpoint".to_string());
3911        let client = endpoint.client().await.unwrap();
3912        endpoint.register_endpoint_instance().await.unwrap();
3913        let instance_id = client.wait_for_instances().await.unwrap()[0].id();
3914        assert!(
3915            poll_until(|| client.instance_ids_avail().contains(&instance_id)).await,
3916            "precondition: worker should be available"
3917        );
3918
3919        let dispatch = Arc::new(DeadlineRecordingDispatch::default());
3920        let mut router = PushRouter::<u64, TestResponse>::from_client_with_options(
3921            client.clone(),
3922            RouterMode::RoundRobin,
3923            PushRouterOptions {
3924                selectors: Some(test_selectors()),
3925                dispatch: Some(dispatch.clone()),
3926                ..PushRouterOptions::default()
3927            },
3928        )
3929        .await
3930        .unwrap();
3931        router.establish_timeout = Some(std::time::Duration::from_millis(200));
3932        router.fault_detection_enabled = fault_detection_enabled;
3933
3934        let mut stream = router.generate(SingleIn::new(42u64)).await.unwrap();
3935        while stream.next().await.is_some() {}
3936
3937        let seen = dispatch.seen.lock().unwrap().clone();
3938        rt.shutdown();
3939        assert_eq!(seen.len(), 1, "expected exactly one unary dispatch");
3940        seen[0]
3941    }
3942
3943    /// The deadline rides on the addressed request so the transport can start
3944    /// it at the worker's ACK rather than around local admission and send.
3945    #[tokio::test]
3946    async fn establish_timeout_is_passed_to_dispatch() {
3947        assert_eq!(
3948            establish_timeout_seen_by_dispatch("test_establish_timeout", true).await,
3949            Some(std::time::Duration::from_millis(200))
3950        );
3951    }
3952
3953    /// A monitor that records whether the router started it.
3954    #[derive(Default)]
3955    struct CountingMonitor {
3956        started: AtomicUsize,
3957    }
3958
3959    #[async_trait::async_trait]
3960    impl WorkerLoadMonitor for CountingMonitor {
3961        async fn start_monitoring(&self) -> anyhow::Result<()> {
3962            self.started.fetch_add(1, Ordering::SeqCst);
3963            Ok(())
3964        }
3965    }
3966
3967    async fn options_test_client(namespace: &str) -> (Client, Runtime) {
3968        let rt = Runtime::from_current().unwrap();
3969        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
3970            .await
3971            .unwrap();
3972        let endpoint = drt
3973            .namespace(namespace.to_string())
3974            .unwrap()
3975            .component("test_component".to_string())
3976            .unwrap()
3977            .endpoint("test_endpoint".to_string());
3978        let client = endpoint.client().await.unwrap();
3979        endpoint.register_endpoint_instance().await.unwrap();
3980        client.wait_for_instances().await.unwrap();
3981        (client, rt)
3982    }
3983
3984    #[tokio::test]
3985    async fn named_constructors_set_fault_detection_as_advertised() {
3986        let (client, rt) = options_test_client("test_options_fault_detection").await;
3987        let default =
3988            PushRouter::<u64, TestResponse>::from_client(client.clone(), RouterMode::Direct)
3989                .await
3990                .unwrap();
3991        assert!(default.fault_detection_enabled);
3992        let recovery = PushRouter::<u64, TestResponse>::from_client_no_fault_detection(
3993            client,
3994            RouterMode::Direct,
3995        )
3996        .await
3997        .unwrap();
3998        assert!(!recovery.fault_detection_enabled);
3999        rt.shutdown();
4000    }
4001
4002    #[tokio::test]
4003    async fn options_combine_a_dispatch_with_a_monitor() {
4004        let (client, rt) = options_test_client("test_options_dispatch_and_monitor").await;
4005        let dispatch = Arc::new(RecordingDispatch::default());
4006        let monitor = Arc::new(CountingMonitor::default());
4007        let router = PushRouter::<u64, TestResponse>::from_client_with_options(
4008            client,
4009            RouterMode::RoundRobin,
4010            PushRouterOptions {
4011                selectors: Some(test_selectors()),
4012                dispatch: Some(dispatch.clone()),
4013                worker_monitor: Some(monitor.clone()),
4014                ..PushRouterOptions::default()
4015            },
4016        )
4017        .await
4018        .unwrap();
4019        assert_eq!(monitor.started.load(Ordering::SeqCst), 1);
4020        assert!(router.fault_detection_enabled);
4021
4022        let mut stream = router.generate(SingleIn::new(7u64)).await.unwrap();
4023        while stream.next().await.is_some() {}
4024        let unary = dispatch.unary.lock().unwrap();
4025        assert_eq!(
4026            unary.len(),
4027            1,
4028            "the request must reach the supplied dispatch"
4029        );
4030        assert_eq!(unary[0].0, 7);
4031        drop(unary);
4032        rt.shutdown();
4033    }
4034
4035    #[tokio::test]
4036    async fn establish_timeout_skipped_without_fault_detection() {
4037        assert_eq!(
4038            establish_timeout_seen_by_dispatch("test_establish_timeout_no_fd", false).await,
4039            None,
4040            "routers without fault detection must not bound dispatch"
4041        );
4042    }
4043
4044    /// Poll a predicate until it holds or a short deadline elapses; discovery
4045    /// events reach the watcher's spawned task asynchronously.
4046    async fn poll_until(mut pred: impl FnMut() -> bool) -> bool {
4047        for _ in 0..200 {
4048            if pred() {
4049                return true;
4050            }
4051            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4052        }
4053        pred()
4054    }
4055}