From d800b00e886a77181baf03e9e9aa2ea3445d9a4b Mon Sep 17 00:00:00 2001 From: felixxia-oai Date: Wed, 25 Nov 2026 16:22:14 +0000 Subject: [PATCH] Restart Guardian v3 shadow intake when Auto Review resumes (#63988) ## Why Switching an enrolled thread to user approvals stops Guardian v3 shadow intake. Previously, switching the same thread back to Auto Review left intake stopped for subsequent turns. ## What changed Restart intake in the background with a fresh evidence board after checking that the thread still routes approvals to Auto Review. Start at the end of persisted history so the new board only receives new evidence. Existing child threads can attach to the new board on their next turn. ## Testing Add app-server coverage for routing later turns after Auto Review resumes without replaying earlier turns. Extend the host test to cover stale settings notifications, cancellation of a queued restart, and creation of a fresh board and reviewer. GitOrigin-RevId: 5201d7f7a7e3f2c045c69b9584b036467a5767d7 --- .../tests/suite/v2/guardian_v3_sync_tests.rs | 101 ++++++++++++++++++ codex-rs/ext/guardian-v3/src/host.rs | 54 ++++++---- codex-rs/ext/guardian-v3/src/host_tests.rs | 40 +++++++ codex-rs/ext/guardian-v3/src/shadow.rs | 66 ++++++++++-- 4 files changed, 227 insertions(+), 34 deletions(-) diff --git a/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs b/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs index cc2ff4d75a..e87d9529d7 100644 --- a/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs +++ b/codex-rs/app-server/tests/suite/v2/guardian_v3_sync_tests.rs @@ -28,6 +28,107 @@ fn expects_field(request: &responses::ResponsesRequest, field: &str) -> bool { .is_some() } +#[tokio::test] +async fn returning_to_auto_review_restarts_shadow_intake_without_replaying_history() -> Result<()> { + skip_if_no_network!(Ok(())); + const FIRST: &str = "Review the first release."; + const PRIVATE: &str = "I will review the second release."; + const RESUME: &str = "Resume auto review."; + const LATER: &str = "Review the third release."; + + let server = responses::start_mock_server().await; + let routed = Arc::new(Notify::new()); + let later_routed = Arc::new(Notify::new()); + let notify_first = routed.clone(); + let notify_later = later_routed.clone(); + let requests = responses::mount_response_handler(&server, move |request| { + let body = request.body_json(); + let text = + if let Some(routes) = body["text"]["format"]["schema"]["properties"].get("routes") { + let count = routes["minItems"].as_u64().expect("routing batch size") as usize; + let input = body["input"].to_string(); + if input.contains(FIRST) { + notify_first.notify_one(); + } + if input.contains(LATER) { + notify_later.notify_one(); + } + json!({ + "routes": vec![vec!["release"]; count], + "descriptions": [{"channel": "release", "description": "Release policy"}], + }) + .to_string() + } else { + "Done.".to_owned() + }; + responses::sse_response(assistant_response(&text).expect("mock response")) + }) + .await; + let home = TempDir::new()?; + MockResponsesConfig::new(&server.uri()) + .with_provider_config("supports_websockets = false") + .with_approval_policy("on-request") + .enable_feature(Feature::GuardianApproval) + .enable_feature(Feature::GuardianV2) + .enable_feature(Feature::GuardianV3Shadow) + .write(home.path())?; + let mut app = TestAppServer::builder() + .with_codex_home(home.path()) + .with_json_logging("warn,codex_guardian_v3::host=debug") + .build_initialized_with_timeout(TIMEOUT) + .await?; + let thread = app + .start_thread(ThreadStartParams { + approvals_reviewer: Some(ApprovalsReviewer::AutoReview), + history_mode: Some(ThreadHistoryMode::Paginated), + ..Default::default() + }) + .await? + .thread; + for (reviewer, text) in [ + (ApprovalsReviewer::AutoReview, FIRST), + (ApprovalsReviewer::User, PRIVATE), + (ApprovalsReviewer::AutoReview, RESUME), + (ApprovalsReviewer::AutoReview, LATER), + ] { + let completed = app + .start_turn_and_wait_for_completion(TurnStartParams { + thread_id: thread.id.clone(), + approvals_reviewer: Some(reviewer), + input: vec![UserInput::Text { + text: text.to_owned(), + text_elements: vec![], + }], + ..Default::default() + }) + .await?; + assert_eq!(completed.turn.status, TurnStatus::Completed); + if text == FIRST { + timeout(TIMEOUT, routed.notified()).await?; + } else if text == RESUME { + // The enabling turn may precede the new board's history cursor. + app.wait_for_json_log_event("guardian_v3.shadow_intake_restarted", TIMEOUT) + .await?; + } + } + timeout(TIMEOUT, later_routed.notified()).await?; + app.shutdown_gracefully().await?; + for request in requests + .requests() + .iter() + .filter(|r| expects_field(r, "routes")) + { + let body = request.body_json(); + assert_eq!(body["model"], "gpt-5.6-luna"); + let input = body["input"].to_string(); + assert!(!input.contains(PRIVATE)); + if input.contains(LATER) { + assert!(!input.contains(FIRST)); + } + } + Ok(()) +} + fn received_user_instruction(request: &responses::ResponsesRequest, text: &str) -> bool { request .inputs_of_type("function_call_output") diff --git a/codex-rs/ext/guardian-v3/src/host.rs b/codex-rs/ext/guardian-v3/src/host.rs index 50330ca03e..a9be015fbc 100644 --- a/codex-rs/ext/guardian-v3/src/host.rs +++ b/codex-rs/ext/guardian-v3/src/host.rs @@ -121,6 +121,15 @@ impl Host { } } +#[derive(Clone, Copy)] +enum IntakeStart { + Initial( + codex_protocol::protocol::ThreadHistoryMode, + HistoryInitialization, + ), + Restart, +} + #[derive(Clone)] enum BoardStorage { File(SqliteConfig), @@ -193,25 +202,32 @@ impl Host { root: ThreadId, tree: &TreeDelivery, thread: &ExtensionData, - mode: codex_protocol::protocol::ThreadHistoryMode, - initialization: HistoryInitialization, + start: IntakeStart, ) -> anyhow::Result<()> { let history = self .manager .upgrade() .context("Guardian host stopped")? .thread_store(); - if matches!(self.storage, BoardStorage::Memory) { - anyhow::ensure!( - matches!( - initialization, - HistoryInitialization::New | HistoryInitialization::Cleared - ), - "in-memory Guardian evidence requires a fresh root" - ); - } - let cursor = - EvidenceCursor::at_thread_ready(history.as_ref(), root, mode, initialization).await?; + let cursor = match start { + IntakeStart::Initial(mode, initialization) => { + if matches!(self.storage, BoardStorage::Memory) { + anyhow::ensure!( + matches!( + initialization, + HistoryInitialization::New | HistoryInitialization::Cleared + ), + "in-memory Guardian evidence requires a fresh root" + ); + } + EvidenceCursor::at_thread_ready(history.as_ref(), root, mode, initialization) + .await? + } + IntakeStart::Restart => { + history.flush_thread(root).await?; + EvidenceCursor::from_now(history.as_ref(), root).await? + } + }; let board_host = (self.board_host)(root); let board = match &self.storage { BoardStorage::File(sqlite) => { @@ -414,16 +430,8 @@ impl ThreadLifecycleContributor for Host { if actor != root { return; } - if let Err(error) = self - .activate( - root, - &tree, - input.thread_store, - input.history_mode, - input.history_initialization, - ) - .await - { + let start = IntakeStart::Initial(input.history_mode, input.history_initialization); + if let Err(error) = self.activate(root, &tree, input.thread_store, start).await { tracing::warn!(%root, error = %error, "Guardian intake unavailable"); return; } diff --git a/codex-rs/ext/guardian-v3/src/host_tests.rs b/codex-rs/ext/guardian-v3/src/host_tests.rs index 2a57671035..634c5948aa 100644 --- a/codex-rs/ext/guardian-v3/src/host_tests.rs +++ b/codex-rs/ext/guardian-v3/src/host_tests.rs @@ -603,6 +603,7 @@ async fn shadow_intake_enrolls_only_new_opted_in_roots() -> anyhow::Result<()> { assert_eq!(thread.get::().is_some(), expected); assert!(thread.get::>().is_none()); } + let old_worker = thread.get::().context("first board")?; let old_reviewer = thread.get::().context("first reviewer")?; let child = ExtensionData::new(ThreadId::new().to_string()); let source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { @@ -638,6 +639,45 @@ async fn shadow_intake_enrolls_only_new_opted_in_roots() -> anyhow::Result<()> { assert!(thread.get::().is_none()); assert!(thread.get::().is_none()); + test.thread_store + .persist_thread(root, PersistContext::Standard) + .await?; + let enrollment = thread + .get::() + .context("enrollment")?; + let set_reviewer = |reviewer| { + test.codex + .update_thread_settings(codex_protocol::protocol::ThreadSettingsOverrides { + approval_policy: Some(AskForApproval::OnRequest), + approvals_reviewer: Some(reviewer), + ..Default::default() + }) + }; + // A delayed Auto Review notification must not override the root's live settings. + set_reviewer(ApprovalsReviewer::User).await?; + settings.on_config_changed(&session, thread, &disabled, &config); + assert_eq!(turns.on_turn_start(start()).now_or_never(), Some(())); + enrollment.drain().await; + assert!(thread.get::().is_none()); + assert!(thread.get::().is_none()); + + // Keep the root eligible so only cancellation can stop the queued restart. + set_reviewer(ApprovalsReviewer::AutoReview).await?; + settings.on_config_changed(&session, thread, &disabled, &config); + assert_eq!(turns.on_turn_start(start()).now_or_never(), Some(())); + settings.on_config_changed(&session, thread, &config, &disabled); + enrollment.drain().await; + assert!(thread.get::().is_none()); + assert!(thread.get::().is_none()); + + settings.on_config_changed(&session, thread, &disabled, &config); + assert_eq!(turns.on_turn_start(start()).now_or_never(), Some(())); + enrollment.drain().await; + let new_worker = thread.get::().context("fresh board")?; + let new_reviewer = thread.get::().context("fresh reviewer")?; + assert!(!Arc::ptr_eq(&old_worker.reader, &new_worker.reader)); + assert!(!Arc::ptr_eq(&old_reviewer.reviewer, &new_reviewer.reviewer)); + assert!(!new_reviewer.cancellation.is_cancelled()); lifecycle .on_thread_stop(ThreadStopInput { thread_store: thread, diff --git a/codex-rs/ext/guardian-v3/src/shadow.rs b/codex-rs/ext/guardian-v3/src/shadow.rs index 61c659079a..d6255d5b1c 100644 --- a/codex-rs/ext/guardian-v3/src/shadow.rs +++ b/codex-rs/ext/guardian-v3/src/shadow.rs @@ -1,4 +1,5 @@ -//! Shadow intake starts off the live path and stops when the root leaves Auto Review. +//! A root keeps its enrollment across settings changes, but each stretch of +//! Auto Review owns a separate board, housekeeper and set of reviewers. use std::sync::Arc; use std::sync::Mutex; @@ -10,12 +11,14 @@ use codex_core::config::Config; use codex_core::guardian_review::ShadowReviewer; use codex_extension_api::ConfigContributor; use codex_extension_api::ExtensionData; +use codex_guardian_reviewer::routes_approval_policy_to_guardian; use codex_protocol::AgentPath; use codex_protocol::ThreadId; use tokio_util::task::TaskTracker; use super::ActorReviewer; use super::Host; +use super::IntakeStart; use super::RootWorker; use super::TreeDelivery; @@ -25,21 +28,30 @@ pub(super) struct Actor { pub(super) path: AgentPath, } -#[derive(Default)] enum State { // Covers startup and the published worker. Both share one cancellation token. Running(Arc), Off, - #[default] - PendingStart, + PendingStart(IntakeStart), } -#[derive(Default)] pub(super) struct Enrollment { state: Mutex, tasks: TaskTracker, } +impl Default for Enrollment { + fn default() -> Self { + Self { + state: Mutex::new(State::PendingStart(IntakeStart::Initial( + codex_protocol::protocol::ThreadHistoryMode::Paginated, + codex_history::HistoryInitialization::New, + ))), + tasks: TaskTracker::new(), + } + } +} + impl Enrollment { pub(super) fn stop(&self, thread: &ExtensionData) { let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); @@ -85,6 +97,14 @@ impl ConfigContributor for Host { }; if !self.enabled(config) { enrollment.stop(thread); + } else { + let mut state = enrollment + .state + .lock() + .unwrap_or_else(PoisonError::into_inner); + if matches!(*state, State::Off) { + *state = State::PendingStart(IntakeStart::Restart); + } } } } @@ -117,8 +137,11 @@ impl Host { }; let root = identity.root; if identity.actor != root { - // The root board may become available after a child starts. - if thread.get::().is_some() { + // A surviving child joins the new board on its next turn. + if thread + .get::() + .is_some_and(|r| !r.cancellation.is_cancelled()) + { return; } self.attach_shadow(thread, &identity, &self.tree_delivery(root)); @@ -131,7 +154,7 @@ impl Host { .state .lock() .unwrap_or_else(PoisonError::into_inner); - let State::PendingStart = *state else { + let State::PendingStart(start) = *state else { return; }; let tree = self.tree_delivery(root); @@ -139,6 +162,8 @@ impl Host { let host = self.clone(); let current = Arc::clone(&enrollment); enrollment.tasks.spawn(async move { + // On restart the durable tail may already include the enabling turn. + // Missing it is preferable to delaying the turn or replaying disabled history. let startup = async { let manager = host.manager.upgrade().context("Guardian host stopped")?; let root_thread = manager @@ -146,18 +171,37 @@ impl Host { std::ptr::eq(e, current.as_ref()) }) .await?; + // Config notifications can arrive out of order. Confirm the root + // still uses Auto Review before opening a board or reading history. + if matches!(start, IntakeStart::Restart) { + let settings = root_thread.thread_settings_snapshot().await; + if !routes_approval_policy_to_guardian( + settings.approval_policy, + settings.approvals_reviewer, + ) { + let mut state = current.state.lock().unwrap_or_else(PoisonError::into_inner); + if !tree.stop.is_cancelled() { + *state = State::Off; + } + return anyhow::Ok(()); + } + } let thread = root_thread.thread_extension_data(); - host.activate(root, &tree, thread, codex_protocol::protocol::ThreadHistoryMode::Paginated, codex_history::HistoryInitialization::New).await?; + host.activate(root, &tree, thread, start).await?; host.attach_shadow(thread, &identity, &tree); if !tree.stop.is_cancelled() { - tracing::debug!(event.name = "guardian_v3.shadow_intake_started", %root, "Guardian shadow intake started"); + let event_name = match start { + IntakeStart::Initial(..) => "guardian_v3.shadow_intake_started", + IntakeStart::Restart => "guardian_v3.shadow_intake_restarted", + }; + tracing::debug!(event.name = event_name, %root, "Guardian shadow intake started"); } anyhow::Ok(()) }; if let Some(Err(_)) = tree.stop.run_until_cancelled(startup).await { let mut state = current.state.lock().unwrap_or_else(PoisonError::into_inner); if !tree.stop.is_cancelled() { - *state = State::PendingStart; + *state = State::PendingStart(start); drop(state); tracing::warn!(%root, "Guardian shadow intake unavailable until the next turn"); }