Skip to main content

agentmux_srv_core/backend/
worker_failure_note.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a leader is told about why a worker's turn failed, and what happens next (#2617): the class the
5//! failure was stored under (`agent:last_failure`, written before the `agentfailure` event that
6//! `worker_notes` hears), whether it is worth retrying, and who retries it.
7
8use 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/// The failure stored in a block's meta, as a note reads it.
17#[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
24/// Whether `worker_notes`'s own note for a worker's failure was actually admitted (delivered), or held by its
25/// one-note-a-minute throttle (`worker_notes::Gaps`, SPEC_AGENT_WORKERS_2026_10_15.md ยง"at most one note per
26/// worker per minute") โ€” keyed by the worker's own block id, the outcome of its most recent `Failed` event.
27/// `sender_failure_note::already_tells_its_leader` reads this before skipping its own note: a held note tells
28/// the leader nothing, so the sender's own note must go through instead (#2629). Set only by `worker_notes`'s
29/// own processing of a `Failed` event, never read-and-cleared, since a later failure simply overwrites it.
30pub(crate) static FAILURE_NOTE_ADMITTED: LazyLock<Mutex<HashMap<String, bool>>> = LazyLock::new(Default::default);
31
32/// Records whether `worker_notes` admitted (delivered) or held its own note for `block_id`'s failure.
33pub(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(); // a long-running instance's worker count is nowhere near this; cheap enough to just reset
37    }
38    map.insert(block_id.to_string(), admitted);
39}
40
41/// Whether `worker_notes` is known to have admitted (delivered) its own note for `block_id`'s most recent
42/// failure. `false` when nothing was ever recorded for it โ€” the conservative default: tell the sender rather
43/// than risk assuming a note went out that didn't.
44pub(crate) fn failure_note_was_admitted(block_id: &str) -> bool {
45    FAILURE_NOTE_ADMITTED.lock().get(block_id).copied().unwrap_or(false)
46}
47
48/// The block's stored failure, or `None` when it has none this build can read.
49pub(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
58/// The stored failure's class as the wire names it (`rate_limited`, `network`...), for the `detail` of an
59/// agent whose last run ended in an error: `error` alone doesn't say whether to retry.
60pub 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/// When each worker pane's last `agentfailure` was heard: the exit of the turn it ended is not news of its own.
66#[derive(Default)]
67pub(crate) struct FailedAt {
68    by_block: std::collections::HashMap<String, std::time::Instant>,
69}
70
71/// The pane's failure that belongs to an exit heard at `heard_at` came within this long before it or after it
72/// (the exit and the failure are published back to back; either may come first).
73const 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    /// Whether a failure of this pane came within `SAME_TURN` of the exit heard at `heard_at`: its note says why.
82    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
93/// The sentence that follows "stopped with an error: <title>.": the class, and what happens to the
94/// turn's message. Empty for a class with nothing useful to add.
95pub(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            // No `resets_at_ms` here is normal: a rate limit is a short burst, not an account quota with a reset.
112            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
120/// The note for whoever sent a message whose turn then exited on `f`, naming `target_name` (the agent that was
121/// sent the message): `None` for anything but a retryable transient failure (#2627) โ€” a usage limit or a
122/// refused sign-in has its own path (the availability view, the limit wake), and is not a silently lost message.
123pub(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
140/// The body of the note for a failed worker.
141pub(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    /// The default, with nothing recorded yet, is `false` (not admitted): the conservative read, so a
159    /// caller that finds no record tells the sender rather than assume a note went out that didn't (#2629).
160    #[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    /// An exit is silenced only by a failure heard around it, never by one stored by an earlier turn (#2617).
191    #[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", &not_retryable_429, 1), plain, "only a retryable one promises a retry");
234    }
235}