Skip to main content

agentmux_srv_core/backend/
panic_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! srv's own panics, counted and made visible.
5//!
6//! On 2026-11-15 narko's srv panicked about 30,000 times in two hours. The panics went to the log and nowhere else, `/health`
7//! kept answering, and nobody knew until an agent's send failed (docs/incident/RCA_BUILD_SLOT_IDLE_NOTE_POISONS_MESSAGE_HANDLER_2026_11_15.md).
8//!
9//! - [`install_hook`] chains a panic hook that counts every panic by where it happened. The log stays as it is: the earlier hook
10//!   runs first, and the hook itself only counts.
11//! - [`start_reporter`] looks at the count every few seconds. Above [`WARN_ABOVE`] panics in the last minute it publishes the
12//!   `srv-panics` event (the status bar's backend dot and notices follow it) and, once an hour, holds an `[AgentMux]` note for
13//!   every agent. The event is persisted, so a window that opens mid-storm gets the current state.
14//! - [`snapshot`] is what `/health` and `app.health` report.
15//!
16//! The decisions are pure ([`Counts`]), so they are tested without a clock or a panic.
17
18use std::collections::HashMap;
19use std::panic::PanicHookInfo;
20use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
21use std::time::Duration;
22
23/// More panics than this in the last minute is a warning.
24pub const WARN_ABOVE: u32 = 20;
25/// More than this is critical.
26pub const CRITICAL_ABOVE: u32 = 200;
27/// The key of the held note: a later note replaces an earlier one that its agent has not read yet.
28pub const NOTE_KEY: &str = "srv-panics";
29
30const WINDOW_SECS: u64 = 60;
31/// Distinct places remembered; more are counted together as [`OTHER`].
32const MAX_PLACES: usize = 64;
33const OTHER: &str = "(other places)";
34/// The same note to the agents at most this often.
35const NOTE_EVERY_MS: u64 = 60 * 60 * 1000;
36const LOOK_EVERY: Duration = Duration::from_secs(5);
37const TOP_PLACES: usize = 3;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
40pub enum Level {
41    Normal,
42    Warn,
43    Critical,
44}
45
46impl Level {
47    pub fn as_str(self) -> &'static str {
48        match self {
49            Level::Normal => "normal",
50            Level::Warn => "warn",
51            Level::Critical => "critical",
52        }
53    }
54
55    /// The level for this many panics in the last minute.
56    pub fn for_count(last_minute: u32) -> Level {
57        if last_minute > CRITICAL_ABOVE {
58            Level::Critical
59        } else if last_minute > WARN_ABOVE {
60            Level::Warn
61        } else {
62            Level::Normal
63        }
64    }
65}
66
67/// One place that panicked, and how often.
68#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
69#[ts(export, export_to = "../../../frontend/types/rpc/")]
70pub struct PanicPlace {
71    /// `backend/reactive/handler.rs:1416`: the source file below `src/`, and the line.
72    pub location: String,
73    #[ts(type = "number")]
74    pub count: u64,
75}
76
77/// The `srv-panics` event's payload (`mps_events::SrvPanics`), shaped like the host's `health-signal` payloads so the status
78/// bar's store takes it unchanged: `kind` is `panics`, and a `normal` level clears the signal.
79#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
80#[ts(export, export_to = "../../../frontend/types/rpc/")]
81pub struct SrvPanicsEvent {
82    /// Always `panics`.
83    #[ts(type = "\"panics\"")]
84    pub kind: String,
85    /// `normal`, `warn` or `critical`.
86    #[ts(type = "\"normal\" | \"warn\" | \"critical\"")]
87    pub level: String,
88    /// When this episode began (ms since the epoch); absent while normal.
89    #[ts(type = "number | null")]
90    pub since_ms: Option<u64>,
91    /// Panics in the last minute.
92    pub last_minute: u32,
93    /// Panics since srv started.
94    #[ts(type = "number")]
95    pub total: u64,
96    /// Times the message handler's lock was found poisoned and recovered since srv started.
97    #[ts(type = "number")]
98    pub recovered_lock: u64,
99    /// The places that panicked most, biggest first.
100    pub top: Vec<PanicPlace>,
101}
102
103#[derive(Debug, Clone, Copy, Default)]
104struct Bucket {
105    second: u64,
106    count: u32,
107}
108
109/// What the watch knows: a per-second ring for the last minute, a total, and a count per place.
110#[derive(Debug)]
111pub struct Counts {
112    total: u64,
113    ring: [Bucket; WINDOW_SECS as usize],
114    places: HashMap<String, u64>,
115    level: Level,
116    since_ms: Option<u64>,
117    noted_at_ms: Option<u64>,
118}
119
120/// What a look found: the event to publish, and the note to hold for the agents.
121#[derive(Debug, Default, PartialEq, Eq)]
122pub struct Step {
123    pub publish: Option<SrvPanicsEvent>,
124    pub note: Option<String>,
125}
126
127impl Default for Counts {
128    fn default() -> Self {
129        Counts { total: 0, ring: [Bucket::default(); WINDOW_SECS as usize], places: HashMap::new(), level: Level::Normal, since_ms: None, noted_at_ms: None }
130    }
131}
132
133impl Counts {
134    /// One panic at `location`, at `now_ms`.
135    pub fn record(&mut self, location: &str, now_ms: u64) {
136        self.total = self.total.saturating_add(1);
137        let second = now_ms / 1000;
138        let bucket = &mut self.ring[(second % WINDOW_SECS) as usize];
139        if bucket.second != second {
140            *bucket = Bucket { second, count: 0 };
141        }
142        bucket.count = bucket.count.saturating_add(1);
143        let key = if self.places.contains_key(location) || self.places.len() < MAX_PLACES { location } else { OTHER };
144        *self.places.entry(key.to_string()).or_insert(0) += 1;
145    }
146
147    /// Panics in the last [`WINDOW_SECS`] seconds.
148    pub fn last_minute(&self, now_ms: u64) -> u32 {
149        let now = now_ms / 1000;
150        self.ring.iter().filter(|b| b.count > 0 && b.second <= now && now - b.second < WINDOW_SECS).fold(0u32, |sum, b| sum.saturating_add(b.count))
151    }
152
153    fn top(&self) -> Vec<PanicPlace> {
154        let mut places: Vec<PanicPlace> = self.places.iter().map(|(location, count)| PanicPlace { location: location.clone(), count: *count }).collect();
155        places.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.location.cmp(&b.location)));
156        places.truncate(TOP_PLACES);
157        places
158    }
159
160    /// The state now, as the event and the health report carry it.
161    pub fn snapshot(&self, now_ms: u64, recovered_lock: u64) -> SrvPanicsEvent {
162        let last_minute = self.last_minute(now_ms);
163        let level = Level::for_count(last_minute);
164        SrvPanicsEvent {
165            kind: "panics".to_string(),
166            level: level.as_str().to_string(),
167            since_ms: if level == Level::Normal { None } else { Some(self.since_ms.unwrap_or(now_ms)) },
168            last_minute,
169            total: self.total,
170            recovered_lock,
171            top: self.top(),
172        }
173    }
174
175    /// One look. The level follows the last minute, so a storm that ends clears itself one quiet minute later. An active level is
176    /// published on every look (its counts move); a change to normal is published once. The note goes out when the level leaves
177    /// normal, and then at most once an hour.
178    pub fn look(&mut self, now_ms: u64, recovered_lock: u64) -> Step {
179        let was = self.level;
180        let last_minute = self.last_minute(now_ms);
181        let level = Level::for_count(last_minute);
182        if level != Level::Normal && self.since_ms.is_none() {
183            self.since_ms = Some(now_ms);
184        }
185        if level == Level::Normal {
186            self.since_ms = None;
187        }
188        self.level = level;
189        let event = self.snapshot(now_ms, recovered_lock);
190        let mut step = Step::default();
191        if level != Level::Normal || was != Level::Normal {
192            step.publish = Some(event.clone());
193        }
194        let rising = was == Level::Normal && level != Level::Normal;
195        if rising && self.noted_at_ms.is_none_or(|at| now_ms.saturating_sub(at) >= NOTE_EVERY_MS) {
196            self.noted_at_ms = Some(now_ms);
197            step.note = Some(note_text(&event));
198        }
199        step
200    }
201}
202
203/// What the agents are told.
204pub fn note_text(event: &SrvPanicsEvent) -> String {
205    let place = event.top.first().map(|p| format!(" (most often at {})", p.location)).unwrap_or_default();
206    format!(
207        "[AgentMux] srv is panicking: {} times in the last minute, {} since it started{place}. \
208         Messages between agents, spawns or the Kanban may fail until AgentMux is restarted; restarting AgentMux (not the computer) clears a stuck messaging path. \
209         Tell your leader.",
210        event.last_minute, event.total
211    )
212}
213
214/// `crates\srv\src\backend\reactive\handler.rs` and line 1416 as `backend/reactive/handler.rs:1416`: below the last `src/`, with
215/// forward slashes, so a build path never leaves the machine.
216pub fn short_location(file: &str, line: u32) -> String {
217    let file = file.replace('\\', "/");
218    let tail = file.rsplit_once("/src/").map(|(_, tail)| tail).unwrap_or_else(|| file.rsplit('/').next().unwrap_or(&file));
219    format!("{tail}:{line}")
220}
221
222static WATCH: OnceLock<Mutex<Counts>> = OnceLock::new();
223
224fn watch() -> MutexGuard<'static, Counts> {
225    // Counts never panics while it holds this lock, so the lock is never poisoned; if it were, the numbers are still numbers.
226    WATCH.get_or_init(|| Mutex::new(Counts::default())).lock().unwrap_or_else(|e| e.into_inner())
227}
228
229/// What this srv's panics add up to now, with the handler lock's recoveries.
230pub fn snapshot() -> SrvPanicsEvent {
231    let recovered = crate::backend::reactive::get_global_handler().recovered_lock_count();
232    watch().snapshot(agentmux_common::time::now_ms_u64(), recovered)
233}
234
235/// Counts every panic from now on. The earlier hook (the default one, which writes the message) runs first and unchanged.
236pub fn install_hook() {
237    let previous = std::panic::take_hook();
238    std::panic::set_hook(Box::new(move |info| {
239        previous(info);
240        record(info);
241    }));
242}
243
244fn record(info: &PanicHookInfo<'_>) {
245    let place = info.location().map(|l| short_location(l.file(), l.line())).unwrap_or_else(|| "(unknown place)".to_string());
246    watch().record(&place, agentmux_common::time::now_ms_u64());
247}
248
249/// Holds `text` for every agent that is registered: it waits for each agent's next turn and starts none. Takes the handler's lock,
250/// which can be stuck: never call it from the reporter's own thread (see [`hand_to_agents`]).
251fn hold_for_agents(handler: &crate::backend::reactive::ReactiveHandler, text: &str) {
252    for agent in handler.list_agents() {
253        if let Err(e) = handler.hold_system_note(&agent.agent_id, NOTE_KEY, text) {
254            tracing::debug!(agent = %agent.agent_id, error = %e, "srv panics: an agent was not told");
255        }
256    }
257}
258
259/// Runs `deliver` on a thread of its own and returns at once. Delivering the note needs the handler's lock, and a stuck lock is one of
260/// the things this watch exists to report: on the reporter's thread the wait would stop every later look (the worse levels and the
261/// clearing event). A note is sent at most once an hour, so a thread left waiting is at most one an hour.
262fn hand_to_agents(text: String, deliver: impl FnOnce(&str) + Send + 'static) {
263    let spawned = std::thread::Builder::new().name("srv-panic-note".into()).spawn(move || {
264        if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| deliver(&text))).is_err() {
265            tracing::warn!("srv panics: telling the agents failed");
266        }
267    });
268    if let Err(e) = spawned {
269        tracing::warn!(error = %e, "srv panics: the agents were not told");
270    }
271}
272
273/// Looks at the count every few seconds, on a thread of its own: publishes the event and holds the note. A failed look costs
274/// that look, not the watch.
275pub fn start_reporter(broker: Arc<crate::backend::mps::Broker>) {
276    let spawned = std::thread::Builder::new().name("srv-panic-watch".into()).spawn(move || loop {
277        std::thread::sleep(LOOK_EVERY);
278        let step = std::panic::catch_unwind(|| {
279            let recovered = crate::backend::reactive::get_global_handler().recovered_lock_count();
280            watch().look(agentmux_common::time::now_ms_u64(), recovered)
281        });
282        let Ok(step) = step else { continue };
283        if let Some(event) = &step.publish {
284            broker.publish_event::<crate::backend::mps_events::SrvPanics>(event, vec![], 1);
285        }
286        if let Some(text) = &step.note {
287            tracing::warn!(note = %text, "srv panics: telling the agents");
288            hand_to_agents(text.clone(), |text| hold_for_agents(crate::backend::reactive::get_global_handler(), text));
289        }
290    });
291    if let Err(e) = spawned {
292        tracing::warn!(error = %e, "srv panics: the watch did not start");
293    }
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    const T0: u64 = 1_000_000_000;
301
302    fn storm(counts: &mut Counts, n: u32, at_ms: u64) {
303        for _ in 0..n {
304            counts.record("backend/reactive/handler.rs:1416", at_ms);
305        }
306    }
307
308    #[test]
309    fn the_level_follows_the_panics_of_the_last_minute() {
310        assert_eq!(Level::for_count(0), Level::Normal);
311        assert_eq!(Level::for_count(WARN_ABOVE), Level::Normal, "more than N, not N");
312        assert_eq!(Level::for_count(WARN_ABOVE + 1), Level::Warn);
313        assert_eq!(Level::for_count(CRITICAL_ABOVE), Level::Warn);
314        assert_eq!(Level::for_count(CRITICAL_ABOVE + 1), Level::Critical);
315    }
316
317    #[test]
318    fn the_last_minute_counts_only_the_last_sixty_seconds() {
319        let mut c = Counts::default();
320        storm(&mut c, 5, T0);
321        storm(&mut c, 3, T0 + 30_000);
322        assert_eq!(c.last_minute(T0 + 30_000), 8);
323        assert_eq!(c.last_minute(T0 + 59_000), 8, "59 seconds after the first");
324        assert_eq!(c.last_minute(T0 + 60_000), 3, "the first five are 60 seconds old");
325        assert_eq!(c.last_minute(T0 + 90_000), 0);
326        assert_eq!(c.total, 8, "the total never drops");
327    }
328
329    #[test]
330    fn a_bucket_is_reused_when_its_second_comes_round_again() {
331        let mut c = Counts::default();
332        storm(&mut c, 4, T0);
333        storm(&mut c, 2, T0 + 60_000); // the same ring slot, a minute later
334        assert_eq!(c.last_minute(T0 + 60_000), 2, "the old second is gone");
335    }
336
337    #[test]
338    fn a_note_stuck_on_the_handler_lock_does_not_stop_the_looks() {
339        use crate::backend::reactive::ReactiveHandler;
340        use std::sync::mpsc;
341        use std::time::{Duration, Instant};
342
343        let handler: &'static ReactiveHandler = Box::leak(Box::new(ReactiveHandler::new()));
344        handler.try_register_agent_with_nonce("panic-watch-test-agent", "panic-watch-test-block", None, 1, None).expect("an agent to tell");
345        // The lock is held on a thread of its own for the whole storm: the delivery of the note cannot get in.
346        let (held_tx, held_rx) = mpsc::channel::<()>();
347        let (release_tx, release_rx) = mpsc::channel::<()>();
348        let holder = std::thread::spawn(move || {
349            let _guard = handler.hold_lock_for_test();
350            held_tx.send(()).unwrap();
351            let _ = release_rx.recv();
352        });
353        held_rx.recv().unwrap();
354
355        let mut counts = Counts::default();
356        storm(&mut counts, WARN_ABOVE + 1, T0);
357        let first = counts.look(T0, 0);
358        let text = first.note.expect("the storm starts with a note");
359        let (done_tx, done_rx) = mpsc::channel::<()>();
360        let started = Instant::now();
361        hand_to_agents(text, move |text| {
362            hold_for_agents(handler, text);
363            let _ = done_tx.send(());
364        });
365        assert!(started.elapsed() < Duration::from_secs(1), "handing the note over does not wait for the lock");
366        assert!(done_rx.recv_timeout(Duration::from_millis(100)).is_err(), "the note is stuck behind the lock");
367
368        // The reporter goes on: the storm worsens and clears while the note still waits.
369        storm(&mut counts, CRITICAL_ABOVE, T0 + 5_000);
370        let worse = counts.look(T0 + 5_000, 0);
371        assert_eq!(worse.publish.map(|e| e.level), Some("critical".to_string()));
372        let cleared = counts.look(T0 + 5_000 + 61_000, 0);
373        assert_eq!(cleared.publish.map(|e| e.level), Some("normal".to_string()), "and the clearing event is published");
374
375        release_tx.send(()).unwrap();
376        holder.join().unwrap();
377        done_rx.recv_timeout(Duration::from_secs(5)).expect("the note is delivered once the lock is free");
378    }
379
380    #[test]
381    fn a_note_that_panics_costs_only_that_note() {
382        use std::sync::mpsc;
383        use std::time::Duration;
384        let (tx, rx) = mpsc::channel::<&'static str>();
385        hand_to_agents("a storm".to_string(), |_| panic!("the delivery went wrong"));
386        let tx2 = tx.clone();
387        hand_to_agents("a storm".to_string(), move |_| tx2.send("delivered").unwrap());
388        assert_eq!(rx.recv_timeout(Duration::from_secs(5)), Ok("delivered"), "the next note is handed over as usual");
389    }
390
391    #[test]
392    fn a_quiet_srv_publishes_and_notes_nothing() {
393        let mut c = Counts::default();
394        storm(&mut c, WARN_ABOVE, T0);
395        assert_eq!(c.look(T0 + 1000, 0), Step::default());
396    }
397
398    #[test]
399    fn a_storm_publishes_every_look_and_notes_the_agents_once() {
400        let mut c = Counts::default();
401        storm(&mut c, WARN_ABOVE + 1, T0);
402        let first = c.look(T0 + 1000, 0);
403        let event = first.publish.expect("a warning is published");
404        assert_eq!((event.kind.as_str(), event.level.as_str(), event.since_ms, event.last_minute), ("panics", "warn", Some(T0 + 1000), WARN_ABOVE + 1));
405        let note = first.note.expect("the agents are told when it starts");
406        assert!(note.starts_with("[AgentMux] srv is panicking: 21 times in the last minute") && note.contains("backend/reactive/handler.rs:1416"), "{note}");
407        let second = c.look(T0 + 6000, 0);
408        assert!(second.publish.is_some(), "the counts move, so it is published again");
409        assert_eq!(second.publish.unwrap().since_ms, Some(T0 + 1000), "the episode began once");
410        assert_eq!(second.note, None, "the agents are not told twice");
411    }
412
413    #[test]
414    fn it_goes_critical_and_clears_itself_after_a_quiet_minute() {
415        let mut c = Counts::default();
416        storm(&mut c, CRITICAL_ABOVE + 1, T0);
417        assert_eq!(c.look(T0 + 1000, 0).publish.unwrap().level, "critical");
418        let ended = c.look(T0 + 61_000, 0);
419        let event = ended.publish.expect("the change back to normal is published, so the signal clears");
420        assert_eq!((event.level.as_str(), event.since_ms, event.last_minute), ("normal", None, 0));
421        assert_eq!(c.look(T0 + 66_000, 0), Step::default(), "and then it is quiet again");
422        assert_eq!(event.total, CRITICAL_ABOVE as u64 + 1, "the total stays");
423    }
424
425    #[test]
426    fn a_second_storm_within_the_hour_is_published_but_not_noted() {
427        let mut c = Counts::default();
428        storm(&mut c, WARN_ABOVE + 1, T0);
429        assert!(c.look(T0 + 1000, 0).note.is_some());
430        c.look(T0 + 61_000, 0); // clear
431        storm(&mut c, WARN_ABOVE + 1, T0 + 120_000);
432        let again = c.look(T0 + 121_000, 0);
433        assert!(again.publish.is_some() && again.note.is_none(), "the agents heard of it a few minutes ago");
434        c.look(T0 + 181_000, 0); // clear
435        let later = T0 + 61 * 60 * 1000;
436        storm(&mut c, WARN_ABOVE + 1, later);
437        assert!(c.look(later + 1000, 0).note.is_some(), "an hour on, they are told again");
438    }
439
440    #[test]
441    fn the_top_places_are_the_biggest_three_and_the_list_stays_bounded() {
442        let mut c = Counts::default();
443        for (place, n) in [("a.rs:1", 5), ("b.rs:2", 9), ("c.rs:3", 7), ("d.rs:4", 1)] {
444            for _ in 0..n {
445                c.record(place, T0);
446            }
447        }
448        let top: Vec<_> = c.top().into_iter().map(|p| (p.location, p.count)).collect();
449        assert_eq!(top, [("b.rs:2".to_string(), 9), ("c.rs:3".to_string(), 7), ("a.rs:1".to_string(), 5)]);
450        for i in 0..(MAX_PLACES + 40) {
451            c.record(&format!("many/{i}.rs:1"), T0);
452        }
453        assert!(c.places.len() <= MAX_PLACES + 1, "{} places", c.places.len());
454        assert!(c.places.contains_key(OTHER), "the rest are counted together");
455    }
456
457    #[test]
458    fn a_location_loses_its_build_path_and_its_backslashes() {
459        assert_eq!(short_location("crates\\srv\\src\\backend\\reactive\\handler.rs", 1416), "backend/reactive/handler.rs:1416");
460        assert_eq!(short_location("/home/someone/work/agentmux/crates/srv/src/main.rs", 7), "main.rs:7");
461        assert_eq!(short_location("/rustc/abc123/library/core/src/result.rs", 1), "result.rs:1");
462        assert_eq!(short_location("lonely.rs", 3), "lonely.rs:3", "no src folder: the file name");
463    }
464
465    #[test]
466    fn the_hook_counts_a_real_panic_and_leaves_the_earlier_hook_in_place() {
467        // One test owns the process-wide hook: it chains whatever is there and counts what panics after it.
468        let before = watch().snapshot(agentmux_common::time::now_ms_u64(), 0).total;
469        let saw_first = Arc::new(std::sync::atomic::AtomicBool::new(false));
470        let flag = saw_first.clone();
471        let original = std::panic::take_hook();
472        std::panic::set_hook(Box::new(move |_| flag.store(true, std::sync::atomic::Ordering::SeqCst)));
473        install_hook();
474        let panicked = std::thread::spawn(|| panic!("counted")).join().is_err();
475        std::panic::set_hook(original);
476        assert!(panicked);
477        assert!(saw_first.load(std::sync::atomic::Ordering::SeqCst), "the earlier hook still runs");
478        let after = watch().snapshot(agentmux_common::time::now_ms_u64(), 0);
479        assert!(after.total > before, "the panic was counted");
480        assert!(after.top.iter().any(|p| p.location.starts_with("backend/panic_watch.rs:")), "at its place: {:?}", after.top);
481    }
482}