Skip to main content

agentmux_srv_core/backend/
sender_failure_note.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Tells whoever sent a message that its turn died of a retryable failure with nothing to redeliver it (#2627):
5//! `Message send` answers "Delivered" once the text is injected, but if the turn it started then exits on a
6//! transient failure (a rate limit, an overload, a network error), nothing retries it and the sender hears
7//! nothing — the message is silently lost, with no sign of it anywhere the sender would look.
8//!
9//! Its own broker observer, parsing the same `agentturn` event `worker_notes` does, for `end: "exited"` and its
10//! senders (a jekt's sender, `backend::blockcontroller::health::TurnTrigger`): its `trigger`, the one that
11//! started the turn, and its `absorbed` list, the ones that joined an already-running turn (#2629 — a sender
12//! who only joined was dropped before). Only a sender of kind `agent` is a message that was ever answered
13//! "Delivered" — the user, a service, a schedule, a background task or AgentMux itself is told by other means
14//! already. The failure that ended the turn is read off the same settle wait and shared record as
15//! `worker_notes`'s own exit note (`worker_failure_note::FAILED_AT`), since the two events are published back
16//! to back for one turn. A worker whose leader already hears of this, richer, from `worker_notes`
17//! (`worker_notes::already_tells_its_leader`), is skipped — but only when that richer note was actually
18//! admitted, not held by `worker_notes`'s own one-note-a-minute throttle (#2629 again: a held note tells the
19//! leader nothing, so this note must go through instead).
20
21use std::collections::VecDeque;
22use std::sync::Arc;
23
24use crate::backend::mps::{Broker, MuxEvent};
25use crate::backend::obj::Block;
26use crate::backend::storage::store::Store;
27
28/// Mirrors `worker_notes::EXIT_SETTLE`: how long an exit waits for the failure that ended it to be stored.
29const EXIT_SETTLE: std::time::Duration = std::time::Duration::from_millis(1_000);
30
31/// An exit worth telling its senders about.
32#[derive(Debug, Clone, PartialEq, Eq)]
33struct SenderExit {
34    block_id: String,
35    /// The jekts' `from`: every distinct agent sender of this turn, from its `trigger` and its `absorbed`
36    /// list, in the order first seen.
37    senders: Vec<String>,
38    /// The turn's identity, so a turn end published twice is handled once (mirrors `worker_notes::Seen`).
39    key: String,
40}
41
42/// `t`'s sender, if it is a jekt from another agent (not the user, a service, a schedule, a task or
43/// AgentMux itself — none of those was ever answered "Delivered").
44fn agent_sender(t: &serde_json::Value) -> Option<&str> {
45    if t.get("kind").and_then(|k| k.as_str()) != Some("agent") {
46        return None;
47    }
48    t.get("from").and_then(|f| f.as_str()).filter(|s| !s.is_empty())
49}
50
51/// Every distinct agent sender of the turn `d` describes: its `trigger` (the one that started it) and its
52/// `absorbed` list (ones that joined it already running), in the order first seen.
53fn agent_senders(d: &serde_json::Value) -> Vec<String> {
54    let mut out: Vec<String> = Vec::new();
55    let mut push = |t: &serde_json::Value| {
56        if let Some(from) = agent_sender(t) {
57            if !out.iter().any(|s| s == from) {
58                out.push(from.to_string());
59            }
60        }
61    };
62    if let Some(trigger) = d.get("trigger") {
63        push(trigger);
64    }
65    for absorbed in d.get("absorbed").and_then(|a| a.as_array()).into_iter().flatten() {
66        push(absorbed);
67    }
68    out
69}
70
71fn parse_event(event: &str, data: Option<&serde_json::Value>) -> Option<SenderExit> {
72    if event != crate::backend::mps::EVENT_AGENT_TURN {
73        return None;
74    }
75    let d = data?;
76    if d.get("end").and_then(|e| e.as_str()) != Some("exited") {
77        return None;
78    }
79    let senders = agent_senders(d);
80    if senders.is_empty() {
81        return None;
82    }
83    let block_id = d.get("block_id")?.as_str()?.to_string();
84    let key = format!(
85        "{block_id}/{}/{}",
86        d.get("turn_id").and_then(|t| t.as_u64()).unwrap_or(0),
87        d.get("ended_at_ms").and_then(|t| t.as_u64()).unwrap_or(0)
88    );
89    Some(SenderExit { block_id, senders, key })
90}
91
92/// Exits already handled: a turn end can be published twice (its settle window, then the tracker's close).
93/// Kept separate from `worker_notes::Seen`, which dedupes a different, narrower set of exits (a worker's).
94#[derive(Default)]
95struct Seen {
96    keys: VecDeque<String>,
97}
98
99impl Seen {
100    fn first(&mut self, key: &str) -> bool {
101        if self.keys.iter().any(|k| k == key) {
102            return false;
103        }
104        if self.keys.len() >= 256 {
105            self.keys.pop_front();
106        }
107        self.keys.push_back(key.to_string());
108        true
109    }
110}
111
112/// The agent definition's name for the one that owns `block`, or its id when the definition is gone.
113fn target_name(mstore: &Store, block: &Block) -> String {
114    let id = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
115    if id.is_empty() {
116        return "it".to_string();
117    }
118    mstore.agent_def_get(&id).ok().flatten().map(|d| d.name).unwrap_or(id)
119}
120
121/// Start listening. Called once from `main`, alongside `worker_notes::install`.
122pub fn install(broker: Arc<Broker>, mstore: Arc<Store>) {
123    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<SenderExit>();
124    broker.add_observer(Arc::new(move |ev: &MuxEvent| {
125        if let Some(e) = parse_event(&ev.event, ev.data.as_ref()) {
126            let _ = tx.send(e);
127        }
128    }));
129    tokio::spawn(async move {
130        let mut seen = Seen::default();
131        while let Some(ev) = rx.recv().await {
132            if !seen.first(&ev.key) {
133                continue;
134            }
135            tokio::spawn(note_sender(ev, mstore.clone()));
136        }
137    });
138}
139
140/// What to tell `sender` about `block_id`'s exit, heard at `heard_at`: `None` when nothing is said — no failure
141/// heard around this exit, a worker whose leader already hears of it richer, or a failure that isn't a
142/// retryable transient one.
143fn note_for(mstore: &Store, block_id: &str, sender: &str, heard_at: std::time::Instant) -> Option<String> {
144    if !super::worker_failure_note::FAILED_AT.lock().speaks_for_exit(block_id, heard_at) {
145        return None;
146    }
147    if super::worker_notes::already_tells_its_leader(mstore, block_id, sender) {
148        return None;
149    }
150    let block = mstore.get::<Block>(block_id).ok().flatten()?;
151    let failure = super::worker_failure_note::stored(&block.meta)?;
152    let name = target_name(mstore, &block);
153    super::worker_failure_note::sender_body(&name, &failure)
154}
155
156/// Tell each of `ev`'s senders, once the failure that may have ended the turn has had time to be stored.
157async fn note_sender(ev: SenderExit, mstore: Arc<Store>) {
158    let heard_at = std::time::Instant::now();
159    tokio::time::sleep(EXIT_SETTLE).await;
160    let (store, block_id, senders) = (mstore.clone(), ev.block_id.clone(), ev.senders.clone());
161    let bodies = tokio::task::spawn_blocking(move || {
162        senders.into_iter().filter_map(|s| note_for(&store, &block_id, &s, heard_at).map(|body| (s, body))).collect::<Vec<_>>()
163    })
164    .await
165    .unwrap_or_default();
166    for (sender, body) in bodies {
167        let text = format!("[AgentMux] {}", super::reactive::sanitize::quote_in_system_note(&body));
168        if let Err(e) = super::reactive::get_global_handler().deliver_system_note(&sender, &text) {
169            tracing::debug!(sender = %sender, block_id = %ev.block_id, error = %e, "sender failure note not delivered");
170        }
171    }
172}
173
174#[cfg(test)]
175#[path = "sender_failure_note_tests.rs"]
176mod tests;