Improve Guardian retries and review failure reporting (#44482)

## Why

Transient rate limits can end automatic approval reviews prematurely, and review failures currently report high risk even when no assessment completed.

## What changed

- Retry rate limits and recoverable exhausted-stream errors, while excluding non-transient HTTP failures.
- Preserve server retry delays after stream retries are exhausted and honor them within the review deadline. Scope retry advice to the current turn so reused sessions cannot apply stale delays.
- Keep failed reviews denied, but leave risk and authorization unset and explain that the review could not complete without declaring the action unsafe.

## Testing

Add an integration test covering rate-limit recovery through approval and tool execution, asserting that the action executes exactly once after approval. Update failure assertions to check absent assessment fields and the review-failure explanation.

GitOrigin-RevId: 1163cfde35c6b8eb23b6f24f1f24461b86ded838
This commit is contained in:
jif authored and copyberry committed 2026-09-10 09:50:59 +00:00
1 parent 03f014564d
commit 5d3fe48b08
11 files changed
+226 -42

No files matched your search

@@ -12,7 +12,6 @@ use codex_protocol::protocol::GuardianRiskLevel;
use codex_protocol::protocol::GuardianUserAuthorization;
use codex_protocol::protocol::ReviewDecision;
use crate::GuardianAssessment;
use crate::GuardianReviewError;
use crate::GuardianReviewOutcome;
@@ -23,6 +22,11 @@ const REJECTION_INSTRUCTIONS: &str = concat!(
"or if the user explicitly approves the action after being informed of the risk. ",
"Otherwise, stop and request user input.",
);
const REVIEW_FAILURE_INSTRUCTIONS: &str = concat!(
"The action was not executed because automatic approval review could not be completed. ",
"This is a review failure, not a determination that the action is unsafe. ",
"Do not bypass the approval check; resolve the error or ask the user for guidance.",
);
const TIMEOUT_INSTRUCTIONS: &str = concat!(
"The automatic permission approval review did not finish before its deadline. ",
"Do not assume the action is unsafe based on the timeout alone. ",
@@ -111,12 +115,19 @@ pub fn complete_review(
| GuardianReviewError::Parse { message } => {
analytics.decision = GuardianReviewDecision::Denied;
analytics.terminal_status = GuardianReviewTerminalStatus::FailedClosed;
GuardianAssessment {
risk_level: GuardianRiskLevel::High,
user_authorization: GuardianUserAuthorization::Unknown,
outcome: GuardianAssessmentOutcome::Deny,
rationale: format!("Automatic approval review failed: {message}"),
}
let rationale = format!("Automatic approval review failed: {message}");
// Keep the existing blocked status for client compatibility.
event.status = GuardianAssessmentStatus::Denied;
event.rationale = Some(rationale.clone());
return ReviewCompletion {
decision: ReviewDecision::denied(format!(
"{rationale}\n{REVIEW_FAILURE_INSTRUCTIONS}"
)),
event,
warning: Some(rationale),
analytics,
assessment_outcome: None,
};
}
}
}
+16 -9
View File
@@ -3,6 +3,7 @@
use crate::GuardianAssessment;
use codex_analytics::GuardianReviewFailureReason;
use codex_protocol::protocol::CodexErrorInfo;
use tokio::time::Instant;
#[derive(Debug)]
pub enum GuardianReviewOutcome {
@@ -18,6 +19,7 @@ pub enum GuardianReviewError {
Session {
message: String,
error_info: Option<CodexErrorInfo>,
retry_at: Option<Instant>,
},
Parse {
message: String,
@@ -37,13 +39,16 @@ impl GuardianReviewError {
Self::Session {
message: err.to_string(),
error_info: None,
retry_at: None,
}
}
pub fn session_with_error_info(err: anyhow::Error, error_info: CodexErrorInfo) -> Self {
#[cfg(test)]
pub(crate) fn session_with_error_info(err: anyhow::Error, error_info: CodexErrorInfo) -> Self {
Self::Session {
message: err.to_string(),
error_info: Some(error_info),
retry_at: None,
}
}
@@ -71,6 +76,7 @@ pub enum GuardianReviewSessionOutcome {
SessionFailed {
error: anyhow::Error,
error_info: Option<CodexErrorInfo>,
retry_at: Option<Instant>,
},
TimedOut,
Aborted,
@@ -96,14 +102,15 @@ impl From<GuardianReviewSessionOutcome> for GuardianReviewOutcome {
GuardianReviewSessionOutcome::PromptBuildFailed(error) => {
Self::Error(GuardianReviewError::prompt_build(error))
}
GuardianReviewSessionOutcome::SessionFailed { error, error_info } => {
Self::Error(match error_info {
Some(error_info) => {
GuardianReviewError::session_with_error_info(error, error_info)
}
None => GuardianReviewError::session(error),
})
}
GuardianReviewSessionOutcome::SessionFailed {
error,
error_info,
retry_at,
} => Self::Error(GuardianReviewError::Session {
message: error.to_string(),
error_info,
retry_at,
}),
GuardianReviewSessionOutcome::TimedOut => Self::Error(GuardianReviewError::Timeout),
GuardianReviewSessionOutcome::Aborted => Self::Error(GuardianReviewError::Cancelled),
}
+48 -17
View File
@@ -39,8 +39,14 @@ where
if attempt_count >= max_attempts || !should_retry_guardian_review(&outcome) {
return (outcome, analytics_result);
}
let retry_at = match &outcome {
GuardianReviewOutcome::Error(GuardianReviewError::Session { retry_at, .. }) => {
*retry_at
}
_ => None,
};
if let Some(error) =
wait_before_guardian_retry(attempt_count, deadline, external_cancel).await
wait_before_guardian_retry(attempt_count, retry_at, deadline, external_cancel).await
{
return (GuardianReviewOutcome::Error(error), analytics_result);
}
@@ -50,13 +56,16 @@ where
async fn wait_before_guardian_retry(
attempt_count: i64,
retry_not_before: Option<Instant>,
deadline: Instant,
external_cancel: Option<&CancellationToken>,
) -> Option<GuardianReviewError> {
let exponential_delay = 200.0 * 2.0_f64.powi(attempt_count.saturating_sub(1) as i32);
let jitter = rand::rng().random_range(0.9..1.1);
let retry_delay = Duration::from_millis((exponential_delay * jitter) as u64);
let retry_at = (Instant::now() + retry_delay).min(deadline);
let retry_at = (Instant::now() + retry_delay)
.max(retry_not_before.unwrap_or_else(Instant::now))
.min(deadline);
tokio::select! {
_ = sleep_until(retry_at) => {
(Instant::now() >= deadline).then_some(GuardianReviewError::Timeout)
@@ -72,21 +81,43 @@ async fn wait_before_guardian_retry(
}
fn should_retry_guardian_review(outcome: &GuardianReviewOutcome) -> bool {
matches!(
outcome,
GuardianReviewOutcome::Error(
GuardianReviewError::Session {
error_info: Some(
CodexErrorInfo::ServerOverloaded
| CodexErrorInfo::HttpConnectionFailed { .. }
| CodexErrorInfo::ResponseStreamConnectionFailed { .. }
| CodexErrorInfo::InternalServerError
| CodexErrorInfo::ResponseStreamDisconnected { .. }
),
..
} | GuardianReviewError::Parse { .. }
)
)
match outcome {
GuardianReviewOutcome::Error(GuardianReviewError::Parse { .. }) => true,
GuardianReviewOutcome::Error(GuardianReviewError::Session {
error_info: Some(error),
..
}) => match error {
CodexErrorInfo::RateLimitExceeded
| CodexErrorInfo::ServerOverloaded
| CodexErrorInfo::InternalServerError => true,
CodexErrorInfo::HttpConnectionFailed { http_status_code }
| CodexErrorInfo::ResponseStreamConnectionFailed { http_status_code }
| CodexErrorInfo::ResponseStreamDisconnected { http_status_code }
| CodexErrorInfo::ResponseTooManyFailedAttempts { http_status_code } => {
matches!(http_status_code, None | Some(408 | 429 | 500..=599))
}
CodexErrorInfo::ContextWindowExceeded
| CodexErrorInfo::SessionBudgetExceeded
| CodexErrorInfo::UsageLimitExceeded
| CodexErrorInfo::CyberPolicy
| CodexErrorInfo::MisalignmentPolicyViolation
| CodexErrorInfo::Unauthorized
| CodexErrorInfo::BadRequest
| CodexErrorInfo::SandboxError
| CodexErrorInfo::ActiveTurnNotSteerable { .. }
| CodexErrorInfo::ThreadRollbackFailed
| CodexErrorInfo::Other => false,
},
GuardianReviewOutcome::Completed(_)
| GuardianReviewOutcome::Error(
GuardianReviewError::PromptBuild { .. }
| GuardianReviewError::Session {
error_info: None, ..
}
| GuardianReviewError::Timeout
| GuardianReviewError::Cancelled,
) => false,
}
}
#[cfg(test)]
@@ -114,6 +114,7 @@ async fn guardian_review_retry_wait_honors_cancellation() {
let error = wait_before_guardian_retry(
/*attempt_count*/ 1,
/*retry_not_before*/ None,
Instant::now() + Duration::from_secs(/*secs*/ 1),
Some(&cancel_token),
)
@@ -126,6 +127,7 @@ async fn guardian_review_retry_wait_honors_cancellation() {
async fn guardian_review_retry_wait_honors_deadline() {
let error = wait_before_guardian_retry(
/*attempt_count*/ 1,
/*retry_not_before*/ None,
Instant::now(),
/*external_cancel*/ None,
)