a2a_protocol_server/tool_loop/
loop_error.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct ApprovalNeeded {
20 pub request_id: String,
23 pub summary: String,
25 pub digest: String,
27 pub tool: String,
29 pub call_id: String,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum LoopError {
37 AwaitingApproval(Box<ApprovalNeeded>),
40 Journal(String),
43 PinMismatch(String),
46 Indeterminate {
50 tool: String,
52 call_id: String,
54 },
55 Model(ModelError),
57 Fatal {
59 tool: String,
61 message: String,
63 },
64 TurnLimit(usize),
66 Cancelled,
68 Budget(Exhausted),
71 EmptyAnswer {
76 finish_reason: Option<String>,
78 },
79 AmbiguousCalls {
83 id: String,
85 },
86 TooLarge {
89 bytes: usize,
91 limit: usize,
93 },
94}
95
96const 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 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 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 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 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 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 #[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 #[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 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 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 #[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 #[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 #[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}