Centralize Guardian context mode and checkpoint policy (#43458)

## What changed

Resolve `GuardianContextMode` once at session construction and share it across history retention, replay, evidence capture, compaction, and review consumers.

Extract synchronous reviewer context policy and consolidate Guardian V2 parent checkpoint selection so sampling and fast approval use the same eligibility checks. Preserve legacy checkpoint omission and strict compatibility requirements for thread-owned context.

## Testing

Adapt existing review and history tests to the explicit context mode. Move checkpoint tests alongside the extracted selector, retaining coverage for latest-item identity, unusable checkpoints, and complete-item size limits.

GitOrigin-RevId: c73fb6fea556921acfffe758a5f709d7494019dd
This commit is contained in:
felixxia-oai authored and copyberry committed 2026-09-07 12:53:57 +00:00
1 parent f3f53ee949
commit 8260619cb6
26 files changed
+599 -482

No files matched your search

+2 -1
View File
@@ -1,3 +1,4 @@
use crate::context::GuardianContextMode;
use codex_analytics::GuardianApprovalRequestSource;
use codex_analytics::GuardianReviewAnalyticsResult;
use codex_analytics::GuardianReviewDecision;
@@ -627,7 +628,7 @@ pub(super) async fn run_synchronous_review(
},
))
.await;
if session.enabled(Feature::GuardianThreadContext)
if session.guardian_context_mode == GuardianContextMode::ThreadOwned
&& matches!(&outcome, GuardianReviewOutcome::Completed(assessment) if assessment.outcome == GuardianAssessmentOutcome::Allow)
&& (root_authorization_version
!= session
+37 -105
View File
@@ -1,3 +1,7 @@
#[path = "review_session_context.rs"]
mod context_policy;
use context_policy::ReviewContextPolicy;
use std::collections::HashMap;
use std::collections::HashSet;
use std::future::Future;
@@ -52,6 +56,7 @@ use crate::config::ManagedFeatures;
use crate::config::NetworkProxySpec;
use crate::config::Permissions;
use crate::context::ContextualUserFragment;
use crate::context::GuardianContextMode;
use crate::context::GuardianFollowupReviewReminder;
use crate::context::GuardianNodeReplPolicy;
use crate::context_manager::ContextManager;
@@ -228,19 +233,17 @@ impl GuardianReviewSessionReuseKey {
spawn_config: &Config,
user_instructions: Option<Instructions>,
parent_history_version: u64,
context_mode: GuardianContextMode,
) -> Self {
Self {
root_authorization_version: None,
parent_history_version: if spawn_config
.features
.enabled(Feature::GuardianReuseParentCompaction)
|| spawn_config
.features
.enabled(Feature::GuardianThreadContext)
{
parent_history_version
} else {
0
parent_history_version: match ReviewContextPolicy::for_context(
context_mode,
&spawn_config.features,
) {
ReviewContextPolicy::Legacy => 0,
ReviewContextPolicy::LegacyWithCheckpointReuse
| ReviewContextPolicy::ThreadOwned => parent_history_version,
},
node_repl_auto_review_required: false,
node_repl_policy: String::new(),
@@ -287,64 +290,6 @@ impl GuardianReviewSessionReuseKey {
}
}
fn encrypted_parent_compaction(
history: &ContextManager,
features: &ManagedFeatures,
reviewer_compaction_hash: Option<&str>,
) -> anyhow::Result<Option<ResponseItem>> {
let strict = features.enabled(Feature::GuardianThreadContext);
if !strict && !features.enabled(Feature::GuardianReuseParentCompaction) {
return Ok(None);
}
let Some(envelope) = history.annotated_items().iter().rev().find(|envelope| {
matches!(
envelope.item,
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. }
)
}) else {
return Ok(None);
};
let item = &envelope.item;
let valid = match item {
ResponseItem::Compaction {
id: Some(_),
encrypted_content,
..
} if !encrypted_content.is_empty() => true,
ResponseItem::ContextCompaction {
id: Some(_),
encrypted_content: Some(encrypted_content),
..
} if !encrypted_content.is_empty() => true,
_ => false,
};
if !valid && !strict {
return Ok(None);
}
anyhow::ensure!(
valid,
"parent compaction checkpoint is unusable for Guardian review"
);
if strict {
// A resumed parent may now use a different model. Compare the actual
// checkpoint producer with the selected reviewer, not the live parent model.
let producer_hash = envelope
.metadata
.as_ref()
.and_then(|metadata| metadata.compaction_model_hash.as_deref());
anyhow::ensure!(
producer_hash
.zip(reviewer_compaction_hash)
.is_some_and(|(producer, reviewer)| {
!producer.is_empty() && producer == reviewer
}),
"parent compaction checkpoint is incompatible with the Guardian review model or its compatibility is unknown"
);
}
Ok(Some(item.clone()))
}
pub(crate) fn prompt_cache_key_override_for_review_session(
session_source: &SessionSource,
parent_thread_id: Option<ThreadId>,
@@ -473,20 +418,15 @@ impl GuardianReviewSessionManager {
guardian_review_session_config(&parent_session, &parent_turn).await?;
let spawn_config = session_config.spawn_config;
let parent_history = parent_session.clone_history().await;
let root_authorization_version =
if parent_session.enabled(Feature::GuardianThreadContext) {
parent_session
.services
.agent_control
.root_user_authorization(parent_session.thread_id)
.await
.map(|snapshot| snapshot.authorization_version)
} else {
None
};
let parent_compaction = encrypted_parent_compaction(
&parent_history,
let context_policy = ReviewContextPolicy::for_context(
parent_session.guardian_context_mode,
&spawn_config.features,
);
let root_authorization_version = context_policy
.root_authorization_version(&parent_session)
.await;
let parent_compaction = context_policy.parent_compaction(
&parent_history,
session_config.compaction_model_hash.as_deref(),
)?;
let parent_context = GuardianReviewContext::from(parent_turn);
@@ -494,6 +434,7 @@ impl GuardianReviewSessionManager {
&spawn_config,
parent_session.user_instructions().await,
parent_history.history_version(),
parent_session.guardian_context_mode,
)
.with_environments(parent_context.environments())
.with_node_repl_policy_eligibility(
@@ -575,25 +516,16 @@ impl GuardianReviewSessionManager {
) -> (GuardianReviewSessionOutcome, GuardianReviewAnalyticsResult) {
let deadline = params.deadline;
let parent_history = &params.parent_history;
let root_authorization_version = if params
.parent_session
.enabled(Feature::GuardianThreadContext)
{
params
.parent_session
.services
.agent_control
.root_user_authorization(params.parent_session.thread_id)
.await
.map(|snapshot| snapshot.authorization_version)
} else {
None
};
let parent_compaction = match encrypted_parent_compaction(
parent_history,
let context_policy = ReviewContextPolicy::for_context(
params.parent_session.guardian_context_mode,
&params.spawn_config.features,
params.compaction_model_hash.as_deref(),
) {
);
let root_authorization_version = context_policy
.root_authorization_version(&params.parent_session)
.await;
let parent_compaction = match context_policy
.parent_compaction(parent_history, params.compaction_model_hash.as_deref())
{
Ok(checkpoint) => checkpoint,
Err(error) => {
return (
@@ -606,6 +538,7 @@ impl GuardianReviewSessionManager {
&params.spawn_config,
params.parent_session.user_instructions().await,
parent_history.history_version(),
params.parent_session.guardian_context_mode,
)
.with_environments(params.parent_context.environments())
.with_node_repl_policy_eligibility(
@@ -626,9 +559,7 @@ impl GuardianReviewSessionManager {
.await
{
Ok(mut state) => {
if !params
.parent_session
.enabled(Feature::GuardianThreadContext)
if context_policy != ReviewContextPolicy::ThreadOwned
&& parent_compaction.is_none()
&& let Some(trunk) = state.trunk.as_ref()
{
@@ -752,6 +683,7 @@ impl GuardianReviewSessionManager {
session.get_config().await.as_ref(),
session.user_instructions().await,
session.clone_history().await.history_version(),
session.guardian_context_mode,
);
self.state.lock().await.trunk = Some(Arc::new(GuardianReviewSession {
reuse_key,
@@ -775,6 +707,7 @@ impl GuardianReviewSessionManager {
session.get_config().await.as_ref(),
session.user_instructions().await,
session.clone_history().await.history_version(),
session.guardian_context_mode,
);
self.state
.lock()
@@ -1129,9 +1062,8 @@ async fn run_review_on_session(
.sync_session_approved_hosts_to(&review_session.session.services.network_approval)
.await;
let history = if params
.parent_session
.enabled(Feature::GuardianThreadContext)
let history = if params.parent_session.guardian_context_mode
== GuardianContextMode::ThreadOwned
{
params.parent_history.conversation_history_snapshot()
} else {
@@ -0,0 +1,105 @@
//! Owns sync reviewer checkpoint and invalidation policy for both context modes.
//! Legacy may keep its existing transcript; thread-owned mode requires current parent context.
use codex_features::Feature;
use codex_protocol::models::ResponseItem;
use crate::codex_thread::GuardianAuthorizationVersion;
use crate::config::ManagedFeatures;
use crate::context::GuardianContextMode;
use crate::context_manager::ContextManager;
use crate::session::session::Session;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum ReviewContextPolicy {
Legacy,
LegacyWithCheckpointReuse,
ThreadOwned,
}
impl ReviewContextPolicy {
pub(super) fn for_context(mode: GuardianContextMode, features: &ManagedFeatures) -> Self {
match mode {
GuardianContextMode::ThreadOwned => Self::ThreadOwned,
GuardianContextMode::Legacy
if features.enabled(Feature::GuardianReuseParentCompaction) =>
{
Self::LegacyWithCheckpointReuse
}
GuardianContextMode::Legacy => Self::Legacy,
}
}
pub(super) async fn root_authorization_version(
self,
session: &Session,
) -> Option<GuardianAuthorizationVersion> {
if self != Self::ThreadOwned {
return None;
}
session
.services
.agent_control
.root_user_authorization(session.thread_id)
.await
.map(|snapshot| snapshot.authorization_version)
}
pub(super) fn parent_compaction(
self,
history: &ContextManager,
reviewer_compaction_hash: Option<&str>,
) -> anyhow::Result<Option<ResponseItem>> {
let strict = self == Self::ThreadOwned;
if self == Self::Legacy {
return Ok(None);
}
let Some(envelope) = history.annotated_items().iter().rev().find(|envelope| {
matches!(
envelope.item,
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. }
)
}) else {
return Ok(None);
};
let item = &envelope.item;
let valid = match item {
ResponseItem::Compaction {
id: Some(_),
encrypted_content,
..
} if !encrypted_content.is_empty() => true,
ResponseItem::ContextCompaction {
id: Some(_),
encrypted_content: Some(encrypted_content),
..
} if !encrypted_content.is_empty() => true,
_ => false,
};
if !valid && !strict {
return Ok(None);
}
anyhow::ensure!(
valid,
"parent compaction checkpoint is unusable for Guardian review"
);
if strict {
// A resumed parent may now use a different model. Compare the actual
// checkpoint producer with the selected reviewer, not the live parent model.
let producer_hash = envelope
.metadata
.as_ref()
.and_then(|metadata| metadata.compaction_model_hash.as_deref());
anyhow::ensure!(
producer_hash
.zip(reviewer_compaction_hash)
.is_some_and(|(producer, reviewer)| {
!producer.is_empty() && producer == reviewer
}),
"parent compaction checkpoint is incompatible with the Guardian review model or its compatibility is unknown"
);
}
Ok(Some(item.clone()))
}
}
@@ -1,4 +1,5 @@
use super::*;
use crate::context_manager::ContextManager;
use codex_history::CodexHarnessMetadata;
use codex_history::ResponseItemEnvelope;
use codex_protocol::openai_models::AutoReviewMessages;
@@ -54,6 +55,7 @@ async fn run_review_preserves_evidence_during_parent_compaction() {
&params.spawn_config,
parent.user_instructions().await,
params.parent_history.history_version(),
parent.guardian_context_mode,
)
.with_environments(params.parent_context.environments())
.with_node_repl_policy_eligibility(
@@ -146,6 +148,7 @@ async fn test_review_session() -> (
session.get_config().await.as_ref(),
session.user_instructions().await,
session.clone_history().await.history_version(),
GuardianContextMode::Legacy,
);
(
@@ -298,6 +301,7 @@ async fn guardian_review_session_config_change_invalidates_cached_session() {
&cached_spawn_config,
/*user_instructions*/ None,
/*parent_history_version*/ 0,
GuardianContextMode::Legacy,
);
let mut changed_parent_config = parent_config;
@@ -315,6 +319,7 @@ async fn guardian_review_session_config_change_invalidates_cached_session() {
&next_spawn_config,
/*user_instructions*/ None,
/*parent_history_version*/ 0,
GuardianContextMode::Legacy,
);
assert_eq!(
@@ -328,6 +333,7 @@ async fn guardian_review_session_config_change_invalidates_cached_session() {
&cached_spawn_config,
/*user_instructions*/ None,
/*parent_history_version*/ 0,
GuardianContextMode::Legacy,
)
);
@@ -337,6 +343,7 @@ async fn guardian_review_session_config_change_invalidates_cached_session() {
&cached_spawn_config,
/*user_instructions*/ None,
/*parent_history_version*/ 1,
GuardianContextMode::Legacy,
)
);
assert_ne!(
@@ -372,11 +379,13 @@ async fn guardian_review_session_config_change_invalidates_cached_session() {
&compaction_enabled_config,
/*user_instructions*/ None,
/*parent_history_version*/ 0,
GuardianContextMode::Legacy,
),
GuardianReviewSessionReuseKey::from_spawn_config(
&compaction_enabled_config,
/*user_instructions*/ None,
/*parent_history_version*/ 1,
GuardianContextMode::Legacy,
)
);
}
@@ -393,6 +402,8 @@ async fn encrypted_parent_compaction_requires_original_item_id(thread_context_en
features
.set_enabled(Feature::GuardianThreadContext, thread_context_enabled)
.expect("context mode");
let policy =
ReviewContextPolicy::for_context(GuardianContextMode::from_features(&features), &features);
let item = ResponseItem::Compaction {
id: Some(codex_protocol::ResponseItemId::from_server(
"cmp_guardian_parent_summary".to_string(),
@@ -410,7 +421,8 @@ async fn encrypted_parent_compaction_requires_original_item_id(thread_context_en
}),
}]);
assert_eq!(
encrypted_parent_compaction(&history, &features, Some("compatible"))
policy
.parent_compaction(&history, Some("compatible"))
.expect("valid checkpoint"),
Some(item)
);
@@ -425,7 +437,7 @@ async fn encrypted_parent_compaction_requires_original_item_id(thread_context_en
.into(),
);
history.replace_annotated(items);
let result = encrypted_parent_compaction(&history, &features, Some("compatible"));
let result = policy.parent_compaction(&history, Some("compatible"));
if thread_context_enabled {
assert!(result.is_err());
} else {
@@ -484,6 +496,7 @@ async fn guardian_review_session_compact_scope_change_invalidates_cached_session
&cached_spawn_config,
/*user_instructions*/ None,
/*parent_history_version*/ 0,
GuardianContextMode::Legacy,
);
let mut changed_parent_config = parent_config;
@@ -501,6 +514,7 @@ async fn guardian_review_session_compact_scope_change_invalidates_cached_session
&next_spawn_config,
/*user_instructions*/ None,
/*parent_history_version*/ 0,
GuardianContextMode::Legacy,
);
assert_ne!(cached_reuse_key, next_reuse_key);
@@ -897,6 +911,7 @@ async fn run_review_removes_trunk_when_event_stream_is_broken() {
.clone_history()
.await
.history_version(),
GuardianContextMode::Legacy,
)
.with_environments(params.parent_context.environments())
.with_node_repl_policy(&params.node_repl_policy);