From cc6e8a968de32f83552eef9854151782d6db0db6 Mon Sep 17 00:00:00 2001 From: felixxia-oai Date: Wed, 25 Nov 2026 14:59:13 +0000 Subject: [PATCH] Use reset checks for attached Guardian V3 reviews (#63948) ## Why Attached reviewers need to detect root history resets that can invalidate an approval. Preparing an attached review previously fetched root conversation evidence even though the reviewer did not use it for preparation. ## What changed - Check the root history version before starting an attached review and while it runs. Local MultiAgent V2 workers resolve the currently loaded root thread, and hosted workers use the host's root snapshot. - Skip root evidence capture when preparing or prewarming attached reviewers. Skip per-attempt evidence collection for attached observers and sessions without an evidence store. Live reviewers with an evidence store still record their verdicts. ## Testing Add coverage for root history version changes on reset, version stability on append, root resolution after reload, and verdict recording when the first approval reuses a prewarmed reviewer. GitOrigin-RevId: b3ff7e58883d5f72bea3d774e05ba2f678df45fc --- codex-rs/core/src/guardian/attached_review.rs | 42 +++++++++++++--- codex-rs/core/src/guardian/review_request.rs | 50 +++++++++++-------- .../core/src/guardian/review_session_setup.rs | 11 +++- codex-rs/core/src/guardian_review.rs | 5 ++ .../core/src/session/guardian_checkpoint.rs | 15 +++++- .../src/session/guardian_checkpoint_tests.rs | 19 +++++++ codex-rs/ext/guardian-v3/src/actor.rs | 9 ++++ .../ext/guardian-v3/tests/housekeeping.rs | 28 +++++++++++ 8 files changed, 149 insertions(+), 30 deletions(-) diff --git a/codex-rs/core/src/guardian/attached_review.rs b/codex-rs/core/src/guardian/attached_review.rs index 7bc84e1559..a3e37c1200 100644 --- a/codex-rs/core/src/guardian/attached_review.rs +++ b/codex-rs/core/src/guardian/attached_review.rs @@ -17,6 +17,28 @@ use codex_guardian_reviewer::SessionDisposition; use codex_protocol::user_input::UserInput; use tokio::sync::Mutex; +pub(super) async fn root_history_version( + parent: &Session, + reviewer: &dyn AttachedReviewer, +) -> codex_protocol::error::Result> { + // A hosted worker's authoritative runtime and reset version come from its host. + if parent.host_guardian_context().is_some() { + return Ok(parent + .guardian_root_snapshot() + .await? + .as_ref() + .map(super::root_history_key)); + } + let Some(root) = reviewer.root_thread().await else { + return Ok(None); + }; + Ok(root + .session + .guardian_root_history_version() + .await + .map(|(id, version)| (id, None, version))) +} + pub(super) struct AttachedApproval { provider: Arc, config: GuardianReviewSessionConfig, @@ -64,6 +86,7 @@ impl AttachedApproval { config.spawn_config.clone(), &parent.clone_history().await, &config.node_repl_policy, + /*uses_root_evidence*/ false, ) .await .map_err(|_| ReviewPreparationError::ReviewerUnavailable)?; @@ -78,10 +101,21 @@ impl AttachedApproval { deadline: ReviewDeadline, cancel: &CancellationToken, ) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) { + let root_error = |error: codex_protocol::error::CodexErr| match error.details() { + super::CodexErrorDetails::Timeout => GuardianReviewSessionOutcome::TimedOut, + _ => GuardianReviewSessionOutcome::Aborted, + }; let mut reservation = None; let mut analytics = GuardianReviewAnalyticsResult::without_session(); let mut usage_at_start = None; let prepare = async { + if approval.root_history + != root_history_version(parent, self.provider.as_ref()) + .await + .map_err(root_error)? + { + return Err(GuardianReviewSessionOutcome::Aborted); + } let first = self.first.lock().await.take(); let model = match first { Some(first) => first, @@ -179,12 +213,8 @@ impl AttachedApproval { return Err(GuardianReviewSessionOutcome::TimedOut); } } - root = parent.guardian_root_snapshot() => { - let root = root.map_err(|error| match error.details() { - super::CodexErrorDetails::Timeout => GuardianReviewSessionOutcome::TimedOut, - _ => GuardianReviewSessionOutcome::Aborted, - })?; - if approval.root_history != root.as_ref().map(super::root_history_key) { + root = root_history_version(parent, self.provider.as_ref()) => { + if approval.root_history != root.map_err(root_error)? { return Err(GuardianReviewSessionOutcome::Aborted); } } diff --git a/codex-rs/core/src/guardian/review_request.rs b/codex-rs/core/src/guardian/review_request.rs index 24c136ca8c..3d7bee7c67 100644 --- a/codex-rs/core/src/guardian/review_request.rs +++ b/codex-rs/core/src/guardian/review_request.rs @@ -6,6 +6,7 @@ mod attached; use super::super::runtime::validate; use super::*; use crate::codex_thread::GuardianAuthorizationVersion; +use crate::guardian_review::AttachedReviewer; use crate::guardian_review::ReviewPreparationError; use attached::AttachedApproval; use codex_config::config_toml::CircuitBreakAction; @@ -229,12 +230,10 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { model_context, timeout: turn.config.guardian_review_timeout, }; - let root = session - .guardian_root_snapshot() - .await - .map_err(|error| ReviewDecision::denied(error.to_string()))?; - let root_history = root.as_ref().map(root_history_key); - let attached = if let Some(provider) = attached_reviewer { + let (root_history, attached) = if let Some(provider) = attached_reviewer { + let root_history = attached::root_history_version(&session, provider.as_ref()) + .await + .map_err(|error| ReviewDecision::denied(error.to_string()))?; let started = Instant::now(); tracing::info!( %review_id, @@ -267,9 +266,13 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { "Guardian V3 could not prepare the evidence for this action: {error}" )), })?; - Some(prepared) + (root_history, Some(prepared)) } else { - None + let root = session + .guardian_root_snapshot() + .await + .map_err(|error| ReviewDecision::denied(error.to_string()))?; + (root.as_ref().map(root_history_key), None) }; Ok(( PreparedApproval { @@ -301,9 +304,20 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { None, ); } - // Every attempt rebuilds the prompt from live history. Capture its revision and - // cache attribution anew too; a retried verdict must not use the first snapshot. let session = &self.session; + let extensions = &session.services.thread_extension_data; + let store = extensions.get::(); + // Only the thread's live reviewer publishes previous reviews. An + // observer or a session without a store needs just the reset checks. + if let Some(attached) = &prepared.attached + && (store.is_none() || extensions.get::>().is_none()) + { + let (outcome, analytics) = attached + .attempt(session, prepared, &self.reasons, deadline, cancellation) + .await; + return (outcome, analytics, None); + } + // Attribute the verdict to the history versions at the start of this attempt. let root_snapshot = match session.guardian_root_snapshot().await { Ok(snapshot) => snapshot, Err(error) => { @@ -329,16 +343,12 @@ impl ReviewHost for super::super::runtime::ReviewRuntime { let history = session.conversation_history_snapshot().await; let user_message_revision = history.user_message_revision(); let review_context_revision = history.guardian_review_context_revision(); - let review_evidence = session - .services - .thread_extension_data - .get::() - .map(|store| ApprovalEvidence { - authorization_version: store.authorization_version(history.as_ref()), - review_context_revision, - store, - root_versions, - }); + let review_evidence = store.map(|store| ApprovalEvidence { + authorization_version: store.authorization_version(history.as_ref()), + review_context_revision, + store, + root_versions, + }); drop(history); let (outcome, analytics) = if let Some(attached) = &prepared.attached { attached diff --git a/codex-rs/core/src/guardian/review_session_setup.rs b/codex-rs/core/src/guardian/review_session_setup.rs index 6385f2aca2..8f5b77d6e4 100644 --- a/codex-rs/core/src/guardian/review_session_setup.rs +++ b/codex-rs/core/src/guardian/review_session_setup.rs @@ -37,6 +37,7 @@ impl PreparedGuardianContext { config: Config, history: &ContextManager, node_repl_policy: &GuardianNodeReplPolicy, + uses_root_evidence: bool, ) -> anyhow::Result { let (reset_version, history_reset) = parent.history_reset().await; // Preparation may have raced with a history reset before capturing the reviewer context. @@ -46,8 +47,11 @@ impl PreparedGuardianContext { let context_mode = GuardianContextMode::from_history(history.conversation_history_snapshot().as_ref()); let context_policy = ReviewContextPolicy::for_context(context_mode, &config.features); - let root_review_version = - context_policy::root_review_version(context_policy, &parent).await?; + let root_review_version = if uses_root_evidence { + context_policy::root_review_version(context_policy, &parent).await? + } else { + None + }; let parent_compaction = context_policy.parent_compaction(history.annotated_items())?; let mut instructions = parent.inherited_instructions().await; context.capture_project_instructions(&parent).await; @@ -424,6 +428,7 @@ pub(in crate::guardian) async fn prepare_review( params.spawn_config.clone(), ¶ms.parent_history, ¶ms.node_repl_policy, + /*uses_root_evidence*/ true, ) .await?; Ok(PreparedReview { @@ -453,6 +458,7 @@ pub(super) fn prepare_prewarm( ) -> BoxFuture<'static, anyhow::Result> { Box::pin(async move { let context = GuardianReviewContext::from(turn); + let uses_root_evidence = matches!(retrieval, ReviewRetrieval::ConversationHistory); let config = guardian_review_session_config(&parent, &context, retrieval).await?; let history = parent.clone_history().await; PreparedGuardianContext::prepare( @@ -461,6 +467,7 @@ pub(super) fn prepare_prewarm( config.spawn_config, &history, &config.node_repl_policy, + uses_root_evidence, ) .await }) diff --git a/codex-rs/core/src/guardian_review.rs b/codex-rs/core/src/guardian_review.rs index a26e9d54b7..2a7e3ad793 100644 --- a/codex-rs/core/src/guardian_review.rs +++ b/codex-rs/core/src/guardian_review.rs @@ -60,6 +60,11 @@ pub enum ReviewPreparationError { pub trait AttachedReviewer: Send + Sync { fn retrieval(&self) -> ReviewRetrieval; + /// Resolve the worker's currently loaded root. The root actor uses its own reset signal. + fn root_thread( + &self, + ) -> codex_extension_api::ExtensionFuture<'_, Option>>; + fn prepare<'a>( &'a self, setup: &'a PreparedGuardianContext, diff --git a/codex-rs/core/src/session/guardian_checkpoint.rs b/codex-rs/core/src/session/guardian_checkpoint.rs index 1d5498369f..fccf28b89e 100644 --- a/codex-rs/core/src/session/guardian_checkpoint.rs +++ b/codex-rs/core/src/session/guardian_checkpoint.rs @@ -1,13 +1,24 @@ -//! Captures a completed Guardian model context using the existing fork replay format. -//! This snapshot is in memory only; transcript durability remains part of turn completion. +//! Reads Guardian history lifetimes and captures completed reviewer contexts for fork replay. +//! Both operate on live state. Transcript durability remains part of turn completion. use super::session::Session; use codex_history::CompactedItem; use codex_history::RolloutItem; +use codex_protocol::ThreadId; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::MultiAgentVersion; use codex_protocol::protocol::TokenCountEvent; impl Session { + /// Only MultiAgent V2 workers use a separate root history for review. + pub(crate) async fn guardian_root_history_version(&self) -> Option<(ThreadId, u64)> { + if self.multi_agent_version() != Some(MultiAgentVersion::V2) { + return None; + } + let version = self.state.lock().await.history.reset_version; + Some((self.thread_id, version)) + } + pub(crate) async fn guardian_fork_history(&self) -> Vec { let state = self.state.lock().await; let history = &state.history; diff --git a/codex-rs/core/src/session/guardian_checkpoint_tests.rs b/codex-rs/core/src/session/guardian_checkpoint_tests.rs index 799fc1f7f6..4ed0525f0a 100644 --- a/codex-rs/core/src/session/guardian_checkpoint_tests.rs +++ b/codex-rs/core/src/session/guardian_checkpoint_tests.rs @@ -4,13 +4,32 @@ use crate::context_manager::ContextManager; use crate::session::tests::make_session_and_context; use codex_history::InitialHistory; use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::MultiAgentVersion; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::protocol::TokenUsage; use codex_thread_context_ids_test_support::thread_context_ids; +use core_test_support::responses::user_message_item; use pretty_assertions::assert_eq; use serde_json::json; use test_case::test_case; +#[tokio::test] +async fn guardian_root_version_changes_on_history_reset_but_not_on_append() { + let (mut root, turn) = make_session_and_context().await; + root.multi_agent_version = MultiAgentVersion::V2.into(); + let before = root.guardian_root_history_version().await.unwrap(); + assert_eq!(before.0, root.thread_id); + + let message = user_message_item("Update the README."); + root.record_conversation_items(&turn, turn.model_info(), &[message]) + .await; + assert_eq!(root.guardian_root_history_version().await, Some(before)); + + root.replace_history(Vec::new(), /*reference_context_item*/ None) + .await; + assert_ne!(root.guardian_root_history_version().await.unwrap(), before); +} + #[test_case(GuardianContextMode::Legacy, ThreadHistoryMode::Legacy; "legacy_context_legacy_storage")] #[test_case(GuardianContextMode::ThreadOwned, ThreadHistoryMode::Legacy; "thread_owned_context_legacy_storage")] #[test_case(GuardianContextMode::Legacy, ThreadHistoryMode::Paginated; "legacy_context_paginated_storage")] diff --git a/codex-rs/ext/guardian-v3/src/actor.rs b/codex-rs/ext/guardian-v3/src/actor.rs index c6b16cf1c2..3bcb41d2d6 100644 --- a/codex-rs/ext/guardian-v3/src/actor.rs +++ b/codex-rs/ext/guardian-v3/src/actor.rs @@ -261,6 +261,15 @@ impl AttachedReviewer for ActorReviewer { self.retrieval.clone() } + fn root_thread(&self) -> codex_extension_api::ExtensionFuture<'_, Option>> { + Box::pin(async move { + if self.actor == self.root { + return None; + } + self.manager.upgrade()?.get_thread(self.root).await.ok() + }) + } + fn prepare<'a>( &'a self, setup: &'a PreparedGuardianContext, diff --git a/codex-rs/ext/guardian-v3/tests/housekeeping.rs b/codex-rs/ext/guardian-v3/tests/housekeeping.rs index f416ea8b1e..2fbd5d6f1b 100644 --- a/codex-rs/ext/guardian-v3/tests/housekeeping.rs +++ b/codex-rs/ext/guardian-v3/tests/housekeeping.rs @@ -8,6 +8,7 @@ use codex_core::CodexThread; use codex_core::config::Config; use codex_core::config::Constrained; use codex_core::config::GuardianInferenceProvider; +use codex_core::context::GuardianReviewEvidence; use codex_core::guardian_review::AttachedReviewer; use codex_core::guardian_review::PreserveReviewWrites; use codex_core::guardian_review::ReviewPreparationError; @@ -43,10 +44,12 @@ use codex_message_board::SortDirection; use codex_message_board::UpsertChannelRequest; use codex_protocol::AgentPath; use codex_protocol::ThreadId; +use codex_protocol::approvals::GuardianAssessmentStatus; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::TruncationPolicyConfig; use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadHistoryMode; @@ -62,6 +65,7 @@ use core_test_support::responses::*; use core_test_support::test_codex::TestCodexHarness; use core_test_support::test_codex::test_codex; use core_test_support::tracing::NamedTraceEvents; +use core_test_support::wait_for_event_match; use core_test_support::wait_for_successful_turn; use pretty_assertions::assert_eq; use reviewer_tool_call::invoke; @@ -1324,7 +1328,27 @@ async fn first_approval_reuses_the_prewarmed_root_reviewer() -> anyhow::Result<( }), ) .await?; + let review_id = wait_for_event_match(&fixture.root, |event| match event { + EventMsg::GuardianAssessment(review) + if review.status == GuardianAssessmentStatus::Approved => + { + Some(review.id.clone()) + } + _ => None, + }) + .await; wait_for_successful_turn(&fixture.root).await; + let reviews = fixture + .root + .thread_extension_data() + .get::() + .expect("shared review evidence") + .snapshot(); + let [saved] = reviews.as_slice() else { + anyhow::bail!("expected one saved GV3 verdict"); + }; + assert_eq!(saved.correlation["review_id"], review_id); + assert_eq!(saved.decision["status"], "approved"); let output = responses .requests() .iter() @@ -1450,6 +1474,10 @@ async fn child_keeps_searched_and_subscribed_evidence_after_root_reload() -> any // Reload resumes at the surviving child's published position. fixture.mock_reply("resume", TO_RELEASE).await; fixture.resume_root().await?; + let child = fixture.child.thread_extension_data(); + let actor = child.get::().expect("child reviewer"); + let reviewer_root = actor.root_thread().await.expect("reloaded root"); + assert!(Arc::ptr_eq(&reviewer_root, &fixture.root)); routed.next().await?; wait_for_revocation(&reviewer).await?;