Skip to main content

agentmux_srv/server/
messaging_health.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Health of the messaging path, for `/health` and `app.health`.
5//!
6//! On 2026-11-15 narko's message handler stopped answering for two hours while `/health` kept saying `ok`, because it only said
7//! that the process answered. Now the report also says whether the handler's lock can be taken (every message, spawn and Kanban
8//! load needs it), how many times a panic left it poisoned and it was recovered, and whether srv is panicking in bulk
9//! (`backend::panic_watch`). Either problem makes the status `degraded`.
10//!
11//! The HTTP status stays 200: `agentmux`'s own `health_ok` (agentmux_cli/process.rs) reads anything else as "no server here" and
12//! could start a second one beside a working srv. The word is in the body.
13
14use std::time::Duration;
15
16use serde_json::{json, Value};
17
18use crate::backend::panic_watch::{self, SrvPanicsEvent};
19use crate::backend::reactive::ReactiveHandler;
20
21/// How long the lock may stay taken before the path counts as stuck. A delivery holds it for milliseconds.
22const LOCK_WAIT: Duration = Duration::from_millis(500);
23const LOCK_POLL: Duration = Duration::from_millis(10);
24
25/// What the messaging path looks like just now.
26pub(crate) struct MessagingHealth {
27    lock_free: bool,
28    recovered_lock: u64,
29    panics: SrvPanicsEvent,
30}
31
32impl MessagingHealth {
33    pub(crate) fn new(lock_free: bool, recovered_lock: u64, panics: SrvPanicsEvent) -> Self {
34        Self { lock_free, recovered_lock, panics }
35    }
36
37    /// Looks now. The wait for the lock is bounded and does not block the executor.
38    pub(crate) async fn probe(handler: &ReactiveHandler) -> Self {
39        let lock_free = lock_taken_within(|| handler.lock_is_free(), LOCK_WAIT, LOCK_POLL).await;
40        Self::new(lock_free, handler.recovered_lock_count(), panic_watch::snapshot())
41    }
42
43    /// `ok`, or `degraded`: the lock stayed taken, or srv is panicking above the warning level.
44    pub(crate) fn status(&self) -> &'static str {
45        if self.lock_free && self.panics.level == "normal" {
46            "ok"
47        } else {
48            "degraded"
49        }
50    }
51
52    pub(crate) fn to_json(&self) -> Value {
53        json!({
54            "status": self.status(),
55            "handler_lock": if self.lock_free { "free" } else { "busy" },
56            "recovered_lock": self.recovered_lock,
57            "panics": {
58                "level": self.panics.level,
59                "last_minute": self.panics.last_minute,
60                "total": self.panics.total,
61                "top": self.panics.top.iter().map(|p| json!({ "location": p.location, "count": p.count })).collect::<Vec<_>>(),
62            },
63        })
64    }
65}
66
67/// Whether `free` answers true within `wait`, asking every `poll`.
68async fn lock_taken_within(free: impl Fn() -> bool, wait: Duration, poll: Duration) -> bool {
69    let mut waited = Duration::ZERO;
70    loop {
71        if free() {
72            return true;
73        }
74        if waited >= wait {
75            return false;
76        }
77        tokio::time::sleep(poll).await;
78        waited += poll;
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use std::sync::atomic::{AtomicU32, Ordering};
86
87    fn panics(level: &str, last_minute: u32) -> SrvPanicsEvent {
88        SrvPanicsEvent {
89            kind: "panics".into(),
90            level: level.into(),
91            since_ms: None,
92            last_minute,
93            total: 7,
94            recovered_lock: 0,
95            top: vec![panic_watch::PanicPlace { location: "backend/x.rs:1".into(), count: 7 }],
96        }
97    }
98
99    #[test]
100    fn a_free_lock_and_a_quiet_srv_are_ok() {
101        let h = MessagingHealth::new(true, 0, panics("normal", 0));
102        assert_eq!(h.status(), "ok");
103        let json = h.to_json();
104        assert_eq!((json["status"].as_str(), json["handler_lock"].as_str(), json["recovered_lock"].as_u64()), (Some("ok"), Some("free"), Some(0)));
105        assert_eq!(json["panics"]["top"][0]["location"], "backend/x.rs:1");
106    }
107
108    #[test]
109    fn a_stuck_lock_is_degraded() {
110        let h = MessagingHealth::new(false, 0, panics("normal", 0));
111        assert_eq!(h.status(), "degraded");
112        assert_eq!(h.to_json()["handler_lock"], "busy");
113    }
114
115    #[test]
116    fn a_panic_storm_is_degraded_even_with_the_lock_free() {
117        for level in ["warn", "critical"] {
118            assert_eq!(MessagingHealth::new(true, 0, panics(level, 500)).status(), "degraded", "{level}");
119        }
120    }
121
122    #[test]
123    fn a_recovered_poisoning_alone_is_reported_but_is_not_degraded() {
124        let h = MessagingHealth::new(true, 3, panics("normal", 1));
125        assert_eq!(h.status(), "ok", "messaging works again: the count is history");
126        assert_eq!(h.to_json()["recovered_lock"], 3);
127    }
128
129    #[tokio::test]
130    async fn the_wait_ends_when_the_lock_frees_and_gives_up_when_it_does_not() {
131        let asked = AtomicU32::new(0);
132        let frees_on_third = || asked.fetch_add(1, Ordering::SeqCst) >= 2;
133        assert!(lock_taken_within(frees_on_third, Duration::from_millis(200), Duration::from_millis(1)).await);
134        assert_eq!(asked.load(Ordering::SeqCst), 3);
135        let started = std::time::Instant::now();
136        assert!(!lock_taken_within(|| false, Duration::from_millis(30), Duration::from_millis(5)).await, "a lock held for good is not free");
137        assert!(started.elapsed() < Duration::from_secs(2), "and the wait is bounded");
138    }
139
140    #[tokio::test]
141    async fn the_probe_sees_a_held_handler_lock_and_a_free_one() {
142        let handler = ReactiveHandler::new();
143        assert_eq!(MessagingHealth::probe(&handler).await.to_json()["handler_lock"], "free");
144        // Held on a thread of its own, so the probe's wait runs out against a real held lock.
145        let (held_tx, held_rx) = std::sync::mpsc::channel::<()>();
146        let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
147        let handler: &'static ReactiveHandler = Box::leak(Box::new(handler));
148        let holder = std::thread::spawn(move || {
149            let _guard = handler.hold_lock_for_test();
150            held_tx.send(()).unwrap();
151            let _ = done_rx.recv();
152        });
153        held_rx.recv().unwrap();
154        let busy = MessagingHealth::probe(handler).await;
155        assert_eq!((busy.to_json()["handler_lock"].as_str(), busy.status()), (Some("busy"), "degraded"));
156        done_tx.send(()).unwrap();
157        holder.join().unwrap();
158        assert_eq!(MessagingHealth::probe(handler).await.status(), "ok", "free again");
159    }
160}