vtcode_core/core/agent/runner/
retry.rs1use super::AgentRunner;
2use crate::core::agent::task::{ContextItem, Task, TaskResults};
3use crate::error::{ErrorCode, Result as VtCodeResult, VtCodeError};
4use crate::retry::{RetryEvent, RetryPolicy, run_with_retry};
5use tracing::{info, warn};
6use vtcode_commons::diagnostics::{Diagnostic, DiagnosticSeverity, redact_diagnostic};
7
8struct AgentRetryContext<'a> {
12 runner: &'a mut AgentRunner,
13 metrics: std::sync::Arc<crate::metrics::MetricsCollector>,
14 policy_max_attempts: u32,
15 task_id: String,
16}
17
18#[derive(Clone, Copy)]
19enum TaskRetryDiagnosticStatus {
20 Retrying,
21 Recovered,
22 Stopped,
23}
24
25fn task_retry_diagnostic(
26 ctx: &AgentRetryContext<'_>,
27 status: TaskRetryDiagnosticStatus,
28 attempt: u32,
29 evidence: serde_json::Value,
30) -> Diagnostic {
31 let (severity, code, summary) = match status {
32 TaskRetryDiagnosticStatus::Retrying => (
33 DiagnosticSeverity::Warning,
34 "agent.retrying",
35 "The task failed. Retrying with the existing retry budget; cancel to stop.",
36 ),
37 TaskRetryDiagnosticStatus::Recovered => {
38 (DiagnosticSeverity::Info, "agent.retry_recovered", "The task recovered after retrying.")
39 }
40 TaskRetryDiagnosticStatus::Stopped => (
41 DiagnosticSeverity::Error,
42 "agent.retry_stopped",
43 "The task could not recover. Review Details before retrying.",
44 ),
45 };
46 redact_diagnostic(&Diagnostic {
47 severity, code: code.into(), summary: summary.into(), correlation_id: format!("agent-retry:{}", ctx.task_id),
48 agent_details: serde_json::json!({
49 "task_id": ctx.task_id, "provider": ctx.runner.provider_client.name(), "model": ctx.runner.model,
50 "attempt": attempt, "max_attempts": ctx.policy_max_attempts,
51 "remaining_allowance": ctx.policy_max_attempts.saturating_sub(attempt), "allowance_scope": "task_retries", "evidence": evidence,
52 }).to_string(), actions: Vec::new(),
53 })
54}
55
56impl AgentRunner {
57 pub async fn execute_task_with_retry(
63 &mut self,
64 task: &Task,
65 contexts: &[ContextItem],
66 max_retries: u32,
67 ) -> VtCodeResult<TaskResults> {
68 use std::time::Duration;
69
70 let policy = RetryPolicy::from_retries(max_retries, Duration::from_secs(2), Duration::from_secs(30), 2.0);
71 let metrics = self.tool_registry.metrics_collector();
72 let task_id = task.id.clone();
73 let mut ctx = AgentRetryContext {
74 runner: self,
75 metrics,
76 policy_max_attempts: policy.max_attempts,
77 task_id: task_id.clone(),
78 };
79
80 run_with_retry(
81 &policy,
82 &mut ctx,
83 |ctx, event| match event {
84 RetryEvent::AttemptStart { attempt, max_attempts } => {
85 info!(
86 attempt = attempt + 1,
87 max_attempts,
88 task_id = %ctx.task_id,
89 "agent task attempt starting"
90 );
91 }
92 RetryEvent::Success { attempt } if attempt > 0 => {
93 ctx.metrics.record_retry_success();
94 ctx.runner.emit_diagnostic(&task_retry_diagnostic(ctx, TaskRetryDiagnosticStatus::Recovered, attempt + 1, serde_json::json!({})));
95 info!(
96 attempt = attempt + 1,
97 task_id = %ctx.task_id,
98 "agent task succeeded after retry"
99 );
100 }
101 RetryEvent::Success { .. } => {}
102 RetryEvent::GiveUp { attempt, error, decision, category_was_retryable } => {
103 if category_was_retryable && attempt + 1 == ctx.policy_max_attempts {
104 ctx.metrics.record_retry_exhausted();
105 }
106 warn!(
107 attempt = attempt + 1,
108 max_attempts = ctx.policy_max_attempts,
109 task_id = %ctx.task_id,
110 error = %error,
111 category = ?decision.category,
112 "agent task attempt failed (non-retryable)"
113 );
114 ctx.runner.emit_diagnostic(&task_retry_diagnostic(ctx, TaskRetryDiagnosticStatus::Stopped, attempt + 1, serde_json::json!({"category": format!("{:?}", decision.category), "error": vtcode_commons::sanitizer::sanitize_provider_diagnostic(error.to_string())})));
115 }
116 RetryEvent::Backoff { attempt, error, decision, delay, .. } => {
117 warn!(
118 attempt = attempt + 1,
119 max_attempts = ctx.policy_max_attempts,
120 task_id = %ctx.task_id,
121 error = %error,
122 category = ?decision.category,
123 "agent task attempt failed"
124 );
125 ctx.metrics.record_retry_attempt();
126 ctx.runner.emit_diagnostic(&task_retry_diagnostic(ctx, TaskRetryDiagnosticStatus::Retrying, attempt + 1, serde_json::json!({"category": format!("{:?}", decision.category), "error": vtcode_commons::sanitizer::sanitize_provider_diagnostic(error.to_string()), "delay_ms": delay.as_millis()})));
127 info!(
128 delay_ms = delay.as_millis() as u64,
129 next_attempt = attempt + 2,
130 task_id = %ctx.task_id,
131 category = ?decision.category,
132 "backing off before retry"
133 );
134 }
135 RetryEvent::Exhausted { last_error } => {
136 warn!(
137 task_id = %ctx.task_id,
138 attempts = ctx.policy_max_attempts,
139 "agent task failed after all retries"
140 );
141 ctx.runner.emit_diagnostic(&task_retry_diagnostic(ctx, TaskRetryDiagnosticStatus::Stopped, ctx.policy_max_attempts, serde_json::json!({"error": last_error.map(|error| vtcode_commons::sanitizer::sanitize_provider_diagnostic(error.to_string()))})));
142 }
143 },
144 |ctx| {
145 let task = task.clone();
146 let contexts = contexts.to_vec();
147 let runner = &mut *ctx.runner;
148 Box::pin(async move { Box::pin(runner.execute_task(&task, &contexts)).await })
149 },
150 move |_policy| {
151 VtCodeError::execution(
152 ErrorCode::ToolExecutionFailed,
153 format!("agent task '{task_id}' exhausted the retry loop without an error payload"),
154 )
155 },
156 )
157 .await
158 }
159}