Skip to main content

vtcode_core/core/agent/runner/
retry.rs

1use 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
8/// Per-retry-loop context for the agent runner. Held by `&mut` inside
9/// `run_with_retry` so the `on_event` and `operation` callbacks can
10/// share access to the runner's mutable state without splitting borrows.
11struct 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    /// Execute a task with automatic retry on transient failures
58    ///
59    /// Wraps `execute_task` with retry logic using exponential backoff.
60    /// Retries only occur for transient errors (timeouts, network issues, 5xx errors).
61    /// Non-retryable errors (auth failures, invalid requests) fail immediately.
62    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            .with_jitter(RetryPolicy::DEFAULT_JITTER);
72        let metrics = self.tool_registry.metrics_collector();
73        let task_id = task.id.clone();
74        let mut ctx = AgentRetryContext {
75            runner: self,
76            metrics,
77            policy_max_attempts: policy.max_attempts,
78            task_id: task_id.clone(),
79        };
80
81        run_with_retry(
82            &policy,
83            &mut ctx,
84            |ctx, event| match event {
85                RetryEvent::AttemptStart { attempt, max_attempts } => {
86                    info!(
87                        attempt = attempt + 1,
88                        max_attempts,
89                        task_id = %ctx.task_id,
90                        "agent task attempt starting"
91                    );
92                }
93                RetryEvent::Success { attempt } if attempt > 0 => {
94                    ctx.metrics.record_retry_success();
95                    ctx.runner.emit_diagnostic(&task_retry_diagnostic(ctx, TaskRetryDiagnosticStatus::Recovered, attempt + 1, serde_json::json!({})));
96                    info!(
97                        attempt = attempt + 1,
98                        task_id = %ctx.task_id,
99                        "agent task succeeded after retry"
100                    );
101                }
102                RetryEvent::Success { .. } => {}
103                RetryEvent::GiveUp { attempt, error, decision, category_was_retryable } => {
104                    if category_was_retryable && attempt + 1 == ctx.policy_max_attempts {
105                        ctx.metrics.record_retry_exhausted();
106                    }
107                    warn!(
108                        attempt = attempt + 1,
109                        max_attempts = ctx.policy_max_attempts,
110                        task_id = %ctx.task_id,
111                        error = %error,
112                        category = ?decision.category,
113                        "agent task attempt failed (non-retryable)"
114                    );
115                    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())})));
116                }
117                RetryEvent::Backoff { attempt, error, decision, delay, .. } => {
118                    warn!(
119                        attempt = attempt + 1,
120                        max_attempts = ctx.policy_max_attempts,
121                        task_id = %ctx.task_id,
122                        error = %error,
123                        category = ?decision.category,
124                        "agent task attempt failed"
125                    );
126                    ctx.metrics.record_retry_attempt();
127                    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()})));
128                    info!(
129                        delay_ms = delay.as_millis() as u64,
130                        next_attempt = attempt + 2,
131                        task_id = %ctx.task_id,
132                        category = ?decision.category,
133                        "backing off before retry"
134                    );
135                }
136                RetryEvent::Exhausted { last_error } => {
137                    warn!(
138                        task_id = %ctx.task_id,
139                        attempts = ctx.policy_max_attempts,
140                        "agent task failed after all retries"
141                    );
142                    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()))})));
143                }
144            },
145            |ctx| {
146                let task = task.clone();
147                let contexts = contexts.to_vec();
148                let runner = &mut *ctx.runner;
149                Box::pin(async move { Box::pin(runner.execute_task(&task, &contexts)).await })
150            },
151            move |_policy| {
152                VtCodeError::execution(
153                    ErrorCode::ToolExecutionFailed,
154                    format!("agent task '{task_id}' exhausted the retry loop without an error payload"),
155                )
156            },
157        )
158        .await
159    }
160}