Extract Guardian review evaluation from approval handling (#64812)

## What changed

Move review preparation, retries, and cached approval handling into
`ReviewRequest::evaluate`. Return the outcome, report, analytics, and
evidence to the synchronous reviewer so it can finish reporting and
produce the approval decision.

GitOrigin-RevId: 3db2b9dadd6c6f15f0e66995f26705ca5c29e6a3
This commit is contained in:
felixxia-oai
2026-11-30 21:34:37 +00:00
committed by copyberry
parent 7d60863a4a
commit fd36cdebbe
+116 -84
View File
@@ -92,6 +92,114 @@ pub trait ReviewHost: Clone + Send + Sync + 'static {
) -> impl Future<Output = ()> + Send;
}
struct EvaluatedReview<H: ReviewHost> {
prepared: Arc<H::Prepared>,
report: ReviewReport,
outcome: GuardianReviewOutcome,
analytics: GuardianReviewAnalyticsResult,
evidence: Option<H::Evidence>,
}
impl<H: ReviewHost> ReviewRequest<'_, H> {
async fn evaluate(
&self,
reason: GuardianReviewReason,
async_approval: Option<ExtensionFuture<'_, CachedApprovalContext>>,
deadline: ReviewDeadline,
) -> Result<EvaluatedReview<H>, ReviewDecision> {
let host_deadline = self.host_deadline;
let (prepared, report) = self
.host
.prepare(self.approval_id, reason, deadline, &self.cancellation)
.await?;
if let Some(event) = report.started_event() {
self.host.emit(EventMsg::GuardianAssessment(event)).await;
}
let prepared = Arc::new(prepared);
let cancellation = self.cancellation.child_token();
let attempts = Arc::new(AtomicI64::new(/*v*/ 0));
let mut review = Box::pin({
let host = self.host.clone();
let prepared = Arc::clone(&prepared);
let cancellation = cancellation.clone();
let attempts = Arc::clone(&attempts);
let telemetry = self.telemetry.clone();
async move {
crate::run_with_retry(
GuardianReviewSessionLimits {
max_attempts: crate::MAX_REVIEW_ATTEMPTS,
deadline,
},
Some(&cancellation),
Some(&telemetry),
|deadline| {
attempts.fetch_add(/*val*/ 1, Ordering::Relaxed);
// A cached approval can cancel and move the attempt to a cleanup task.
crate::with_root_evidence_limits(
host_deadline,
&cancellation,
host.attempt(&prepared, deadline, &cancellation),
)
},
)
.await
}
});
let (outcome, analytics, evidence) = if let Some(async_approval) = async_approval {
tokio::select! {
biased;
result = &mut review => result,
scored = async_approval => {
cancellation.cancel();
let analytics = if let Some(runtime) = self.thread_store.get::<crate::ReviewerTasks>() {
// Keep driving the same attempt: its pool reservation stays held
// until it drains, and parent shutdown joins the tracked cleanup.
runtime.tasks.spawn(async move { let _ = review.await; });
// Final session and usage metadata are not available yet.
GuardianReviewAnalyticsResult {
attempt_count: attempts.load(Ordering::Relaxed),
..GuardianReviewAnalyticsResult::without_session()
}
} else {
// Hosts without a lifetime tracker must finish cleanup here.
let (_, analytics, _) = review.await;
analytics
};
let outcome = if self.host.cached_approval_context(&prepared).await != Some(scored)
|| self.cancellation.is_cancelled() {
GuardianReviewOutcome::Error(GuardianReviewError::Cancelled)
} else if deadline.is_elapsed() {
GuardianReviewOutcome::Error(GuardianReviewError::Timeout)
} else {
GuardianReviewOutcome::CachedApproval
};
(outcome, analytics, None)
}
}
} else {
review.await
};
// A timed-out second sample can still return the first denial.
let denied = matches!(&outcome, GuardianReviewOutcome::Completed(assessment)
if assessment.outcome == GuardianAssessmentOutcome::Deny);
// Provider reads stopped during prompt building or validation lose the stop reason.
let outcome = if host_deadline.is_some() && self.cancellation.is_cancelled() {
GuardianReviewOutcome::Error(GuardianReviewError::Cancelled)
} else if !denied && host_deadline.is_some_and(ReviewDeadline::is_elapsed) {
GuardianReviewOutcome::Error(GuardianReviewError::Timeout)
} else {
outcome
};
Ok(EvaluatedReview {
prepared,
report,
outcome,
analytics,
evidence,
})
}
}
impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
#[tracing::instrument(
name = "guardian_review",
@@ -124,12 +232,14 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
let host_deadline = self.host_deadline;
let deadline =
host_deadline.unwrap_or_else(|| ReviewDeadline::from_timeout(self.timeout));
let (prepared, report) = match self
.host
.prepare(self.approval_id, reason, deadline, &self.cancellation)
.await
{
Ok(prepared) => prepared,
let EvaluatedReview {
prepared,
report,
outcome,
analytics,
evidence,
} = match self.evaluate(reason, async_approval, deadline).await {
Ok(result) => result,
Err(mut decision) => {
if host_deadline.is_some_and(ReviewDeadline::is_elapsed) {
decision = ReviewDecision::TimedOut;
@@ -140,84 +250,6 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
return Some(decision);
}
};
if let Some(event) = report.started_event() {
self.host.emit(EventMsg::GuardianAssessment(event)).await;
}
let prepared = Arc::new(prepared);
let cancellation = self.cancellation.child_token();
let attempts = Arc::new(AtomicI64::new(/*v*/ 0));
let mut review = Box::pin({
let host = self.host.clone();
let prepared = Arc::clone(&prepared);
let cancellation = cancellation.clone();
let attempts = Arc::clone(&attempts);
let telemetry = self.telemetry.clone();
async move {
crate::run_with_retry(
GuardianReviewSessionLimits {
max_attempts: crate::MAX_REVIEW_ATTEMPTS,
deadline,
},
Some(&cancellation),
Some(&telemetry),
|deadline| {
attempts.fetch_add(/*val*/ 1, Ordering::Relaxed);
// A cached approval can cancel and move the attempt to a cleanup task.
crate::with_root_evidence_limits(
host_deadline,
&cancellation,
host.attempt(&prepared, deadline, &cancellation),
)
},
)
.await
}
});
let (outcome, analytics, evidence) = if let Some(async_approval) = async_approval {
tokio::select! {
biased;
result = &mut review => result,
scored = async_approval => {
cancellation.cancel();
let analytics = if let Some(runtime) = self.thread_store.get::<crate::ReviewerTasks>() {
// Keep driving the same attempt: its pool reservation stays held
// until it drains, and parent shutdown joins the tracked cleanup.
runtime.tasks.spawn(async move { let _ = review.await; });
// Final session and usage metadata are not available yet.
GuardianReviewAnalyticsResult {
attempt_count: attempts.load(Ordering::Relaxed),
..GuardianReviewAnalyticsResult::without_session()
}
} else {
// Hosts without a lifetime tracker must finish cleanup here.
let (_, analytics, _) = review.await;
analytics
};
let outcome = if self.host.cached_approval_context(&prepared).await != Some(scored)
|| self.cancellation.is_cancelled() {
GuardianReviewOutcome::Error(GuardianReviewError::Cancelled)
} else if deadline.is_elapsed() {
GuardianReviewOutcome::Error(GuardianReviewError::Timeout)
} else {
GuardianReviewOutcome::CachedApproval
};
(outcome, analytics, None)
}
}
} else {
review.await
};
// A timed-out second sample can still return the first denial.
let denied = matches!(&outcome, GuardianReviewOutcome::Completed(assessment)
if assessment.outcome == GuardianAssessmentOutcome::Deny);
// Provider reads stopped during prompt building or validation lose the stop reason.
let outcome = if host_deadline.is_some() && self.cancellation.is_cancelled() {
GuardianReviewOutcome::Error(GuardianReviewError::Cancelled)
} else if !denied && host_deadline.is_some_and(ReviewDeadline::is_elapsed) {
GuardianReviewOutcome::Error(GuardianReviewError::Timeout)
} else {
outcome
};
let completed_at_ms = codex_analytics::now_unix_millis();
let cached_approval = matches!(outcome, GuardianReviewOutcome::CachedApproval);
if let Some(sample) = baseline {