Measure Guardian v3 shadow review outcomes and latency (#64783)

## Why

Comparing the live v2 reviewer with the v3 shadow reviewer requires
measuring both on the same action. A live retry can pick up new context,
which can affect how a verdict disagreement is interpreted.

## What changed

Record outcomes for each reviewer and emit paired outcomes and timings
when both return validated verdicts. Measure from a shared start to each
verdict's validation and tag the pair when the live review's context
changed.

Track shadow skips when the reviewer is busy or intake has stopped, and
exclude shadow denial retries from live reconsideration metrics.

## Testing

Add a metrics test that checks exactly-once reporting for completed,
failed, and cancelled samples and verifies pair emission for two
validated verdicts.

GitOrigin-RevId: 1a0f8e4e38099ea172e6511d4fa2fe8735b82ea4
This commit is contained in:
felixxia-oai
2026-11-30 18:28:15 +00:00
committed by copyberry
parent 457ea27b0b
commit 6984bcc0c2
11 changed files with 370 additions and 56 deletions
+3
View File
@@ -591,6 +591,8 @@ impl GuardianReviewTrackContext {
#[derive(Debug)]
pub struct GuardianReviewAnalyticsResult {
pub guardian_context_mode: Option<&'static str>,
/// Local completion time of the final attempt's accepted assessment, before feedback and cleanup.
pub verdict_validated_at: Option<std::time::Instant>,
pub decision: GuardianReviewDecision,
pub terminal_status: GuardianReviewTerminalStatus,
pub failure_reason: Option<GuardianReviewFailureReason>,
@@ -620,6 +622,7 @@ impl GuardianReviewAnalyticsResult {
pub fn without_session() -> Self {
Self {
guardian_context_mode: None,
verdict_validated_at: None,
decision: GuardianReviewDecision::Denied,
terminal_status: GuardianReviewTerminalStatus::FailedClosed,
failure_reason: None,
@@ -222,6 +222,11 @@ impl AttachedApproval {
}
}
}
if let GuardianReviewSessionOutcome::Completed(Ok(Some(response))) = &turn.outcome
&& response.assessment().is_ok()
{
analytics.verdict_validated_at = Some(std::time::Instant::now());
}
Ok((turn.outcome, turn.disposition))
}
.await;
+6 -2
View File
@@ -227,8 +227,12 @@ impl ReviewHost for ReviewRuntime {
Some((turn.sub_id.clone(), Arc::clone(&turn.model_info().model)))
}
fn start_shadow(&self, approval_id: &str, reason: GuardianReviewReason) {
attached::shadow::start(self, approval_id, reason);
fn start_shadow(
&self,
approval_id: &str,
reason: GuardianReviewReason,
) -> Option<codex_guardian_reviewer::CohortSample> {
attached::shadow::start(self, approval_id, reason)
}
async fn prepare(
+7 -1
View File
@@ -832,7 +832,13 @@ impl GuardianReviewSession {
let resample = store.remove::<codex_guardian_reviewer::DenialResample>();
result.map(|turn| {
let turn = match resample {
Some(resample) => resample.finish(turn, &context.turn().session_telemetry),
Some(resample) => {
let telemetry = store
.get::<crate::guardian_review::ShadowReviewSession>()
.is_none()
.then_some(&context.turn().session_telemetry);
resample.finish(turn, telemetry)
}
None => turn,
};
(turn, admitted)
@@ -327,8 +327,11 @@ impl ReviewerRequest for PreparedReview {
// All checkpoint capture and lock acquisition must precede validation. No await
// may follow a valid assessment before publication; new guidance during capture
// invalidates either verdict without overwriting the last committed review.
if let GuardianReviewSessionOutcome::Completed(Ok(Some(response))) = &result.outcome
&& response.assessment().is_ok()
let has_assessment = matches!(
&result.outcome,
GuardianReviewSessionOutcome::Completed(Ok(Some(response))) if response.assessment().is_ok()
);
if has_assessment
&& let Some(authorization) = &self.params.authorization
&& let Some(invalidation) = authorization
.invalidation(
@@ -342,6 +345,7 @@ impl ReviewerRequest for PreparedReview {
&& result.outcome.is_recovered_denial()
{
// Keep the first denial and the interrupted turn's rollback or discard.
result.analytics.verdict_validated_at = Some(std::time::Instant::now());
return result;
}
result.analytics.context_changed |= invalidation.context_changed;
@@ -356,6 +360,7 @@ impl ReviewerRequest for PreparedReview {
result.outcome = outcome;
return result;
}
result.analytics.verdict_validated_at = has_assessment.then(std::time::Instant::now);
if let Some((items, history_version, mut state)) = checkpoint {
state.commit_snapshot(
items,
+33 -16
View File
@@ -5,13 +5,17 @@ use crate::guardian::routes_approval_policy_to_guardian;
use crate::guardian::runtime::ReviewRuntime;
use crate::guardian_review::ShadowReviewer;
use codex_features::Feature;
use codex_guardian_reviewer::CohortSample;
use codex_guardian_reviewer::GuardianReviewOutcome;
use codex_guardian_reviewer::GuardianReviewSessionOutcome;
use codex_guardian_reviewer::ReviewDeadline;
use codex_guardian_reviewer::ReviewHost;
use codex_guardian_reviewer::ReviewerTasks;
use codex_guardian_reviewer::run_before_review_deadline;
use codex_protocol::approvals::GuardianReviewReason;
use codex_protocol::protocol::ReviewDecision;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Mutex;
#[derive(Default)]
@@ -21,15 +25,13 @@ pub(in crate::guardian) fn start(
live: &ReviewRuntime,
approval_id: &str,
reason: GuardianReviewReason,
) {
) -> Option<CohortSample> {
// A fresh review cannot be cut short by a late async approval.
if reason != GuardianReviewReason::FreshRequired {
return;
return None;
}
let store = &live.session.services.thread_extension_data;
let Some(observer) = store.get::<ShadowReviewer>() else {
return;
};
let observer = store.get::<ShadowReviewer>()?;
let config = &live.context.turn().config;
if observer.cancellation.is_cancelled()
|| live.attached_reviewer.is_some()
@@ -43,25 +45,28 @@ pub(in crate::guardian) fn start(
|| live.session.work_budget().config().is_some()
|| live.validate_action().is_err()
{
return;
return None;
}
let Some(runtime) = store.get::<ReviewerTasks>() else {
return;
};
let runtime = store.get::<ReviewerTasks>()?;
// The live decision already holds a tracker token until this dispatch completes.
if live.history_reset.is_cancelled() || runtime.cancellation.is_cancelled() {
return;
return None;
}
let telemetry = &live.context.turn().session_telemetry;
let category = live.request.category;
let slot = store.get_or_init(ShadowSlot::default);
let Ok(permit) = Arc::clone(&slot.0).try_lock_owned() else {
tracing::debug!("Guardian shadow reviewer busy");
return;
CohortSample::skipped(telemetry, category, "busy");
return None;
};
// Admission only. A later intake failure must not cancel this verdict.
if observer.intake_stopped.is_cancelled() {
tracing::debug!("Guardian shadow review skipped after intake stopped");
return;
CohortSample::skipped(telemetry, category, "intake_stopped");
return None;
}
let [baseline, candidate] = CohortSample::start(telemetry, category, Instant::now());
let deadline = ReviewDeadline::from_timeout(config.guardian_review_timeout);
let mut shadow = live.clone();
shadow.attached_reviewer = Some(Arc::clone(&observer.reviewer));
@@ -78,9 +83,19 @@ pub(in crate::guardian) fn start(
.await
})
.await;
let Ok(Ok(mut prepared)) = prepared else {
tracing::debug!(%review_id, "Guardian shadow preparation failed");
return;
let mut prepared = match prepared {
Ok(Ok(result)) => result,
Err(GuardianReviewSessionOutcome::TimedOut) => {
tracing::debug!(%review_id, "Guardian shadow preparation timed out");
candidate.preparation_failed(&ReviewDecision::TimedOut, deadline);
return;
}
Err(_) => return, // Cancelled while waiting for preparation.
Ok(Err(decision)) => {
tracing::debug!(%review_id, "Guardian shadow preparation failed");
candidate.preparation_failed(&decision, deadline);
return;
}
};
let Some(attached) = &mut prepared.attached else {
return;
@@ -88,7 +103,8 @@ pub(in crate::guardian) fn start(
attached.config.spawn_config.feedback_enabled = false;
// Drive a single attempt to completion, including cancellation and draining the session.
// A retry could observe instructions that arrived after the live decision.
let (outcome, _analytics, _evidence) = shadow.attempt(&prepared, deadline, &cancel).await;
let (outcome, analytics, _evidence) = shadow.attempt(&prepared, deadline, &cancel).await;
candidate.finish(&outcome, &analytics);
drop(prepared);
drop(permit);
match outcome {
@@ -101,4 +117,5 @@ pub(in crate::guardian) fn start(
GuardianReviewOutcome::CachedApproval => {}
}
});
Some(baseline)
}
@@ -39,6 +39,8 @@ mod pool;
mod prompt;
mod reconsideration;
mod reporting;
mod shadow_metrics;
pub use shadow_metrics::CohortSample;
mod retry;
mod review;
mod review_action;
+49 -2
View File
@@ -262,7 +262,7 @@ fn optional_bool_tag(value: Option<bool>) -> &'static str {
}
}
fn bool_tag(value: bool) -> &'static str {
pub(super) fn bool_tag(value: bool) -> &'static str {
if value { "true" } else { "false" }
}
@@ -286,7 +286,7 @@ fn user_authorization_tag(user_authorization: Option<GuardianUserAuthorization>)
}
}
fn outcome_tag(outcome: Option<GuardianAssessmentOutcome>) -> &'static str {
pub(super) fn outcome_tag(outcome: Option<GuardianAssessmentOutcome>) -> &'static str {
match outcome {
Some(GuardianAssessmentOutcome::Allow) => "allow",
Some(GuardianAssessmentOutcome::Deny) => "deny",
@@ -369,6 +369,53 @@ mod tests {
.with_metrics_without_metadata_tags(metrics)
}
#[test]
fn shadow_comparison_reports_each_sample_once() {
use crate::CohortSample;
use crate::GuardianReviewOutcome;
use crate::ReviewDeadline;
use codex_protocol::openai_models::GuardianScope;
use codex_protocol::protocol::ReviewDecision;
let telemetry = test_session_telemetry();
let started = std::time::Instant::now();
let allow = GuardianReviewOutcome::Completed(
crate::parse_guardian_assessment(r#"{"outcome":"allow"}"#).unwrap(),
);
let deny = GuardianReviewOutcome::Completed(
crate::parse_guardian_assessment(r#"{"outcome":"deny"}"#).unwrap(),
);
let [live, shadow] = CohortSample::start(&telemetry, GuardianScope::Mcp, started);
let mut analytics = GuardianReviewAnalyticsResult::without_session();
analytics.verdict_validated_at = Some(started);
shadow.finish(&allow, &analytics);
analytics.context_changed = true;
live.finish(&deny, &analytics);
let [live, shadow] = CohortSample::start(&telemetry, GuardianScope::Mcp, started);
live.preparation_failed(&ReviewDecision::TimedOut, ReviewDeadline::Unlimited);
drop(shadow);
let snapshot = telemetry.snapshot_metrics().unwrap();
let (pair, count) = counter_point(&snapshot, "codex.guardian_v3.shadow.pair");
assert_eq!(count, 1);
assert_eq!(pair["v2_outcome"], "deny");
assert_eq!(pair["v3_outcome"], "allow");
assert_eq!(pair["context_changed"], "true");
let reviews = find_metric(&snapshot, "codex.guardian_v3.shadow.review");
let AggregatedMetrics::U64(MetricData::Sum(counts)) = reviews.data() else {
panic!("expected counter");
};
let mut outcomes = Vec::new();
for point in counts.data_points() {
assert_eq!(point.value(), 1);
outcomes.push(attributes_to_map(point.attributes())["outcome"].clone());
}
outcomes.sort_unstable();
assert_eq!(outcomes, ["allow", "cancelled", "deny", "error"]);
}
fn find_metric<'a>(resource_metrics: &'a ResourceMetrics, name: &str) -> &'a Metric {
for scope_metrics in resource_metrics.scope_metrics() {
for metric in scope_metrics.metrics() {
@@ -45,7 +45,7 @@ impl DenialResample {
pub fn finish(
&self,
mut result: ReviewTurnResult,
telemetry: &SessionTelemetry,
telemetry: Option<&SessionTelemetry>,
) -> ReviewTurnResult {
let Some(mut first) = self
.denial
@@ -67,30 +67,32 @@ impl DenialResample {
| GuardianReviewSessionOutcome::TimedOut
| GuardianReviewSessionOutcome::Aborted => None,
};
let outcome = match assessment.map(|assessment| assessment.outcome) {
Some(GuardianAssessmentOutcome::Allow) => "allow",
Some(GuardianAssessmentOutcome::Deny) => "deny",
None => match &result.outcome {
GuardianReviewSessionOutcome::TimedOut => "timed_out",
GuardianReviewSessionOutcome::Aborted => "cancelled",
GuardianReviewSessionOutcome::Completed(_)
| GuardianReviewSessionOutcome::PromptBuildFailed(_)
| GuardianReviewSessionOutcome::InputBudgetExceeded
| GuardianReviewSessionOutcome::SessionFailed { .. }
| GuardianReviewSessionOutcome::StaleAuthorization => "failed",
},
};
let tags = [("outcome", outcome)];
telemetry.counter(
"codex.guardian.review.reconsideration",
/*inc*/ 1,
&tags,
);
telemetry.record_duration(
"codex.guardian.review.reconsideration_duration_ms",
first.started.elapsed(),
&tags,
);
if let Some(telemetry) = telemetry {
let outcome = match assessment.map(|assessment| assessment.outcome) {
Some(GuardianAssessmentOutcome::Allow) => "allow",
Some(GuardianAssessmentOutcome::Deny) => "deny",
None => match &result.outcome {
GuardianReviewSessionOutcome::TimedOut => "timed_out",
GuardianReviewSessionOutcome::Aborted => "cancelled",
GuardianReviewSessionOutcome::Completed(_)
| GuardianReviewSessionOutcome::PromptBuildFailed(_)
| GuardianReviewSessionOutcome::InputBudgetExceeded
| GuardianReviewSessionOutcome::SessionFailed { .. }
| GuardianReviewSessionOutcome::StaleAuthorization => "failed",
},
};
let tags = [("outcome", outcome)];
telemetry.counter(
"codex.guardian.review.reconsideration",
/*inc*/ 1,
&tags,
);
telemetry.record_duration(
"codex.guardian.review.reconsideration_duration_ms",
first.started.elapsed(),
&tags,
);
}
if assessment.is_none() && !matches!(result.outcome, GuardianReviewSessionOutcome::Aborted)
{
first.response.recovered_denial = !result.turn_completed;
+24 -8
View File
@@ -43,8 +43,14 @@ pub trait ReviewHost: Clone + Send + Sync + 'static {
fn servicing_turn(&self) -> impl Future<Output = Option<(String, Arc<ModelInfo>)>> + Send;
/// Returns the owning turn and optional target item after validating the action.
fn validate_action(&self) -> Result<(&str, Option<&str>), ReviewDecision>;
/// Optionally observe a synchronous review without affecting the live decision.
fn start_shadow(&self, _approval_id: &str, _reason: GuardianReviewReason) {}
/// Return a live comparison sample only when a shadow review starts.
fn start_shadow(
&self,
_approval_id: &str,
_reason: GuardianReviewReason,
) -> Option<crate::CohortSample> {
None
}
/// Prepares evidence and accounting, with a client event only for supported actions.
fn prepare(
&self,
@@ -110,9 +116,11 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
&[("route", "required_sync"), ("reason", reason.into())],
);
}
if !self.cancellation.is_cancelled() {
self.host.start_shadow(self.approval_id, reason);
}
let baseline = if self.cancellation.is_cancelled() {
None
} else {
self.host.start_shadow(self.approval_id, reason)
};
let host_deadline = self.host_deadline;
let deadline =
host_deadline.unwrap_or_else(|| ReviewDeadline::from_timeout(self.timeout));
@@ -122,10 +130,15 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
.await
{
Ok(prepared) => prepared,
Err(_) if host_deadline.is_some_and(ReviewDeadline::is_elapsed) => {
return Some(ReviewDecision::TimedOut);
Err(mut decision) => {
if host_deadline.is_some_and(ReviewDeadline::is_elapsed) {
decision = ReviewDecision::TimedOut;
}
if let Some(sample) = baseline {
sample.preparation_failed(&decision, deadline);
}
return Some(decision);
}
Err(decision) => return Some(decision),
};
if let Some(event) = report.started_event() {
self.host.emit(EventMsg::GuardianAssessment(event)).await;
@@ -207,6 +220,9 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
};
let completed_at_ms = codex_analytics::now_unix_millis();
let cached_approval = matches!(outcome, GuardianReviewOutcome::CachedApproval);
if let Some(sample) = baseline {
sample.finish(&outcome, &analytics);
}
let (completed, elapsed) = report.complete(
outcome,
self.model,
@@ -0,0 +1,207 @@
//! Each admitted reviewer reports independently. When both return validated verdicts,
//! the second finisher also reports their outcomes and durations for the same action.
use std::sync::Arc;
use std::sync::OnceLock;
use std::time::Duration;
use std::time::Instant;
use codex_analytics::GuardianReviewAnalyticsResult;
use codex_otel::SessionTelemetry;
use codex_protocol::openai_models::GuardianScope;
use codex_protocol::protocol::ReviewDecision;
use crate::GuardianReviewError;
use crate::GuardianReviewOutcome;
use crate::ReviewDeadline;
use crate::metrics::bool_tag;
use crate::metrics::failure_reason_tag;
use crate::metrics::outcome_tag;
struct Comparison {
telemetry: SessionTelemetry,
started: Instant,
scope: &'static str,
first: OnceLock<Verdict>,
}
#[derive(Clone, Copy)]
struct Verdict {
version: &'static str,
outcome: &'static str,
elapsed: Duration,
context_changed: bool,
}
/// Reports one side of an admitted comparison, including cancellation on drop.
pub struct CohortSample {
comparison: Arc<Comparison>,
version: &'static str,
reported: bool,
}
impl CohortSample {
/// Start both clocks together after admission, before either reviewer prepares.
pub fn start(
telemetry: &SessionTelemetry,
category: GuardianScope,
started: Instant,
) -> [Self; 2] {
let comparison = Arc::new(Comparison {
telemetry: telemetry.clone(),
started,
scope: scope_tag(category),
first: OnceLock::new(),
});
["v2", "v3"].map(|version| Self {
comparison: Arc::clone(&comparison),
version,
reported: false,
})
}
pub fn skipped(telemetry: &SessionTelemetry, category: GuardianScope, reason: &'static str) {
report(
telemetry,
scope_tag(category),
"v3",
"skipped",
reason,
/*elapsed*/ None,
);
}
/// Preparation can return a denial when its inner deadline wins the timeout race.
pub fn preparation_failed(mut self, decision: &ReviewDecision, deadline: ReviewDeadline) {
let (outcome, reason) = if matches!(decision, ReviewDecision::Abort) {
("cancelled", "cancelled")
} else if matches!(decision, ReviewDecision::TimedOut) || deadline.is_elapsed() {
("error", "preparation_timeout")
} else {
("error", "preparation")
};
self.report_result(outcome, reason, /*elapsed*/ None);
}
pub fn finish(
mut self,
result: &GuardianReviewOutcome,
analytics: &GuardianReviewAnalyticsResult,
) {
let (outcome, reason, elapsed) = match result {
GuardianReviewOutcome::Completed(assessment) => (
outcome_tag(Some(assessment.outcome)),
"none",
analytics
.verdict_validated_at
.map(|at| at.duration_since(self.comparison.started)),
),
GuardianReviewOutcome::CachedApproval => ("cached", "none", None),
GuardianReviewOutcome::Error(GuardianReviewError::Cancelled) => {
("cancelled", "cancelled", None)
}
GuardianReviewOutcome::Error(error) => (
"error",
failure_reason_tag(Some(error.failure_reason())),
None,
),
};
self.report_result(outcome, reason, elapsed);
if let Some(elapsed) = elapsed {
self.comparison.record_verdict(Verdict {
version: self.version,
outcome,
elapsed,
context_changed: analytics.context_changed,
});
}
}
fn report_result(&mut self, outcome: &str, reason: &str, elapsed: Option<Duration>) {
self.reported = true;
report(
&self.comparison.telemetry,
self.comparison.scope,
self.version,
outcome,
reason,
elapsed,
);
}
}
impl Drop for CohortSample {
fn drop(&mut self) {
if !self.reported {
self.report_result("cancelled", "cancelled", /*elapsed*/ None);
}
}
}
impl Comparison {
fn record_verdict(&self, verdict: Verdict) {
// One sample per version. The first leaves its verdict and returns immediately.
let first = *self.first.get_or_init(|| verdict);
if first.version == verdict.version {
return;
}
let [live, shadow] = if first.version == "v2" {
[first, verdict]
} else {
[verdict, first]
};
let scope = ("scope", self.scope);
let v2 = ("v2_outcome", live.outcome);
let v3 = ("v3_outcome", shadow.outcome);
// GV2 may retry with new evidence after GV3 finishes. Disagreement rates
// should use only pairs with context_changed=false.
let changed = ("context_changed", bool_tag(live.context_changed));
self.telemetry.counter(
"codex.guardian_v3.shadow.pair",
/*inc*/ 1,
&[scope, v2, v3, changed],
);
for side in [live, shadow] {
self.telemetry.record_duration(
"codex.guardian_v3.shadow.pair.duration_ms",
side.elapsed,
&[scope, v2, v3, changed, ("reviewer", side.version)],
);
}
}
}
fn scope_tag(category: GuardianScope) -> &'static str {
match category {
GuardianScope::ComputerUse => "computer_use",
GuardianScope::Shell => "shell",
GuardianScope::FileChanges => "file_changes",
GuardianScope::Mcp => "mcp",
GuardianScope::Network => "network",
GuardianScope::Permissions => "permissions",
GuardianScope::NativeTool => "native_tool",
}
}
fn report(
telemetry: &SessionTelemetry,
scope: &str,
version: &str,
outcome: &str,
reason: &str,
elapsed: Option<Duration>,
) {
let tags = [
("reviewer", version),
("scope", scope),
("outcome", outcome),
("reason", reason),
];
telemetry.counter("codex.guardian_v3.shadow.review", /*inc*/ 1, &tags);
if let Some(elapsed) = elapsed {
telemetry.record_duration(
"codex.guardian_v3.shadow.review.duration_ms",
elapsed,
&tags,
);
}
}