agentmux_srv_core/backend/
worker_failure_note.rs1use std::collections::HashMap;
9use std::sync::LazyLock;
10
11use parking_lot::Mutex;
12
13use crate::agents::failure::FailureClass;
14use crate::backend::obj::MetaMapType;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub(crate) struct StoredFailure {
19 pub code: FailureClass,
20 pub retryable: bool,
21 pub resets_at_ms: Option<u64>,
22}
23
24pub(crate) static FAILURE_NOTE_ADMITTED: LazyLock<Mutex<HashMap<String, bool>>> = LazyLock::new(Default::default);
31
32pub(crate) fn record_failure_admission(block_id: &str, admitted: bool) {
34 let mut map = FAILURE_NOTE_ADMITTED.lock();
35 if map.len() > 4096 {
36 map.clear(); }
38 map.insert(block_id.to_string(), admitted);
39}
40
41pub(crate) fn failure_note_was_admitted(block_id: &str) -> bool {
45 FAILURE_NOTE_ADMITTED.lock().get(block_id).copied().unwrap_or(false)
46}
47
48pub(crate) fn stored(meta: &MetaMapType) -> Option<StoredFailure> {
50 let f = meta.get(crate::backend::blockcontroller::core::META_LAST_FAILURE)?;
51 Some(StoredFailure {
52 code: serde_json::from_value(f.get("code")?.clone()).ok()?,
53 retryable: f.get("retryable").and_then(|r| r.as_bool()).unwrap_or(false),
54 resets_at_ms: f.get("resetsAtMs").and_then(|r| r.as_u64()),
55 })
56}
57
58pub fn code_name(meta: &MetaMapType) -> Option<String> {
61 let code = stored(meta)?.code;
62 serde_json::to_value(code).ok()?.as_str().map(str::to_string)
63}
64
65#[derive(Default)]
67pub(crate) struct FailedAt {
68 by_block: std::collections::HashMap<String, std::time::Instant>,
69}
70
71const SAME_TURN: std::time::Duration = std::time::Duration::from_secs(2);
74
75impl FailedAt {
76 pub(crate) fn record(&mut self, block_id: &str, at: std::time::Instant) {
77 self.by_block.retain(|_, t| at.saturating_duration_since(*t) < SAME_TURN * 5);
78 self.by_block.insert(block_id.to_string(), at);
79 }
80
81 pub(crate) fn speaks_for_exit(&self, block_id: &str, heard_at: std::time::Instant) -> bool {
83 self.by_block.get(block_id).is_some_and(|t| *t + SAME_TURN >= heard_at)
84 }
85}
86
87pub(crate) static FAILED_AT: std::sync::LazyLock<parking_lot::Mutex<FailedAt>> = std::sync::LazyLock::new(Default::default);
88
89fn minutes_until(at_ms: u64, now_ms: u64) -> u64 {
90 at_ms.saturating_sub(now_ms).div_ceil(60_000).max(1)
91}
92
93pub(crate) fn what_next(f: &StoredFailure, now_ms: u64) -> String {
96 match (f.code, f.resets_at_ms) {
97 (FailureClass::UsageLimit, Some(at)) if at > now_ms => format!(
98 "Its account is out of quota (usage limit), which lifts in about {} min; AgentMux wakes it a little after that. Messages sent to it wait until then.",
99 minutes_until(at, now_ms)
100 ),
101 (FailureClass::UsageLimit, _) => {
102 "Its account is out of quota (usage limit) and the provider gave no reset time; AgentMux can't wake it by itself.".to_string()
103 }
104 (FailureClass::Auth, _) => "Its sign-in was refused; it can't work until someone signs it in again.".to_string(),
105 (FailureClass::RateLimited | FailureClass::Overloaded | FailureClass::Network, _) if f.retryable => {
106 let why = match f.code {
107 FailureClass::RateLimited => "The provider rate-limited it (HTTP 429)",
108 FailureClass::Overloaded => "The provider was overloaded (HTTP 529)",
109 _ => "It could not reach the provider",
110 };
111 format!(
113 "{why}; this is transient and has no reset time. The message it was working on was not answered, and AgentMux retries it by itself only while the worker's pane is open in a window. Otherwise send it another message to start a new turn."
114 )
115 }
116 _ => String::new(),
117 }
118}
119
120pub(crate) fn sender_body(target_name: &str, f: &StoredFailure) -> Option<String> {
124 if !f.retryable {
125 return None;
126 }
127 let why = match f.code {
128 FailureClass::RateLimited => "The provider rate-limited it (HTTP 429)",
129 FailureClass::Overloaded => "The provider was overloaded (HTTP 529)",
130 FailureClass::Network => "It could not reach the provider",
131 _ => return None,
132 };
133 Some(format!(
134 "Your message to {target_name} wasn't answered: its turn ended on an error, not a reply. {why}; this is \
135 transient and has no reset time. AgentMux retries it by itself only while {target_name}'s own pane is \
136 open in a window; otherwise send it another message if it still matters."
137 ))
138}
139
140pub(crate) fn failed_body(worker: &str, title: &str, meta: &MetaMapType, now_ms: u64) -> String {
142 let base = format!("Your worker {worker} stopped with an error: {title}.");
143 match stored(meta).map(|f| what_next(&f, now_ms)).filter(|s| !s.is_empty()) {
144 Some(next) => format!("{base} {next}"),
145 None => base,
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use serde_json::json;
153
154 fn meta(f: serde_json::Value) -> MetaMapType {
155 MetaMapType::from([("agent:last_failure".to_string(), f)])
156 }
157
158 #[test]
161 fn failure_note_admission_defaults_to_false_and_round_trips() {
162 let block = format!("block-{}", uuid::Uuid::new_v4());
163 assert!(!failure_note_was_admitted(&block), "nothing recorded yet");
164 record_failure_admission(&block, true);
165 assert!(failure_note_was_admitted(&block));
166 record_failure_admission(&block, false);
167 assert!(!failure_note_was_admitted(&block), "the latest record wins");
168 }
169
170 #[test]
171 fn a_rate_limit_says_it_is_transient_has_no_reset_and_who_retries() {
172 let m = meta(json!({ "code": "rate_limited", "title": "Rate limited", "detail": "", "retryable": true }));
173 let body = failed_body("Pulp", "Rate limited", &m, 1_000);
174 assert!(body.starts_with("Your worker Pulp stopped with an error: Rate limited. The provider rate-limited it (HTTP 429)"), "{body}");
175 assert!(body.contains("transient and has no reset time"), "{body}");
176 assert!(body.contains("only while the worker's pane is open"), "{body}");
177 assert!(body.contains("send it another message"), "{body}");
178 }
179
180 #[test]
181 fn a_usage_limit_names_its_reset_or_says_there_is_none() {
182 let with = meta(json!({ "code": "usage_limit", "title": "Usage limit reached", "retryable": false, "resetsAtMs": 1_000 + 90 * 60_000 }));
183 assert!(failed_body("W", "Usage limit reached", &with, 1_000).contains("lifts in about 90 min"));
184 let without = meta(json!({ "code": "usage_limit", "title": "Usage limit reached", "retryable": false }));
185 assert!(failed_body("W", "Usage limit reached", &without, 1_000).contains("no reset time"));
186 let past = meta(json!({ "code": "usage_limit", "title": "x", "retryable": false, "resetsAtMs": 5 }));
187 assert!(failed_body("W", "x", &past, 1_000).contains("no reset time"), "a reset already past says nothing to wait for");
188 }
189
190 #[test]
192 fn only_a_failure_heard_around_the_exit_speaks_for_it() {
193 use std::time::{Duration, Instant};
194 let t0 = Instant::now();
195 let mut failed = FailedAt::default();
196 assert!(!failed.speaks_for_exit("b", t0), "no failure heard");
197 failed.record("b", t0 + Duration::from_millis(30));
198 assert!(failed.speaks_for_exit("b", t0), "the failure came just after the exit");
199 assert!(failed.speaks_for_exit("b", t0 + Duration::from_secs(1)), "or just before it");
200 assert!(!failed.speaks_for_exit("b", t0 + Duration::from_secs(60)), "a failure of an earlier turn");
201 assert!(!failed.speaks_for_exit("other", t0), "another pane");
202 }
203
204 #[test]
205 fn a_senders_note_is_only_for_a_retryable_transient_failure() {
206 let retryable = StoredFailure { code: FailureClass::RateLimited, retryable: true, resets_at_ms: None };
207 let body = sender_body("Lowly", &retryable).unwrap();
208 assert!(body.starts_with("Your message to Lowly wasn't answered: its turn ended on an error, not a reply. The provider rate-limited it (HTTP 429)"), "{body}");
209 assert!(body.contains("Lowly's own pane is open") && body.contains("send it another message"), "{body}");
210 assert!(sender_body("Lowly", &StoredFailure { code: FailureClass::UsageLimit, retryable: false, resets_at_ms: None }).is_none(), "its own path tells it");
211 assert!(sender_body("Lowly", &StoredFailure { code: FailureClass::Auth, retryable: false, resets_at_ms: None }).is_none());
212 assert!(
213 sender_body("Lowly", &StoredFailure { code: FailureClass::RateLimited, retryable: false, resets_at_ms: None }).is_none(),
214 "a class that is usually transient but wasn't marked retryable this time"
215 );
216 }
217
218 #[test]
219 fn the_error_states_reason_is_the_stored_class() {
220 assert_eq!(code_name(&meta(json!({ "code": "rate_limited", "title": "x", "retryable": true }))).as_deref(), Some("rate_limited"));
221 assert_eq!(code_name(&MetaMapType::new()), None);
222 }
223
224 #[test]
225 fn a_failure_with_nothing_to_add_or_none_stored_keeps_the_plain_note() {
226 let plain = "Your worker W stopped with an error: Boom.";
227 assert_eq!(failed_body("W", "Boom", &MetaMapType::new(), 1), plain);
228 let unknown = meta(json!({ "code": "unknown_non_zero", "title": "Boom", "retryable": false }));
229 assert_eq!(failed_body("W", "Boom", &unknown, 1), plain);
230 let unreadable = meta(json!({ "code": "no_such_class", "title": "Boom" }));
231 assert_eq!(failed_body("W", "Boom", &unreadable, 1), plain);
232 let not_retryable_429 = meta(json!({ "code": "rate_limited", "title": "Boom", "retryable": false }));
233 assert_eq!(failed_body("W", "Boom", ¬_retryable_429, 1), plain, "only a retryable one promises a retry");
234 }
235}