Let Guardian V3 review actions while evidence routing is pending (#63941)

## Why

Guardian V3 approval reviews waited for the housekeeper to catch up on
conversation history before they could start. Slow evidence routing could
delay an action review, and a routing failure could prevent a verdict.

## What changed

Each review attempt, including retries, drains the reviewer's available
inbox when it reserves the reviewer. The housekeeper flushes and routes
history independently in response to thread activity.

## Testing

Cover reviews that start with an empty board or while evidence routing
resumes after a root thread reload. Verify that a revocation published
during an in-flight verdict is available to a subsequent review.

GitOrigin-RevId: f84f424b57538fa9562d8f4d47e38ce7a0a84dcd
This commit is contained in:
felixxia-oai
2026-11-25 15:37:35 +00:00
committed by copyberry
parent 34fcbc8caf
commit d1e982d7eb
13 changed files with 362 additions and 1075 deletions
@@ -8,7 +8,6 @@ use codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification;
use codex_app_server_protocol::ThreadGoalSetResponse;
use codex_app_server_protocol::ThreadHistoryMode;
use codex_models_manager::model_info::model_info_from_slug;
use codex_state::SqlitePoolWriteExt;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::streaming_sse::StreamingSseChunk;
use core_test_support::streaming_sse::start_streaming_sse_server;
@@ -19,7 +18,6 @@ use test_case::test_case;
enum ReviewCase {
V3,
V3WithReconsideration,
V3RoutingFailure,
EphemeralV3,
Native,
}
@@ -63,7 +61,6 @@ fn received_user_instruction(request: &responses::ResponsesRequest, text: &str)
#[test_case(ReviewCase::V3, Some(true); "v3_reports_high_probe_without_changing_verdicts")]
#[test_case(ReviewCase::V3, Some(false); "v3_reports_low_probe_without_changing_verdicts")]
#[test_case(ReviewCase::V3WithReconsideration, None; "v3_resamples_a_terminal_denial_once")]
#[test_case(ReviewCase::V3RoutingFailure, None; "v3_denies_when_pending_routing_fails")]
#[test_case(ReviewCase::Native, None; "native_without_v3")]
#[test_case(ReviewCase::EphemeralV3, None; "ephemeral_uses_native_with_v3")]
#[tokio::test]
@@ -73,11 +70,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
) -> Result<()> {
skip_if_no_network!(Ok(()));
let reconsider = matches!(case, ReviewCase::V3WithReconsideration);
let uses_board = matches!(
case,
ReviewCase::V3 | ReviewCase::V3WithReconsideration | ReviewCase::V3RoutingFailure
);
let routing_failure = matches!(case, ReviewCase::V3RoutingFailure);
let uses_board = matches!(case, ReviewCase::V3 | ReviewCase::V3WithReconsideration);
let server_enabled = !matches!(case, ReviewCase::Native);
let server = responses::start_mock_server().await;
const REVOCATION: &str = "I revoke permission for the release. Do not deploy.";
@@ -87,8 +80,13 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
const FIRST_DENIAL_REASON: &str = "The user explicitly stopped this deployment.";
const UNRELATED_GOAL: &str = "Write release notes in French.";
const PENDING_CALL: &str = "release-pending";
let next_call = Arc::new(Mutex::new(None));
let actor_call = Arc::clone(&next_call);
const LATE_REVOCATION: &str = "release-revoked-in-flight";
const AFTER_REVOCATION: &str = "release-after-revocation";
let actor_url = Arc::new(Mutex::new(None::<String>));
let actor_redirect = Arc::clone(&actor_url);
let route_url = Arc::new(Mutex::new(None::<String>));
let route_redirect = Arc::clone(&route_url);
let (routing, mut source_ordinals) = tokio::sync::mpsc::unbounded_channel();
let held_allow_url = Arc::new(Mutex::new(None::<String>));
let redirect = Arc::clone(&held_allow_url);
let ask_to_subscribe = AtomicBool::new(uses_board);
@@ -107,12 +105,23 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
let output = item["output"].as_str().expect("housekeeper input text");
let input: Value = serde_json::from_str(output).expect("valid housekeeper input JSON");
let sources = input["sources"].as_array().expect("housekeeper sources");
// A nonempty batch with no destinations is a terminal routing error.
let routes = if routing_failure {
Vec::new()
} else {
vec![vec!["release"]; sources.len()]
};
let held_route = route_redirect.lock().expect("route URL").take();
for source in sources {
let item = &source["original"]["payload"];
if matches!(item["role"].as_str(), Some("user" | "assistant")) {
let ordinal = source["id"]["ordinal"].as_u64().expect("source ordinal");
for part in item["content"].as_array().expect("message content") {
if let Some(text) = part["text"].as_str() {
routing.send((text.to_owned(), ordinal)).expect("routing receiver");
}
}
}
}
if let Some(url) = held_route {
assert_eq!(sources.len(), 1, "held batch should contain only the user prompt");
return wiremock::ResponseTemplate::new(/*s*/ 307).insert_header("location", url);
}
let routes = vec![vec!["release"]; sources.len()];
let text =
json!({"descriptions":[{"channel":"release","description":"Release policy"}],"routes":routes}).to_string();
responses::sse(vec![
@@ -159,23 +168,8 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
} else {
response
};
} else if let Some(call_id) = actor_call.lock().expect("next actor call").take() {
let mut call = responses::ev_function_call_with_namespace(
call_id,
"mcp__codex_apps__browser",
"_js",
r#"{"code":"release-action"}"#,
);
call["item"]["id"] = json!(call_id);
let mut events = vec![responses::ev_response_created(call_id)];
if let Some(requires_review) = probe {
events.push(json!({
"type": "response.metadata", "response_id": call_id,
"metadata": {"guardian": {"item_id": call_id, "requires_review": requires_review}},
}));
}
events.extend([call, responses::ev_completed(call_id)]);
responses::sse(events)
} else if let Some(url) = actor_redirect.lock().expect("actor URL").take() {
return wiremock::ResponseTemplate::new(/*s*/ 307).insert_header("location", url);
} else {
responses::sse(vec![
responses::ev_assistant_message("actor", "Done."),
@@ -242,7 +236,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.with_json_logging("warn,codex_core::guardian=info")
.with_json_logging("warn,codex_core::guardian=info,codex_guardian_v3::host=debug")
.build_initialized_with_timeout(TIMEOUT)
.await?;
let thread = app
@@ -260,7 +254,7 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
"Check the release candidate.",
GuardianApprovalReviewStatus::Approved,
)];
if uses_board && !routing_failure {
if uses_board {
turns.extend([
(
"release-revoked",
@@ -281,43 +275,88 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
GuardianApprovalReviewStatus::Denied,
));
}
if matches!(case, ReviewCase::V3) {
if matches!(case, ReviewCase::V3) && probe.is_none() {
turns.push((
PENDING_CALL,
"Proceed with the release.",
GuardianApprovalReviewStatus::Approved,
));
turns.push((
LATE_REVOCATION,
FINAL_REVOCATION,
GuardianApprovalReviewStatus::Approved,
));
turns.push((
AFTER_REVOCATION,
"Summarize the release status.",
GuardianApprovalReviewStatus::Denied,
));
}
let hold_response = async |redirect: &Mutex<Option<String>>, body| {
let (release, gate) = tokio::sync::oneshot::channel();
let (stream, _) = start_streaming_sse_server(vec![vec![StreamingSseChunk {
gate: Some(gate),
body,
}]])
.await;
*redirect.lock().expect("redirect URL") = Some(format!("{}/v1/responses", stream.uri()));
(stream, release)
};
let mut wait_for_source = async |expected: &str| -> Result<u64> {
loop {
let (text, ordinal) = timeout(TIMEOUT, source_ordinals.recv())
.await?
.expect("routing input");
if text == expected {
return Ok(ordinal);
}
}
};
let mut previous_reviewer = None;
let mut previous_review_id = None;
let mut denied_turns = Vec::new();
let mut seen_requests = 0;
let root_turn_id = "reviewed-root-turn";
for (call_id, prompt, status) in turns {
// Keep the revocation out of the board until the pending action requests its review.
let gate = if prompt == REVOCATION {
let sqlite = load_default_config_for_test(&home).await.sqlite;
let pool = sqlite
.open_read_write_pool(&sqlite.home().join("message_board_guardian_1.sqlite"))
.await?;
Some(pool.begin_immediate().await?)
// Block publication until the first review finishes on an empty board, or
// until the review has started sampling without the late revocation.
let empty_board = uses_board && previous_reviewer.is_none();
let late = call_id == LATE_REVOCATION;
if late {
// Let intake capture the previous turn's final answer so the held batch
// contains only the new user prompt.
wait_for_source("Done.").await?;
}
let mut held_route = if empty_board || late {
let body = assistant_response(
r#"{"descriptions":[{"channel":"release","description":"Release policy"}],"routes":[["release"]]}"#,
)?;
Some(hold_response(&route_url, body).await)
} else {
None
};
let held_allow = if call_id == PENDING_CALL {
let (release, gate) = tokio::sync::oneshot::channel();
let (stream, _) = start_streaming_sse_server(vec![vec![StreamingSseChunk {
gate: Some(gate),
body: assistant_response(r#"{"outcome":"allow","rationale":"Release approved."}"#)?,
}]])
.await;
*held_allow_url.lock().expect("held allow URL") =
Some(format!("{}/v1/responses", stream.uri()));
Some((stream, release))
let held_allow = if call_id == PENDING_CALL || late {
let body =
assistant_response(r#"{"outcome":"allow","rationale":"Release approved."}"#)?;
Some(hold_response(&held_allow_url, body).await)
} else {
None
};
*next_call.lock().expect("next actor call") = Some(call_id);
let mut call = responses::ev_function_call_with_namespace(
call_id,
"mcp__codex_apps__browser",
"_js",
r#"{"code":"release-action"}"#,
);
call["item"]["id"] = json!(call_id);
let mut events = vec![responses::ev_response_created(call_id)];
if let Some(requires_review) = probe {
events.push(json!({
"type": "response.metadata", "response_id": call_id,
"metadata": {"guardian": {"item_id": call_id, "requires_review": requires_review}},
}));
}
events.extend([call, responses::ev_completed(call_id)]);
let (_actor, issue_call) = hold_response(&actor_url, responses::sse(events)).await;
let id = app
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
@@ -330,24 +369,59 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
})
.await?;
let started: TurnStartResponse = timeout(TIMEOUT, app.read_response(id)).await??;
if let Some((stream, release)) = held_allow {
let mut wait_for_publication = async || {
// Wait for this prompt, not an earlier capture from the preceding turn.
let ordinal = wait_for_source(prompt).await?;
app.wait_for_matching_json_log_event(
"publication of the user prompt",
|event| {
let fields = &event["fields"];
fields["message"] == "Guardian housekeeper routed evidence"
&& fields["root_thread_id"] == thread.id
&& fields["end_ordinal_exclusive"]
.as_u64()
.is_some_and(|end| end > ordinal)
},
TIMEOUT,
)
.await
};
if let Some((stream, _)) = &held_route {
timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 1)).await?;
// A paused user goal updates authorization without starting a turn or waking intake.
let id = app
.send_raw_request(
"thread/goal/set",
Some(json!({
"threadId": thread.id, "origin": "user",
"status": "paused", "objective": UNRELATED_GOAL,
})),
)
.await?;
let _: ThreadGoalSetResponse = timeout(TIMEOUT, app.read_response(id)).await??;
}
if late {
issue_call.send(()).expect("issue action");
let (stream, _) = held_allow.as_ref().expect("held verdict");
timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 1)).await?;
let (_route, release) = held_route.take().expect("held revocation");
release.send(()).expect("route revocation");
wait_for_publication().await?;
} else {
if uses_board && !empty_board {
wait_for_publication().await?;
}
issue_call.send(()).expect("issue action");
}
if let Some((stream, release)) = held_allow {
if !late {
timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 1)).await?;
// A paused user goal updates authorization without starting a turn or waking intake.
let id = app
.send_raw_request(
"thread/goal/set",
Some(json!({
"threadId": thread.id, "origin": "user",
"status": "paused", "objective": UNRELATED_GOAL,
})),
)
.await?;
let _: ThreadGoalSetResponse = timeout(TIMEOUT, app.read_response(id)).await??;
}
release.send(()).expect("release allow");
}
if let Some(gate) = gate {
if prompt == REVOCATION {
app.wait_for_matching_json_log_event(
"revocation catch-up",
"release review probe",
|event| {
let fields = &event["fields"];
fields["message"] == "Guardian V3 review preparation started"
@@ -358,18 +432,17 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
Some(false) => "not_required",
None => "not_reported",
}
&& fields["review_id"]
.as_str()
.is_some_and(|id| Some(id) != previous_review_id.as_deref())
},
TIMEOUT,
)
.await?;
gate.rollback().await?;
}
let completed: TurnCompletedNotification =
timeout(TIMEOUT, app.read_notification("turn/completed")).await??;
assert_eq!(completed.turn.id, started.turn.id);
if let Some((_route, release)) = held_route {
release.send(()).expect("publish first prompt");
}
let calls = requests.requests();
let assessments: Vec<_> = calls[seen_requests..]
.iter()
@@ -377,34 +450,6 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
.collect();
seen_requests = calls.len();
assert!(!calls.iter().any(|r| expects_field(r, "channels")));
if routing_failure {
let denied = wait_for_mcp_tool_call_completed(&mut app, call_id).await?;
assert_eq!(
(&denied.thread_id, &denied.turn_id),
(&thread.id, &started.turn.id)
);
let ThreadItemPayload::McpToolCall {
status: McpToolCallStatus::Failed,
error: Some(error),
..
} = &denied.item.payload
else {
anyhow::bail!(
"expected a failed MCP call for {call_id}, got {:?}",
denied.item.payload
);
};
assert!(
error
.message
.contains("Guardian V3 could not prepare the evidence"),
"{}",
error.message
);
assert!(calls.iter().any(|r| expects_field(r, "routes")));
assert!(assessments.is_empty());
continue;
}
let review: ItemGuardianApprovalReviewCompletedNotification = timeout(
TIMEOUT,
app.read_notification("item/autoApprovalReview/completed"),
@@ -415,31 +460,48 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
(&review.thread_id, &review.turn_id, review.review.status),
(&thread.id, &completed.turn.id, status)
);
previous_review_id = Some(review.review_id);
if status == GuardianApprovalReviewStatus::Denied {
denied_turns.push(review.turn_id);
}
let verdict = assessments.last().expect("verdict");
if call_id == PENDING_CALL {
let [allow] = assessments.as_slice() else {
anyhow::bail!("an unrouted goal should not invalidate the verdict for {call_id}");
};
assert!(!received_user_instruction(allow, UNRELATED_GOAL));
assert!(!received_user_instruction(verdict, UNRELATED_GOAL));
assert_eq!(review.target_item_id.as_deref(), Some(call_id));
}
if prompt == FINAL_REVOCATION {
if late || call_id == AFTER_REVOCATION {
assert_eq!(review.target_item_id.as_deref(), Some(call_id));
let tool = wait_for_mcp_tool_call_completed(&mut app, call_id).await?;
let ThreadItemPayload::McpToolCall { status, error, .. } = tool.item.payload else {
anyhow::bail!("expected MCP action {call_id}");
};
if late {
assert!(!received_user_instruction(verdict, FINAL_REVOCATION));
assert_eq!(status, McpToolCallStatus::Completed);
} else {
assert!(received_user_instruction(verdict, FINAL_REVOCATION));
assert_eq!(status, McpToolCallStatus::Failed);
assert!(error.is_some_and(|error| error.message.contains(FIRST_DENIAL_REASON)));
}
}
if prompt == FINAL_REVOCATION && reconsider {
assert_eq!(
review.review.rationale.as_deref(),
Some(FIRST_DENIAL_REASON)
);
}
if prompt == REVOCATION || prompt == REAPPROVAL || prompt == FINAL_REVOCATION {
let followup = previous_reviewer.is_some();
if followup {
if reconsider {
let [first, second] = assessments.as_slice() else {
anyhow::bail!("expected exactly two verdict samples for {call_id}");
};
assert_eq!(first.input(), second.input());
} else {
assert_eq!(assessments.len(), 1);
assert_eq!(
assessments.len(),
1,
"unexpected verdict retry for {call_id}"
);
}
}
// A subscription tool call can add a sampling step. Every assessment must
@@ -450,12 +512,10 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
.contains("guardian_board")
== uses_board
}));
let verdict = assessments.last().expect("verdict");
let body = verdict.body_json();
let reviewer = body["client_metadata"]["thread_id"]
.as_str()
.expect("reviewer thread");
let followup = previous_reviewer.is_some();
if let Some(previous) = previous_reviewer.replace(reviewer.to_owned()) {
assert_eq!(previous, reviewer);
}
@@ -515,14 +575,14 @@ async fn pending_mcp_action_uses_the_configured_reviewer(
&& parts.iter().any(|text| text.contains("release-action")))
);
}
if followup {
if followup && !late {
assert!(
received_user_instruction(verdict, prompt),
"missing subscribed instruction: {prompt}"
);
}
}
if uses_board && !routing_failure {
if uses_board {
let state = StateRuntime::init(
load_default_config_for_test(&home).await.sqlite,
"openai-custom".into(),