Skip to main content

agentmux_srv_core/backend/reactive/
handler_lock.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The handler's lock, which a panic cannot leave closed.
5//!
6//! Every `ReactiveHandler` method takes this lock, and a delivery calls code the handler does not own (the controller's
7//! message sender, the identity confirmers) while it holds it. A panic in any of them used to poison a plain
8//! `std::sync::Mutex`, and every later `lock().unwrap()` then panicked too: on 2026-11-15 one panic on the build-slot
9//! idle watch stopped all agent messaging, spawns and the Kanban on a machine for two hours, until AgentMux was
10//! restarted (docs/incident/RCA_BUILD_SLOT_IDLE_NOTE_POISONS_MESSAGE_HANDLER_2026_11_15.md).
11//!
12//! [`HandlerLock::lock`] takes the lock whatever state it is in. After a panic it clears the poison, resets what a
13//! half-finished delivery leaves in the handler, and logs one warning. A panic costs the delivery it happened in, not
14//! the ones after it.
15
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::sync::{Mutex, MutexGuard, PoisonError, TryLockError};
18
19use super::handler::{Handler, ReactiveHandler};
20
21/// `Mutex<Handler>` whose locks recover from a poisoning panic instead of passing it on.
22pub(super) struct HandlerLock {
23    mutex: Mutex<Handler>,
24    /// How many times a poisoned lock was recovered since srv started: `/health` and the status bar report it.
25    recovered: AtomicU64,
26}
27
28impl HandlerLock {
29    pub(super) fn new(handler: Handler) -> Self {
30        Self { mutex: Mutex::new(handler), recovered: AtomicU64::new(0) }
31    }
32
33    /// Waits for the lock. Never panics because another thread did.
34    pub(super) fn lock(&self) -> MutexGuard<'_, Handler> {
35        self.mutex.lock().unwrap_or_else(|poisoned| self.recover(poisoned))
36    }
37
38    /// Takes the lock if it is free right now; `None` when another thread holds it. A poisoned lock is recovered, not refused.
39    pub(super) fn try_lock(&self) -> Option<MutexGuard<'_, Handler>> {
40        match self.mutex.try_lock() {
41            Ok(guard) => Some(guard),
42            Err(TryLockError::WouldBlock) => None,
43            Err(TryLockError::Poisoned(poisoned)) => Some(self.recover(poisoned)),
44        }
45    }
46
47    #[cold]
48    fn recover<'a>(&'a self, poisoned: PoisonError<MutexGuard<'a, Handler>>) -> MutexGuard<'a, Handler> {
49        let mut handler = poisoned.into_inner();
50        handler.reset_delivery_context();
51        self.recovered.fetch_add(1, Ordering::Relaxed);
52        // Cleared while the guard is held: the next thread to lock sees a healthy lock, and the warning is written once per panic.
53        self.mutex.clear_poison();
54        tracing::warn!("reactive: a panic under the handler lock was recovered; the delivery it happened in is lost, messaging goes on");
55        handler
56    }
57
58    pub(super) fn recovered(&self) -> u64 {
59        self.recovered.load(Ordering::Relaxed)
60    }
61
62    #[cfg(test)]
63    fn is_poisoned(&self) -> bool {
64        self.mutex.is_poisoned()
65    }
66}
67
68impl ReactiveHandler {
69    /// How many times the handler's lock was found poisoned and recovered since srv started.
70    pub fn recovered_lock_count(&self) -> u64 {
71        self.inner.recovered()
72    }
73
74    /// Holds the lock until the guard is dropped: for a test of what health says about a lock that stays taken.
75    #[cfg(any(test, feature = "test-support"))]
76    pub fn hold_lock_for_test(&self) -> std::sync::MutexGuard<'_, Handler> {
77        self.inner.lock()
78    }
79
80    /// Whether the lock could be taken just now (and is let go at once): the pulse of the messaging path, for health. A lock held for
81    /// good, as a deadlock or a stuck delivery would, is never free.
82    pub fn lock_is_free(&self) -> bool {
83        self.inner.try_lock().is_some()
84    }
85}
86
87impl Handler {
88    /// `inject_message_inner` puts the sender's identity, the WAN verdict and the trust label of the delivery in flight
89    /// into the handler and restores them when the delivery ends. A panic in between skips the restore, and the next
90    /// audit entry would carry another delivery's sender. Nothing is in flight when the lock is recovered (the one
91    /// thread that held it is gone), so the idle values are the right ones.
92    pub(super) fn reset_delivery_context(&mut self) {
93        self.delivery_source_uid = String::new();
94        self.delivery_wan = None;
95        self.delivery_lan_claimed_uid = String::new();
96        self.delivery_turn = None;
97        self.delivery_how = None;
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use std::sync::atomic::{AtomicBool, Ordering};
104    use std::sync::Arc;
105
106    use super::super::handler::ReactiveHandler;
107    use super::super::types::{InjectionRequest, SenderDelivery};
108
109    /// Runs `f` on a thread of its own, which is expected to panic, and returns whether it did.
110    fn panics_on_a_thread(f: impl FnOnce() + Send) -> bool {
111        std::thread::scope(|s| s.spawn(f).join().is_err())
112    }
113
114    /// A message sender that panics on its first call (as the controller did without a Tokio runtime) and delivers after that.
115    fn sender_that_panics_once() -> super::super::types::MessageSender {
116        let first = AtomicBool::new(true);
117        Arc::new(move |_block: &str, _text: &str, _inline: &[serde_json::Value], _origin: &crate::backend::message_origin::MessageOrigin, _expires: Option<i64>| {
118            if first.swap(false, Ordering::SeqCst) {
119                panic!("there is no reactor running, must be called from the context of a Tokio 1.x runtime");
120            }
121            Ok(SenderDelivery::Delivered)
122        })
123    }
124
125    #[test]
126    fn a_panic_under_the_lock_does_not_stop_the_next_caller() {
127        let handler = ReactiveHandler::new();
128        handler.inner.lock().register_agent("agent1", "block1", None).unwrap();
129        assert!(panics_on_a_thread(|| {
130            let mut guard = handler.inner.lock();
131            guard.delivery_source_uid = "another-delivery".to_string();
132            panic!("a panic while the lock is held");
133        }));
134        assert!(handler.inner.is_poisoned(), "the std lock was poisoned: this is the state that used to stop everything");
135        assert_eq!(handler.list_agents().len(), 1, "the next caller gets the lock and its data");
136        assert!(!handler.inner.is_poisoned(), "and the lock is healthy again, so the warning is not repeated");
137        assert_eq!(handler.inner.lock().delivery_source_uid, "", "a half-finished delivery's sender is not left behind");
138    }
139
140    #[test]
141    fn a_system_note_that_panics_in_the_sender_costs_only_that_note() {
142        let handler = ReactiveHandler::new();
143        handler.set_message_sender(sender_that_panics_once());
144        handler.inner.lock().register_agent("agent1", "block1", None).unwrap();
145        assert!(panics_on_a_thread(|| {
146            let _ = handler.deliver_system_note("agent1", "[AgentMux] idle");
147        }));
148        handler.deliver_system_note("agent1", "[AgentMux] again").expect("the next note is delivered");
149        assert_eq!(handler.list_agents().len(), 1);
150        let notes = handler.get_audit_log(10).iter().filter(|entry| entry.outcome.as_deref() == Some("system_note")).count();
151        assert_eq!(notes, 1, "only the note that was delivered is audited; the one that panicked never reached its audit row");
152    }
153
154    #[test]
155    fn a_jekt_that_panics_mid_delivery_leaves_no_sender_on_the_next_audit_entry() {
156        let handler = ReactiveHandler::new();
157        handler.set_message_sender(sender_that_panics_once());
158        handler.inner.lock().register_agent("agentg", "block1", None).unwrap();
159        let request = |uid: &str| InjectionRequest {
160            target_agent: "agentg".to_string(),
161            message: "hello".to_string(),
162            audit_source_uid: uid.to_string(),
163            lan_claimed_uid: uid.to_string(),
164            ..Default::default()
165        };
166        assert!(panics_on_a_thread(|| {
167            handler.inject_message(request("uid-of-the-first-sender"));
168        }));
169        let resp = handler.inject_message(request(""));
170        assert!(resp.success, "{:?}", resp.error);
171        assert_eq!(handler.inner.lock().delivery_source_uid, "");
172        assert_eq!(handler.inner.lock().delivery_lan_claimed_uid, "");
173        assert!(
174            handler.get_audit_log(5).iter().all(|entry| !format!("{entry:?}").contains("uid-of-the-first-sender")),
175            "no audit entry carries the failed delivery's sender"
176        );
177    }
178
179    #[test]
180    fn the_spawn_path_locks_recover_too() {
181        let handler = ReactiveHandler::new();
182        handler.inner.lock().register_agent("agent1", "block1", None).unwrap();
183        assert!(panics_on_a_thread(|| {
184            let _guard = handler.inner.lock();
185            panic!("a panic while the lock is held");
186        }));
187        // These two answered "mutex poisoned" and None for the rest of the process's life.
188        assert!(handler.try_get_agent_by_block("block1").is_some());
189        assert!(!handler.inner.is_poisoned());
190        assert!(panics_on_a_thread(|| {
191            let _guard = handler.inner.lock();
192            panic!("and again");
193        }));
194        handler.try_register_agent_with_nonce("agent2", "block2", None, 1, None).expect("the spawn-path registration goes through");
195    }
196
197    #[test]
198    fn every_recovery_is_counted_for_health() {
199        let handler = ReactiveHandler::new();
200        assert_eq!(handler.recovered_lock_count(), 0);
201        for expected in 1..=2u64 {
202            assert!(panics_on_a_thread(|| {
203                let _guard = handler.inner.lock();
204                panic!("a panic while the lock is held");
205            }));
206            assert_eq!(handler.list_agents().len(), 0);
207            assert_eq!(handler.recovered_lock_count(), expected, "one recovery per poisoning, not one per later call");
208            handler.list_agents();
209            assert_eq!(handler.recovered_lock_count(), expected, "a healthy lock adds nothing");
210        }
211    }
212
213    #[test]
214    fn the_lock_is_free_unless_someone_holds_it() {
215        let handler = ReactiveHandler::new();
216        assert!(handler.lock_is_free());
217        let guard = handler.inner.lock();
218        assert!(!handler.lock_is_free(), "a lock held for good (a stuck delivery, a deadlock) is not free: health says so");
219        drop(guard);
220        assert!(handler.lock_is_free());
221        // A poisoned lock is recovered by the probe itself, and counted.
222        assert!(panics_on_a_thread(|| {
223            let _guard = handler.inner.lock();
224            panic!("a panic while the lock is held");
225        }));
226        assert!(handler.lock_is_free());
227        assert_eq!(handler.recovered_lock_count(), 1);
228    }
229}