1use std::future::Future;
11use std::result::Result as StdResult;
12use std::time::Duration;
13
14use crate::error::{ErrorCategory, VtCodeError};
15use crate::retry_after::retry_after_from_llm_metadata;
16use crate::tools::registry::ToolExecutionError;
17use crate::tools::tool_intent::is_command_tool;
18use crate::tools::unified_error::UnifiedToolError;
19use vtcode_commons::llm::LLMError;
20use vtcode_commons::misconfiguration::detect_misconfiguration;
21
22pub use vtcode_commons::retry::{RetryDecision, RetryPolicy};
23
24pub trait RetryPolicyCoreExt {
29 fn decision_for_vtcode_error(
30 &self,
31 error: &VtCodeError,
32 attempt_index: u32,
33 tool_name: Option<&str>,
34 ) -> RetryDecision;
35
36 fn decision_for_anyhow(&self, error: &anyhow::Error, attempt_index: u32, tool_name: Option<&str>) -> RetryDecision;
37
38 fn decision_for_llm_error(&self, error: &LLMError, attempt_index: u32) -> RetryDecision;
39
40 fn decision_for_tool_error(&self, error: &UnifiedToolError, attempt_index: u32) -> RetryDecision;
41
42 fn decision_for_tool_execution_error(&self, error: &ToolExecutionError, attempt_index: u32) -> RetryDecision;
43
44 fn step_for_vtcode_error(&self, error: VtCodeError, attempt_index: u32, tool_name: Option<&str>) -> RetryStep;
51
52 fn apply_to_tool_execution_error(
53 &self,
54 error: ToolExecutionError,
55 attempt_index: u32,
56 tool_name: Option<&str>,
57 ) -> ToolExecutionError;
58}
59
60impl RetryPolicyCoreExt for RetryPolicy {
61 fn decision_for_vtcode_error(
62 &self,
63 error: &VtCodeError,
64 attempt_index: u32,
65 tool_name: Option<&str>,
66 ) -> RetryDecision {
67 if error.is_misconfiguration() {
69 return misconfiguration_decision(error.category, error.retry_after());
70 }
71 decision_for_category_with_tool(self, error.category, attempt_index, error.retry_after(), tool_name)
72 }
73
74 fn decision_for_anyhow(&self, error: &anyhow::Error, attempt_index: u32, tool_name: Option<&str>) -> RetryDecision {
75 if let Some(vtcode_error) = error.downcast_ref::<VtCodeError>() {
76 return self.decision_for_vtcode_error(vtcode_error, attempt_index, tool_name);
77 }
78 if let Some(llm_error) = error.downcast_ref::<LLMError>() {
79 return self.decision_for_llm_error(llm_error, attempt_index);
80 }
81 if let Some(tool_error) = error.downcast_ref::<UnifiedToolError>() {
82 let category = tool_error.category();
83 if detect_misconfiguration(category, &unified_tool_text(tool_error)).is_some() {
84 return misconfiguration_decision(category, None);
85 }
86 let effective_tool = tool_name.or_else(|| {
88 tool_error
89 .debug_context
90 .as_ref()
91 .map(|ctx| ctx.tool_name.as_str())
92 .filter(|name| !name.is_empty())
93 });
94 return decision_for_category_with_tool(self, category, attempt_index, None, effective_tool);
95 }
96
97 let category = vtcode_commons::classify_anyhow_error(error);
98 let message = format!("{error:#}");
99 if detect_misconfiguration(category, &message).is_some() {
100 return misconfiguration_decision(category, None);
101 }
102 decision_for_category_with_tool(self, category, attempt_index, None, tool_name)
103 }
104
105 fn decision_for_llm_error(&self, error: &LLMError, attempt_index: u32) -> RetryDecision {
106 let retry_after = error.metadata().and_then(retry_after_from_llm_metadata);
107 let category = ErrorCategory::from(error);
108 if vtcode_commons::detect_misconfiguration_in_llm_error(error).is_some() {
109 return misconfiguration_decision(category, retry_after);
110 }
111 decision_for_category_with_tool(self, category, attempt_index, retry_after, None)
112 }
113
114 fn decision_for_tool_error(&self, error: &UnifiedToolError, attempt_index: u32) -> RetryDecision {
115 let category = error.category();
116 if detect_misconfiguration(category, &unified_tool_text(error)).is_some() {
117 return misconfiguration_decision(category, None);
118 }
119 let tool_name = error
120 .debug_context
121 .as_ref()
122 .map(|ctx| ctx.tool_name.as_str())
123 .filter(|tool_name| !tool_name.is_empty());
124 decision_for_category_with_tool(self, category, attempt_index, None, tool_name)
125 }
126
127 fn decision_for_tool_execution_error(&self, error: &ToolExecutionError, attempt_index: u32) -> RetryDecision {
128 if error.patch_failure.is_some() {
129 return RetryDecision {
130 category: error.category,
131 retryable: false,
132 delay: None,
133 retry_after: None,
134 };
135 }
136 if detect_misconfiguration(error.category, &tool_execution_text(error)).is_some() {
137 return misconfiguration_decision(error.category, error.retry_after());
138 }
139 decision_for_category_with_tool(
140 self,
141 error.category,
142 attempt_index,
143 error.retry_after(),
144 Some(error.tool_name.as_str()),
145 )
146 }
147
148 fn step_for_vtcode_error(&self, error: VtCodeError, attempt_index: u32, tool_name: Option<&str>) -> RetryStep {
149 let error = error.with_misconfiguration_guidance();
152 let decision = self.decision_for_vtcode_error(&error, attempt_index, tool_name);
153 if decision.retryable {
154 let delay = decision.delay.unwrap_or_else(|| self.delay_for_attempt(attempt_index));
155 RetryStep::Backoff { delay, decision, error }
156 } else {
157 RetryStep::GiveUp { decision, error }
158 }
159 }
160
161 fn apply_to_tool_execution_error(
162 &self,
163 error: ToolExecutionError,
164 attempt_index: u32,
165 tool_name: Option<&str>,
166 ) -> ToolExecutionError {
167 if error.patch_failure.is_some() {
168 return error;
169 }
170 if let Some(guidance) = detect_misconfiguration(error.category, &tool_execution_text(&error)) {
171 let decision = misconfiguration_decision(error.category, error.retry_after());
172 let mut guided = error.with_retry_decision(decision);
173 let mut suggestions = vec![std::borrow::Cow::Owned(guidance.user_message())];
175 suggestions.append(&mut guided.recovery_suggestions);
176 guided.recovery_suggestions = suggestions;
177 guided.retryable = false;
178 guided.is_recoverable = false;
179 guided.circuit_breaker_impact = false;
180 return guided;
181 }
182 let decision = decision_for_category_with_tool(
183 self,
184 error.category,
185 attempt_index,
186 error.retry_after(),
187 tool_name.or(Some(error.tool_name.as_str())),
188 );
189 error.with_retry_decision(decision)
190 }
191}
192
193fn decision_for_category_with_tool(
194 policy: &RetryPolicy,
195 category: ErrorCategory,
196 attempt_index: u32,
197 retry_after: Option<Duration>,
198 tool_name: Option<&str>,
199) -> RetryDecision {
200 if is_non_retryable_command_timeout(category, tool_name) {
201 return RetryDecision {
202 category,
203 retryable: false,
204 delay: None,
205 retry_after,
206 };
207 }
208
209 policy.decision_for_category(category, attempt_index, retry_after)
210}
211
212fn category_was_retryable(error: &VtCodeError) -> bool {
213 error.category.is_retryable() && !error.is_misconfiguration()
214}
215
216fn misconfiguration_decision(category: ErrorCategory, retry_after: Option<Duration>) -> RetryDecision {
219 RetryDecision {
220 category,
221 retryable: false,
222 delay: None,
223 retry_after,
224 }
225}
226
227pub(crate) fn is_non_retryable_command_timeout(category: ErrorCategory, tool_name: Option<&str>) -> bool {
231 matches!(category, ErrorCategory::Timeout) && tool_name.is_some_and(is_command_tool)
232}
233
234fn unified_tool_text(error: &UnifiedToolError) -> String {
235 let mut text = error.user_message.clone();
236 if let Some(source) = error.source.as_ref() {
237 text.push('\n');
238 text.push_str(&format!("{source:#}"));
239 }
240 text
241}
242
243fn tool_execution_text(error: &ToolExecutionError) -> String {
244 let mut text = error.message.clone();
245 if let Some(original) = error.original_error.as_deref() {
246 text.push('\n');
247 text.push_str(original);
248 }
249 text
250}
251
252#[derive(Debug)]
257#[must_use = "retry steps must be handled before another attempt"]
258pub enum RetryStep {
259 Backoff {
261 delay: Duration,
262 decision: RetryDecision,
263 error: VtCodeError,
264 },
265 GiveUp {
267 decision: RetryDecision,
268 error: VtCodeError,
269 },
270}
271
272#[derive(Debug)]
281pub enum RetryEvent<'a> {
282 AttemptStart { attempt: u32, max_attempts: u32 },
284 Success { attempt: u32 },
286 GiveUp {
288 attempt: u32,
289 error: &'a VtCodeError,
290 decision: &'a RetryDecision,
291 category_was_retryable: bool,
292 },
293 Backoff {
296 attempt: u32,
297 error: &'a VtCodeError,
298 decision: &'a RetryDecision,
299 delay: Duration,
300 category_was_retryable: bool,
301 },
302 Exhausted { last_error: Option<&'a VtCodeError> },
305}
306
307#[allow(
327 clippy::too_many_arguments,
328 reason = "Intentional compatibility, platform, or test-only suppression."
329)]
330pub async fn run_with_retry<T, E, S, F, OnEvent, Synthesize>(
331 policy: &RetryPolicy,
332 state: &mut S,
333 mut on_event: OnEvent,
334 mut operation: F,
335 synthesize_exhausted_error: Synthesize,
336) -> crate::error::Result<T>
337where
338 F: for<'a> FnMut(&'a mut S) -> std::pin::Pin<Box<dyn Future<Output = StdResult<T, E>> + Send + 'a>>,
339 E: Into<VtCodeError>,
340 OnEvent: FnMut(&mut S, RetryEvent<'_>),
341 Synthesize: FnOnce(&RetryPolicy) -> VtCodeError,
342{
343 use tokio::time::sleep;
344
345 let mut last_error: Option<VtCodeError> = None;
346 for attempt in 0..policy.max_attempts {
347 on_event(state, RetryEvent::AttemptStart { attempt, max_attempts: policy.max_attempts });
348 match operation(state).await {
349 Ok(value) => {
350 on_event(state, RetryEvent::Success { attempt });
351 return Ok(value);
352 }
353 Err(err) => {
354 let err: VtCodeError = err.into();
355 let category_was_retryable = category_was_retryable(&err);
356 let step = policy.step_for_vtcode_error(err, attempt, None);
357 match step {
358 RetryStep::GiveUp { decision, error } => {
359 on_event(
360 state,
361 RetryEvent::GiveUp {
362 attempt,
363 error: &error,
364 decision: &decision,
365 category_was_retryable,
366 },
367 );
368 return Err(error);
369 }
370 RetryStep::Backoff { delay, decision, error } => {
371 on_event(
372 state,
373 RetryEvent::Backoff {
374 attempt,
375 error: &error,
376 decision: &decision,
377 delay,
378 category_was_retryable,
379 },
380 );
381 last_error = Some(error);
382 sleep(delay).await;
383 }
384 }
385 }
386 }
387 }
388 let final_error = last_error.unwrap_or_else(|| synthesize_exhausted_error(policy));
389 on_event(state, RetryEvent::Exhausted { last_error: Some(&final_error) });
390 Err(final_error)
391}
392
393pub fn decision_for_vtcode_error(
394 error: &VtCodeError,
395 attempt_index: u32,
396 tool_name: Option<&str>,
397 policy_override: Option<&RetryPolicy>,
398) -> RetryDecision {
399 let policy = policy_override.unwrap_or(&RetryPolicy::DEFAULT);
400 policy.decision_for_vtcode_error(error, attempt_index, tool_name)
401}
402
403pub fn decision_for_anyhow_error(
404 error: &anyhow::Error,
405 attempt_index: u32,
406 tool_name: Option<&str>,
407 policy_override: Option<&RetryPolicy>,
408) -> RetryDecision {
409 let policy = policy_override.unwrap_or(&RetryPolicy::DEFAULT);
410 policy.decision_for_anyhow(error, attempt_index, tool_name)
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416 use crate::config::constants::tools;
417 use crate::error::{ErrorCode, VtCodeError};
418 use vtcode_commons::llm::LLMErrorMetadata;
419
420 #[test]
421 fn non_retryable_categories_stop_immediately() {
422 let policy = RetryPolicy::from_retries(2, Duration::from_secs(1), Duration::from_secs(8), 2.0);
423 let err = VtCodeError::security(ErrorCode::PermissionDenied, "blocked by policy");
424
425 let decision = policy.decision_for_vtcode_error(&err, 0, None);
426 assert_eq!(decision.category, ErrorCategory::PolicyViolation);
427 assert!(!decision.retryable);
428 assert!(decision.delay.is_none());
429 }
430
431 #[test]
432 fn retry_after_header_overrides_backoff_delay() {
433 let policy = RetryPolicy::from_retries(3, Duration::from_secs(1), Duration::from_secs(8), 2.0);
434 let err = LLMError::RateLimit {
435 metadata: Some(LLMErrorMetadata::new(
436 "Anthropic",
437 Some(429),
438 Some("rate_limit_error".to_string()),
439 None,
440 None,
441 Some("7".to_string()),
442 Some("too many requests".to_string()),
443 )),
444 };
445
446 let decision = policy.decision_for_llm_error(&err, 0);
447 assert!(decision.retryable);
448 assert_eq!(decision.retry_after, Some(Duration::from_secs(7)));
449 assert_eq!(decision.delay, Some(Duration::from_secs(7)));
450 }
451
452 #[test]
453 fn quota_exhaustion_is_not_retryable() {
454 let policy = RetryPolicy::from_retries(3, Duration::from_secs(1), Duration::from_secs(8), 2.0);
455 let err = LLMError::RateLimit {
456 metadata: Some(LLMErrorMetadata::new(
457 "OpenAI",
458 Some(429),
459 Some("insufficient_quota".to_string()),
460 None,
461 None,
462 None,
463 Some("quota exceeded".to_string()),
464 )),
465 };
466
467 let decision = policy.decision_for_llm_error(&err, 0);
468 assert_eq!(decision.category, ErrorCategory::ResourceExhausted);
469 assert!(!decision.retryable);
470 }
471
472 #[test]
473 fn anyhow_fallback_uses_shared_classifier() {
474 let policy = RetryPolicy::from_retries(1, Duration::from_secs(1), Duration::from_secs(8), 2.0);
475
476 let decision = policy.decision_for_anyhow(&anyhow::anyhow!("HTTP 503 Service Unavailable"), 0, None);
477 assert_eq!(decision.category, ErrorCategory::ServiceUnavailable);
478 assert!(decision.retryable);
479 assert_eq!(decision.delay, Some(Duration::from_secs(1)));
480 }
481
482 #[test]
483 fn anyhow_prefers_typed_llm_errors() {
484 let policy = RetryPolicy::from_retries(3, Duration::from_secs(1), Duration::from_secs(8), 2.0);
485 let err = anyhow::Error::new(LLMError::RateLimit {
486 metadata: Some(LLMErrorMetadata::new(
487 "Anthropic",
488 Some(429),
489 Some("rate_limit_error".to_string()),
490 None,
491 None,
492 Some("9".to_string()),
493 Some("too many requests".to_string()),
494 )),
495 });
496
497 let decision = policy.decision_for_anyhow(&err, 0, None);
498 assert!(decision.retryable);
499 assert_eq!(decision.retry_after, Some(Duration::from_secs(9)));
500 assert_eq!(decision.delay, Some(Duration::from_secs(9)));
501 }
502
503 #[test]
504 fn canonical_exec_aliases_are_command_tools() {
505 for alias in [
506 tools::RUN_PTY_CMD,
507 tools::EXEC_COMMAND,
508 tools::WRITE_STDIN,
509 tools::UNIFIED_EXEC,
510 "shell",
511 "bash",
512 "container.exec",
513 ] {
514 assert!(is_command_tool(alias), "expected {alias} to be a command tool");
515 }
516 }
517
518 #[test]
519 fn typed_tool_timeout_for_command_tools_is_not_retryable() {
520 let policy = RetryPolicy::from_retries(2, Duration::from_secs(1), Duration::from_secs(8), 2.0);
521 let err = UnifiedToolError::new(crate::tools::unified_error::UnifiedErrorKind::Timeout, "timed out")
522 .with_tool_name(tools::RUN_PTY_CMD);
523
524 let decision = policy.decision_for_tool_error(&err, 0);
525 assert_eq!(decision.category, ErrorCategory::Timeout);
526 assert!(!decision.retryable);
527 }
528
529 #[test]
530 fn anyhow_typed_tool_timeout_uses_fallback_tool_name() {
531 let policy = RetryPolicy::from_retries(2, Duration::from_secs(1), Duration::from_secs(8), 2.0);
532 let err = anyhow::Error::new(UnifiedToolError::new(
533 crate::tools::unified_error::UnifiedErrorKind::Timeout,
534 "timed out",
535 ));
536
537 let decision = policy.decision_for_anyhow(&err, 0, Some(tools::RUN_PTY_CMD));
538 assert_eq!(decision.category, ErrorCategory::Timeout);
539 assert!(!decision.retryable);
540 }
541
542 #[test]
543 fn command_timeouts_do_not_retry() {
544 let policy = RetryPolicy::from_retries(2, Duration::from_secs(1), Duration::from_secs(8), 2.0);
545 let err = VtCodeError::new(ErrorCategory::Timeout, ErrorCode::Timeout, "timed out");
546
547 let decision = policy.decision_for_vtcode_error(&err, 0, Some(tools::RUN_PTY_CMD));
548 assert_eq!(decision.category, ErrorCategory::Timeout);
549 assert!(!decision.retryable);
550 }
551
552 #[tokio::test]
553 async fn run_with_retry_returns_first_success() {
554 use std::sync::Arc;
555 use std::sync::atomic::{AtomicU32, Ordering};
556 let policy = RetryPolicy::from_retries(3, Duration::from_millis(0), Duration::from_millis(1), 2.0);
557 let attempts = Arc::new(AtomicU32::new(0));
558 let attempts_for_op = attempts.clone();
559 let result: crate::error::Result<String> = run_with_retry(
560 &policy,
561 &mut (),
562 |_: &mut (), _| {},
563 |_| {
564 let attempts = attempts_for_op.clone();
565 Box::pin(async move {
566 let n = attempts.fetch_add(1, Ordering::SeqCst) + 1;
567 if n < 2 {
568 Err(VtCodeError::network(ErrorCode::ConnectionFailed, "transient"))
569 } else {
570 Ok("ok".to_string())
571 }
572 })
573 },
574 |_: &RetryPolicy| VtCodeError::execution(ErrorCode::ToolExecutionFailed, "exhausted"),
575 )
576 .await;
577 assert_eq!(result.unwrap(), "ok");
578 assert_eq!(attempts.load(Ordering::SeqCst), 2);
579 }
580
581 #[tokio::test]
582 async fn run_with_retry_surfaces_give_up_immediately() {
583 use std::sync::Arc;
584 use std::sync::atomic::{AtomicU32, Ordering};
585 let policy = RetryPolicy::from_retries(5, Duration::from_millis(0), Duration::from_millis(1), 2.0);
586 let attempts = Arc::new(AtomicU32::new(0));
587 let attempts_for_op = attempts.clone();
588 let result: crate::error::Result<String> = run_with_retry(
589 &policy,
590 &mut (),
591 |_: &mut (), _| {},
592 |_| {
593 let attempts = attempts_for_op.clone();
594 Box::pin(async move {
595 attempts.fetch_add(1, Ordering::SeqCst);
596 Err::<String, _>(VtCodeError::input(ErrorCode::InvalidArgument, "bad input"))
597 })
598 },
599 |_: &RetryPolicy| VtCodeError::execution(ErrorCode::ToolExecutionFailed, "exhausted"),
600 )
601 .await;
602 assert!(result.is_err());
603 assert_eq!(attempts.load(Ordering::SeqCst), 1, "GiveUp should short-circuit retries");
604 }
605
606 #[test]
607 fn misconfiguration_fails_fast_with_guidance() {
608 let policy = RetryPolicy::from_retries(5, Duration::from_secs(1), Duration::from_secs(8), 2.0);
609 let err = VtCodeError::new(
610 ErrorCategory::Authentication,
611 ErrorCode::AuthenticationFailed,
612 "Authentication failed: invalid api key",
613 );
614
615 let decision = policy.decision_for_vtcode_error(&err, 0, None);
616 assert!(!decision.retryable);
617 assert!(decision.delay.is_none());
618
619 let step = policy.step_for_vtcode_error(err, 0, None);
620 match step {
621 RetryStep::GiveUp { error, .. } => {
622 assert!(error.message.contains("Check settings/config first"));
623 assert!(error.message.contains("before retrying"));
624 }
625 RetryStep::Backoff { .. } => panic!("misconfiguration must not back off"),
626 }
627 }
628
629 #[test]
630 fn misconfiguration_model_error_does_not_retry() {
631 let policy = RetryPolicy::from_retries(5, Duration::from_secs(1), Duration::from_secs(8), 2.0);
632 let err = VtCodeError::input(ErrorCode::InvalidArgument, "unknown model 'gpt-99' in agent.model");
633
634 assert!(err.is_misconfiguration());
635 let decision = policy.decision_for_vtcode_error(&err, 0, None);
636 assert!(!decision.retryable);
637 }
638
639 #[test]
640 fn transient_errors_still_retry_without_guidance() {
641 let policy = RetryPolicy::from_retries(3, Duration::from_secs(1), Duration::from_secs(8), 2.0);
642 let err = VtCodeError::network(ErrorCode::ConnectionFailed, "connection reset by peer");
643
644 assert!(!err.is_misconfiguration());
645 let decision = policy.decision_for_vtcode_error(&err, 0, None);
646 assert!(decision.retryable);
647 }
648
649 #[test]
650 fn misconfiguration_does_not_count_as_retryable_category() {
651 let err = VtCodeError::network(ErrorCode::ConnectionFailed, "invalid provider_overrides configuration");
652
653 assert!(err.is_misconfiguration());
654 assert!(!category_was_retryable(&err));
655 }
656
657 #[test]
658 fn llm_auth_error_is_misconfiguration() {
659 let policy = RetryPolicy::from_retries(3, Duration::from_secs(1), Duration::from_secs(8), 2.0);
660 let err = LLMError::Authentication {
661 message: "invalid api key".to_string(),
662 metadata: None,
663 };
664
665 let decision = policy.decision_for_llm_error(&err, 0);
666 assert!(!decision.retryable);
667 assert_eq!(decision.category, ErrorCategory::Authentication);
668 }
669
670 #[test]
671 fn tool_execution_misconfiguration_prepends_guidance() {
672 use crate::tools::registry::ToolErrorType;
673
674 let policy = RetryPolicy::from_retries(3, Duration::from_secs(1), Duration::from_secs(8), 2.0);
675 let err = ToolExecutionError::new(
676 "test_tool".to_string(),
677 ToolErrorType::ExecutionError,
678 "unknown model 'foo' in agent.model".to_string(),
679 );
680
681 let guided = policy.apply_to_tool_execution_error(err, 0, None);
682 assert!(!guided.retryable);
683 assert!(!guided.is_recoverable);
684 assert!(!guided.circuit_breaker_impact);
685 assert!(
686 guided
687 .recovery_suggestions
688 .first()
689 .is_some_and(|s| s.contains("Check settings/config first"))
690 );
691 }
692}