diff --git a/codex-rs/ext/guardian-reviewer/src/review.rs b/codex-rs/ext/guardian-reviewer/src/review.rs index e7bd1991e6..90674f8ba4 100644 --- a/codex-rs/ext/guardian-reviewer/src/review.rs +++ b/codex-rs/ext/guardian-reviewer/src/review.rs @@ -92,6 +92,114 @@ pub trait ReviewHost: Clone + Send + Sync + 'static { ) -> impl Future + Send; } +struct EvaluatedReview { + prepared: Arc, + report: ReviewReport, + outcome: GuardianReviewOutcome, + analytics: GuardianReviewAnalyticsResult, + evidence: Option, +} + +impl ReviewRequest<'_, H> { + async fn evaluate( + &self, + reason: GuardianReviewReason, + async_approval: Option>, + deadline: ReviewDeadline, + ) -> Result, 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::() { + // 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 SynchronousApprovalReviewer for ReviewRequest<'_, H> { #[tracing::instrument( name = "guardian_review", @@ -124,12 +232,14 @@ impl 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 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::() { - // 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 {