agentmux_srv_core/backend/reactive/
handler_lock.rs1use std::sync::atomic::{AtomicU64, Ordering};
17use std::sync::{Mutex, MutexGuard, PoisonError, TryLockError};
18
19use super::handler::{Handler, ReactiveHandler};
20
21pub(super) struct HandlerLock {
23 mutex: Mutex<Handler>,
24 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 pub(super) fn lock(&self) -> MutexGuard<'_, Handler> {
35 self.mutex.lock().unwrap_or_else(|poisoned| self.recover(poisoned))
36 }
37
38 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 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 pub fn recovered_lock_count(&self) -> u64 {
71 self.inner.recovered()
72 }
73
74 #[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 pub fn lock_is_free(&self) -> bool {
83 self.inner.try_lock().is_some()
84 }
85}
86
87impl Handler {
88 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 fn panics_on_a_thread(f: impl FnOnce() + Send) -> bool {
111 std::thread::scope(|s| s.spawn(f).join().is_err())
112 }
113
114 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 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 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}