diff --git a/codex-rs/app-server/tests/suite/v2/guardian_v3_shadow_tests.rs b/codex-rs/app-server/tests/suite/v2/guardian_v3_shadow_tests.rs index 2380309b0e..b3df31d1dc 100644 --- a/codex-rs/app-server/tests/suite/v2/guardian_v3_shadow_tests.rs +++ b/codex-rs/app-server/tests/suite/v2/guardian_v3_shadow_tests.rs @@ -28,20 +28,28 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( ) -> Result<()> { skip_if_no_network!(Ok(())); let server = responses::start_mock_server().await; + let expect_shadow = sensitive_action == Some(true) && enforce_budget.is_none(); + let (stop_holds, stop_gates): (Vec<_>, Vec<_>) = + (0..4).map(|_| tokio::sync::oneshot::channel()).unzip(); let (release, gate) = tokio::sync::oneshot::channel(); let (hold, second_gate) = tokio::sync::oneshot::channel(); let denial = assistant_response(r#"{"outcome":"deny","rationale":"shadow only"}"#)?; - let replies = [gate, second_gate].map(|gate| { - vec![StreamingSseChunk { - gate: Some(gate), - body: denial.clone(), - }] - }); - let (stream, _completions) = start_streaming_sse_server(replies.into()).await; + let replies = stop_gates + .into_iter() + .chain([gate, second_gate]) + .map(|gate| { + vec![StreamingSseChunk { + gate: Some(gate), + body: denial.clone(), + }] + }); + let (stream, _completions) = start_streaming_sse_server(replies.collect()).await; let redirect = format!("{}/v1/responses", stream.uri()); const STOP_INTAKE: &str = "Trigger a routing failure."; + const STOP_AFTER_APPROVAL: &str = "stop-after-approval"; let next_call = Arc::new(Mutex::new(None::<&str>)); let pending_call = Arc::clone(&next_call); + let live_reviews = AtomicUsize::new(0); let requests = responses::mount_response_handler(&server, move |request| { let body = request.body_json(); let properties = &body["text"]["format"]["schema"]["properties"]; @@ -55,7 +63,10 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( let count = input["sources"].as_array().expect("batch sources").len(); json!({"descriptions":[{"channel":"task","description":"User task"}],"routes":vec![vec!["task"];count]}).to_string() } else if properties.get("outcome").is_some() { - if body["tools"].to_string().contains("guardian_board") { + // Allow the first MCP preflight, then hold its sensitive elicitation and shadow. + if body["tools"].to_string().contains("guardian_board") + || (expect_shadow && live_reviews.fetch_add(/*val*/ 1, Ordering::Relaxed) == 1) + { return wiremock::ResponseTemplate::new(/*s*/ 307) .insert_header("location", redirect.as_str()); } @@ -66,6 +77,14 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( responses::ev_function_call_with_namespace(id, &format!("mcp__{name}"), tool, &json!({"message": id}).to_string()), responses::ev_completed(id), ])); + } else if request + .inputs_of_type("function_call_output") + .last() + .is_some_and(|item| item["call_id"] == STOP_AFTER_APPROVAL) + { + // Keep the parent turn active after the approved tool returns. + return wiremock::ResponseTemplate::new(/*s*/ 307) + .insert_header("location", redirect.as_str()); } else { "Done.".to_string() }; @@ -115,7 +134,6 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( // Ensure the action exercises an enrolled reviewer even when startup is slow. app.wait_for_json_log_event("guardian_v3.shadow_intake_started", TIMEOUT) .await?; - // Neither the tool nor the parent turn needs the held GV3 verdict. let turn = |text: &str| TurnStartParams { thread_id: thread.id.clone(), input: vec![UserInput::Text { @@ -124,6 +142,47 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( }], ..Default::default() }; + if expect_shadow { + for (call, count, status) in [ + ("interrupt", 2, GuardianApprovalReviewStatus::Aborted), + ( + STOP_AFTER_APPROVAL, + 4, + GuardianApprovalReviewStatus::Approved, + ), + ] { + *next_call.lock().unwrap() = Some(call); + let id = app.send_turn_start_request(turn(USER_CONTEXT)).await?; + let started: TurnStartResponse = timeout(TIMEOUT, app.read_response(id)).await??; + // Hold the shadow alongside GV2 on the first turn and the parent on the second. + timeout(TIMEOUT, stream.wait_for_request_count(count)).await?; + app.interrupt_turn_and_wait_for_aborted(thread.id.clone(), started.turn.id, TIMEOUT) + .await?; + let method = "item/autoApprovalReview/completed"; + let preflight: ItemGuardianApprovalReviewCompletedNotification = + timeout(TIMEOUT, app.read_notification(method)).await??; + assert_eq!( + preflight.review.status, + GuardianApprovalReviewStatus::Approved + ); + let review: ItemGuardianApprovalReviewCompletedNotification = + timeout(TIMEOUT, app.read_notification(method)).await??; + assert_eq!(review.review.status, status); + app.wait_for_matching_json_log_event( + "interrupted shadow cancelled", + |event| { + event["fields"]["message"] == "Guardian shadow review cancelled" + && event["fields"]["review_id"] == review.review_id.as_str() + }, + TIMEOUT, + ) + .await?; + app.clear_message_buffer(); + } + drop(stop_holds); + } + let prior_requests = requests.requests().len(); + // The next review can start a shadow, and normal completion leaves it running. let check = async |app: &mut TestAppServer, id: &'static str, prompt: &str| { *next_call.lock().unwrap() = Some(id); let completed = timeout( @@ -162,17 +221,17 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( .count(), expected_reviews ); - if sensitive_action.is_none() || enforce_budget.is_some() { + if !expect_shadow { app.shutdown_gracefully().await?; assert!(stream.requests().await.is_empty()); stream.shutdown().await; mcp.abort(); return Ok(()); } - timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 1)).await?; - let verdicts = requests - .requests() - .into_iter() + timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 5)).await?; + let calls = requests.requests(); + let verdicts = calls[prior_requests..] + .iter() .filter(|r| { r.body_json()["text"]["format"]["schema"]["properties"] .get("outcome") @@ -181,10 +240,9 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( .count(); assert_eq!(verdicts, expected_reviews + 1); - let shadow = requests - .requests() - .into_iter() - .map(|r| r.body_json()) + let shadow = calls[prior_requests..] + .iter() + .map(responses::ResponsesRequest::body_json) .find(|body| body["tools"].to_string().contains("guardian_board")) .expect("shadow reviewer request"); let metadata = &shadow["client_metadata"]; @@ -199,7 +257,7 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( check(&mut app, "busy", "Check while the reviewer is busy.").await?; app.wait_for_stderr_line("Guardian shadow reviewer busy", TIMEOUT) .await?; - assert_eq!(stream.requests().await.len(), 1); + assert_eq!(stream.requests().await.len(), 5); // GV2 already approved the action. Let GV3 finish its independent denial. release.send(()).expect("shadow is still running"); @@ -218,15 +276,24 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( ); // Fail intake only after the next shadow has started. - check(&mut app, "in-flight", "Check before intake stops.").await?; - timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 2)).await?; + let in_flight = check(&mut app, "in-flight", "Check before intake stops.").await?; + timeout(TIMEOUT, stream.wait_for_request_count(/*count*/ 6)).await?; app.start_turn_and_wait_for_completion(turn(STOP_INTAKE)) .await?; app.wait_for_stderr_line("Guardian housekeeping stopped", TIMEOUT) .await?; // Cancellation must finish while the response is still held open. - app.wait_for_stderr_line("Guardian shadow review cancelled", TIMEOUT) - .await?; + app.wait_for_matching_json_log_event( + "in-flight shadow cancelled", + |event| { + event["fields"]["message"] == "Guardian shadow review cancelled" + && in_flight + .iter() + .any(|id| event["fields"]["review_id"] == id.as_str()) + }, + TIMEOUT, + ) + .await?; drop(hold); check(&mut app, "next", "Check again.").await?; app.wait_for_stderr_line( @@ -234,7 +301,7 @@ async fn only_fresh_reviews_start_a_nonblocking_shadow( TIMEOUT, ) .await?; - assert_eq!(stream.requests().await.len(), 2); + assert_eq!(stream.requests().await.len(), 6); app.shutdown_gracefully().await?; assert!( codex_core::find_thread_path_by_id_str(home.path(), shadow_id, /*state_db_ctx*/ None) diff --git a/codex-rs/core/src/guardian/review_request.rs b/codex-rs/core/src/guardian/review_request.rs index 6a570f0f9b..f4d57b7519 100644 --- a/codex-rs/core/src/guardian/review_request.rs +++ b/codex-rs/core/src/guardian/review_request.rs @@ -17,6 +17,7 @@ use codex_guardian_reviewer::ReviewHost; use codex_protocol::approvals::GuardianReviewReason; use codex_protocol::error::CodexErrorDetails; use codex_protocol::protocol::ErrorEvent; +use tokio_util::sync::DropGuard; type RootHistory = (codex_protocol::ThreadId, Option<[u8; 16]>, u64); @@ -231,7 +232,7 @@ impl ReviewHost for ReviewRuntime { &self, approval_id: &str, reason: GuardianReviewReason, - ) -> Option { + ) -> Option<(DropGuard, codex_guardian_reviewer::CohortSample)> { attached::shadow::start(self, approval_id, reason) } diff --git a/codex-rs/core/src/guardian/shadow.rs b/codex-rs/core/src/guardian/shadow.rs index f06ee26252..fd097e73c2 100644 --- a/codex-rs/core/src/guardian/shadow.rs +++ b/codex-rs/core/src/guardian/shadow.rs @@ -5,6 +5,7 @@ use crate::guardian::routes_approval_policy_to_guardian; use crate::guardian::runtime::ReviewRuntime; use crate::guardian_review::ShadowIntake; use crate::guardian_review::ShadowReviewer; +use codex_extension_api::ExtensionData; use codex_features::Feature; use codex_guardian_reviewer::CohortSample; use codex_guardian_reviewer::GuardianReviewOutcome; @@ -18,22 +19,37 @@ use codex_protocol::protocol::ReviewDecision; use std::sync::Arc; use std::time::Instant; use tokio::sync::Mutex; +use tokio_util::sync::CancellationToken; +use tokio_util::sync::DropGuard; #[derive(Default)] struct ShadowSlot(Arc>); +#[derive(Default)] +struct ShadowTurn { + aborted: CancellationToken, +} + +impl ShadowReviewer { + /// Cancel pending shadows and prevent later reviews from starting one for this turn. + pub fn cancel_for_turn(turn_store: &ExtensionData) { + turn_store.get_or_init(ShadowTurn::default).aborted.cancel(); + } +} + pub(in crate::guardian) fn start( live: &ReviewRuntime, approval_id: &str, reason: GuardianReviewReason, -) -> Option { +) -> Option<(DropGuard, CohortSample)> { // A fresh review cannot be cut short by a late async approval. if reason != GuardianReviewReason::FreshRequired { return None; } let store = &live.session.services.thread_extension_data; let intake = store.get::()?; - let config = &live.context.turn().config; + let turn = live.context.turn(); + let config = &turn.config; if live.attached_reviewer.is_some() || !config.features.enabled(Feature::GuardianV3Shadow) || !config.features.enabled(Feature::GuardianV2) @@ -48,8 +64,12 @@ pub(in crate::guardian) fn start( return None; } let runtime = store.get::()?; + let shadow_turn = turn.extension_data.get_or_init(ShadowTurn::default); // The live decision already holds a tracker token until this dispatch completes. - if live.history_reset.is_cancelled() || runtime.cancellation.is_cancelled() { + if live.history_reset.is_cancelled() + || runtime.cancellation.is_cancelled() + || shadow_turn.aborted.is_cancelled() + { return None; } let telemetry = &live.context.turn().session_telemetry; @@ -75,10 +95,10 @@ pub(in crate::guardian) fn start( shadow.attached_reviewer = Some(Arc::clone(&observer.reviewer)); shadow.context.review_execution = None; let review_id = approval_id.to_owned(); - let cancel = - crate::exec::cancel_when_either(observer.cancellation.clone(), live.history_reset.clone()); - runtime.tasks.spawn(async move { - let _cancel_on_drop = cancel.clone().drop_guard(); + let cancel = observer.cancellation.child_token(); + let pending = cancel.clone().drop_guard(); + let cancel_on_interrupt = cancel.clone().drop_guard(); + let review = async move { let prepared = run_before_review_deadline(deadline, Some(&cancel), async { let (request, context) = shadow.approval_inputs().await?; shadow @@ -110,6 +130,8 @@ pub(in crate::guardian) fn start( // 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; + drop(prepared); + drop(permit); // Retirement can surface as a transport error or arrive during usage recording // after the verdict was validated. Keep completed verdicts in the comparison. if cancel.is_cancelled() && matches!(&outcome, GuardianReviewOutcome::Error(_)) { @@ -117,8 +139,6 @@ pub(in crate::guardian) fn start( return; // Dropping the sample records cancellation. } candidate.finish(&outcome, &analytics); - drop(prepared); - drop(permit); match outcome { GuardianReviewOutcome::Completed(assessment) => { tracing::debug!(%review_id, outcome = ?assessment.outcome, "Guardian shadow verdict"); @@ -128,6 +148,19 @@ pub(in crate::guardian) fn start( } GuardianReviewOutcome::CachedApproval => {} } + }; + let history_reset = live.history_reset.clone(); + runtime.tasks.spawn(async move { + tokio::pin!(review); + // These signals still apply after GV2 releases its pending-review guard. + tokio::select! { + biased; + _ = shadow_turn.aborted.cancelled() => {} + _ = history_reset.cancelled() => {} + () = &mut review => return, + } + drop(cancel_on_interrupt); + review.await; // Drain the cancelled attempt before releasing the actor's slot. }); - Some(baseline) + Some((pending, baseline)) } diff --git a/codex-rs/ext/guardian-reviewer/src/review.rs b/codex-rs/ext/guardian-reviewer/src/review.rs index 90674f8ba4..e356c8a33f 100644 --- a/codex-rs/ext/guardian-reviewer/src/review.rs +++ b/codex-rs/ext/guardian-reviewer/src/review.rs @@ -27,6 +27,7 @@ use std::sync::Arc; use std::sync::atomic::AtomicI64; use std::sync::atomic::Ordering; use tokio_util::sync::CancellationToken; +use tokio_util::sync::DropGuard; /// Operations bound to one immutable action and its issuing context. /// Hosts validate authority, publish supplied events and interrupt only the selected turn; @@ -43,12 +44,12 @@ pub trait ReviewHost: Clone + Send + Sync + 'static { fn servicing_turn(&self) -> impl Future)>> + Send; /// Returns the owning turn and optional target item after validating the action. fn validate_action(&self) -> Result<(&str, Option<&str>), ReviewDecision>; - /// Return a live comparison sample only when a shadow review starts. + /// Start a shadow and return a guard that cancels it if the live review is interrupted. fn start_shadow( &self, _approval_id: &str, _reason: GuardianReviewReason, - ) -> Option { + ) -> Option<(DropGuard, crate::CohortSample)> { None } /// Prepares evidence and accounting, with a client event only for supported actions. @@ -92,6 +93,28 @@ pub trait ReviewHost: Clone + Send + Sync + 'static { ) -> impl Future + Send; } +/// Cancel the shadow if the pending live review is interrupted or dropped. +/// Once the live outcome is ready, let the shadow finish independently. +async fn run_with_pending_shadow( + live: F, + cancellation: &CancellationToken, + guard: Option, +) -> F::Output { + tokio::pin!(live); + let Some(guard) = guard else { + return live.await; + }; + let Some(result) = cancellation.run_until_cancelled(&mut live).await else { + drop(guard); + return live.await; // Finish the same live review's cleanup. + }; + // The outcome and cancellation can become ready in the same poll. + if !cancellation.is_cancelled() { + guard.disarm(); + } + result +} + struct EvaluatedReview { prepared: Arc, report: ReviewReport, @@ -224,21 +247,23 @@ impl SynchronousApprovalReviewer for ReviewRequest<'_, H> { &[("route", "required_sync"), ("reason", reason.into())], ); } - let baseline = if self.cancellation.is_cancelled() { + let (guard, baseline) = if self.cancellation.is_cancelled() { None } else { self.host.start_shadow(self.approval_id, reason) - }; + } + .unzip(); let host_deadline = self.host_deadline; let deadline = host_deadline.unwrap_or_else(|| ReviewDeadline::from_timeout(self.timeout)); + let live = self.evaluate(reason, async_approval, deadline); let EvaluatedReview { prepared, report, outcome, analytics, evidence, - } = match self.evaluate(reason, async_approval, deadline).await { + } = match run_with_pending_shadow(live, &self.cancellation, guard).await { Ok(result) => result, Err(mut decision) => { if host_deadline.is_some_and(ReviewDeadline::is_elapsed) { diff --git a/codex-rs/ext/guardian-reviewer/src/review_tests.rs b/codex-rs/ext/guardian-reviewer/src/review_tests.rs index 56e2204c7d..c03d791b1b 100644 --- a/codex-rs/ext/guardian-reviewer/src/review_tests.rs +++ b/codex-rs/ext/guardian-reviewer/src/review_tests.rs @@ -1,4 +1,4 @@ -//! Exercises async approval and recovered denials at the host boundary. +//! Exercises async approval, recovered denials and shadow cancellation at the host boundary. use super::*; use crate::ReviewMetadata; @@ -37,6 +37,7 @@ const SCORED: CachedApprovalContext = CachedApprovalContext { #[derive(Clone)] struct GatedHost { + shadow: Option<(CancellationToken, SessionTelemetry)>, started: Arc, cleaning: Arc, cleanup: Arc, @@ -59,6 +60,19 @@ impl ReviewHost for GatedHost { fn validate_action(&self) -> Result<(&str, Option<&str>), ReviewDecision> { Ok(("turn", Some("call"))) } + fn start_shadow( + &self, + _: &str, + _: GuardianReviewReason, + ) -> Option<(DropGuard, crate::CohortSample)> { + let (cancel, telemetry) = self.shadow.as_ref()?; + let [live, _] = crate::CohortSample::start( + telemetry, + GuardianScope::Permissions, + std::time::Instant::now(), + ); + Some((cancel.clone().drop_guard(), live)) + } async fn prepare( &self, approval_id: &str, @@ -135,7 +149,10 @@ impl ReviewHost for GatedHost { ApprovalState::ContextChanged => *context += 1, ApprovalState::WorkerRevoked => current.user_message_revision += 1, ApprovalState::WorkerContextChanged => current.review_context_revision += 1, - ApprovalState::Current | ApprovalState::Cancelled | ApprovalState::RecoveredDenial => {} + ApprovalState::Current + | ApprovalState::Cancelled + | ApprovalState::ToolCancelledWithShadow + | ApprovalState::RecoveredDenial => {} } Some(current) } @@ -157,6 +174,7 @@ enum ApprovalState { WorkerRevoked, WorkerContextChanged, Cancelled, + ToolCancelledWithShadow, RecoveredDenial, } @@ -167,10 +185,12 @@ enum ApprovalState { #[test_case::test_case(ApprovalState::WorkerRevoked; "worker authorization changes after late low")] #[test_case::test_case(ApprovalState::WorkerContextChanged; "worker review context changes after late low")] #[test_case::test_case(ApprovalState::Cancelled; "cancelled action")] +#[test_case::test_case(ApprovalState::ToolCancelledWithShadow; "tool cancellation stops the shadow during live cleanup")] #[test_case::test_case(ApprovalState::RecoveredDenial; "hosted timeout retains denial")] #[tokio::test(start_paused = true)] async fn review_handles_async_approval_and_timeout(state: ApprovalState) { let host = GatedHost { + shadow: None, started: Arc::new(Notify::new()), cleaning: Arc::new(Notify::new()), cleanup: Arc::new(Semaphore::new(/*permits*/ 0)), @@ -242,6 +262,33 @@ async fn review_handles_async_approval_and_timeout(state: ApprovalState) { | ApprovalState::WorkerRevoked | ApprovalState::WorkerContextChanged | ApprovalState::Cancelled => ReviewDecision::Abort, + ApprovalState::ToolCancelledWithShadow => { + let turn = CancellationToken::new(); + let shadow = CancellationToken::new(); + let mut request = request; + request.cancellation = turn.child_token(); + request.host.shadow = Some((shadow.clone(), telemetry.clone())); + let review = request.review( + GuardianReviewReason::FreshRequired, + /*async_approval*/ None, + ); + tokio::pin!(review); + tokio::select! { + _ = &mut review => panic!("live review returned before cleanup was released"), + () = async { + host.started.notified().await; + assert!(!shadow.is_cancelled()); + request.cancellation.cancel(); + host.cleaning.notified().await; + } => {} + } + assert!(!turn.is_cancelled()); + assert!(shadow.is_cancelled()); + host.cleanup.add_permits(/*n*/ 1); + let _ = review.await; + assert!(host.cleaned.load(Ordering::SeqCst)); + return; + } ApprovalState::RecoveredDenial => { let decision = request .review( diff --git a/codex-rs/ext/guardian-v3/src/host.rs b/codex-rs/ext/guardian-v3/src/host.rs index cc7ca00472..e17feece67 100644 --- a/codex-rs/ext/guardian-v3/src/host.rs +++ b/codex-rs/ext/guardian-v3/src/host.rs @@ -600,6 +600,9 @@ impl TurnLifecycleContributor for Host { } fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> { + if input.thread_store.get::().is_some() { + ShadowReviewer::cancel_for_turn(input.turn_store); + } wake_worker(input.thread_store); Box::pin(std::future::ready(())) }