Skip to main content

a2a_protocol_server/tool_loop/
loop_error.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`LoopError`]: why a run of the loop produced no answer.
5
6use std::fmt;
7#[cfg(test)]
8use std::time::Duration;
9
10use a2a_protocol_types::budget::Exhausted;
11use a2a_protocol_types::failure::FailureClass;
12
13use super::answer::FINISH_REASON_LENGTH;
14use super::model::ModelError;
15
16/// A call a person has to approve before the run can go on.
17#[derive(Debug, Clone, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct ApprovalNeeded {
20    /// Names the request: the run's journal key, which the decision echoes
21    /// and by which the run is found again.
22    pub request_id: String,
23    /// What the person is shown.
24    pub summary: String,
25    /// The digest of the call ([`call_digest`](super::call_digest)).
26    pub digest: String,
27    /// The tool.
28    pub tool: String,
29    /// The call's id.
30    pub call_id: String,
31}
32
33/// Why a run produced no answer.
34#[derive(Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum LoopError {
37    /// The run is parked on a call a person has to approve; it is not a
38    /// failure, and the executor ends the turn `input-required`.
39    AwaitingApproval(Box<ApprovalNeeded>),
40    /// The run journal could not be read or written, or was not what the run
41    /// needed. The run stopped before the step it could not record.
42    Journal(String),
43    /// A run begun with one model, tool set or configuration was asked to
44    /// continue under another.
45    PinMismatch(String),
46    /// A call may have run before the replica died, and this loop cannot
47    /// safely run it again: its idempotency secret was not set explicitly, so
48    /// its key would differ on this replica.
49    Indeterminate {
50        /// The tool.
51        tool: String,
52        /// The call's id.
53        call_id: String,
54    },
55    /// The model provider failed a turn.
56    Model(ModelError),
57    /// A tool returned [`ToolError::Fatal`](super::ToolError::Fatal).
58    Fatal {
59        /// The tool that failed.
60        tool: String,
61        /// What it said.
62        message: String,
63    },
64    /// The model asked for tools on every one of this many turns.
65    TurnLimit(usize),
66    /// The cancellation token fired.
67    Cancelled,
68    /// The caller's budget ran out: its deadline passed, or the model's
69    /// reported usage spent the [`TOKENS_METER`](a2a_protocol_types::budget::TOKENS_METER) (ADR 0023).
70    Budget(Exhausted),
71    /// The model's final reply had no text: it was empty, or only
72    /// whitespace. The usual cause is a reply cut at the output limit before
73    /// the model had written anything, as a reasoning model whose limit goes
74    /// on thinking does.
75    EmptyAnswer {
76        /// Why the reply stopped, as the provider spelled it, when it said.
77        finish_reason: Option<String>,
78    },
79    /// The model's reply named two calls with one id, so no result could be
80    /// told apart from the other's; no call in it was run (adversarial review
81    /// N08, 2026-11-13).
82    AmbiguousCalls {
83        /// The id named twice.
84        id: String,
85    },
86    /// What the run would have sent the model was past the loop's request
87    /// limit, and was not sent (adversarial review N09, 2026-11-13).
88    TooLarge {
89        /// Its size in bytes.
90        bytes: usize,
91        /// The limit ([`ToolLoop::with_request_limit`](super::ToolLoop::with_request_limit)).
92        limit: usize,
93    },
94}
95
96/// The `finish_reason` OpenAI-compatible providers send when a content filter
97/// withheld the reply.
98const FINISH_REASON_CONTENT_FILTER: &str = "content_filter";
99
100impl fmt::Display for LoopError {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        match self {
103            Self::Model(e) => e.fmt(f),
104            Self::Fatal { tool, message } => write!(f, "tool '{tool}' failed: {message}"),
105            Self::TurnLimit(turns) => write!(
106                f,
107                "the model asked for tools on all {turns} turns without answering"
108            ),
109            Self::Cancelled => f.write_str("cancelled"),
110            Self::AwaitingApproval(n) => {
111                write!(f, "waiting for approval of a call to '{}'", n.tool)
112            }
113            Self::Journal(why) => write!(f, "the run journal: {why}"),
114            Self::PinMismatch(why) => f.write_str(why),
115            Self::Indeterminate { tool, call_id } => write!(
116                f,
117                "the call {call_id} to '{tool}' may have run before the replica stopped, and \
118                 its idempotency key is not the same on every replica; set \
119                 with_idempotency_secret to resume it"
120            ),
121            Self::Budget(e) => e.fmt(f),
122            Self::EmptyAnswer {
123                finish_reason: Some(reason),
124            } => write!(
125                f,
126                "the model returned an empty answer (finish_reason: {reason})"
127            ),
128            Self::EmptyAnswer {
129                finish_reason: None,
130            } => f.write_str("the model returned an empty answer"),
131            Self::AmbiguousCalls { id } => write!(
132                f,
133                "the model's reply named two tool calls with the id {id:?}; none of its calls \
134                 was run"
135            ),
136            Self::TooLarge { bytes, limit } => write!(
137                f,
138                "the next model request is {bytes} bytes, past the loop's request limit of \
139                 {limit}; it was not sent"
140            ),
141        }
142    }
143}
144
145impl std::error::Error for LoopError {}
146
147impl LoopError {
148    /// Whether the run failed for a reason that may pass: the model
149    /// provider overloaded or briefly away (HTTP 429, 502, 503, 504), not
150    /// answering in time, or not reachable. The task then ends failure class
151    /// `transient`, which tells the caller a retry may succeed; any other
152    /// failure is `internal`. Seen live (2026-10-30): `llama-server` answers
153    /// `503` while it loads a model, for minutes, and every task ended
154    /// `internal`, which a client does not retry.
155    pub(super) const fn is_transient(&self) -> bool {
156        matches!(
157            self,
158            Self::Model(
159                ModelError::Status {
160                    status: 429 | 502 | 503 | 504,
161                    ..
162                } | ModelError::RateLimited { .. }
163                    | ModelError::Timeout(_)
164                    | ModelError::Transport(_)
165            )
166        )
167    }
168
169    /// What the A2A caller is told when the run fails.
170    ///
171    /// Not [`Display`](fmt::Display): that carries what the provider sent
172    /// back, up to 512 bytes of an error body for a status (which can echo
173    /// the prompt, an account or quota detail, or an internal address), and
174    /// the text of a transport error (which names the provider's URL). The
175    /// caller is another agent or a person at the other end of the network,
176    /// not the operator, so it gets the status or the kind of failure and
177    /// the operator gets the rest in the log. A tool's own message and a
178    /// [`ToolModel`](super::ToolModel)'s [`Other`](ModelError::Other) are the
179    /// integrator's words and go through unchanged.
180    pub(super) fn caller_message(&self) -> String {
181        match self {
182            Self::Model(ModelError::Status { status, .. }) => {
183                format!("the model provider answered HTTP {status}")
184            }
185            Self::Model(ModelError::RateLimited { .. }) => {
186                "the model provider answered HTTP 429".to_owned()
187            }
188            Self::Model(ModelError::Transport(_)) => {
189                "could not reach the model provider".to_owned()
190            }
191            Self::Model(ModelError::InvalidResponse(_)) => {
192                "the model provider's answer could not be read".to_owned()
193            }
194            Self::Model(ModelError::Config(_)) => "the model client is misconfigured".to_owned(),
195            // The reason is the provider's own string: named when it is one
196            // of the two this crate knows, and left to the operator's log
197            // otherwise.
198            Self::EmptyAnswer { finish_reason } => match finish_reason.as_deref() {
199                Some(FINISH_REASON_LENGTH) => {
200                    "the model stopped at its output limit before it wrote any text".to_owned()
201                }
202                Some(FINISH_REASON_CONTENT_FILTER) => {
203                    "the model provider withheld the answer (content filter)".to_owned()
204                }
205                _ => "the model returned an empty answer".to_owned(),
206            },
207            other => other.to_string(),
208        }
209    }
210
211    /// The `error.type` a run that ended in this records
212    /// (`rpc_span/tool_metrics.rs` lists them).
213    pub(super) fn error_type(&self) -> String {
214        match self {
215            Self::Model(e) => e.error_type(),
216            Self::Fatal { .. } => "tool_fatal".to_owned(),
217            Self::TurnLimit(_) => "turn_limit".to_owned(),
218            Self::Cancelled => "cancelled".to_owned(),
219            Self::AwaitingApproval(_) => "awaiting_approval".to_owned(),
220            Self::Journal(_) => "journal".to_owned(),
221            Self::PinMismatch(_) => "pin_mismatch".to_owned(),
222            Self::Indeterminate { .. } => "indeterminate_call".to_owned(),
223            Self::Budget(_) => "budget_exhausted".to_owned(),
224            Self::EmptyAnswer { .. } => "empty_answer".to_owned(),
225            Self::AmbiguousCalls { .. } => "ambiguous_calls".to_owned(),
226            Self::TooLarge { .. } => "too_large".to_owned(),
227        }
228    }
229
230    /// The failure class a task ends in for this error (the failure-class
231    /// extension; `FailureClass`'s own page says what each means to a
232    /// caller). A provider that may come back is `transient`. An empty
233    /// answer is a bound when the model hit its output limit (`length`:
234    /// retrying the same request hits it again), a refusal when the
235    /// provider's content filter withheld it, and `internal` when the model
236    /// just sent nothing. [`TurnLimit`](Self::TurnLimit) and
237    /// [`Budget`](Self::Budget) are bounds, and so is
238    /// [`TooLarge`](Self::TooLarge). [`Cancelled`](Self::Cancelled)
239    /// ends no task as failed, so what it returns is not sent.
240    pub(super) fn failure_class(&self) -> FailureClass {
241        if self.is_transient() {
242            return FailureClass::Transient;
243        }
244        match self {
245            Self::TurnLimit(_) | Self::Budget(_) | Self::TooLarge { .. } => {
246                FailureClass::BudgetExhausted
247            }
248            Self::EmptyAnswer { finish_reason } => match finish_reason.as_deref() {
249                Some(FINISH_REASON_LENGTH) => FailureClass::BudgetExhausted,
250                Some(FINISH_REASON_CONTENT_FILTER) => FailureClass::PolicyRefusal,
251                _ => FailureClass::Internal,
252            },
253            Self::Model(_)
254            | Self::Fatal { .. }
255            | Self::Cancelled
256            | Self::AwaitingApproval(_)
257            | Self::Journal(_)
258            | Self::PinMismatch(_)
259            | Self::Indeterminate { .. }
260            | Self::AmbiguousCalls { .. } => FailureClass::Internal,
261        }
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    #[test]
270    fn a_provider_that_may_come_back_is_transient_and_nothing_else_is() {
271        let status = |status| {
272            LoopError::Model(ModelError::Status {
273                status,
274                body: String::new(),
275            })
276        };
277        for s in [429, 502, 503, 504] {
278            assert!(status(s).is_transient(), "{s}");
279        }
280        for s in [400, 401, 404, 500, 501] {
281            assert!(!status(s).is_transient(), "{s}");
282        }
283        assert!(LoopError::Model(ModelError::Timeout(Duration::from_secs(1))).is_transient());
284        assert!(LoopError::Model(ModelError::Transport("refused".into())).is_transient());
285        assert!(!LoopError::Model(ModelError::InvalidResponse("x".into())).is_transient());
286        assert!(!LoopError::Model(ModelError::Config("x".into())).is_transient());
287        assert!(!LoopError::Model(ModelError::Other("x".into())).is_transient());
288        assert!(!LoopError::TurnLimit(3).is_transient());
289    }
290
291    /// A rate-limited turn is a 429 to everything outside the loop: transient,
292    /// told to the caller as the status alone (not the body, which can carry
293    /// the account's quota), and recorded as `429` (audit H17).
294    #[test]
295    fn a_rate_limited_turn_is_a_transient_429_without_its_body() {
296        let limited = LoopError::Model(ModelError::RateLimited {
297            retry_after: Some(Duration::from_secs(2)),
298            body: "quota for org-acme exceeded".to_owned(),
299        });
300        assert!(limited.is_transient());
301        assert_eq!(
302            limited.caller_message(),
303            "the model provider answered HTTP 429"
304        );
305        assert_eq!(limited.error_type(), "429");
306    }
307
308    /// What a caller is told, per failure: the status or the kind, never the
309    /// provider's body, URL or response text; the integrator's own words as
310    /// they wrote them.
311    #[test]
312    fn the_caller_is_told_the_kind_of_failure_not_what_the_provider_sent() {
313        let said = |e: LoopError| e.caller_message();
314        assert_eq!(
315            said(LoopError::Model(ModelError::Status {
316                status: 429,
317                body: "quota for org-acme exceeded; prompt: <the user's text>".to_owned(),
318            })),
319            "the model provider answered HTTP 429"
320        );
321        assert_eq!(
322            said(LoopError::Model(ModelError::Transport(
323                "connect to http://10.0.3.7:8080 refused".to_owned()
324            ))),
325            "could not reach the model provider"
326        );
327        assert_eq!(
328            said(LoopError::Model(ModelError::InvalidResponse(
329                "expected a string at line 1 column 9: sk-live-123".to_owned()
330            ))),
331            "the model provider's answer could not be read"
332        );
333        assert_eq!(
334            said(LoopError::Model(ModelError::Config(
335                "https endpoint https://llm.internal without TLS".to_owned()
336            ))),
337            "the model client is misconfigured"
338        );
339        // Words the integrator wrote, and facts the caller needs.
340        assert_eq!(
341            said(LoopError::Model(ModelError::Other(
342                "quota exhausted for this tenant".to_owned()
343            ))),
344            "quota exhausted for this tenant"
345        );
346        assert_eq!(
347            said(LoopError::Fatal {
348                tool: "restart".to_owned(),
349                message: "no such service".to_owned()
350            }),
351            "tool 'restart' failed: no such service"
352        );
353        assert_eq!(
354            said(LoopError::Model(ModelError::Timeout(Duration::from_secs(
355                30
356            )))),
357            "the model provider did not answer within 30s"
358        );
359        // The full text, for the operator, still carries the body.
360        let full = LoopError::Model(ModelError::Status {
361            status: 500,
362            body: "details".to_owned(),
363        });
364        assert!(full.to_string().contains("details"));
365    }
366
367    fn empty(reason: Option<&str>) -> LoopError {
368        LoopError::EmptyAnswer {
369            finish_reason: reason.map(str::to_owned),
370        }
371    }
372
373    /// An empty answer is not transient, is recorded as `empty_answer`, and
374    /// says the reason in the operator's text only when there is one.
375    #[test]
376    fn an_empty_answer_is_recorded_and_worded() {
377        assert!(!empty(Some("length")).is_transient());
378        assert_eq!(empty(None).error_type(), "empty_answer");
379        assert_eq!(empty(Some("stop")).error_type(), "empty_answer");
380        assert_eq!(
381            empty(Some("stop")).to_string(),
382            "the model returned an empty answer (finish_reason: stop)"
383        );
384        assert_eq!(
385            empty(None).to_string(),
386            "the model returned an empty answer"
387        );
388    }
389
390    /// The caller is told the cause when it is one of the two this crate
391    /// knows, and otherwise nothing of what the provider sent as a reason.
392    #[test]
393    fn the_caller_is_told_why_an_answer_is_empty_without_the_providers_words() {
394        assert_eq!(
395            empty(Some("length")).caller_message(),
396            "the model stopped at its output limit before it wrote any text"
397        );
398        assert_eq!(
399            empty(Some("content_filter")).caller_message(),
400            "the model provider withheld the answer (content filter)"
401        );
402        for other in [
403            Some("stop"),
404            Some("account acme is over quota"),
405            Some(""),
406            None,
407        ] {
408            assert_eq!(
409                empty(other).caller_message(),
410                "the model returned an empty answer",
411                "{other:?}"
412            );
413        }
414    }
415
416    /// The failure class of every way a run can end: transient for a provider
417    /// that may come back; a bound for the turn limit, the budget and a reply
418    /// cut at the output limit; a refusal for a content filter; internal for
419    /// the rest.
420    #[test]
421    fn each_error_maps_to_the_failure_class_a_caller_can_act_on() {
422        use FailureClass::{BudgetExhausted, Internal, PolicyRefusal, Transient};
423        let status = |status| {
424            LoopError::Model(ModelError::Status {
425                status,
426                body: String::new(),
427            })
428        };
429        let cases = [
430            (status(503), Transient),
431            (
432                LoopError::Model(ModelError::Timeout(Duration::from_secs(1))),
433                Transient,
434            ),
435            (status(500), Internal),
436            (LoopError::Model(ModelError::Config("x".into())), Internal),
437            (
438                LoopError::Fatal {
439                    tool: "t".into(),
440                    message: "m".into(),
441                },
442                Internal,
443            ),
444            (LoopError::TurnLimit(3), BudgetExhausted),
445            (LoopError::Budget(Exhausted::Time), BudgetExhausted),
446            (LoopError::Cancelled, Internal),
447            (empty(Some("length")), BudgetExhausted),
448            (empty(Some("content_filter")), PolicyRefusal),
449            (empty(Some("stop")), Internal),
450            (empty(Some("Length")), Internal),
451            (empty(None), Internal),
452        ];
453        for (error, class) in cases {
454            assert_eq!(error.failure_class(), class, "{error:?}");
455        }
456    }
457}