Skip to main content

saluki_core/health/
mod.rs

1//! Health registry for tracking component readiness and liveness.
2
3use std::future::Future;
4#[cfg(test)]
5use std::sync::atomic::AtomicUsize;
6use std::{
7    collections::HashSet,
8    sync::{
9        atomic::{AtomicBool, Ordering::Relaxed},
10        Arc, Mutex,
11    },
12    time::Duration,
13};
14
15use futures::StreamExt as _;
16use saluki_error::{generic_error, GenericError};
17use saluki_metrics::{static_metrics, Gauge, Histogram};
18use tokio::{pin, time::Instant};
19use tokio::{
20    select,
21    sync::{
22        mpsc::{self, error::TrySendError},
23        Notify,
24    },
25};
26use tokio_util::time::{delay_queue::Key, DelayQueue};
27use tracing::{debug, info, trace};
28
29use crate::support::SubsystemIdentifier;
30
31mod api;
32pub use self::api::HealthAPIHandler;
33
34mod worker;
35pub use self::worker::HealthRegistryWorker;
36
37const DEFAULT_PROBE_TIMEOUT_DUR: Duration = Duration::from_secs(5);
38const DEFAULT_PROBE_BACKOFF_DUR: Duration = Duration::from_secs(1);
39
40/// A handle for updating the health of a component.
41pub struct Health {
42    shared: Arc<SharedComponentState>,
43    liveness: Option<LivenessChannel>,
44    readiness_notify: Arc<Notify>,
45}
46
47impl Health {
48    /// Marks the component as ready.
49    pub fn mark_ready(&mut self) {
50        self.update_readiness(true);
51    }
52
53    /// Marks the component as not ready.
54    pub fn mark_not_ready(&mut self) {
55        self.update_readiness(false);
56    }
57
58    fn update_readiness(&self, ready: bool) {
59        self.shared.ready.store(ready, Relaxed);
60        self.shared.telemetry.update_readiness(ready);
61
62        // Wake any tasks waiting in `HealthRegistry::all_ready` so they can re-check whether all components are ready.
63        if ready {
64            self.readiness_notify.notify_waiters();
65        }
66    }
67
68    /// Waits for a liveness probe to be sent to the component, and then responds to it.
69    ///
70    /// This should generally be polled as part of a `select!` block to ensure it's checked alongside other
71    /// asynchronous operations.
72    ///
73    /// For a component that runs in a topology, this method never resolves, because the topology answers liveness
74    /// probes around the run future of the component.
75    pub async fn live(&mut self) {
76        match self.liveness.as_mut() {
77            Some(channel) => {
78                channel.respond().await;
79            }
80            None => std::future::pending().await,
81        }
82    }
83
84    /// Takes the liveness responder out of this handle.
85    ///
86    /// After this call, the returned [`LivenessResponder`] answers the liveness probes for the component, and
87    /// [`live`][Self::live] never resolves. The handle still controls readiness.
88    ///
89    /// Returns `None` if the responder was already taken.
90    pub(crate) fn take_liveness_responder(&mut self) -> Option<LivenessResponder> {
91        self.liveness.take().map(|channel| LivenessResponder { channel })
92    }
93}
94
95/// The channel pair that carries liveness probes to a component and its responses back to the registry.
96struct LivenessChannel {
97    request_rx: mpsc::Receiver<LivenessRequest>,
98    response_tx: mpsc::Sender<LivenessResponse>,
99}
100
101impl LivenessChannel {
102    /// Waits for a liveness probe and responds to it.
103    ///
104    /// Returns `false` if the registry closed the probe channel, and `true` otherwise.
105    async fn respond(&mut self) -> bool {
106        match self.request_rx.recv().await {
107            Some(request) => {
108                let response = request.into_response();
109                let _ = self.response_tx.send(response).await;
110                true
111            }
112            None => false,
113        }
114    }
115}
116
117/// Answers liveness probes for a component while it runs a future.
118///
119/// A component that waits on an `.await` outside its `select!` loop can't answer probes. One example is a send into a
120/// full downstream channel. The component is not stuck. It waits for backpressure to clear, but the registry marks it
121/// as not live. `LivenessResponder` moves probe handling out of the component: [`drive`][Self::drive] answers probes
122/// whenever the task of the component runs, whatever the component is waiting on.
123///
124/// The component is live while its task is scheduled and polled. A probe still fails if the task blocks the thread, or
125/// if the runtime can't poll the task within the probe timeout.
126///
127/// # Missing
128///
129/// - Detection of a run future that waits forever. Such a component stays live, because its task still gets polled.
130///   Examples are two components that each wait on a full channel that the other one drains, and a forwarder that
131///   waits on a request that never completes. Catching these cases needs a progress-based signal, such as a check that
132///   a component with buffered input still sends events.
133pub(crate) struct LivenessResponder {
134    channel: LivenessChannel,
135}
136
137impl LivenessResponder {
138    /// Runs `fut` to completion and answers liveness probes while it runs.
139    ///
140    /// The probes and `fut` run in the same task. When `fut` completes, the responder is dropped, and the registry
141    /// marks the component as dead at the next probe.
142    pub(crate) async fn drive<F: Future>(mut self, fut: F) -> F::Output {
143        pin!(fut);
144
145        loop {
146            select! {
147                // Check probes first, so that each time the task wakes, a waiting probe is seen, even when `fut` uses
148                // up the cooperative budget of the task.
149                biased;
150
151                open = self.channel.respond() => {
152                    if !open {
153                        // The registry is gone, so there are no more probes to answer.
154                        return fut.await;
155                    }
156                },
157                output = &mut fut => return output,
158            }
159        }
160    }
161}
162
163#[derive(Clone, Copy, Eq, PartialEq)]
164enum HealthState {
165    Live,
166    Unknown,
167    Dead,
168}
169
170#[static_metrics(prefix = health, labels(component_id))]
171#[derive(Clone)]
172struct Telemetry {
173    component_ready: Gauge,
174    component_live: Gauge,
175    #[metric(level = trace)]
176    component_liveness_latency_seconds: Histogram,
177}
178
179impl Telemetry {
180    fn from_name(name: &SubsystemIdentifier) -> Self {
181        Self::new(name)
182    }
183
184    fn update_readiness(&self, ready: bool) {
185        self.component_ready().set(if ready { 1.0 } else { 0.0 });
186    }
187
188    fn update_liveness(&self, state: HealthState, response_latency: Duration) {
189        let live = match state {
190            HealthState::Live => 1.0,
191            HealthState::Unknown => 0.0,
192            HealthState::Dead => -1.0,
193        };
194
195        self.component_live().set(live);
196        self.component_liveness_latency_seconds()
197            .record(response_latency.as_secs_f64());
198    }
199}
200
201struct SharedComponentState {
202    ready: AtomicBool,
203    telemetry: Telemetry,
204}
205
206struct ComponentState {
207    name: SubsystemIdentifier,
208    health: HealthState,
209    shared: Arc<SharedComponentState>,
210    request_tx: mpsc::Sender<LivenessRequest>,
211    last_response: Instant,
212    last_response_latency: Duration,
213}
214
215impl ComponentState {
216    fn new(
217        name: SubsystemIdentifier, response_tx: mpsc::Sender<LivenessResponse>, readiness_notify: Arc<Notify>,
218    ) -> (Self, Health) {
219        let shared = Arc::new(SharedComponentState {
220            ready: AtomicBool::new(false),
221            telemetry: Telemetry::from_name(&name),
222        });
223        let (request_tx, request_rx) = mpsc::channel(1);
224
225        let state = Self {
226            name,
227            health: HealthState::Unknown,
228            shared: Arc::clone(&shared),
229            request_tx,
230            last_response: Instant::now(),
231            last_response_latency: Duration::from_secs(0),
232        };
233
234        let handle = Health {
235            shared,
236            liveness: Some(LivenessChannel {
237                request_rx,
238                response_tx,
239            }),
240            readiness_notify,
241        };
242
243        (state, handle)
244    }
245
246    fn is_ready(&self) -> bool {
247        // We consider a component ready if it's marked as ready (duh) and it's not dead.
248        //
249        // Being "dead" is a special case as it means the component is very likely not even running at all, not just
250        // responding slowly or deadlocked. In these cases, it can't possibly be ready since it's not even running.
251        self.shared.ready.load(Relaxed) && self.health != HealthState::Dead
252    }
253
254    fn is_live(&self) -> bool {
255        self.health == HealthState::Live
256    }
257
258    fn mark_live(&mut self, response_sent: Instant, response_latency: Duration) {
259        self.health = HealthState::Live;
260        self.last_response = response_sent;
261        self.last_response_latency = response_latency;
262        self.shared.telemetry.update_liveness(self.health, response_latency);
263    }
264
265    fn mark_not_live(&mut self) {
266        self.health = HealthState::Unknown;
267
268        // We use the default timeout as the latency for when the component is not considered alive.
269        self.shared
270            .telemetry
271            .update_liveness(self.health, DEFAULT_PROBE_TIMEOUT_DUR);
272    }
273
274    fn mark_dead(&mut self) {
275        self.health = HealthState::Dead;
276
277        // We use the default timeout as the latency for when the component is not considered alive.
278        self.shared
279            .telemetry
280            .update_liveness(self.health, DEFAULT_PROBE_TIMEOUT_DUR);
281    }
282}
283
284struct LivenessRequest {
285    component_id: usize,
286    timeout_key: Key,
287    request_sent: Instant,
288}
289
290impl LivenessRequest {
291    fn new(component_id: usize, timeout_key: Key) -> Self {
292        Self {
293            component_id,
294            timeout_key,
295            request_sent: Instant::now(),
296        }
297    }
298
299    fn into_response(self) -> LivenessResponse {
300        LivenessResponse {
301            request: self,
302            response_sent: Instant::now(),
303        }
304    }
305}
306
307struct LivenessResponse {
308    request: LivenessRequest,
309    response_sent: Instant,
310}
311
312enum HealthUpdate {
313    Alive {
314        last_response: Instant,
315        last_response_latency: Duration,
316    },
317    Unknown,
318    Dead,
319}
320
321impl HealthUpdate {
322    fn as_str(&self) -> &'static str {
323        match self {
324            HealthUpdate::Alive { .. } => "alive",
325            HealthUpdate::Unknown => "unknown",
326            HealthUpdate::Dead => "dead",
327        }
328    }
329}
330
331struct RegistryState {
332    registered_components: HashSet<SubsystemIdentifier>,
333    component_state: Vec<ComponentState>,
334    responses_tx: mpsc::Sender<LivenessResponse>,
335    responses_rx: Option<mpsc::Receiver<LivenessResponse>>,
336    pending_components: Vec<usize>,
337    pending_components_notify: Arc<Notify>,
338    readiness_notify: Arc<Notify>,
339}
340
341impl RegistryState {
342    fn new() -> Self {
343        let (responses_tx, responses_rx) = mpsc::channel(16);
344
345        Self {
346            registered_components: HashSet::new(),
347            component_state: Vec::new(),
348            responses_tx,
349            responses_rx: Some(responses_rx),
350            pending_components: Vec::new(),
351            pending_components_notify: Arc::new(Notify::new()),
352            readiness_notify: Arc::new(Notify::new()),
353        }
354    }
355}
356
357/// A registry of components and their health.
358///
359/// `HealthRegistry` is responsible for tracking the health of all registered components, by storing both their
360/// readiness, which indicates whether or not they're initialized and generally ready to process data, as well as
361/// probing their liveness, which indicates if they're currently responding, or able to respond, to requests.
362///
363/// # Telemetry
364///
365/// The health registry emits some internal telemetry about the status of registered components. In particular, three
366/// metrics are emitted:
367///
368/// - `health_component_ready`: whether or not a component is ready (`gauge`, `0` for not ready, `1` for ready)
369/// - `health_component_live`: whether or not a component is alive (`gauge`, `0` for not alive/unknown, `1` for alive, `-1` for dead)
370/// - `health_component_liveness_latency_seconds`: the response latency of the component for liveness probes (`histogram`,
371///   in seconds)
372///
373/// All metrics have a `component_id` tag that corresponds to the name of the component that was given when registering it.
374#[derive(Clone)]
375pub struct HealthRegistry {
376    inner: Arc<Mutex<RegistryState>>,
377}
378
379impl HealthRegistry {
380    /// Creates an empty registry.
381    pub fn new() -> Self {
382        Self {
383            inner: Arc::new(Mutex::new(RegistryState::new())),
384        }
385    }
386
387    #[cfg(test)]
388    fn state(&self) -> Arc<Mutex<RegistryState>> {
389        Arc::clone(&self.inner)
390    }
391
392    /// Registers a component with the registry, keyed by its canonical [`SubsystemIdentifier`].
393    ///
394    /// Returns `None` if a component with the same identifier is already registered. Otherwise, a handle is returned
395    /// that must be used by the component to set its readiness as well as respond to liveness probes. See
396    /// [`Health::mark_ready`], [`Health::mark_not_ready`], and [`Health::live`] for more information.
397    pub fn register_component(&self, id: &SubsystemIdentifier) -> Option<Health> {
398        let mut inner = self.inner.lock().unwrap();
399
400        // Make sure we don't already have this component registered.
401        if !inner.registered_components.insert(id.clone()) {
402            return None;
403        }
404
405        // Add the component state.
406        let readiness_notify = Arc::clone(&inner.readiness_notify);
407        let (state, handle) = ComponentState::new(id.clone(), inner.responses_tx.clone(), readiness_notify);
408        let component_id = inner.component_state.len();
409        inner.component_state.push(state);
410
411        debug!(component_id, "Registered component '{}'.", id);
412
413        // Mark ourselves as having a pending component that needs to be scheduled.
414        inner.pending_components.push(component_id);
415        inner.pending_components_notify.notify_one();
416
417        Some(handle)
418    }
419
420    /// Gets an API handler for reporting the health of all components.
421    ///
422    /// This handler exposes routes for querying the readiness and liveness of all registered components. See
423    /// [`HealthAPIHandler`] for more information about routes and responses.
424    pub fn api_handler(&self) -> HealthAPIHandler {
425        HealthAPIHandler::from_state(Arc::clone(&self.inner))
426    }
427
428    /// Waits until all registered components are ready.
429    ///
430    /// If no components are registered, or all currently registered components are ready, the method returns immediately. Otherwise,
431    /// the method will return as soon as all registered components transition to ready.
432    ///
433    /// Note that components can be registered while this method is waiting, which will influence how long this method
434    /// takes to return. Callers should ensure that all components have been registered before calling this method.
435    pub async fn all_ready(&self) {
436        self.all_ready_matching(|_| true).await
437    }
438
439    /// Waits until all currently registered components whose name matches `predicate` are ready.
440    ///
441    /// This is a scoped variant of [`all_ready`][Self::all_ready] that only considers components whose name satisfies
442    /// the given predicate, which is useful for waiting on a specific subsystem's components to become ready without
443    /// waiting on every other component in the registry.
444    ///
445    /// If no registered component matches the predicate, the method returns immediately. As with
446    /// [`all_ready`][Self::all_ready], components can be registered while this method is waiting, so callers should
447    /// ensure all components they care about have been registered before calling this method.
448    pub async fn all_ready_matching<F>(&self, predicate: F)
449    where
450        F: Fn(&SubsystemIdentifier) -> bool,
451    {
452        let readiness_notify = {
453            let inner = self.inner.lock().unwrap();
454            Arc::clone(&inner.readiness_notify)
455        };
456
457        loop {
458            // Register as a waiter _before_ checking to avoid missing notifications during the check.
459            let notified = readiness_notify.notified();
460
461            if self.check_ready_matching(&predicate) {
462                return;
463            }
464
465            notified.await;
466        }
467    }
468
469    /// Waits until all currently registered components that are strict descendants of `root` are ready.
470    ///
471    /// This is a convenience wrapper over [`all_ready_matching`][Self::all_ready_matching] for the common case of
472    /// waiting on a single subsystem: it matches exactly the components whose identifier is a strict descendant of
473    /// `root` (see [`SubsystemIdentifier::is_ancestor_of`]). The same registration caveats as
474    /// [`all_ready`][Self::all_ready] apply.
475    pub async fn all_ready_under(&self, root: SubsystemIdentifier) {
476        self.all_ready_matching(move |id| root.is_ancestor_of(id)).await
477    }
478
479    fn check_ready_matching<F>(&self, predicate: &F) -> bool
480    where
481        F: Fn(&SubsystemIdentifier) -> bool,
482    {
483        let inner = self.inner.lock().unwrap();
484        inner
485            .component_state
486            .iter()
487            .filter(|component| predicate(&component.name))
488            .all(|component| component.is_ready())
489    }
490
491    /// Returns a JSON snapshot of the current readiness and liveness state of all registered components.
492    ///
493    /// Each component appears as a key in the returned JSON object, with its `live` and `ready` boolean fields
494    /// reflecting the state at the time of the call. This is the same data exposed by the `/ready` and `/live`
495    /// HTTP endpoints, but collected in a single pass for use outside of the HTTP handler path (for
496    /// example, when building a diagnostic artifact).
497    pub fn snapshot_json(&self) -> String {
498        #[derive(serde::Serialize)]
499        struct ComponentSnapshot {
500            live: bool,
501            ready: bool,
502        }
503
504        let inner = self.inner.lock().unwrap();
505        let mut state: std::collections::HashMap<String, ComponentSnapshot> = std::collections::HashMap::new();
506        for component in &inner.component_state {
507            state.insert(
508                component.name.to_string(),
509                ComponentSnapshot {
510                    live: component.is_live(),
511                    ready: component.is_ready(),
512                },
513            );
514        }
515        serde_json::to_string_pretty(&state).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}"))
516    }
517
518    /// Creates a [`HealthRegistryWorker`] that can be added to a supervisor to run the health registry.
519    ///
520    /// The worker handles the lifecycle of the health registry runner, including registering the health API routes
521    /// dynamically and running the liveness probing event loop.
522    pub fn worker(&self) -> HealthRegistryWorker {
523        HealthRegistryWorker::new(self.clone())
524    }
525
526    pub(crate) fn into_runner(self) -> Result<Runner, GenericError> {
527        // Make sure the runner hasn't already been spawned.
528        let (responses_rx, pending_components_notify) = {
529            let mut inner = self.inner.lock().unwrap();
530            let responses_rx = match inner.responses_rx.take() {
531                Some(rx) => rx,
532                None => return Err(generic_error!("health registry already spawned")),
533            };
534
535            let pending_components_notify = Arc::clone(&inner.pending_components_notify);
536            (responses_rx, pending_components_notify)
537        };
538
539        Ok(Runner::new(self.inner, responses_rx, pending_components_notify))
540    }
541}
542
543/// A guard that returns the response receiver back to the registry when dropped.
544///
545/// This allows the health registry runner to be restarted gracefully: whenever the runner task
546/// finishes and this guard is dropped (for example, after a shutdown or task cancellation), the
547/// receiver is returned to the registry state so that a subsequent call to `spawn()` can succeed.
548struct RunnerGuard {
549    registry: Arc<Mutex<RegistryState>>,
550    responses_rx: Option<mpsc::Receiver<LivenessResponse>>,
551}
552
553impl Drop for RunnerGuard {
554    fn drop(&mut self) {
555        if let Some(rx) = self.responses_rx.take() {
556            let mut inner = self.registry.lock().expect("registry state poisoned");
557            inner.responses_rx = Some(rx);
558            debug!("Returned response receiver to registry state.");
559        }
560    }
561}
562
563#[cfg(test)]
564struct RunnerState {
565    pending_scheduled_probes: AtomicUsize,
566    pending_probe_timeouts: AtomicUsize,
567}
568
569#[cfg(test)]
570impl RunnerState {
571    fn new() -> Self {
572        Self {
573            pending_scheduled_probes: AtomicUsize::new(0),
574            pending_probe_timeouts: AtomicUsize::new(0),
575        }
576    }
577
578    fn pending_scheduled_probes(&self) -> usize {
579        self.pending_scheduled_probes.load(Relaxed)
580    }
581
582    fn pending_probe_timeouts(&self) -> usize {
583        self.pending_probe_timeouts.load(Relaxed)
584    }
585
586    fn increment_pending_scheduled_probes(&self) {
587        self.pending_scheduled_probes.fetch_add(1, Relaxed);
588    }
589
590    fn increment_pending_probe_timeouts(&self) {
591        self.pending_probe_timeouts.fetch_add(1, Relaxed);
592    }
593
594    fn decrement_pending_scheduled_probes(&self) {
595        self.pending_scheduled_probes.fetch_sub(1, Relaxed);
596    }
597
598    fn decrement_pending_probe_timeouts(&self) {
599        self.pending_probe_timeouts.fetch_sub(1, Relaxed);
600    }
601}
602
603pub(super) struct Runner {
604    registry: Arc<Mutex<RegistryState>>,
605    pending_probes: DelayQueue<usize>,
606    pending_timeouts: DelayQueue<usize>,
607    guard: RunnerGuard,
608    pending_components_notify: Arc<Notify>,
609    #[cfg(test)]
610    state: Arc<RunnerState>,
611}
612
613impl Runner {
614    fn new(
615        registry: Arc<Mutex<RegistryState>>, responses_rx: mpsc::Receiver<LivenessResponse>,
616        pending_components_notify: Arc<Notify>,
617    ) -> Self {
618        #[cfg(test)]
619        let state = Arc::new(RunnerState::new());
620
621        let guard = RunnerGuard {
622            registry: Arc::clone(&registry),
623            responses_rx: Some(responses_rx),
624        };
625
626        Self {
627            registry,
628            pending_probes: DelayQueue::new(),
629            pending_timeouts: DelayQueue::new(),
630            guard,
631            pending_components_notify,
632            #[cfg(test)]
633            state,
634        }
635    }
636
637    #[cfg(test)]
638    fn state(&self) -> Arc<RunnerState> {
639        Arc::clone(&self.state)
640    }
641
642    fn drain_pending_components(&mut self) -> Vec<usize> {
643        // Drain all pending components.
644        let mut registry = self.registry.lock().unwrap();
645        registry.pending_components.drain(..).collect()
646    }
647
648    fn send_component_probe_request(&mut self, component_id: usize) -> Option<HealthUpdate> {
649        let mut registry = self.registry.lock().unwrap();
650        let component_state = &mut registry.component_state[component_id];
651
652        // Check if our component is already dead, in which case we don't need to send a liveness probe.
653        if component_state.request_tx.is_closed() {
654            debug!(component_name = %component_state.name, "Component is dead, skipping liveness probe.");
655            return Some(HealthUpdate::Dead);
656        }
657
658        trace!(component_name = %component_state.name, probe_timeout = ?DEFAULT_PROBE_TIMEOUT_DUR, "Sending liveness probe to component.");
659
660        // Our component _isn't_ dead, so try to send a liveness probe to it.
661        //
662        // We'll register an entry in `pending_timeouts` that automatically marks the component as not live if we don't
663        // receive a response to the liveness probe within the timeout duration.
664        let timeout_key = self.pending_timeouts.insert(component_id, DEFAULT_PROBE_TIMEOUT_DUR);
665
666        #[cfg(test)]
667        self.state.increment_pending_probe_timeouts();
668
669        let request = LivenessRequest::new(component_id, timeout_key);
670        if let Err(TrySendError::Closed(request)) = component_state.request_tx.try_send(request) {
671            debug!(component_name = %component_state.name, "Component is dead, removing pending timeout.");
672
673            // We failed to send the probe to the component due to the component being dead. We'll drop our pending
674            // timeout as we're going to mark this component dead right now.
675            //
676            // When our send fails due to the channel being full, that's OK: it means it's going to be handled by an
677            // existing timeout and will be probed again later.
678            self.pending_timeouts.remove(&request.timeout_key);
679
680            #[cfg(test)]
681            self.state.decrement_pending_probe_timeouts();
682
683            return Some(HealthUpdate::Dead);
684        }
685
686        None
687    }
688
689    fn schedule_probe_for_component(&mut self, component_id: usize, duration: Duration) {
690        #[cfg(test)]
691        self.state.increment_pending_scheduled_probes();
692
693        self.pending_probes.insert(component_id, duration);
694    }
695
696    fn schedule_all_existing_components(&mut self, responses_rx: &mut mpsc::Receiver<LivenessResponse>) {
697        // First, drain any pending components to avoid scheduling them twice.
698        // This handles the case where components were registered before the runner started.
699        let _pending = self.drain_pending_components();
700
701        // Drain any queued probe responses from the previous runner. These responses were sent by
702        // components before the runner shut down but weren't processed. Processing them now updates
703        // `last_response` timestamps, which affects the staleness check below — a response that
704        // arrived just before shutdown should count as fresh.
705        while let Ok(response) = responses_rx.try_recv() {
706            self.handle_component_probe_response(response);
707        }
708
709        // Determine which components have stale probe results. Components whose last response is
710        // within the probe timeout are considered fresh and their health state is preserved,
711        // avoiding unnecessary bursts of failed liveness/readiness probes on runner restart.
712        let (component_count, stale_component_ids) = {
713            let registry = self.registry.lock().unwrap();
714            let now = Instant::now();
715            let stale_ids: Vec<usize> = (0..registry.component_state.len())
716                .filter(|&id| {
717                    let last = registry.component_state[id].last_response;
718                    saluki_antithesis::always_or_unreachable!(
719                        now >= last,
720                        "health probe last-response clock did not move backward"
721                    );
722                    now.saturating_duration_since(last) >= DEFAULT_PROBE_TIMEOUT_DUR
723                })
724                .collect();
725            (registry.component_state.len(), stale_ids)
726        };
727
728        // Only reset health to Unknown for components with stale probe results.
729        for &component_id in &stale_component_ids {
730            self.process_component_health_update(component_id, HealthUpdate::Unknown);
731        }
732
733        // Schedule immediate probes for all components regardless of staleness.
734        for component_id in 0..component_count {
735            self.schedule_probe_for_component(component_id, Duration::ZERO);
736        }
737
738        if component_count > 0 {
739            let fresh_count = component_count - stale_component_ids.len();
740            debug!(
741                component_count,
742                fresh_count,
743                stale_count = stale_component_ids.len(),
744                "Scheduled probes for all existing components."
745            );
746        }
747    }
748
749    fn handle_component_probe_response(&mut self, response: LivenessResponse) {
750        let component_id = response.request.component_id;
751        let timeout_key = response.request.timeout_key;
752        let request_sent = response.request.request_sent;
753        let response_sent = response.response_sent;
754        let response_latency = response_sent.checked_duration_since(request_sent).unwrap_or_default();
755
756        // Clear any pending timeouts for this component and schedule the next probe.
757        let timeout_was_pending = self.pending_timeouts.try_remove(&timeout_key).is_some();
758        if !timeout_was_pending {
759            let mut registry = self.registry.lock().unwrap();
760            let component_state = &mut registry.component_state[component_id];
761
762            debug!(component_name = %component_state.name, "Received probe response for component that already timed out.");
763        }
764
765        // Update the component's health to show as alive.
766        let update = HealthUpdate::Alive {
767            last_response: response_sent,
768            last_response_latency: response_latency,
769        };
770        self.process_component_health_update(component_id, update);
771
772        // Only schedule the next probe if we successfully removed the timeout, meaning it hadn't fired yet.
773        // This prevents duplicate probe scheduling when a response arrives after a timeout.
774        if timeout_was_pending {
775            #[cfg(test)]
776            self.state.decrement_pending_probe_timeouts();
777
778            self.schedule_probe_for_component(component_id, DEFAULT_PROBE_BACKOFF_DUR);
779        }
780    }
781
782    fn handle_component_timeout(&mut self, component_id: usize) {
783        // Update the component's health to show as not alive.
784        self.process_component_health_update(component_id, HealthUpdate::Unknown);
785
786        // Schedule the next probe for this component.
787        self.schedule_probe_for_component(component_id, DEFAULT_PROBE_BACKOFF_DUR);
788    }
789
790    fn process_component_health_update(&mut self, component_id: usize, update: HealthUpdate) {
791        // Update the component's health state based on the given update.
792        let mut registry = self.registry.lock().unwrap();
793        let component_state = &mut registry.component_state[component_id];
794        trace!(component_name = %component_state.name, status = update.as_str(), "Updating component health status.");
795
796        match update {
797            HealthUpdate::Alive {
798                last_response,
799                last_response_latency,
800            } => component_state.mark_live(last_response, last_response_latency),
801            HealthUpdate::Unknown => component_state.mark_not_live(),
802            HealthUpdate::Dead => component_state.mark_dead(),
803        }
804    }
805
806    async fn run<F: Future<Output = ()>>(mut self, shutdown: F) {
807        info!("Health checker running.");
808
809        // Take the response receiver out of the guard so we can use it in the select loop.
810        // It will be put back when the guard is dropped.
811        let mut responses_rx = self
812            .guard
813            .responses_rx
814            .take()
815            .expect("responses_rx should always be Some when Runner is created");
816
817        // Schedule probes for all existing components. This allows the runner to "pick up where it
818        // left off" after a restart - any components that were registered before the runner was
819        // restarted will be immediately probed.
820        self.schedule_all_existing_components(&mut responses_rx);
821
822        // Pin the shutdown future so we can poll it in the select loop.
823        pin!(shutdown);
824
825        loop {
826            select! {
827                // Shutdown signal received - exit the run loop gracefully.
828                _ = &mut shutdown => {
829                    info!("Health checker shutting down.");
830                    break;
831                },
832
833                // A component has been scheduled to have a liveness probe sent to it.
834                Some(entry) = self.pending_probes.next() => {
835                    #[cfg(test)]
836                    self.state.decrement_pending_scheduled_probes();
837
838                    let component_id = entry.into_inner();
839                    if let Some(health_update) = self.send_component_probe_request(component_id) {
840                        // If we got a health update for this component, that means we detected that it's dead, so we need
841                        // to do an out-of-band update to its health.
842                        self.process_component_health_update(component_id, health_update);
843                    }
844                },
845
846                // A component's outstanding liveness probe has expired.
847                Some(entry) = self.pending_timeouts.next() => {
848                    #[cfg(test)]
849                    self.state.decrement_pending_probe_timeouts();
850
851                    let component_id = entry.into_inner();
852                    self.handle_component_timeout(component_id);
853                },
854
855                // A probe response has been received.
856                Some(response) = responses_rx.recv() => {
857                    self.handle_component_probe_response(response);
858                },
859
860                // A component is pending finalization of their registration.
861                _ = self.pending_components_notify.notified() => {
862                    // Drain all pending components, give them a clean initial state of "unknown", and immediately schedule a probe for them.
863                    let pending_component_ids = self.drain_pending_components();
864                    for pending_component_id in pending_component_ids {
865                        self.process_component_health_update(pending_component_id, HealthUpdate::Unknown);
866                        self.schedule_probe_for_component(pending_component_id, Duration::ZERO);
867                    }
868                },
869            }
870        }
871
872        // Put the receiver back in the guard so it can be returned to the registry state when dropped.
873        self.guard.responses_rx = Some(responses_rx);
874
875        // When we exit the loop, the RunnerGuard will be dropped, returning the response receiver
876        // back to the registry state so that a subsequent spawn() can succeed.
877    }
878}
879
880#[cfg(test)]
881mod tests {
882    use std::future::Future;
883
884    use futures::FutureExt as _;
885    use saluki_metrics::test::TestRecorder;
886    use tokio::sync::oneshot;
887    use tokio_test::{
888        assert_pending, assert_ready,
889        task::{spawn, Spawn},
890    };
891
892    use super::*;
893
894    const COMPONENT_ID: &str = "test_component";
895
896    #[track_caller]
897    fn initialize_registry_with_component(
898        component_id: &str,
899    ) -> (
900        Health,
901        Spawn<impl Future<Output = ()>>,
902        Arc<Mutex<RegistryState>>,
903        Arc<RunnerState>,
904    ) {
905        let registry = HealthRegistry::new();
906        let registry_state = registry.state();
907
908        // Add our component to the registry:
909        let handle = registry
910            .register_component(&SubsystemIdentifier::from_dotted(component_id))
911            .unwrap();
912
913        // Extract the registry runner task and poll it until it's quiesced.
914        //
915        // This ensures that the component is registered, and that it schedules/sends an initial probe request to the component:
916        let runner = registry.into_runner().expect("should not fail to create runner");
917        let runner_state = runner.state();
918
919        // Create a shutdown future that never resolves (for tests that don't need shutdown).
920        let shutdown = std::future::pending();
921        let registry_task = spawn(runner.run(shutdown));
922
923        (handle, registry_task, registry_state, runner_state)
924    }
925
926    #[track_caller]
927    fn drive_until_quiesced<F: Future<Output = ()>>(task: &mut Spawn<F>) {
928        assert_pending!(task.poll());
929        while task.is_woken() {
930            assert_pending!(task.poll());
931        }
932    }
933
934    fn component_live(state: &Mutex<RegistryState>, component_id: &str) -> bool {
935        let state = state.lock().unwrap();
936        let target = SubsystemIdentifier::from_dotted(component_id);
937        state
938            .component_state
939            .iter()
940            .find(|state| state.name == target)
941            .map(|state| state.is_live())
942            .unwrap()
943    }
944
945    #[test]
946    fn basic_registration() {
947        let registry = HealthRegistry::new();
948        assert!(registry
949            .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
950            .is_some());
951    }
952
953    #[test]
954    fn duplicate_component_registration_fails() {
955        let registry = HealthRegistry::new();
956
957        // Registering the same component twice should fail:
958        assert!(registry
959            .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
960            .is_some());
961        assert!(registry
962            .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
963            .is_none());
964    }
965
966    #[test]
967    fn duplicate_runner_creation_fails_while_running() {
968        let registry = HealthRegistry::new();
969        let registry2 = registry.clone();
970
971        // First runner creation should succeed. We hold on to it so the RunnerGuard doesn't
972        // return the receiver back to the registry state.
973        let _runner = registry.into_runner().expect("first runner creation should succeed");
974
975        // Second creation should fail while the first runner still holds the receiver.
976        assert!(registry2.into_runner().is_err());
977    }
978
979    #[tokio::test]
980    async fn registry_can_be_respawned_after_shutdown() {
981        let registry = HealthRegistry::new();
982        let registry2 = registry.clone();
983        let registry3 = registry.clone();
984
985        // First runner creation should succeed.
986        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
987        let runner = registry.into_runner().expect("first runner creation should succeed");
988
989        // Run the runner on a spawned task so we can trigger shutdown.
990        let join_handle = tokio::spawn(runner.run(shutdown_rx.map(|_| ())));
991
992        // Trigger shutdown.
993        let _ = shutdown_tx.send(());
994
995        // Wait for the runner to stop.
996        join_handle.await.expect("runner should complete without panic");
997
998        // Now we should be able to create a runner again (the RunnerGuard returned the receiver).
999        let _runner2 = registry2
1000            .into_runner()
1001            .expect("should be able to create runner after shutdown");
1002
1003        // But not a third time while the second runner holds the receiver.
1004        assert!(
1005            registry3.into_runner().is_err(),
1006            "should not be able to create runner while one exists"
1007        );
1008    }
1009
1010    #[test]
1011    fn readiness() {
1012        let registry = HealthRegistry::new();
1013
1014        // An empty registry is always ready, so `all_ready` resolves immediately:
1015        let mut all_ready_fut = spawn(registry.all_ready());
1016        assert_ready!(all_ready_fut.poll());
1017
1018        // Components start out as not ready, so adding this component changes the registry to not ready overall:
1019        let mut handle = registry
1020            .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
1021            .unwrap();
1022
1023        let mut all_ready_fut = spawn(registry.all_ready());
1024        assert_pending!(all_ready_fut.poll());
1025
1026        // Now mark the component as ready. `all_ready` should resolve on the next poll:
1027        handle.mark_ready();
1028
1029        assert!(all_ready_fut.is_woken());
1030        assert_ready!(all_ready_fut.poll());
1031
1032        // Ensure a fresh `all_ready` call immediately observes all components being ready:
1033        let mut all_ready_fut = spawn(registry.all_ready());
1034        assert_ready!(all_ready_fut.poll());
1035
1036        // Finally, make sure that the readiness state isn't latched, as `all_ready` should always reflect the current state:
1037        handle.mark_not_ready();
1038
1039        let mut all_ready_fut = spawn(registry.all_ready());
1040        assert_pending!(all_ready_fut.poll());
1041    }
1042
1043    #[test]
1044    fn readiness_telemetry_tracks_component_ready_gauge() {
1045        // Verifies the documented `health_component_ready` telemetry: a `component_id`-tagged gauge set
1046        // to 1 when the component is ready and 0 when it is not.
1047        let recorder = TestRecorder::default();
1048        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
1049
1050        // Register the component only after installing the recorder so its telemetry binds to it.
1051        let registry = HealthRegistry::new();
1052        let mut handle = registry
1053            .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
1054            .unwrap();
1055
1056        let ready_gauge = || recorder.gauge((Telemetry::component_ready_name(), &[("component_id", COMPONENT_ID)]));
1057
1058        // Components start out not ready.
1059        assert_eq!(ready_gauge(), Some(0.0));
1060
1061        handle.mark_ready();
1062        assert_eq!(ready_gauge(), Some(1.0));
1063
1064        handle.mark_not_ready();
1065        assert_eq!(ready_gauge(), Some(0.0));
1066    }
1067
1068    #[tokio::test(start_paused = true)]
1069    async fn liveness_telemetry_records_live_gauge_and_latency_histogram() {
1070        // Verifies the documented `health_component_live` gauge (1 = alive, 0 = unknown, -1 = dead) and
1071        // `health_component_liveness_latency_seconds` histogram, both tagged with `component_id`.
1072        let recorder = TestRecorder::default();
1073        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
1074
1075        // Register and start the runner after installing the recorder so the telemetry binds to it.
1076        let registry = HealthRegistry::new();
1077        let registry_state = registry.state();
1078        let mut handle = registry
1079            .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
1080            .unwrap();
1081        let runner = registry.into_runner().expect("should not fail to create runner");
1082        let mut registry_task = spawn(runner.run(std::future::pending::<()>()));
1083
1084        let live_gauge = || recorder.gauge((Telemetry::component_live_name(), &[("component_id", COMPONENT_ID)]));
1085        let latency_samples = || {
1086            recorder.histogram((
1087                Telemetry::component_liveness_latency_seconds_name(),
1088                &[("component_id", COMPONENT_ID)],
1089            ))
1090        };
1091
1092        // Drive the runner so it registers the component and sends the initial liveness probe.
1093        let mut live_future = spawn(handle.live());
1094        assert_pending!(live_future.poll());
1095        drive_until_quiesced(&mut registry_task);
1096
1097        // No probe response has been handled yet: the component isn't live and no latency was recorded.
1098        assert!(!component_live(&registry_state, COMPONENT_ID));
1099        assert_eq!(live_gauge(), Some(0.0));
1100        assert_eq!(latency_samples(), Some(Vec::new()));
1101
1102        // Respond to the probe; the runner then observes the response and marks the component live.
1103        assert!(live_future.is_woken());
1104        assert_ready!(live_future.poll());
1105        assert!(registry_task.is_woken());
1106        drive_until_quiesced(&mut registry_task);
1107
1108        assert!(component_live(&registry_state, COMPONENT_ID));
1109        assert_eq!(live_gauge(), Some(1.0));
1110
1111        // Exactly one probe response was handled, so exactly one latency sample was recorded.
1112        let samples = latency_samples().expect("liveness latency histogram should be registered");
1113        assert_eq!(
1114            samples.len(),
1115            1,
1116            "handling one probe response must record exactly one liveness latency sample"
1117        );
1118        assert!(samples[0] >= 0.0, "recorded liveness latency must be non-negative");
1119    }
1120
1121    #[tokio::test(start_paused = true)]
1122    async fn component_responds_before_timeout() {
1123        // Create our registry with a registered component:
1124        let (mut handle, mut registry, registry_state, runner_state) = initialize_registry_with_component(COMPONENT_ID);
1125
1126        // Manually create our `live` call and ensure that it's not ready yet, as the registry task has not yet been driven,
1127        // which means the component hasn't been registered yet and no probe request has been sent:
1128        let mut live_future = spawn(handle.live());
1129        assert_pending!(live_future.poll());
1130        assert_eq!(runner_state.pending_probe_timeouts(), 0);
1131        assert_eq!(runner_state.pending_scheduled_probes(), 0);
1132
1133        // Drive our registry task until it us quiesced to ensure the component is registered and that a probe request is sent:
1134        drive_until_quiesced(&mut registry);
1135        assert_eq!(runner_state.pending_probe_timeouts(), 1);
1136        assert_eq!(runner_state.pending_scheduled_probes(), 0);
1137
1138        // Ensure our component is not live since, despite being registered, we haven't received a probe response for it yet:
1139        assert!(!component_live(&registry_state, COMPONENT_ID));
1140
1141        // After polling the registry task, we should have sent a probe request which will have now woken up our `live` future.
1142        //
1143        // Poll the future which should then respond to the probe request:
1144        assert!(live_future.is_woken());
1145        assert_ready!(live_future.poll());
1146
1147        // The registry task should have been woken by the probe response.
1148        //
1149        // Drive the registry task until it is quiesced and ensure that the component is now live:
1150        assert!(registry.is_woken());
1151        drive_until_quiesced(&mut registry);
1152
1153        assert!(component_live(&registry_state, COMPONENT_ID));
1154
1155        // Since the probe response was received, we should have a pending schedule probe now since this is a "normal" probe now,
1156        // and isn't the initial probe request which is scheduled immediately:
1157        assert_eq!(runner_state.pending_probe_timeouts(), 0);
1158        assert_eq!(runner_state.pending_scheduled_probes(), 1);
1159    }
1160
1161    #[tokio::test(start_paused = true)]
1162    async fn component_responds_after_timeout() {
1163        // Create our registry with a registered component:
1164        let (mut handle, mut registry, registry_state, runner_state) = initialize_registry_with_component(COMPONENT_ID);
1165
1166        // Manually create our `live` call and ensure that it's not ready yet, as the registry task has not yet been driven,
1167        // which means the component hasn't been registered yet and no probe request has been sent:
1168        let mut live_future = spawn(handle.live());
1169        assert_pending!(live_future.poll());
1170        assert_eq!(runner_state.pending_probe_timeouts(), 0);
1171        assert_eq!(runner_state.pending_scheduled_probes(), 0);
1172
1173        // Drive our registry task until it us quiesced to ensure the component is registered and that a probe request is sent:
1174        drive_until_quiesced(&mut registry);
1175        assert_eq!(runner_state.pending_probe_timeouts(), 1);
1176        assert_eq!(runner_state.pending_scheduled_probes(), 0);
1177
1178        // Ensure our component is not live since, despite being registered, we haven't received a probe response for it yet:
1179        assert!(!component_live(&registry_state, COMPONENT_ID));
1180
1181        // After polling the registry task, we should have sent a probe request which will have now woken up
1182        // our `live` future, but we won't yet poll it. In fact, we'll advance time _past_ the probe timeout to simulate
1183        // the probe timeout expiring:
1184        assert!(live_future.is_woken());
1185        assert!(!registry.is_woken());
1186
1187        tokio::time::advance(DEFAULT_PROBE_TIMEOUT_DUR + Duration::from_secs(1)).await;
1188
1189        // The registry task should have been woken by the probe timeout expiring.
1190        //
1191        // Drive the registry task until it is quiesced and ensure that the component is still not live:
1192        assert!(registry.is_woken());
1193        drive_until_quiesced(&mut registry);
1194
1195        assert!(!component_live(&registry_state, COMPONENT_ID));
1196
1197        // Since the probe response was not received, we should have a pending schedule probe now since this is a "normal" probe now,
1198        // and isn't the initial probe request which is scheduled immediately:
1199        assert_eq!(runner_state.pending_probe_timeouts(), 0);
1200        assert_eq!(runner_state.pending_scheduled_probes(), 1);
1201
1202        // Now, we'll actually drive the `live` future to respond to the probe request, which should mark the component as live:
1203        assert_ready!(live_future.poll());
1204
1205        assert!(registry.is_woken());
1206        drive_until_quiesced(&mut registry);
1207
1208        assert!(component_live(&registry_state, COMPONENT_ID));
1209
1210        // However, since the first probe response timed out, and we haven't yet fired off our scheduled probe, receiving this late
1211        // response should not trigger the scheduling of another probe:
1212        assert_eq!(runner_state.pending_probe_timeouts(), 0);
1213        assert_eq!(runner_state.pending_scheduled_probes(), 1);
1214    }
1215
1216    #[track_caller]
1217    #[allow(clippy::type_complexity)]
1218    fn initialize_registry_with_component_and_shutdown(
1219        component_id: &str,
1220    ) -> (
1221        Health,
1222        Spawn<impl Future<Output = ()>>,
1223        Arc<Mutex<RegistryState>>,
1224        Arc<RunnerState>,
1225        oneshot::Sender<()>,
1226    ) {
1227        let registry = HealthRegistry::new();
1228        let registry_state = registry.state();
1229        let handle = registry
1230            .register_component(&SubsystemIdentifier::from_dotted(component_id))
1231            .unwrap();
1232        let runner = registry.into_runner().expect("should not fail to create runner");
1233        let runner_state = runner.state();
1234
1235        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
1236        let registry_task = spawn(runner.run(shutdown_rx.map(|_| ())));
1237
1238        (handle, registry_task, registry_state, runner_state, shutdown_tx)
1239    }
1240
1241    #[tokio::test(start_paused = true)]
1242    async fn respawn_preserves_fresh_component_health() {
1243        // Create our registry with a registered component and drive the runner until the initial probe is sent:
1244        let (mut handle, mut registry, registry_state, _runner_state, shutdown_tx) =
1245            initialize_registry_with_component_and_shutdown(COMPONENT_ID);
1246        drive_until_quiesced(&mut registry);
1247
1248        // Respond to the probe request so the component becomes live:
1249        let mut live_future = spawn(handle.live());
1250        assert_ready!(live_future.poll());
1251        drive_until_quiesced(&mut registry);
1252        assert!(component_live(&registry_state, COMPONENT_ID));
1253
1254        // Shut down the runner gracefully, which returns the response receiver to the registry state:
1255        let _ = shutdown_tx.send(());
1256        assert_ready!(registry.poll());
1257
1258        // Respawn the runner immediately (no time advance), so the probe result is still fresh:
1259        let registry = HealthRegistry {
1260            inner: Arc::clone(&registry_state),
1261        };
1262        let runner = registry
1263            .into_runner()
1264            .expect("should be able to respawn after shutdown");
1265        let _runner_state = runner.state();
1266        let mut registry = spawn(runner.run(std::future::pending()));
1267        drive_until_quiesced(&mut registry);
1268
1269        // The component's health should be preserved as Live since its last response is fresh:
1270        assert!(component_live(&registry_state, COMPONENT_ID));
1271    }
1272
1273    #[tokio::test(start_paused = true)]
1274    async fn respawn_resets_stale_component_health() {
1275        // Create our registry with a registered component and drive the runner until the initial probe is sent:
1276        let (mut handle, mut registry, registry_state, _runner_state, shutdown_tx) =
1277            initialize_registry_with_component_and_shutdown(COMPONENT_ID);
1278        drive_until_quiesced(&mut registry);
1279
1280        // Respond to the probe request so the component becomes live:
1281        let mut live_future = spawn(handle.live());
1282        assert_ready!(live_future.poll());
1283        drive_until_quiesced(&mut registry);
1284        assert!(component_live(&registry_state, COMPONENT_ID));
1285
1286        // Shut down the runner gracefully, which returns the response receiver to the registry state:
1287        let _ = shutdown_tx.send(());
1288        assert_ready!(registry.poll());
1289
1290        // Advance time past the probe timeout so the last response becomes stale:
1291        tokio::time::advance(DEFAULT_PROBE_TIMEOUT_DUR + Duration::from_secs(1)).await;
1292
1293        // Respawn the runner. The stale component should be reset to Unknown:
1294        let registry = HealthRegistry {
1295            inner: Arc::clone(&registry_state),
1296        };
1297        let runner = registry
1298            .into_runner()
1299            .expect("should be able to respawn after shutdown");
1300        let _runner_state = runner.state();
1301        let mut registry = spawn(runner.run(std::future::pending()));
1302        drive_until_quiesced(&mut registry);
1303
1304        // The component's health should have been reset to Unknown since its last response is stale:
1305        assert!(!component_live(&registry_state, COMPONENT_ID));
1306    }
1307
1308    fn component_dead(state: &Mutex<RegistryState>, component_id: &str) -> bool {
1309        let state = state.lock().unwrap();
1310        let target = SubsystemIdentifier::from_dotted(component_id);
1311        state
1312            .component_state
1313            .iter()
1314            .find(|state| state.name == target)
1315            .map(|state| state.health == HealthState::Dead)
1316            .unwrap()
1317    }
1318
1319    #[tokio::test(start_paused = true)]
1320    async fn live_never_resolves_after_responder_is_taken() {
1321        let (mut handle, mut registry, _registry_state, _runner_state) =
1322            initialize_registry_with_component(COMPONENT_ID);
1323        let _responder = handle.take_liveness_responder().expect("responder should be present");
1324        assert!(handle.take_liveness_responder().is_none());
1325
1326        // Send a probe. The handle no longer owns the probe channel, so `live` must not answer it.
1327        drive_until_quiesced(&mut registry);
1328
1329        let mut live_future = spawn(handle.live());
1330        assert_pending!(live_future.poll());
1331    }
1332
1333    #[tokio::test(start_paused = true)]
1334    async fn responder_answers_probes_while_driven_future_waits() {
1335        let (mut handle, mut registry, registry_state, _runner_state) =
1336            initialize_registry_with_component(COMPONENT_ID);
1337        let responder = handle.take_liveness_responder().expect("responder should be present");
1338
1339        // The driven future waits on a channel that nothing sends to yet. This models a component that waits for room
1340        // in a full downstream channel.
1341        let (unblock_tx, unblock_rx) = oneshot::channel::<u32>();
1342        let mut driven = spawn(responder.drive(async move { unblock_rx.await.unwrap() }));
1343        assert_pending!(driven.poll());
1344
1345        // Send a probe. The responder must answer it, even though the driven future is still waiting.
1346        drive_until_quiesced(&mut registry);
1347        assert!(!component_live(&registry_state, COMPONENT_ID));
1348
1349        assert!(driven.is_woken());
1350        assert_pending!(driven.poll());
1351
1352        assert!(registry.is_woken());
1353        drive_until_quiesced(&mut registry);
1354        assert!(component_live(&registry_state, COMPONENT_ID));
1355
1356        // Once the driven future completes, `drive` returns its output.
1357        unblock_tx.send(42).unwrap();
1358        assert!(driven.is_woken());
1359        assert_eq!(assert_ready!(driven.poll()), 42);
1360    }
1361
1362    #[tokio::test(start_paused = true)]
1363    async fn component_is_dead_after_driven_future_completes() {
1364        let (mut handle, mut registry, registry_state, _runner_state) =
1365            initialize_registry_with_component(COMPONENT_ID);
1366        let responder = handle.take_liveness_responder().expect("responder should be present");
1367
1368        // The driven future completes at once, which drops the responder and closes the probe channel.
1369        let mut driven = spawn(responder.drive(async {}));
1370        assert_ready!(driven.poll());
1371
1372        // The handle is still alive, but nothing answers probes any more, so the registry marks the component as dead.
1373        drive_until_quiesced(&mut registry);
1374        assert!(component_dead(&registry_state, COMPONENT_ID));
1375        drop(handle);
1376    }
1377}