Skip to main content

dynamo_runtime/component/
client.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::{HashMap, HashSet},
6    sync::{Arc, LazyLock, Mutex as StdMutex, Weak},
7    time::Duration,
8};
9
10use anyhow::Result;
11use arc_swap::ArcSwap;
12use futures::StreamExt;
13use tokio::time::Instant;
14use tokio_util::sync::{CancellationToken, DropGuard};
15
16use crate::component::{Endpoint, Instance};
17use crate::config::environment_names::runtime as env_runtime;
18use crate::discovery::{Discovery, DiscoveryEvent, DiscoveryInstance, DiscoveryInstanceId};
19use crate::routing_policy::{RoutingOccupancyState, get_or_create_routing_occupancy_state};
20use crate::traits::DistributedRuntimeProvider;
21
22/// Default interval for periodic reconciliation of instance_avail with instance_source
23const DEFAULT_INHIBITED_DURATION_SECS: u64 = 5;
24
25/// Request-path overload is a short-lived routing hint. A worker is probed
26/// again after this cooldown if no authoritative load update arrives first.
27const REQUEST_PATH_OVERLOAD_COOLDOWN: Duration = Duration::from_secs(1);
28
29/// Process-wide inhibited duration, resolved from the environment on first client construction.
30static INHIBITED_DURATION: LazyLock<Duration> =
31    LazyLock::new(|| inhibited_duration_from_env(|name| std::env::var(name).ok()));
32
33fn inhibited_duration_from_env(mut lookup: impl FnMut(&str) -> Option<String>) -> Duration {
34    let seconds = match lookup(env_runtime::DYN_RUNTIME_INHIBITED_DURATION_SECS) {
35        None => DEFAULT_INHIBITED_DURATION_SECS,
36        Some(raw) => match raw.parse::<u64>() {
37            Ok(seconds) => seconds,
38            Err(err) => {
39                tracing::warn!(
40                    value = raw,
41                    %err,
42                    "invalid {}; using the default of {} seconds",
43                    env_runtime::DYN_RUNTIME_INHIBITED_DURATION_SECS,
44                    DEFAULT_INHIBITED_DURATION_SECS,
45                );
46                DEFAULT_INHIBITED_DURATION_SECS
47            }
48        },
49    };
50    Duration::from_secs(seconds)
51}
52
53/// Shared endpoint discovery state for a single endpoint query.
54///
55/// This wraps both the coalesced instance snapshot used for routing decisions
56/// and a raw, lossless per-subscriber event feed used by the response-stream
57/// cancellation watcher. Both outputs are driven by a single underlying
58/// discovery `list_and_watch` task so clients do not multiply control-plane
59/// watches.
60///
61/// Dropping the source stops that watch. A backend producer can park on its own feed without
62/// noticing that its consumer is gone, as the Kubernetes watcher does, so the token ends it.
63#[derive(Debug)]
64pub(crate) struct EndpointDiscoverySource {
65    instance_source: tokio::sync::watch::Receiver<Vec<Instance>>,
66    event_subscribers: StdMutex<Vec<tokio::sync::mpsc::UnboundedSender<DiscoveryEvent>>>,
67    _watch_guard: DropGuard,
68}
69
70pub(crate) struct DiscoveryEventReceiver {
71    receiver: tokio::sync::mpsc::UnboundedReceiver<DiscoveryEvent>,
72    _source: Arc<EndpointDiscoverySource>,
73}
74
75impl std::ops::Deref for DiscoveryEventReceiver {
76    type Target = tokio::sync::mpsc::UnboundedReceiver<DiscoveryEvent>;
77
78    fn deref(&self) -> &Self::Target {
79        &self.receiver
80    }
81}
82
83impl std::ops::DerefMut for DiscoveryEventReceiver {
84    fn deref_mut(&mut self) -> &mut Self::Target {
85        &mut self.receiver
86    }
87}
88
89impl EndpointDiscoverySource {
90    fn new(
91        instance_source: tokio::sync::watch::Receiver<Vec<Instance>>,
92        watch_guard: DropGuard,
93    ) -> Self {
94        Self {
95            instance_source,
96            event_subscribers: StdMutex::new(Vec::new()),
97            _watch_guard: watch_guard,
98        }
99    }
100
101    fn instance_receiver(&self) -> tokio::sync::watch::Receiver<Vec<Instance>> {
102        self.instance_source.clone()
103    }
104
105    fn subscribe_events(&self) -> tokio::sync::mpsc::UnboundedReceiver<DiscoveryEvent> {
106        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
107        self.event_subscribers.lock().unwrap().push(tx);
108        rx
109    }
110
111    fn broadcast_event(&self, event: &DiscoveryEvent) {
112        let subscribers = &mut *self.event_subscribers.lock().unwrap();
113        subscribers.retain(|tx| tx.send(event.clone()).is_ok());
114    }
115}
116
117#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
118pub struct RoutingInstanceCounts {
119    pub discovered: usize,
120    pub routable: usize,
121    pub overloaded: usize,
122    /// IDs not currently reported overloaded, derived from `discovered - overloaded`.
123    pub free: usize,
124}
125
126#[derive(Clone, Debug)]
127pub(crate) struct RoutingInstances {
128    discovered_ids: Vec<u64>,
129    routable_ids: Vec<u64>,
130    monitor_overloaded_ids: HashSet<u64>,
131    request_overload_deadlines: HashMap<u64, Instant>,
132    next_request_overload_expiry: Option<Instant>,
133    /// Shared with readers, and kept across rebuilds that leave it unchanged, so they
134    /// can tell one overload snapshot from another by pointer.
135    overloaded_ids: Arc<HashSet<u64>>,
136    free_ids: Vec<u64>,
137    routable_id_set: Arc<HashSet<u64>>,
138    /// True after this client has observed at least one discovered instance.
139    /// Once set, a later empty snapshot is authoritative rather than startup
140    /// absence of information.
141    availability_initialized: bool,
142}
143
144impl RoutingInstances {
145    fn new(discovered_ids: Vec<u64>) -> Self {
146        let availability_initialized = !discovered_ids.is_empty();
147        Self::from_parts(
148            discovered_ids.clone(),
149            discovered_ids,
150            HashSet::new(),
151            HashMap::new(),
152            availability_initialized,
153        )
154    }
155
156    fn from_parts(
157        mut discovered_ids: Vec<u64>,
158        mut routable_ids: Vec<u64>,
159        monitor_overloaded_ids: HashSet<u64>,
160        request_overload_deadlines: HashMap<u64, Instant>,
161        availability_initialized: bool,
162    ) -> Self {
163        discovered_ids.sort_unstable();
164        discovered_ids.dedup();
165        routable_ids.sort_unstable();
166        routable_ids.dedup();
167        let mut overloaded_ids = monitor_overloaded_ids.clone();
168        let next_request_overload_expiry = request_overload_deadlines.values().min().copied();
169        overloaded_ids.extend(request_overload_deadlines.keys().copied());
170        let free_ids = Self::derive_free_ids(&routable_ids, &overloaded_ids);
171        let routable_id_set = Arc::new(routable_ids.iter().copied().collect());
172        Self {
173            discovered_ids,
174            routable_ids,
175            monitor_overloaded_ids,
176            request_overload_deadlines,
177            next_request_overload_expiry,
178            overloaded_ids: Arc::new(overloaded_ids),
179            free_ids,
180            routable_id_set,
181            availability_initialized,
182        }
183    }
184
185    pub(crate) fn discovered_ids(&self) -> &[u64] {
186        &self.discovered_ids
187    }
188
189    pub(crate) fn routable_ids(&self) -> &[u64] {
190        &self.routable_ids
191    }
192
193    fn available_ids(&self) -> Option<Arc<HashSet<u64>>> {
194        self.availability_initialized
195            .then(|| Arc::clone(&self.routable_id_set))
196    }
197
198    pub(crate) fn free_ids(&self) -> &[u64] {
199        &self.free_ids
200    }
201
202    pub(crate) fn counts(&self) -> RoutingInstanceCounts {
203        RoutingInstanceCounts {
204            discovered: self.discovered_ids.len(),
205            routable: self.routable_ids.len(),
206            overloaded: self.overloaded_ids.len(),
207            free: self.free_ids.len(),
208        }
209    }
210
211    pub(crate) fn is_overloaded(&self, instance_id: u64) -> bool {
212        self.overloaded_ids.contains(&instance_id)
213    }
214
215    fn overloaded_ids(&self) -> Option<Arc<HashSet<u64>>> {
216        if self.overloaded_ids.is_empty() {
217            return None;
218        }
219
220        Some(Arc::clone(&self.overloaded_ids))
221    }
222
223    /// This rebuild of `previous`, sharing its overloaded set when the rebuild left
224    /// the set unchanged.
225    fn sharing_overloaded_ids(mut self, previous: &Self) -> Self {
226        if self.overloaded_ids == previous.overloaded_ids {
227            self.overloaded_ids = Arc::clone(&previous.overloaded_ids);
228        }
229        self
230    }
231
232    fn reconcile_discovered(&self, discovered_ids: Vec<u64>) -> Self {
233        let old_discovered_ids = self.discovered_ids.iter().copied().collect::<HashSet<_>>();
234        let new_discovered_ids = discovered_ids.iter().copied().collect::<HashSet<_>>();
235        let mut monitor_overloaded_ids = self.monitor_overloaded_ids.clone();
236        monitor_overloaded_ids
237            .retain(|id| !old_discovered_ids.contains(id) || new_discovered_ids.contains(id));
238        let mut request_overload_deadlines = self.request_overload_deadlines.clone();
239        request_overload_deadlines
240            .retain(|id, _| !old_discovered_ids.contains(id) || new_discovered_ids.contains(id));
241
242        let availability_initialized = self.availability_initialized || !discovered_ids.is_empty();
243        Self::from_parts(
244            discovered_ids.clone(),
245            discovered_ids,
246            monitor_overloaded_ids,
247            request_overload_deadlines,
248            availability_initialized,
249        )
250    }
251
252    fn report_instance_down(&self, instance_id: u64) -> Self {
253        let routable_ids: Vec<u64> = self
254            .routable_ids
255            .iter()
256            .copied()
257            .filter(|id| *id != instance_id)
258            .collect();
259
260        Self::from_parts(
261            self.discovered_ids.clone(),
262            routable_ids,
263            self.monitor_overloaded_ids.clone(),
264            self.request_overload_deadlines.clone(),
265            self.availability_initialized,
266        )
267    }
268
269    #[cfg(any(test, feature = "testing"))]
270    fn override_routable_ids(&self, routable_ids: Vec<u64>) -> Self {
271        // Route through from_parts so `free_ids` is recomputed from the new
272        // routable set instead of carrying the stale value forward.
273        Self::from_parts(
274            self.discovered_ids.clone(),
275            routable_ids,
276            self.monitor_overloaded_ids.clone(),
277            self.request_overload_deadlines.clone(),
278            self.availability_initialized,
279        )
280    }
281
282    fn set_overloaded(&self, overloaded_ids: HashSet<u64>) -> Self {
283        Self::from_parts(
284            self.discovered_ids.clone(),
285            self.routable_ids.clone(),
286            overloaded_ids,
287            HashMap::new(),
288            self.availability_initialized,
289        )
290    }
291
292    /// Add a single instance to the overloaded set (immediate
293    /// backpressure mark). A monitor update clears all request-path
294    /// marks. Otherwise, each mark expires at its own deadline.
295    fn mark_overloaded_until(&self, instance_id: u64, deadline: Instant) -> Self {
296        let mut request_overload_deadlines = self.request_overload_deadlines.clone();
297        request_overload_deadlines.insert(instance_id, deadline);
298        Self::from_parts(
299            self.discovered_ids.clone(),
300            self.routable_ids.clone(),
301            self.monitor_overloaded_ids.clone(),
302            request_overload_deadlines,
303            self.availability_initialized,
304        )
305    }
306
307    fn has_expired_request_overload(&self, now: Instant) -> bool {
308        self.next_request_overload_expiry
309            .is_some_and(|deadline| deadline <= now)
310    }
311
312    fn clear_expired_request_overloads(&self, now: Instant) -> Self {
313        let mut request_overload_deadlines = self.request_overload_deadlines.clone();
314        request_overload_deadlines.retain(|_, deadline| *deadline > now);
315        Self::from_parts(
316            self.discovered_ids.clone(),
317            self.routable_ids.clone(),
318            self.monitor_overloaded_ids.clone(),
319            request_overload_deadlines,
320            self.availability_initialized,
321        )
322    }
323
324    fn clear_overloaded_for_removed(&self, removed_ids: &HashSet<u64>) -> Self {
325        let mut monitor_overloaded_ids = self.monitor_overloaded_ids.clone();
326        monitor_overloaded_ids.retain(|id| !removed_ids.contains(id));
327        let mut request_overload_deadlines = self.request_overload_deadlines.clone();
328        request_overload_deadlines.retain(|id, _| !removed_ids.contains(id));
329        Self::from_parts(
330            self.discovered_ids.clone(),
331            self.routable_ids.clone(),
332            monitor_overloaded_ids,
333            request_overload_deadlines,
334            self.availability_initialized,
335        )
336    }
337
338    fn derive_free_ids(routable_ids: &[u64], overloaded_ids: &HashSet<u64>) -> Vec<u64> {
339        if overloaded_ids.is_empty() {
340            return routable_ids.to_vec();
341        }
342
343        routable_ids
344            .iter()
345            .copied()
346            .filter(|id| !overloaded_ids.contains(id))
347            .collect()
348    }
349}
350
351#[derive(Debug)]
352struct RoutingInstancesState {
353    snapshot: ArcSwap<RoutingInstances>,
354    update_lock: StdMutex<()>,
355    instance_avail_tx: tokio::sync::watch::Sender<Vec<u64>>,
356}
357
358impl RoutingInstancesState {
359    fn new(discovered_ids: Vec<u64>) -> (Self, tokio::sync::watch::Receiver<Vec<u64>>) {
360        let snapshot = RoutingInstances::new(discovered_ids);
361        let (instance_avail_tx, instance_avail_rx) =
362            tokio::sync::watch::channel(snapshot.routable_ids().to_vec());
363        (
364            Self {
365                snapshot: ArcSwap::from_pointee(snapshot),
366                update_lock: StdMutex::new(()),
367                instance_avail_tx,
368            },
369            instance_avail_rx,
370        )
371    }
372
373    fn snapshot(&self) -> arc_swap::Guard<Arc<RoutingInstances>> {
374        let now = Instant::now();
375        let current = self.snapshot.load();
376        if !current.has_expired_request_overload(now) {
377            return current;
378        }
379        drop(current);
380
381        self.reconcile_expired_request_overloads(now);
382        self.snapshot.load()
383    }
384
385    fn reconcile_expired_request_overloads(&self, now: Instant) {
386        let _guard = self.update_lock.lock().unwrap();
387        let current = self.snapshot.load();
388        if !current.has_expired_request_overload(now) {
389            return;
390        }
391
392        let next = Arc::new(
393            current
394                .clear_expired_request_overloads(now)
395                .sharing_overloaded_ids(&current),
396        );
397        self.snapshot.store(next);
398    }
399
400    fn update(
401        &self,
402        update: impl FnOnce(&RoutingInstances) -> RoutingInstances,
403        publish_routable_ids: bool,
404    ) -> Arc<RoutingInstances> {
405        let _guard = self.update_lock.lock().unwrap();
406        let current = self.snapshot.load();
407        let next = Arc::new(update(&current).sharing_overloaded_ids(&current));
408        self.snapshot.store(next.clone());
409        if publish_routable_ids {
410            self.publish_routable_ids(&next);
411        }
412        next
413    }
414
415    fn publish_routable_ids(&self, routing_instances: &RoutingInstances) {
416        let _ = self
417            .instance_avail_tx
418            .send(routing_instances.routable_ids().to_vec());
419    }
420
421    fn routable_ids(&self) -> Vec<u64> {
422        self.snapshot().routable_ids().to_vec()
423    }
424
425    fn available_ids(&self) -> Option<Arc<HashSet<u64>>> {
426        self.snapshot().available_ids()
427    }
428
429    fn free_ids(&self) -> Vec<u64> {
430        self.snapshot().free_ids.clone()
431    }
432
433    fn counts(&self) -> RoutingInstanceCounts {
434        self.snapshot().counts()
435    }
436
437    fn overloaded_ids(&self) -> Option<Arc<HashSet<u64>>> {
438        self.snapshot().overloaded_ids()
439    }
440
441    fn report_instance_down(&self, instance_id: u64) {
442        self.update(|current| current.report_instance_down(instance_id), true);
443    }
444
445    fn set_overloaded_instances(&self, overloaded_instance_ids: &[u64]) -> bool {
446        let overloaded_ids = overloaded_instance_ids
447            .iter()
448            .copied()
449            .collect::<HashSet<_>>();
450        let _guard = self.update_lock.lock().unwrap();
451        let current = self.snapshot.load();
452        let next = Arc::new(
453            current
454                .set_overloaded(overloaded_ids)
455                .sharing_overloaded_ids(&current),
456        );
457        let effective_changed = current.overloaded_ids != next.overloaded_ids;
458        let source_changed = current.monitor_overloaded_ids != next.monitor_overloaded_ids
459            || !current.request_overload_deadlines.is_empty();
460        if !source_changed {
461            return false;
462        }
463
464        self.snapshot.store(next);
465        effective_changed
466    }
467
468    fn mark_overloaded_immediate(&self, instance_id: u64) {
469        self.mark_overloaded_until(instance_id, Instant::now() + REQUEST_PATH_OVERLOAD_COOLDOWN);
470    }
471
472    fn mark_overloaded_until(&self, instance_id: u64, deadline: Instant) {
473        let _guard = self.update_lock.lock().unwrap();
474        let current = self.snapshot.load();
475        let next = Arc::new(
476            current
477                .mark_overloaded_until(instance_id, deadline)
478                .sharing_overloaded_ids(&current),
479        );
480        self.snapshot.store(next);
481    }
482
483    fn overload_reconciliation_needed(&self) -> bool {
484        !self.snapshot().request_overload_deadlines.is_empty()
485    }
486
487    fn clear_overloaded_for_removed(&self, removed_instance_ids: &[u64]) {
488        if removed_instance_ids.is_empty() {
489            return;
490        }
491
492        let removed_ids = removed_instance_ids.iter().copied().collect::<HashSet<_>>();
493        self.update(
494            move |current| current.clear_overloaded_for_removed(&removed_ids),
495            false,
496        );
497    }
498
499    fn reconcile_discovered(&self, discovered_ids: Vec<u64>) -> Arc<RoutingInstances> {
500        self.update(
501            move |current| current.reconcile_discovered(discovered_ids),
502            true,
503        )
504    }
505
506    #[cfg(any(test, feature = "testing"))]
507    fn override_routable_ids(&self, ids: Vec<u64>) {
508        self.update(move |current| current.override_routable_ids(ids), true);
509    }
510}
511
512#[derive(Clone, Debug)]
513pub struct Client {
514    // This is me
515    pub endpoint: Endpoint,
516    // Shared endpoint discovery source backing both snapshots and raw events.
517    endpoint_discovery_source: Arc<EndpointDiscoverySource>,
518    // These are the remotes I know about from watching key-value store
519    pub instance_source: Arc<tokio::sync::watch::Receiver<Vec<Instance>>>,
520    // Immutable routing snapshot. Free IDs are derived from discovered IDs and overloaded IDs.
521    routing_instances: Arc<RoutingInstancesState>,
522    // Client clones and standalone watchers jointly own the reconciliation task.
523    instance_avail_owner: Arc<tokio::sync::watch::Receiver<Vec<u64>>>,
524    /// Interval for periodic reconciliation of instance_avail with instance_source.
525    /// This ensures instances removed via `report_instance_down` are eventually restored.
526    /// A zero value disables local worker inhibition.
527    reconcile_interval: Duration,
528}
529
530impl Client {
531    // Client with auto-discover instances using key-value store
532    pub(crate) async fn new(endpoint: Endpoint) -> Result<Self> {
533        Self::with_reconcile_interval(endpoint, *INHIBITED_DURATION).await
534    }
535
536    /// Like [`Self::new`], but the `monitor_instance_source` background task
537    /// is bound to `cancel_token` instead of the process-wide primary token.
538    /// See [`Self::with_reconcile_interval_and_cancellation`] for why a
539    /// caller whose own scope is narrower than the process needs this.
540    pub(crate) async fn with_cancellation(
541        endpoint: Endpoint,
542        cancel_token: tokio_util::sync::CancellationToken,
543    ) -> Result<Self> {
544        Self::with_reconcile_interval_and_cancellation(endpoint, *INHIBITED_DURATION, cancel_token)
545            .await
546    }
547
548    /// Create a client with a custom reconcile interval.
549    /// The reconcile interval controls how often `instance_avail` is reset to match
550    /// `instance_source`, restoring any instances removed via `report_instance_down`.
551    pub(crate) async fn with_reconcile_interval(
552        endpoint: Endpoint,
553        reconcile_interval: Duration,
554    ) -> Result<Self> {
555        let cancel_token = endpoint.drt().primary_token();
556        Self::with_reconcile_interval_and_cancellation(endpoint, reconcile_interval, cancel_token)
557            .await
558    }
559
560    /// Like [`Self::with_reconcile_interval`], but the `monitor_instance_source`
561    /// background task is bound to `cancel_token` rather than the process-wide
562    /// primary token.
563    ///
564    /// A caller that builds a `Client` scoped to something narrower than the
565    /// process — a monitor bound to one `WorkerSet`'s lifecycle, say — must use
566    /// this constructor. `Client` is `Clone`, and `monitor_instance_source`
567    /// captures its own clone before returning, so dropping every `Client`
568    /// handle the caller holds does not stop that task; only cancelling its
569    /// token does. Built through [`Self::new`] or [`Self::with_reconcile_interval`]
570    /// instead, that task runs until process shutdown regardless of how long
571    /// the caller actually keeps the `Client` around.
572    pub(crate) async fn with_reconcile_interval_and_cancellation(
573        endpoint: Endpoint,
574        reconcile_interval: Duration,
575        cancel_token: tokio_util::sync::CancellationToken,
576    ) -> Result<Self> {
577        tracing::trace!(
578            "Client::new_dynamic: Creating dynamic client for endpoint: {}",
579            endpoint.id()
580        );
581        let endpoint_discovery_source =
582            Self::get_or_create_dynamic_discovery_source(&endpoint).await?;
583        let instance_source = Arc::new(endpoint_discovery_source.instance_receiver());
584
585        // Seed instance_avail from the current instance_source snapshot so that
586        // callers who proceed immediately after wait_for_instances (which reads
587        // instance_source directly) will also find instances in instance_avail
588        // (which is read by the routing methods like random/round_robin).
589        let initial_ids: Vec<u64> = instance_source
590            .borrow()
591            .iter()
592            .map(|instance| instance.id())
593            .collect();
594        let (routing_instances, instance_avail_owner) = RoutingInstancesState::new(initial_ids);
595        let client = Client {
596            endpoint: endpoint.clone(),
597            endpoint_discovery_source,
598            instance_source: instance_source.clone(),
599            routing_instances: Arc::new(routing_instances),
600            instance_avail_owner: Arc::new(instance_avail_owner),
601            reconcile_interval,
602        };
603        client.monitor_instance_source_with_cancellation(cancel_token, true);
604        Ok(client)
605    }
606
607    /// Instances available from watching key-value store
608    pub fn instances(&self) -> Vec<Instance> {
609        self.instance_source.borrow().clone()
610    }
611
612    pub(crate) fn instance_by_id(&self, instance_id: u64) -> Option<Instance> {
613        self.instance_source
614            .borrow()
615            .iter()
616            .find(|instance| instance.id() == instance_id)
617            .cloned()
618    }
619
620    pub fn instance_ids(&self) -> Vec<u64> {
621        self.instances().into_iter().map(|ep| ep.id()).collect()
622    }
623
624    /// Whether the live discovery source (not the asynchronously reconciled
625    /// routing snapshot) currently contains this instance.
626    pub fn is_instance_live(&self, instance_id: u64) -> bool {
627        self.instance_source
628            .borrow()
629            .iter()
630            .any(|instance| instance.id() == instance_id)
631    }
632
633    /// Whether the latest discovery snapshot contains this instance, including inhibited workers.
634    pub fn is_instance_discovered(&self, instance_id: u64) -> bool {
635        self.routing_instances
636            .snapshot()
637            .discovered_ids()
638            .binary_search(&instance_id)
639            .is_ok()
640    }
641
642    pub fn instance_ids_avail(&self) -> Vec<u64> {
643        self.routing_instances.routable_ids()
644    }
645
646    /// Routable instance ids excluding those currently flagged overloaded — the set used
647    /// for load-aware (random / round-robin) worker selection.
648    pub fn instance_ids_free(&self) -> Vec<u64> {
649        self.routing_instances.free_ids()
650    }
651
652    pub(crate) fn routing_instances(&self) -> arc_swap::Guard<Arc<RoutingInstances>> {
653        self.routing_instances.snapshot()
654    }
655
656    pub fn routing_instance_counts(&self) -> RoutingInstanceCounts {
657        self.routing_instances.counts()
658    }
659
660    /// Get a watcher for available instance IDs
661    pub fn instance_avail_watcher(&self) -> tokio::sync::watch::Receiver<Vec<u64>> {
662        self.instance_avail_owner.as_ref().clone()
663    }
664
665    /// Create a client view whose routable instances are restricted by a caller-owned
666    /// admission set.
667    ///
668    /// Endpoint discovery remains the source of connection metadata and hard availability. The
669    /// returned client publishes only the intersection of that endpoint membership and
670    /// `admitted_ids`, allowing a higher-level controller to keep discovered-but-unvalidated
671    /// instances out of a routing group. The view has independent overload and fault-inhibition
672    /// state, just like a freshly constructed client.
673    pub fn with_admitted_instances(
674        &self,
675        admitted_ids: tokio::sync::watch::Receiver<Vec<u64>>,
676    ) -> Self {
677        self.with_admitted_instances_and_cancellation(
678            admitted_ids,
679            self.endpoint.drt().primary_token(),
680        )
681    }
682
683    /// Like [`Self::with_admitted_instances`], with a lifecycle token for construction-time
684    /// cancellation by an owning controller.
685    pub fn with_admitted_instances_and_cancellation(
686        &self,
687        mut admitted_ids: tokio::sync::watch::Receiver<Vec<u64>>,
688        cancel_token: tokio_util::sync::CancellationToken,
689    ) -> Self {
690        let mut endpoint_instances = self.instance_source.as_ref().clone();
691        let initial = Self::filter_admitted_instances(
692            endpoint_instances.borrow().as_slice(),
693            admitted_ids.borrow().as_slice(),
694        );
695        let initial_ids = initial.iter().map(Instance::id).collect::<Vec<_>>();
696        let (instance_tx, instance_rx) = tokio::sync::watch::channel(initial);
697        let updater_cancel = cancel_token.clone();
698
699        tokio::spawn(async move {
700            loop {
701                tokio::select! {
702                    _ = updater_cancel.cancelled() => break,
703                    _ = instance_tx.closed() => break,
704                    result = endpoint_instances.changed() => {
705                        if result.is_err() {
706                            break;
707                        }
708                    }
709                    result = admitted_ids.changed() => {
710                        if result.is_err() {
711                            break;
712                        }
713                    }
714                }
715
716                let next = Self::filter_admitted_instances(
717                    endpoint_instances.borrow_and_update().as_slice(),
718                    admitted_ids.borrow_and_update().as_slice(),
719                );
720                let changed = *instance_tx.borrow() != next;
721                if changed && instance_tx.send(next).is_err() {
722                    break;
723                }
724            }
725        });
726
727        let (routing_instances, instance_avail_owner) = RoutingInstancesState::new(initial_ids);
728        let client = Self {
729            endpoint: self.endpoint.clone(),
730            endpoint_discovery_source: self.endpoint_discovery_source.clone(),
731            instance_source: Arc::new(instance_rx),
732            routing_instances: Arc::new(routing_instances),
733            instance_avail_owner: Arc::new(instance_avail_owner),
734            reconcile_interval: self.reconcile_interval,
735        };
736        client.monitor_instance_source_with_cancellation(cancel_token, false);
737        client
738    }
739
740    fn filter_admitted_instances(instances: &[Instance], admitted_ids: &[u64]) -> Vec<Instance> {
741        if admitted_ids.is_empty() {
742            return Vec::new();
743        }
744
745        let admitted = admitted_ids.iter().copied().collect::<HashSet<_>>();
746        instances
747            .iter()
748            .filter(|instance| admitted.contains(&instance.id()))
749            .cloned()
750            .collect()
751    }
752
753    /// Subscribe to raw discovery events for this endpoint.
754    ///
755    /// Unlike `instance_source`, this feed does not coalesce remove→add pairs,
756    /// so consumers can react to every removal event exactly once.
757    pub(crate) fn subscribe_discovery_events(&self) -> DiscoveryEventReceiver {
758        DiscoveryEventReceiver {
759            receiver: self.endpoint_discovery_source.subscribe_events(),
760            _source: self.endpoint_discovery_source.clone(),
761        }
762    }
763
764    /// Wait for at least one Instance to be available for this Endpoint
765    pub async fn wait_for_instances(&self) -> Result<Vec<Instance>> {
766        tracing::trace!(
767            "wait_for_instances: Starting wait for endpoint: {}",
768            self.endpoint.id()
769        );
770        let mut rx = self.instance_source.as_ref().clone();
771        // wait for there to be 1 or more endpoints
772        let mut instances: Vec<Instance>;
773        loop {
774            instances = rx.borrow_and_update().to_vec();
775            if instances.is_empty() {
776                rx.changed().await?;
777            } else {
778                tracing::info!(
779                    "wait_for_instances: Found {} instance(s) for endpoint: {}",
780                    instances.len(),
781                    self.endpoint.id()
782                );
783                break;
784            }
785        }
786        Ok(instances)
787    }
788
789    /// Wait for at least one discovered instance to be published as routable.
790    pub async fn wait_for_routable_instances(&self) -> Result<Vec<Instance>> {
791        tracing::trace!(
792            endpoint = %self.endpoint.id(),
793            "Waiting for routable instances"
794        );
795        let mut discovered = self.instance_source.as_ref().clone();
796        let mut available = self.instance_avail_watcher();
797        loop {
798            // Discovery and routing publish on separate tasks. Returning only
799            // after their views overlap prevents a subsequent route seeing no workers.
800            let instances: Vec<Instance> = {
801                let available = available.borrow_and_update();
802                discovered
803                    .borrow_and_update()
804                    .iter()
805                    .filter(|instance| available.contains(&instance.id()))
806                    .cloned()
807                    .collect()
808            };
809            if !instances.is_empty() {
810                tracing::debug!(
811                    endpoint = %self.endpoint.id(),
812                    instances = instances.len(),
813                    "Routable instances are ready"
814                );
815                return Ok(instances);
816            }
817            tokio::select! {
818                result = discovered.changed() => result?,
819                result = available.changed() => result?,
820            }
821        }
822    }
823
824    /// Mark an instance as down/unavailable
825    pub fn report_instance_down(&self, instance_id: u64) {
826        if self.reconcile_interval.is_zero() {
827            tracing::debug!(
828                instance_id,
829                "local worker inhibition is disabled; leaving instance routable"
830            );
831            return;
832        }
833
834        self.routing_instances.report_instance_down(instance_id);
835        tracing::debug!(
836            instance_id,
837            routing_event = "worker_inhibited",
838            "inhibiting instance"
839        );
840    }
841
842    /// Replace the set of overloaded instances reported by the worker monitor.
843    /// Returns true when this changes the effective overloaded set.
844    pub fn set_overloaded_instances(&self, overloaded_instance_ids: &[u64]) -> bool {
845        self.routing_instances
846            .set_overloaded_instances(overloaded_instance_ids)
847    }
848
849    /// Whether an unexpired request-path overload lease remains after the
850    /// monitor's most recent metric publication.
851    pub fn overload_reconciliation_needed(&self) -> bool {
852        self.routing_instances.overload_reconciliation_needed()
853    }
854
855    /// Mark an instance overloaded immediately after a `WorkerOverloaded`
856    /// response for the whole worker. This is backpressure, not a fault, so it
857    /// does not call `report_instance_down`. A fresh worker-monitor publication
858    /// clears this hint early. Its bounded lease otherwise permits a recovery probe.
859    pub fn mark_overloaded_immediate(&self, instance_id: u64) {
860        self.routing_instances
861            .mark_overloaded_immediate(instance_id);
862        tracing::debug!(
863            instance_id,
864            routing_event = "worker_overloaded",
865            "marking instance overloaded with a bounded backpressure lease"
866        );
867    }
868
869    pub fn clear_overloaded_instances_for_removed(&self, removed_instance_ids: &[u64]) {
870        self.routing_instances
871            .clear_overloaded_for_removed(removed_instance_ids);
872    }
873
874    pub fn overloaded_instance_ids(&self) -> Option<Arc<HashSet<u64>>> {
875        self.routing_instances.overloaded_ids()
876    }
877
878    /// Workers currently eligible for selection: discovered and not locally
879    /// inhibited by [`Self::report_instance_down`].
880    ///
881    /// This hard-availability snapshot is separate from transient overload.
882    /// `None` means this client has not discovered an instance yet. After the
883    /// first discovery, `Some` is authoritative, including `Some(empty)` when
884    /// the last previously discovered worker is removed.
885    pub fn available_instance_ids(&self) -> Option<Arc<HashSet<u64>>> {
886        self.routing_instances.available_ids()
887    }
888
889    /// Monitor the key-value instance source and update instance_avail.
890    ///
891    /// This function also performs periodic reconciliation: if `instance_source` hasn't
892    /// changed for `reconcile_interval`, we reset `instance_avail` to match
893    /// `instance_source`. This ensures instances removed via `report_instance_down`
894    /// are eventually restored even if the discovery source doesn't emit updates.
895    ///
896    /// The spawned task runs until `cancel_token` cancels. A caller that wants
897    /// this task to outlive nothing shorter than the process should pass
898    /// `self.endpoint.drt().primary_token()`, as [`Self::new`] does.
899    fn monitor_instance_source_with_cancellation(
900        &self,
901        cancel_token: tokio_util::sync::CancellationToken,
902        prune_shared_occupancy: bool,
903    ) {
904        let reconcile_interval = self.reconcile_interval;
905        let endpoint = self.endpoint.clone();
906        let endpoint_discovery_source = self.endpoint_discovery_source.clone();
907        let routing_instances = self.routing_instances.clone();
908        let instance_source = self.instance_source.clone();
909        let endpoint_id = self.endpoint.id();
910        tokio::task::spawn(async move {
911            let mut rx = instance_source.as_ref().clone();
912            while !cancel_token.is_cancelled() {
913                let instance_ids: Vec<u64> = rx
914                    .borrow_and_update()
915                    .iter()
916                    .map(|instance| instance.id())
917                    .collect();
918
919                let snapshot = routing_instances.reconcile_discovered(instance_ids);
920
921                // Clean up stale occupancy counters for instances that no longer exist.
922                if prune_shared_occupancy {
923                    let registry = endpoint.drt().routing_occupancy_states();
924                    if let Ok(registry) = registry.try_lock()
925                        && let Some(weak) = registry.get(&endpoint)
926                        && let Some(state) = weak.upgrade()
927                    {
928                        state.retain(snapshot.discovered_ids());
929                    }
930                }
931
932                tokio::select! {
933                    _ = cancel_token.cancelled() => break,
934                    _ = routing_instances.instance_avail_tx.closed() => break,
935                    result = rx.changed() => {
936                        if let Err(err) = result {
937                            tracing::error!(
938                                "monitor_instance_source: The Sender is dropped: {err}, endpoint={endpoint_id}",
939                            );
940                            cancel_token.cancel();
941                        }
942                    }
943                    _ = tokio::time::sleep(reconcile_interval), if !reconcile_interval.is_zero() => {
944                        tracing::trace!(
945                            "monitor_instance_source: periodic reconciliation for endpoint={endpoint_id}",
946                        );
947                    }
948                }
949            }
950            drop(endpoint_discovery_source);
951        });
952    }
953
954    /// Simulate a complete discovery snapshot for testing.
955    #[cfg(any(test, feature = "testing"))]
956    pub fn override_discovered_instances(&self, ids: Vec<u64>) {
957        self.reconcile_discovered_instances(ids);
958    }
959
960    /// Override routable IDs for testing while preserving discovery membership.
961    #[cfg(any(test, feature = "testing"))]
962    pub fn override_instance_avail(&self, ids: Vec<u64>) {
963        self.routing_instances.override_routable_ids(ids);
964    }
965
966    fn reconcile_discovered_instances(&self, discovered_ids: Vec<u64>) -> Arc<RoutingInstances> {
967        self.routing_instances.reconcile_discovered(discovered_ids)
968    }
969
970    async fn get_or_create_dynamic_discovery_source(
971        endpoint: &Endpoint,
972    ) -> Result<Arc<EndpointDiscoverySource>> {
973        let sources = endpoint.drt().endpoint_discovery_sources();
974
975        let existing = sources.lock().await.get(endpoint).and_then(Weak::upgrade);
976        if let Some(source) = existing {
977            return Ok(source);
978        }
979
980        // Discovery::list_and_watch establishes the backend watch, so it runs outside the
981        // registry lock. Holding the lock across it serializes every client construction behind
982        // one round trip to the discovery backend.
983        let discovery = endpoint.drt().discovery();
984        let discovery_source = Self::spawn_dynamic_discovery_source(
985            endpoint,
986            discovery.as_ref(),
987            endpoint.drt().primary_token().child_token(),
988        )
989        .await?;
990
991        let mut sources = sources.lock().await;
992        // Another caller can register a source for this endpoint while this watch is
993        // established. Every later client shares that source, and this one drops, which stops
994        // both the watcher task it spawned and the backend watch it established.
995        if let Some(source) = sources.get(endpoint).and_then(Weak::upgrade) {
996            return Ok(source);
997        }
998        sources.insert(endpoint.clone(), Arc::downgrade(&discovery_source));
999        Ok(discovery_source)
1000    }
1001
1002    /// Pass a child of the runtime's primary token as `cancel_token`: the backends fall back to
1003    /// that token, so shutdown still ends a watch that clients are holding.
1004    async fn spawn_dynamic_discovery_source(
1005        endpoint: &Endpoint,
1006        discovery: &dyn Discovery,
1007        cancel_token: CancellationToken,
1008    ) -> Result<Arc<EndpointDiscoverySource>> {
1009        let discovery_query = crate::discovery::DiscoveryQuery::Endpoint {
1010            namespace: endpoint.component.namespace.name.clone(),
1011            component: endpoint.component.name.clone(),
1012            endpoint: endpoint.name.clone(),
1013        };
1014
1015        let mut discovery_stream = discovery
1016            .list_and_watch(discovery_query.clone(), Some(cancel_token.clone()))
1017            .await?;
1018        let (watch_tx, watch_rx) = tokio::sync::watch::channel(vec![]);
1019        let discovery_source = Arc::new(EndpointDiscoverySource::new(
1020            watch_rx,
1021            cancel_token.drop_guard(),
1022        ));
1023
1024        let secondary = endpoint.component.drt.runtime().secondary().clone();
1025        let discovery_source_task = Arc::downgrade(&discovery_source);
1026
1027        secondary.spawn(async move {
1028            tracing::trace!("endpoint_watcher: Starting for discovery query: {:?}", discovery_query);
1029            let mut map: HashMap<u64, Instance> = HashMap::new();
1030
1031            loop {
1032                let discovery_event = tokio::select! {
1033                    _ = watch_tx.closed() => {
1034                        break;
1035                    }
1036                    discovery_event = discovery_stream.next() => {
1037                        match discovery_event {
1038                            Some(Ok(event)) => {
1039                                event
1040                            },
1041                            Some(Err(e)) => {
1042                                tracing::error!("endpoint_watcher: discovery stream error: {}; shutting down for discovery query: {:?}", e, discovery_query);
1043                                break;
1044                            }
1045                            None => {
1046                                break;
1047                            }
1048                        }
1049                    }
1050                };
1051
1052                if let Some(discovery_source) = discovery_source_task.upgrade() {
1053                    discovery_source.broadcast_event(&discovery_event);
1054                }
1055
1056                match discovery_event {
1057                    DiscoveryEvent::Added(DiscoveryInstance::Endpoint(instance)) => {
1058                        map.insert(instance.instance_id, instance);
1059                    }
1060                    DiscoveryEvent::Added(_) => {}
1061                    DiscoveryEvent::ModelTaintsUpdated(_) => {}
1062                    DiscoveryEvent::Resync(instances) => {
1063                        map = instances
1064                            .into_iter()
1065                            .filter_map(|instance| {
1066                                let DiscoveryInstance::Endpoint(instance) = instance else {
1067                                    return None;
1068                                };
1069                                Some((instance.instance_id, instance))
1070                            })
1071                            .collect();
1072                    }
1073                    DiscoveryEvent::Removed(id) => {
1074                        if let DiscoveryInstanceId::Endpoint(endpoint_id) = id {
1075                            map.remove(&endpoint_id.instance_id);
1076                        }
1077                    }
1078                }
1079
1080                let instances: Vec<Instance> = map.values().cloned().collect();
1081                if watch_tx.send(instances).is_err() {
1082                    break;
1083                }
1084            }
1085            let _ = watch_tx.send(vec![]);
1086        });
1087
1088        Ok(discovery_source)
1089    }
1090}
1091
1092#[cfg(test)]
1093mod tests {
1094    use super::*;
1095    use crate::component::TransportType;
1096    use crate::discovery::{
1097        DiscoveryQuery, DiscoverySpec, DiscoveryStream, MockDiscovery, SharedMockRegistry,
1098    };
1099    use crate::{DistributedRuntime, Runtime, distributed::DistributedConfig};
1100    use futures::future::try_join_all;
1101
1102    /// A backend whose watch producer, like the Kubernetes watcher, parks on its own feed and ends
1103    /// only when the token it was given cancels. A test sends events to a watch through `feeds`.
1104    struct ParkedProducerDiscovery {
1105        inner: MockDiscovery,
1106        producers: StdMutex<Vec<tokio::task::JoinHandle<()>>>,
1107        feeds: StdMutex<Vec<tokio::sync::mpsc::UnboundedSender<Result<DiscoveryEvent>>>>,
1108    }
1109
1110    #[async_trait::async_trait]
1111    impl Discovery for ParkedProducerDiscovery {
1112        fn instance_id(&self) -> u64 {
1113            self.inner.instance_id()
1114        }
1115
1116        async fn register_internal(&self, spec: DiscoverySpec) -> Result<DiscoveryInstance> {
1117            self.inner.register_internal(spec).await
1118        }
1119
1120        async fn unregister(&self, instance: DiscoveryInstance) -> Result<()> {
1121            self.inner.unregister(instance).await
1122        }
1123
1124        async fn list(&self, query: DiscoveryQuery) -> Result<Vec<DiscoveryInstance>> {
1125            self.inner.list(query).await
1126        }
1127
1128        async fn list_and_watch(
1129            &self,
1130            _query: DiscoveryQuery,
1131            cancel_token: Option<CancellationToken>,
1132        ) -> Result<DiscoveryStream> {
1133            let (feed_tx, mut feed) =
1134                tokio::sync::mpsc::unbounded_channel::<Result<DiscoveryEvent>>();
1135            self.feeds.lock().unwrap().push(feed_tx.clone());
1136            let producer = tokio::spawn(async move {
1137                let _feed_tx = feed_tx;
1138                match cancel_token {
1139                    Some(token) => token.cancelled().await,
1140                    None => std::future::pending::<()>().await,
1141                }
1142            });
1143            self.producers.lock().unwrap().push(producer);
1144
1145            Ok(Box::pin(async_stream::stream! {
1146                while let Some(event) = feed.recv().await {
1147                    yield event;
1148                }
1149            }))
1150        }
1151    }
1152
1153    #[tokio::test]
1154    async fn test_instance_by_id_returns_owned_current_instance() {
1155        use crate::component::TransportType;
1156
1157        let rt = Runtime::from_current().unwrap();
1158        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1159            .await
1160            .unwrap();
1161        let endpoint = drt
1162            .namespace("test_instance_lookup".to_string())
1163            .unwrap()
1164            .component("test_component".to_string())
1165            .unwrap()
1166            .endpoint("test_endpoint".to_string());
1167        let mut client = endpoint.client().await.unwrap();
1168        let instances: Vec<_> = (1..=2)
1169            .map(|instance_id| Instance {
1170                namespace: "test_instance_lookup".to_string(),
1171                component: "test_component".to_string(),
1172                endpoint: "test_endpoint".to_string(),
1173                instance_id,
1174                transport: TransportType::Tcp(format!("127.0.0.1:{}", 9000 + instance_id)),
1175                device_type: None,
1176                request_plane_codec: None,
1177            })
1178            .collect();
1179        let (tx, rx) = tokio::sync::watch::channel(instances.clone());
1180        client.instance_source = Arc::new(rx);
1181
1182        assert_eq!(client.instance_by_id(1), Some(instances[0].clone()));
1183        let selected = client.instance_by_id(2).unwrap();
1184        assert_eq!(selected, instances[1]);
1185        assert!(client.instance_by_id(3).is_none());
1186
1187        let mut updated = selected.clone();
1188        updated.transport = TransportType::Nats("updated.subject".to_string());
1189        tx.send(vec![instances[0].clone(), updated.clone()])
1190            .unwrap();
1191        assert_eq!(client.instance_by_id(2), Some(updated));
1192
1193        tx.send(vec![instances[0].clone()]).unwrap();
1194        assert!(client.instance_by_id(2).is_none());
1195        assert_eq!(client.instance_by_id(1), Some(instances[0].clone()));
1196
1197        rt.shutdown();
1198    }
1199
1200    async fn wait_for_discovery_event(
1201        receiver: &mut DiscoveryEventReceiver,
1202        predicate: impl Fn(&DiscoveryEvent) -> bool,
1203    ) {
1204        tokio::time::timeout(Duration::from_secs(1), async {
1205            loop {
1206                let event = receiver.recv().await.expect("discovery event feed closed");
1207                if predicate(&event) {
1208                    return;
1209                }
1210            }
1211        })
1212        .await
1213        .expect("expected discovery event was not received");
1214    }
1215
1216    async fn wait_for_watch_state<T>(
1217        receiver: &mut tokio::sync::watch::Receiver<Vec<T>>,
1218        predicate: impl Fn(&[T]) -> bool,
1219    ) {
1220        tokio::time::timeout(Duration::from_secs(1), async {
1221            loop {
1222                if predicate(receiver.borrow_and_update().as_slice()) {
1223                    return;
1224                }
1225                receiver
1226                    .changed()
1227                    .await
1228                    .expect("instance availability feed closed");
1229            }
1230        })
1231        .await
1232        .expect("expected instance availability state was not observed");
1233    }
1234
1235    #[test]
1236    fn test_inhibited_duration_from_env() {
1237        assert_eq!(
1238            inhibited_duration_from_env(|_| None),
1239            Duration::from_secs(DEFAULT_INHIBITED_DURATION_SECS)
1240        );
1241        assert_eq!(
1242            inhibited_duration_from_env(|_| Some("17".to_string())),
1243            Duration::from_secs(17)
1244        );
1245        assert_eq!(
1246            inhibited_duration_from_env(|_| Some("0".to_string())),
1247            Duration::ZERO
1248        );
1249        assert_eq!(
1250            inhibited_duration_from_env(|_| Some("invalid".to_string())),
1251            Duration::from_secs(DEFAULT_INHIBITED_DURATION_SECS)
1252        );
1253    }
1254
1255    #[tokio::test]
1256    async fn wait_for_routable_instances_waits_for_routing_publication() {
1257        let rt = Runtime::from_current().unwrap();
1258        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1259            .await
1260            .unwrap();
1261        let endpoint = drt
1262            .namespace("test_wait_routing".to_string())
1263            .unwrap()
1264            .component("backend".to_string())
1265            .unwrap()
1266            .endpoint("generate".to_string());
1267        let instance = Instance {
1268            namespace: "test_wait_routing".into(),
1269            component: "backend".into(),
1270            endpoint: "generate".into(),
1271            instance_id: 1,
1272            transport: TransportType::Nats("test.subject".into()),
1273            device_type: None,
1274            request_plane_codec: None,
1275        };
1276        let (source_tx, source_rx) = tokio::sync::watch::channel(vec![instance.clone()]);
1277        let source =
1278            EndpointDiscoverySource::new(source_rx.clone(), CancellationToken::new().drop_guard());
1279        let (routing, available) = RoutingInstancesState::new(vec![]);
1280        let client = Client {
1281            endpoint,
1282            endpoint_discovery_source: Arc::new(source),
1283            instance_source: Arc::new(source_rx),
1284            routing_instances: Arc::new(routing),
1285            instance_avail_owner: Arc::new(available),
1286            reconcile_interval: Duration::ZERO,
1287        };
1288
1289        // Discovery publishes first; the routing monitor has not consumed it yet.
1290        assert_eq!(
1291            client.wait_for_instances().await.unwrap(),
1292            vec![instance.clone()]
1293        );
1294        let ready = client.wait_for_routable_instances();
1295        tokio::pin!(ready);
1296        assert!(futures::poll!(ready.as_mut()).is_pending());
1297        client.routing_instances.reconcile_discovered(vec![1]);
1298        assert_eq!(ready.await.unwrap(), vec![instance]);
1299        assert_eq!(client.instance_ids_avail(), vec![1]);
1300
1301        client.routing_instances.reconcile_discovered(vec![]);
1302        drop(source_tx);
1303        assert!(client.wait_for_routable_instances().await.is_err());
1304        rt.shutdown();
1305    }
1306
1307    #[tokio::test]
1308    async fn concurrent_clients_share_one_discovery_source() {
1309        let rt = Runtime::from_current().unwrap();
1310        let drt = DistributedRuntime::new(rt, DistributedConfig::process_local())
1311            .await
1312            .unwrap();
1313        let endpoint = drt
1314            .namespace("test_shared_discovery_source".to_string())
1315            .unwrap()
1316            .component("test_component".to_string())
1317            .unwrap()
1318            .endpoint("decode".to_string());
1319
1320        // Every client passes the registry lookup before the first one establishes its watch, so
1321        // they all take the slow path and race on the insert.
1322        let clients = try_join_all((0..8).map(|_| endpoint.client()))
1323            .await
1324            .unwrap();
1325
1326        let shared = &clients[0].endpoint_discovery_source;
1327        for (index, client) in clients.iter().enumerate() {
1328            assert!(
1329                Arc::ptr_eq(shared, &client.endpoint_discovery_source),
1330                "client {index} watches the endpoint through a second discovery source"
1331            );
1332        }
1333    }
1334
1335    #[tokio::test]
1336    async fn dropping_a_discovery_source_stops_its_backend_watch() {
1337        let rt = Runtime::from_current().unwrap();
1338        let drt = DistributedRuntime::new(rt, DistributedConfig::process_local())
1339            .await
1340            .unwrap();
1341        let endpoint = drt
1342            .namespace("test_discovery_source_drop".to_string())
1343            .unwrap()
1344            .component("test_component".to_string())
1345            .unwrap()
1346            .endpoint("decode".to_string());
1347
1348        let discovery = ParkedProducerDiscovery {
1349            inner: MockDiscovery::new(Some(1), SharedMockRegistry::new()),
1350            producers: StdMutex::default(),
1351            feeds: StdMutex::default(),
1352        };
1353
1354        let source = Client::spawn_dynamic_discovery_source(
1355            &endpoint,
1356            &discovery,
1357            drt.primary_token().child_token(),
1358        )
1359        .await
1360        .unwrap();
1361        let producer = discovery
1362            .producers
1363            .lock()
1364            .unwrap()
1365            .pop()
1366            .expect("the source established no backend watch");
1367        tokio::task::yield_now().await;
1368        assert!(
1369            !producer.is_finished(),
1370            "a live source must keep watching the endpoint"
1371        );
1372
1373        drop(source);
1374        tokio::time::timeout(Duration::from_secs(1), producer)
1375            .await
1376            .expect("the backend watch outlives the source that established it")
1377            .unwrap();
1378    }
1379
1380    fn endpoint_instance(endpoint: &Endpoint, instance_id: u64) -> Instance {
1381        Instance {
1382            namespace: endpoint.component.namespace.name.clone(),
1383            component: endpoint.component.name.clone(),
1384            endpoint: endpoint.name.clone(),
1385            instance_id,
1386            transport: TransportType::Tcp(format!("127.0.0.1:{}", 8000 + instance_id)),
1387            device_type: None,
1388            request_plane_codec: None,
1389        }
1390    }
1391
1392    #[tokio::test]
1393    async fn a_resync_replaces_the_instances_of_a_discovery_source() {
1394        let rt = Runtime::from_current().unwrap();
1395        let drt = DistributedRuntime::new(rt, DistributedConfig::process_local())
1396            .await
1397            .unwrap();
1398        let endpoint = drt
1399            .namespace("test_discovery_source_resync".to_string())
1400            .unwrap()
1401            .component("test_component".to_string())
1402            .unwrap()
1403            .endpoint("decode".to_string());
1404        let discovery = ParkedProducerDiscovery {
1405            inner: MockDiscovery::new(Some(1), SharedMockRegistry::new()),
1406            producers: StdMutex::default(),
1407            feeds: StdMutex::default(),
1408        };
1409
1410        let source = Client::spawn_dynamic_discovery_source(
1411            &endpoint,
1412            &discovery,
1413            drt.primary_token().child_token(),
1414        )
1415        .await
1416        .unwrap();
1417        let feed = discovery
1418            .feeds
1419            .lock()
1420            .unwrap()
1421            .pop()
1422            .expect("the source established no backend watch");
1423        let mut instances = source.instance_receiver();
1424
1425        let first = endpoint_instance(&endpoint, 1);
1426        feed.send(Ok(DiscoveryEvent::Added(DiscoveryInstance::Endpoint(
1427            first.clone(),
1428        ))))
1429        .unwrap();
1430        wait_for_watch_state(&mut instances, |instances| {
1431            instances == std::slice::from_ref(&first)
1432        })
1433        .await;
1434
1435        let second = endpoint_instance(&endpoint, 2);
1436        feed.send(Ok(DiscoveryEvent::Resync(vec![
1437            DiscoveryInstance::Endpoint(second.clone()),
1438        ])))
1439        .unwrap();
1440        wait_for_watch_state(&mut instances, |instances| {
1441            instances == std::slice::from_ref(&second)
1442        })
1443        .await;
1444    }
1445
1446    #[tokio::test]
1447    async fn dropping_last_client_releases_routing_state() {
1448        let rt = Runtime::from_current().unwrap();
1449        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1450            .await
1451            .unwrap();
1452        let endpoint = drt
1453            .namespace("test_client_lifecycle".to_string())
1454            .unwrap()
1455            .component("test_component".to_string())
1456            .unwrap()
1457            .endpoint("decode".to_string());
1458        let client = endpoint.client().await.unwrap();
1459        let routing_instances = Arc::downgrade(&client.routing_instances);
1460        let discovery_source = Arc::downgrade(&client.endpoint_discovery_source);
1461        let mut raw_watcher = client.instance_source.as_ref().clone();
1462        let mut watcher = client.instance_avail_watcher();
1463        let mut event_watcher = client.subscribe_discovery_events();
1464        raw_watcher.borrow_and_update();
1465        watcher.borrow_and_update();
1466
1467        drop(client);
1468        assert!(routing_instances.upgrade().is_some());
1469        assert!(discovery_source.upgrade().is_some());
1470
1471        endpoint.register_endpoint_instance().await.unwrap();
1472        wait_for_watch_state(&mut watcher, |instances| instances.len() == 1).await;
1473        wait_for_discovery_event(&mut event_watcher, |event| {
1474            matches!(event, DiscoveryEvent::Added(DiscoveryInstance::Endpoint(_)))
1475        })
1476        .await;
1477
1478        endpoint.unregister_endpoint_instance().await.unwrap();
1479        wait_for_watch_state(&mut watcher, |instances| instances.is_empty()).await;
1480        assert!(raw_watcher.borrow_and_update().is_empty());
1481        wait_for_discovery_event(&mut event_watcher, |event| {
1482            matches!(event, DiscoveryEvent::Removed(_))
1483        })
1484        .await;
1485
1486        drop(watcher);
1487
1488        tokio::time::timeout(Duration::from_secs(1), async {
1489            while routing_instances.strong_count() != 0 {
1490                tokio::task::yield_now().await;
1491            }
1492        })
1493        .await
1494        .expect("client monitor retained state after its last observer was dropped");
1495        assert!(discovery_source.upgrade().is_some());
1496
1497        endpoint.register_endpoint_instance().await.unwrap();
1498        wait_for_watch_state(&mut raw_watcher, |instances| instances.len() == 1).await;
1499        wait_for_discovery_event(&mut event_watcher, |event| {
1500            matches!(event, DiscoveryEvent::Added(DiscoveryInstance::Endpoint(_)))
1501        })
1502        .await;
1503        endpoint.unregister_endpoint_instance().await.unwrap();
1504        wait_for_watch_state(&mut raw_watcher, |instances| instances.is_empty()).await;
1505        wait_for_discovery_event(&mut event_watcher, |event| {
1506            matches!(event, DiscoveryEvent::Removed(_))
1507        })
1508        .await;
1509
1510        drop(event_watcher);
1511        tokio::time::timeout(Duration::from_secs(1), async {
1512            while discovery_source.strong_count() != 0 {
1513                tokio::task::yield_now().await;
1514            }
1515        })
1516        .await
1517        .expect("discovery event receiver retained its source after being dropped");
1518
1519        rt.shutdown();
1520    }
1521
1522    /// Test that instances removed via report_instance_down are restored after
1523    /// the reconciliation interval elapses.
1524    #[tokio::test]
1525    async fn test_instance_reconciliation() {
1526        const TEST_RECONCILE_INTERVAL: Duration = Duration::from_millis(100);
1527
1528        let rt = Runtime::from_current().unwrap();
1529        // Use process_local config to avoid needing etcd/nats
1530        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1531            .await
1532            .unwrap();
1533        let ns = drt.namespace("test_reconciliation".to_string()).unwrap();
1534        let component = ns.component("test_component".to_string()).unwrap();
1535        let endpoint = component.endpoint("test_endpoint".to_string());
1536
1537        // Use a short reconcile interval for faster tests
1538        let client = Client::with_reconcile_interval(endpoint, TEST_RECONCILE_INTERVAL)
1539            .await
1540            .unwrap();
1541
1542        // Initially, instance_avail should be empty (no registered instances)
1543        assert!(client.instance_ids_avail().is_empty());
1544
1545        // For this test, we'll directly manipulate instance_avail and verify reconciliation
1546        // Store some test IDs
1547        client.override_instance_avail(vec![1, 2, 3]);
1548
1549        assert_eq!(client.instance_ids_avail(), vec![1u64, 2, 3]);
1550
1551        // Simulate report_instance_down removing instance 2
1552        client.report_instance_down(2);
1553        assert_eq!(client.instance_ids_avail(), vec![1u64, 3]);
1554
1555        // Wait for reconciliation interval + buffer
1556        // The monitor_instance_source will reset instance_avail to match instance_source
1557        // Since instance_source is empty, after reconciliation instance_avail should be empty
1558        tokio::time::sleep(TEST_RECONCILE_INTERVAL + Duration::from_millis(50)).await;
1559
1560        // After reconciliation, instance_avail should match instance_source (which is empty)
1561        assert!(
1562            client.instance_ids_avail().is_empty(),
1563            "After reconciliation, instance_avail should match instance_source"
1564        );
1565
1566        rt.shutdown();
1567    }
1568
1569    /// A zero inhibited duration disables local worker inhibition.
1570    #[tokio::test]
1571    async fn test_zero_inhibited_duration_leaves_instance_routable() {
1572        let rt = Runtime::from_current().unwrap();
1573        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1574            .await
1575            .unwrap();
1576        let ns = drt
1577            .namespace("test_disabled_inhibition".to_string())
1578            .unwrap();
1579        let component = ns.component("test_component".to_string()).unwrap();
1580        let endpoint = component.endpoint("test_endpoint".to_string());
1581
1582        let client = Client::with_reconcile_interval(endpoint, Duration::ZERO)
1583            .await
1584            .unwrap();
1585
1586        client.override_instance_avail(vec![1, 2, 3]);
1587        client.report_instance_down(2);
1588
1589        assert_eq!(
1590            client.instance_ids_avail(),
1591            vec![1, 2, 3],
1592            "a zero inhibited duration should leave the reported instance routable"
1593        );
1594
1595        rt.shutdown();
1596    }
1597
1598    /// Test that report_instance_down correctly removes an instance from instance_avail.
1599    #[tokio::test]
1600    async fn test_report_instance_down() {
1601        let rt = Runtime::from_current().unwrap();
1602        // Use process_local config to avoid needing etcd/nats
1603        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1604            .await
1605            .unwrap();
1606        let ns = drt.namespace("test_report_down".to_string()).unwrap();
1607        let component = ns.component("test_component".to_string()).unwrap();
1608        let endpoint = component.endpoint("test_endpoint".to_string());
1609
1610        let client = endpoint.client().await.unwrap();
1611
1612        // Manually set up instance_avail with test instances
1613        client.override_instance_avail(vec![1, 2, 3]);
1614        assert_eq!(client.instance_ids_avail(), vec![1u64, 2, 3]);
1615
1616        // Report instance 2 as down
1617        client.report_instance_down(2);
1618
1619        // Verify instance 2 is removed
1620        let avail = client.instance_ids_avail();
1621        assert!(avail.contains(&1), "Instance 1 should still be available");
1622        assert!(
1623            !avail.contains(&2),
1624            "Instance 2 should be removed after report_instance_down"
1625        );
1626        assert!(avail.contains(&3), "Instance 3 should still be available");
1627
1628        rt.shutdown();
1629    }
1630
1631    #[tokio::test]
1632    async fn test_overloaded_instance_ids_returns_none_when_empty() {
1633        let rt = Runtime::from_current().unwrap();
1634        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1635            .await
1636            .unwrap();
1637        let ns = drt.namespace("test_overloaded_ids".to_string()).unwrap();
1638        let component = ns.component("test_component".to_string()).unwrap();
1639        let endpoint = component.endpoint("test_endpoint".to_string());
1640        let client = endpoint.client().await.unwrap();
1641
1642        assert_eq!(client.overloaded_instance_ids(), None);
1643
1644        assert!(client.set_overloaded_instances(&[7]));
1645        assert_eq!(
1646            client.overloaded_instance_ids(),
1647            Some(Arc::new(HashSet::from([7])))
1648        );
1649        assert!(!client.set_overloaded_instances(&[7]));
1650
1651        assert!(client.set_overloaded_instances(&[]));
1652        assert_eq!(client.overloaded_instance_ids(), None);
1653        assert!(!client.set_overloaded_instances(&[]));
1654
1655        rt.shutdown();
1656    }
1657
1658    #[test]
1659    fn unrelated_rebuild_keeps_the_overloaded_snapshot() {
1660        let (state, _rx) = RoutingInstancesState::new(vec![1, 2, 3]);
1661        assert!(state.set_overloaded_instances(&[1]));
1662        let before = state.overloaded_ids().unwrap();
1663
1664        state.report_instance_down(2);
1665        assert!(Arc::ptr_eq(&before, &state.overloaded_ids().unwrap()));
1666    }
1667
1668    #[tokio::test(start_paused = true)]
1669    async fn request_path_overload_expires_without_monitor_update() {
1670        let rt = Runtime::from_current().unwrap();
1671        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1672            .await
1673            .unwrap();
1674        let client = drt
1675            .namespace("test_request_overload_expiry".to_string())
1676            .unwrap()
1677            .component("test_component".to_string())
1678            .unwrap()
1679            .endpoint("decode".to_string())
1680            .client()
1681            .await
1682            .unwrap();
1683
1684        client.mark_overloaded_immediate(7);
1685        assert_eq!(
1686            client.overloaded_instance_ids(),
1687            Some(Arc::new(HashSet::from([7])))
1688        );
1689
1690        tokio::time::advance(REQUEST_PATH_OVERLOAD_COOLDOWN).await;
1691
1692        assert_eq!(client.overloaded_instance_ids(), None);
1693        assert!(!client.overload_reconciliation_needed());
1694        rt.shutdown();
1695    }
1696
1697    #[tokio::test]
1698    async fn request_path_expiry_preserves_monitor_overload() {
1699        let rt = Runtime::from_current().unwrap();
1700        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1701            .await
1702            .unwrap();
1703        let client = drt
1704            .namespace("test_request_expiry_preserves_monitor".to_string())
1705            .unwrap()
1706            .component("test_component".to_string())
1707            .unwrap()
1708            .endpoint("decode".to_string())
1709            .client()
1710            .await
1711            .unwrap();
1712        let now = Instant::now();
1713
1714        assert!(client.set_overloaded_instances(&[11]));
1715        client
1716            .routing_instances
1717            .mark_overloaded_until(7, now + Duration::from_secs(1));
1718        client
1719            .routing_instances
1720            .mark_overloaded_until(8, now + Duration::from_secs(2));
1721
1722        client
1723            .routing_instances
1724            .reconcile_expired_request_overloads(now + Duration::from_millis(1500));
1725
1726        assert_eq!(
1727            client.overloaded_instance_ids(),
1728            Some(Arc::new(HashSet::from([8, 11])))
1729        );
1730        assert!(client.overload_reconciliation_needed());
1731        rt.shutdown();
1732    }
1733
1734    #[tokio::test]
1735    async fn test_instance_reconciliation_preserves_overloaded_existing_instances() {
1736        const TEST_RECONCILE_INTERVAL: Duration = Duration::from_millis(50);
1737
1738        let rt = Runtime::from_current().unwrap();
1739        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1740            .await
1741            .unwrap();
1742        let ns = drt
1743            .namespace("test_overloaded_reconciliation".to_string())
1744            .unwrap();
1745        let component = ns.component("test_component".to_string()).unwrap();
1746        let endpoint = component.endpoint("test_endpoint".to_string());
1747
1748        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
1749            .await
1750            .unwrap();
1751        endpoint.register_endpoint_instance().await.unwrap();
1752        let instances = client.wait_for_instances().await.unwrap();
1753        let worker_id = instances[0].id();
1754
1755        for _ in 0..10 {
1756            if client.instance_ids_free().contains(&worker_id) {
1757                break;
1758            }
1759            tokio::time::sleep(TEST_RECONCILE_INTERVAL).await;
1760        }
1761        assert!(
1762            client.instance_ids_free().contains(&worker_id),
1763            "worker should be free after initial discovery reconciliation"
1764        );
1765
1766        client.set_overloaded_instances(&[worker_id]);
1767        assert!(
1768            client.instance_ids_free().is_empty(),
1769            "worker should be overloaded before periodic reconciliation"
1770        );
1771
1772        tokio::time::sleep(TEST_RECONCILE_INTERVAL + Duration::from_millis(50)).await;
1773
1774        assert!(
1775            client.instance_ids_free().is_empty(),
1776            "periodic reconciliation should not mark an existing overloaded worker free"
1777        );
1778
1779        rt.shutdown();
1780    }
1781
1782    #[tokio::test]
1783    async fn test_report_instance_down_preserves_overloaded_state() {
1784        const TEST_RECONCILE_INTERVAL: Duration = Duration::from_millis(50);
1785
1786        let rt = Runtime::from_current().unwrap();
1787        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1788            .await
1789            .unwrap();
1790        let ns = drt
1791            .namespace("test_report_down_preserves_overloaded".to_string())
1792            .unwrap();
1793        let component = ns.component("test_component".to_string()).unwrap();
1794        let endpoint = component.endpoint("test_endpoint".to_string());
1795
1796        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
1797            .await
1798            .unwrap();
1799        endpoint.register_endpoint_instance().await.unwrap();
1800        let instances = client.wait_for_instances().await.unwrap();
1801        let worker_id = instances[0].id();
1802
1803        for _ in 0..10 {
1804            if client.instance_ids_avail().contains(&worker_id) {
1805                break;
1806            }
1807            tokio::time::sleep(TEST_RECONCILE_INTERVAL).await;
1808        }
1809
1810        client.set_overloaded_instances(&[worker_id]);
1811        client.report_instance_down(worker_id);
1812
1813        assert!(
1814            !client.instance_ids_avail().contains(&worker_id),
1815            "reported-down worker should leave routable availability"
1816        );
1817        assert_eq!(
1818            client.routing_instance_counts().overloaded,
1819            1,
1820            "reported-down worker should remain overloaded while still discovered"
1821        );
1822        assert!(
1823            client.instance_ids_free().is_empty(),
1824            "reported-down overloaded worker should not become free"
1825        );
1826
1827        endpoint.unregister_endpoint_instance().await.unwrap();
1828        for _ in 0..10 {
1829            if client.routing_instance_counts().overloaded == 0 {
1830                break;
1831            }
1832            tokio::time::sleep(TEST_RECONCILE_INTERVAL).await;
1833        }
1834
1835        assert_eq!(
1836            client.routing_instance_counts().overloaded,
1837            0,
1838            "stable discovery removal should clear overloaded state"
1839        );
1840
1841        rt.shutdown();
1842    }
1843
1844    #[tokio::test]
1845    async fn test_instance_reconciliation_prunes_removed_overloaded_instances() {
1846        const TEST_RECONCILE_INTERVAL: Duration = Duration::from_millis(50);
1847
1848        let rt = Runtime::from_current().unwrap();
1849        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1850            .await
1851            .unwrap();
1852        let ns = drt
1853            .namespace("test_removed_overloaded_cleanup".to_string())
1854            .unwrap();
1855        let component = ns.component("test_component".to_string()).unwrap();
1856        let endpoint = component.endpoint("test_endpoint".to_string());
1857
1858        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
1859            .await
1860            .unwrap();
1861        endpoint.register_endpoint_instance().await.unwrap();
1862        let instances = client.wait_for_instances().await.unwrap();
1863        let worker_id = instances[0].id();
1864
1865        client.set_overloaded_instances(&[worker_id]);
1866        assert_eq!(client.routing_instance_counts().overloaded, 1);
1867        assert!(client.instance_ids_free().is_empty());
1868
1869        endpoint.unregister_endpoint_instance().await.unwrap();
1870        for _ in 0..10 {
1871            if client.routing_instance_counts().overloaded == 0 {
1872                break;
1873            }
1874            tokio::time::sleep(TEST_RECONCILE_INTERVAL).await;
1875        }
1876
1877        assert_eq!(
1878            client.routing_instance_counts().overloaded,
1879            0,
1880            "removed discovered workers should not remain in overloaded state"
1881        );
1882
1883        rt.shutdown();
1884    }
1885
1886    #[tokio::test]
1887    async fn test_instance_ids_free_excludes_overloaded_new_instances() {
1888        const TEST_RECONCILE_INTERVAL: Duration = Duration::from_millis(50);
1889
1890        let rt = Runtime::from_current().unwrap();
1891        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1892            .await
1893            .unwrap();
1894        let worker_id = drt.connection_id();
1895        let ns = drt
1896            .namespace("test_new_overloaded_reconciliation".to_string())
1897            .unwrap();
1898        let component = ns.component("test_component".to_string()).unwrap();
1899        let endpoint = component.endpoint("test_endpoint".to_string());
1900
1901        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
1902            .await
1903            .unwrap();
1904        client.set_overloaded_instances(&[worker_id]);
1905
1906        endpoint.register_endpoint_instance().await.unwrap();
1907        let instances = client.wait_for_instances().await.unwrap();
1908        assert_eq!(instances[0].id(), worker_id);
1909        assert!(
1910            client.instance_ids_free().is_empty(),
1911            "newly discovered overloaded worker should not be free"
1912        );
1913
1914        tokio::time::sleep(TEST_RECONCILE_INTERVAL + Duration::from_millis(50)).await;
1915
1916        assert!(
1917            client.instance_ids_free().is_empty(),
1918            "discovery reconciliation should not affect recomputed free workers"
1919        );
1920
1921        rt.shutdown();
1922    }
1923
1924    #[tokio::test]
1925    async fn test_discovery_add_updates_free_without_overloaded_publish() {
1926        const TEST_RECONCILE_INTERVAL: Duration = Duration::from_millis(50);
1927
1928        let rt = Runtime::from_current().unwrap();
1929        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1930            .await
1931            .unwrap();
1932        let ns = drt
1933            .namespace("test_free_updates_on_discovery_add".to_string())
1934            .unwrap();
1935        let component = ns.component("test_component".to_string()).unwrap();
1936        let endpoint = component.endpoint("test_endpoint".to_string());
1937
1938        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
1939            .await
1940            .unwrap();
1941        endpoint.register_endpoint_instance().await.unwrap();
1942        let instances = client.wait_for_instances().await.unwrap();
1943        let worker_id = instances[0].id();
1944
1945        for _ in 0..10 {
1946            if client.instance_ids_free().contains(&worker_id) {
1947                break;
1948            }
1949            tokio::time::sleep(TEST_RECONCILE_INTERVAL).await;
1950        }
1951
1952        assert_eq!(
1953            client.instance_ids_free(),
1954            vec![worker_id],
1955            "newly discovered non-overloaded workers should appear free without an overload update"
1956        );
1957
1958        rt.shutdown();
1959    }
1960
1961    /// Test that instance_avail_watcher receives updates when instances change.
1962    #[tokio::test]
1963    async fn test_instance_avail_watcher() {
1964        let rt = Runtime::from_current().unwrap();
1965        // Use process_local config to avoid needing etcd/nats
1966        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
1967            .await
1968            .unwrap();
1969        let ns = drt.namespace("test_watcher".to_string()).unwrap();
1970        let component = ns.component("test_component".to_string()).unwrap();
1971        let endpoint = component.endpoint("test_endpoint".to_string());
1972
1973        let client = endpoint.client().await.unwrap();
1974        let watcher = client.instance_avail_watcher();
1975
1976        // Set initial instances
1977        client.override_instance_avail(vec![1, 2, 3]);
1978
1979        // Report instance down - this should notify the watcher
1980        client.report_instance_down(2);
1981
1982        // The watcher should receive the update
1983        // Note: We need to check if changed() was signaled
1984        let current = watcher.borrow().clone();
1985        assert_eq!(current, vec![1, 3]);
1986
1987        rt.shutdown();
1988    }
1989
1990    /// Regression test: `monitor_instance_source_with_cancellation`'s task must
1991    /// exit on its own `cancel_token`, not only at process shutdown.
1992    ///
1993    /// `Client::new` bound this task to the process-wide primary token
1994    /// unconditionally. A caller building a `Client` scoped to something
1995    /// narrower — a monitor bound to one `WorkerSet`'s lifecycle, say — had no
1996    /// way to stop the task before then: dropping every `Client` handle does
1997    /// not stop it, since it holds its own clone. Every WorkerSet rebuild
1998    /// leaked one.
1999    ///
2000    /// The observable is the strong count of `routing_instances`: the spawned
2001    /// task captures a clone of it, so the count returning to 1 proves the
2002    /// task actually exited and dropped that capture.
2003    #[tokio::test]
2004    async fn monitor_instance_source_exits_on_its_own_cancellation_token() {
2005        let rt = Runtime::from_current().unwrap();
2006        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2007            .await
2008            .unwrap();
2009        let ns = drt
2010            .namespace("test_monitor_instance_source_cancellation".to_string())
2011            .unwrap();
2012        let component = ns.component("test_component".to_string()).unwrap();
2013        let endpoint = component.endpoint("test_endpoint".to_string());
2014
2015        let cancel_token = tokio_util::sync::CancellationToken::new();
2016        let client = Client::with_cancellation(endpoint.clone(), cancel_token.clone())
2017            .await
2018            .unwrap();
2019
2020        // Negative control, first: the task must still be alive, and still
2021        // holding its capture, before cancellation.
2022        tokio::time::sleep(Duration::from_millis(200)).await;
2023        assert!(
2024            Arc::strong_count(&client.routing_instances) > 1,
2025            "monitor task must be running (and holding its capture) before cancellation"
2026        );
2027
2028        cancel_token.cancel();
2029        tokio::time::timeout(Duration::from_secs(5), async {
2030            while Arc::strong_count(&client.routing_instances) > 1 {
2031                tokio::time::sleep(Duration::from_millis(10)).await;
2032            }
2033        })
2034        .await
2035        .expect("monitor_instance_source task must exit when its cancel_token cancels");
2036
2037        rt.shutdown();
2038    }
2039
2040    #[tokio::test]
2041    async fn admitted_client_never_routes_unadmitted_endpoint_instances() {
2042        let rt = Runtime::from_current().unwrap();
2043        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2044            .await
2045            .unwrap();
2046        let ns = drt.namespace("test_admitted_client".to_string()).unwrap();
2047        let component = ns.component("test_component".to_string()).unwrap();
2048        let endpoint = component.endpoint("test_endpoint".to_string());
2049        let endpoint_client = endpoint.client().await.unwrap();
2050        endpoint.register_endpoint_instance().await.unwrap();
2051        let worker_id = endpoint_client.wait_for_instances().await.unwrap()[0].id();
2052
2053        let (admission_tx, admission_rx) = tokio::sync::watch::channel(Vec::new());
2054        let admitted_client = endpoint_client.with_admitted_instances(admission_rx);
2055        let mut admitted = admitted_client.instance_avail_watcher();
2056        assert!(admitted.borrow().is_empty());
2057
2058        admission_tx.send_replace(vec![worker_id]);
2059        tokio::time::timeout(Duration::from_secs(1), admitted.changed())
2060            .await
2061            .unwrap()
2062            .unwrap();
2063        assert_eq!(admitted.borrow_and_update().clone(), vec![worker_id]);
2064
2065        admission_tx.send_replace(Vec::new());
2066        tokio::time::timeout(Duration::from_secs(1), admitted.changed())
2067            .await
2068            .unwrap()
2069            .unwrap();
2070        assert!(admitted.borrow_and_update().is_empty());
2071
2072        rt.shutdown();
2073    }
2074
2075    /// Test that concurrent least-loaded increments distribute load correctly.
2076    #[tokio::test]
2077    async fn test_concurrent_select_and_increment() {
2078        let state = Arc::new(RoutingOccupancyState::default());
2079        let instance_ids: Vec<u64> = vec![100, 200, 300];
2080        let num_requests = 90;
2081
2082        let mut handles = Vec::new();
2083        for _ in 0..num_requests {
2084            let state = state.clone();
2085            let ids = instance_ids.clone();
2086            handles.push(tokio::spawn(
2087                async move { state.increment_least_loaded(&ids) },
2088            ));
2089        }
2090
2091        for handle in handles {
2092            handle.await.unwrap();
2093        }
2094
2095        assert_eq!(state.load(100), 30);
2096        assert_eq!(state.load(200), 30);
2097        assert_eq!(state.load(300), 30);
2098    }
2099
2100    #[tokio::test]
2101    async fn test_connection_counts() {
2102        let rt = Runtime::from_current().unwrap();
2103        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2104            .await
2105            .unwrap();
2106        let ns = drt.namespace("test_ll_counts".to_string()).unwrap();
2107        let component = ns.component("test_component".to_string()).unwrap();
2108        let endpoint = component.endpoint("test_endpoint".to_string());
2109
2110        let state1 = get_or_create_routing_occupancy_state(&endpoint).await;
2111        let state2 = get_or_create_routing_occupancy_state(&endpoint).await;
2112
2113        let picked1 = state1.increment_least_loaded(&[10, 20, 30]).unwrap();
2114        assert_eq!(state1.load(picked1), 1);
2115
2116        let picked2 = state1.increment_least_loaded(&[10, 20, 30]).unwrap();
2117        assert_ne!(picked1, picked2);
2118
2119        // state2 should see the same counts (same underlying Arc)
2120        assert_eq!(state2.load(10), state1.load(10));
2121        assert_eq!(state2.load(20), state1.load(20));
2122        assert_eq!(state2.load(30), state1.load(30));
2123
2124        state2.decrement(picked1);
2125        assert_eq!(state1.load(picked1), if picked1 == picked2 { 1 } else { 0 });
2126
2127        rt.shutdown();
2128    }
2129
2130    #[tokio::test]
2131    async fn test_least_loaded_state_retain_preserves_live_counts() {
2132        let state = RoutingOccupancyState::default();
2133
2134        // Add some connections
2135        state.increment_least_loaded(&[1, 2, 3]);
2136        state.increment_least_loaded(&[1, 2, 3]);
2137        state.increment_least_loaded(&[1, 2, 3]);
2138        // Each instance should have 1 connection
2139        assert_eq!(state.load(1), 1);
2140        assert_eq!(state.load(2), 1);
2141        assert_eq!(state.load(3), 1);
2142
2143        // Discovery removal must not delete guard-owned accounting.
2144        state.retain(&[1, 3]);
2145
2146        assert_eq!(state.load(1), 1);
2147        assert_eq!(state.load(2), 1);
2148        assert_eq!(state.load(3), 1);
2149    }
2150
2151    #[tokio::test]
2152    async fn test_monitor_instance_source_defers_removed_worker_cleanup() {
2153        const TEST_RECONCILE_INTERVAL: Duration = Duration::from_millis(50);
2154
2155        let rt = Runtime::from_current().unwrap();
2156        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
2157            .await
2158            .unwrap();
2159        let ns = drt.namespace("test_occupancy_cleanup".to_string()).unwrap();
2160        let component = ns.component("test_component".to_string()).unwrap();
2161        let endpoint = component.endpoint("test_endpoint".to_string());
2162
2163        let client = Client::with_reconcile_interval(endpoint.clone(), TEST_RECONCILE_INTERVAL)
2164            .await
2165            .unwrap();
2166        endpoint.register_endpoint_instance().await.unwrap();
2167        client.wait_for_instances().await.unwrap();
2168
2169        let worker_id = client.instance_ids_avail()[0];
2170        let state = get_or_create_routing_occupancy_state(&endpoint).await;
2171        state.increment(worker_id);
2172        assert_eq!(state.load(worker_id), 1);
2173
2174        endpoint.unregister_endpoint_instance().await.unwrap();
2175
2176        for _ in 0..10 {
2177            if !client.instance_ids().contains(&worker_id) {
2178                break;
2179            }
2180            tokio::time::sleep(TEST_RECONCILE_INTERVAL).await;
2181        }
2182
2183        assert_eq!(
2184            state.load(worker_id),
2185            1,
2186            "discovery absence must retain live accounting"
2187        );
2188        state.decrement(worker_id);
2189        assert_eq!(state.load(worker_id), 0);
2190
2191        rt.shutdown();
2192    }
2193}