Preserve Guardian authorization evidence across checkpoint migration (#45782)

## Why

Older compaction checkpoints can lack a producer model hash. Enabling thread-owned Guardian context must accommodate those checkpoints without losing user instructions or verified answers.

## What changed

- Select review policy from each history snapshot independently of the session's evidence capture policy.
- Keep legacy review for checkpoints with missing or empty producer hashes when the transcript preserves the evidence. Preserve strict compatibility checks when review depends on retained-only evidence.
- Continue capturing retained instructions and answers during migration, while supplying legacy reviews with runtime answers and subagent reviews with root authorization evidence.
- Record producer model hashes on new compactions regardless of context mode.

## Testing

Add coverage for checkpoint migration across compaction and resume in both history storage modes, snapshot policy stability, retained-evidence preservation, and authorization revalidation for owning sessions and subagents.

GitOrigin-RevId: ec72b4a51d40729173e24ac1b53b7d516ddaa825
This commit is contained in:
felixxia-oai authored and copyberry committed 2026-09-15 20:08:36 +00:00
1 parent 1427825c40
commit 0c3a14bbc2
20 files changed
+564 -85

No files matched your search

@@ -1,5 +1,5 @@
//! Projects bounded root evidence for worker reviewers using the thread's context mode.
//! Legacy mode keeps parent-window selection; retained mode preserves original source scope.
//! Projects bounded root evidence for worker reviewers using the session's capture policy.
//! Retained root instructions stay authoritative while old checkpoints use legacy review.
//! Projection limits do not change authorization completeness; unavailable source text does.
//! Retained-history reconciliation owns recovery order and missing-instruction provenance.
@@ -52,12 +52,13 @@ impl AgentControl {
.services
.thread_extension_data
.get_or_init(GuardianReviewEvidence::default);
let context_mode = root_thread.session.guardian_context_mode;
let mut latest_user_turn_id = None;
let (messages, authorization_version) = if root_evidence.context_mode()
== GuardianContextMode::ThreadOwned
let (messages, authorization_version) = if context_mode == GuardianContextMode::ThreadOwned
{
let retained_context = root_history.retained_context();
let reconciled = ReconciledRetainedContext::new(
history.retained_context(),
Some(retained_context),
root_history
.annotated_items()
.iter()
@@ -158,6 +159,12 @@ impl AgentControl {
assistant_messages.drain(..assistant_messages.len().saturating_sub(available));
messages.extend(assistant_messages);
let mut authorization_version = root_evidence.authorization_version(history.as_ref());
if history.retained_context().is_none() {
// Legacy checkpoint review hides retained answers from its snapshot, but
// root authorization still needs their completeness and original restrictions.
authorization_version.retained_context_complete =
codex_guardian_context::render_verified_answers(retained_context).complete;
}
if !authorization_version.retained_context_complete {
messages.insert(
/*index*/ 0,
@@ -174,8 +181,8 @@ impl AgentControl {
messages.insert(/*index*/ 0, GuardianRootMessage::RetainedContextScope);
(messages, authorization_version)
} else {
let mut messages = root_history
.raw_items()
let mut messages = history
.review_items()
.filter_map(|item| match (parse_turn_item(item), item) {
(Some(TurnItem::UserMessage(message)), _) => {
let message = message.message();
@@ -1,10 +1,13 @@
//! Immutable session mode shared by history, evidence projection, and reviewer policy.
//! Resolve the rollout flag at session construction, not independently at each consumer.
//! Session capture policy and the reviewer policy carried by each history snapshot.
//! Older checkpoints keep legacy review while its transcript preserves the retained evidence.
use codex_extension_api::ConversationHistorySnapshot;
use codex_features::Feature;
use codex_features::Features;
use codex_history::ResponseItemEnvelope;
use codex_protocol::models::ResponseItem;
/// Selects legacy compatibility or thread-owned evidence for a session's lifetime.
/// Selects legacy compatibility or thread-owned evidence.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum GuardianContextMode {
#[default]
@@ -13,6 +16,15 @@ pub enum GuardianContextMode {
}
impl GuardianContextMode {
/// Read reviewer policy from the same snapshot as its evidence, including delayed reviews.
pub fn from_history(history: &dyn ConversationHistorySnapshot) -> Self {
if history.retained_context().is_some() {
Self::ThreadOwned
} else {
Self::Legacy
}
}
pub(crate) fn from_features(features: &Features) -> Self {
if features.enabled(Feature::GuardianThreadContext) {
Self::ThreadOwned
@@ -20,4 +32,24 @@ impl GuardianContextMode {
Self::Legacy
}
}
pub(crate) fn for_checkpoint(self, items: &[ResponseItemEnvelope]) -> Self {
let checkpoint = items.iter().rev().find(|envelope| {
matches!(
envelope.item,
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. }
)
});
if checkpoint.is_some_and(|checkpoint| {
checkpoint
.metadata
.as_ref()
.and_then(|metadata| metadata.compaction_model_hash.as_deref())
.is_none_or(str::is_empty)
}) {
Self::Legacy
} else {
self
}
}
}
@@ -1,7 +1,6 @@
//! Selects Guardian answer evidence once per thread and retains completed reviews.
//! The temporary legacy mode preserves its bounded runtime buffer; thread-owned
//! mode reads retained answers from history. Capture uses the same thread feature setting;
//! legacy mode does not produce new retained-answer events.
//! Selects Guardian answer evidence from the review's history snapshot and retains reviews.
//! Legacy review uses a bounded runtime buffer while thread-owned review uses retained answers.
//! A migrating session captures both until its checkpoint can support thread-owned review.
use std::collections::BTreeSet;
use std::collections::VecDeque;
@@ -43,7 +42,6 @@ pub struct GuardianUserInputSnapshot {
/// completed reviews remain thread-local, and authorization changes invalidate stale records.
#[derive(Debug, Default)]
pub struct GuardianReviewEvidence {
mode: GuardianContextMode,
state: Mutex<GuardianReviewEvidenceState>,
}
@@ -57,26 +55,15 @@ struct GuardianReviewEvidenceState {
}
impl GuardianReviewEvidence {
/// Reports the fixed thread mode used for both capture and reviewer policy.
pub fn context_mode(&self) -> GuardianContextMode {
self.mode
}
pub(crate) fn new(mode: GuardianContextMode) -> Self {
Self {
mode,
state: Mutex::default(),
}
}
/// Preserves the legacy capture limits before hooks can replace the tool output.
pub(crate) fn record_user_input(
&self,
history: &dyn ConversationHistorySnapshot,
call_id: &str,
questions: &[RequestUserInputQuestion],
response: &RequestUserInputResponse,
) {
if !matches!(self.mode, GuardianContextMode::Legacy) {
if GuardianContextMode::from_history(history) != GuardianContextMode::Legacy {
return;
}
let fragment = questions
@@ -128,7 +115,7 @@ impl GuardianReviewEvidence {
&self,
history: &dyn ConversationHistorySnapshot,
) -> GuardianUserInputSnapshot {
match self.mode {
match GuardianContextMode::from_history(history) {
GuardianContextMode::ThreadOwned => {
let answers = history
.retained_context()
@@ -181,7 +168,7 @@ impl GuardianReviewEvidence {
history: &dyn ConversationHistorySnapshot,
call_id: &str,
) -> Option<String> {
match self.mode {
match GuardianContextMode::from_history(history) {
GuardianContextMode::ThreadOwned => history
.retained_context()?
.verified_answers()
+55 -6
View File
@@ -33,6 +33,7 @@ use codex_history::CodexHarnessMetadata;
use codex_history::GuardianHistoryCheckpoint;
use codex_history::ResponseItemEnvelope;
use codex_history::RetainedContext;
use codex_history::RetainedContextEntry;
use codex_history::RetainedContextEvent;
use codex_history::RetainedInputSource;
use codex_protocol::DEFAULT_FUNCTION_NAMESPACE;
@@ -78,8 +79,10 @@ pub(crate) struct ContextManager {
review_history: Option<TranscriptHistory>,
/// Host facts independent of the model window; snapshots share immutable state.
retained_context: Arc<RetainedContext>,
/// Capture, replay, and snapshot selection share the immutable session mode.
/// Capture follows the session flag, including while an older checkpoint uses legacy review.
guardian_context_mode: GuardianContextMode,
/// Reviewer policy travels with the history snapshot, independently of capture.
guardian_review_mode: GuardianContextMode,
retain_inherited_user_messages: bool,
/// Bumped whenever history is rewritten, such as compaction or rollback.
history_version: u64,
@@ -181,6 +184,7 @@ impl ContextManager {
review_history: None,
retained_context: Arc::default(),
guardian_context_mode: GuardianContextMode::Legacy,
guardian_review_mode: GuardianContextMode::Legacy,
retain_inherited_user_messages: false,
history_version: 0,
reset_version: 0,
@@ -198,7 +202,7 @@ impl ContextManager {
items: Arc::clone(&self.items),
review_history: self.review_history.clone(),
retained_context: Arc::clone(&self.retained_context),
guardian_context_mode: self.guardian_context_mode,
guardian_context_mode: self.guardian_review_mode,
history_version: self.history_version,
user_message_revision: self.user_message_revision,
})
@@ -214,6 +218,7 @@ impl ContextManager {
) -> Self {
Self {
guardian_context_mode,
guardian_review_mode: guardian_context_mode,
retain_inherited_user_messages: guardian_context_mode
== GuardianContextMode::ThreadOwned
&& !source.is_non_root_agent(),
@@ -234,7 +239,7 @@ impl ContextManager {
}
pub(crate) fn guardian_history_checkpoint(&self) -> Option<GuardianHistoryCheckpoint> {
if self.guardian_context_mode == GuardianContextMode::ThreadOwned {
if self.guardian_review_mode == GuardianContextMode::ThreadOwned {
return None;
}
self.review_history
@@ -247,8 +252,53 @@ impl ContextManager {
retained_context: Option<&RetainedContext>,
checkpoint: Option<&GuardianHistoryCheckpoint>,
) {
// Replay captures ordinary messages too. Legacy review can keep using those messages
// while their original text survives in its selected transcript. Retained-only facts
// and missing-answer markers still require strict checkpoint compatibility.
let has_retained_only_evidence = retained_context.is_some_and(|context| {
!context.verified_answers_complete()
|| context.ordered_entries().any(|(_, entry)| match entry {
RetainedContextEntry::VerifiedAnswer(_) => true,
RetainedContextEntry::UserMessage(message) => {
let contains_message = |item: &ResponseItem| {
if item.id().map(codex_protocol::ResponseItemId::as_str)
!= message.message_id.as_deref()
|| item.turn_id().unwrap_or_default() != message.turn_id
{
return false;
}
let ResponseItem::Message { role, content, .. } = item else {
return false;
};
if role != "user" || is_contextual_user_message_content(content) {
return false;
}
let text = content
.iter()
.filter_map(|content| match content {
ContentItem::InputText { text }
| ContentItem::OutputText { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n");
guardian_truncate_text(&text, GUARDIAN_MAX_ROOT_MESSAGE_TOKENS).0
== message.text
};
!checkpoint.map_or_else(
|| self.raw_items().any(contains_message),
|checkpoint| checkpoint.0.iter().any(contains_message),
)
}
})
});
self.guardian_review_mode = if has_retained_only_evidence {
self.guardian_context_mode
} else {
self.guardian_context_mode.for_checkpoint(&self.items)
};
self.restore_retained_context(retained_context);
if self.guardian_context_mode == GuardianContextMode::ThreadOwned {
if self.guardian_review_mode == GuardianContextMode::ThreadOwned {
// Older retained checkpoints cleared oversized instructions. Recover their
// bounded root excerpts before discarding the legacy source transcript.
let items = &self.items;
@@ -507,8 +557,7 @@ impl ContextManager {
/// Compaction changes the model's history without changing the user's authorization.
pub(crate) fn replace_compacted(&mut self, items: Vec<ResponseItemEnvelope>) {
if self.guardian_context_mode == GuardianContextMode::Legacy
&& self.review_history.is_none()
if self.guardian_review_mode == GuardianContextMode::Legacy && self.review_history.is_none()
{
let mut retained = TranscriptHistory::new(self.history_version.saturating_add(1));
for item in self.raw_items().filter(|item| {
@@ -154,8 +154,11 @@ fn conversation_history_snapshot_shares_response_items_until_history_changes() {
);
}
#[test]
fn conversation_history_snapshot_binds_compaction_hash_to_the_latest_item() {
#[test_case(None; "missing hash")]
#[test_case(Some(""); "empty hash")]
fn conversation_history_snapshot_binds_review_mode_and_hash_to_the_latest_item(
latest_hash: Option<&str>,
) {
let checkpoint = ResponseItemEnvelope {
item: serde_json::from_value(serde_json::json!({
"type": "compaction", "id": "known", "encrypted_content": "opaque checkpoint"
@@ -166,28 +169,51 @@ fn conversation_history_snapshot_binds_compaction_hash_to_the_latest_item() {
..Default::default()
}),
};
let mut history = ContextManager::new();
let mut history = ContextManager::with_guardian_context_mode(
GuardianContextMode::ThreadOwned,
&codex_protocol::protocol::SessionSource::Cli,
);
history.replace_annotated(vec![checkpoint.clone()]);
history.restore_review_context(/*retained_context*/ None, /*checkpoint*/ None);
let snapshot = history.conversation_history_snapshot();
let mut unknown = checkpoint.clone();
unknown.metadata = None;
unknown.metadata = latest_hash.map(|hash| CodexHarnessMetadata {
compaction_model_hash: Some(hash.to_owned()),
..Default::default()
});
unknown.item = serde_json::from_value(serde_json::json!({
"type": "compaction", "id": "unknown", "encrypted_content": "newer opaque checkpoint"
}))
.expect("unknown checkpoint fixture");
history.replace_annotated(vec![checkpoint.clone(), unknown]);
let mut legacy_context = RetainedContext::default();
legacy_context.mark_user_messages_incomplete();
history.restore_review_context(Some(&legacy_context), /*checkpoint*/ None);
assert_eq!(
GuardianContextMode::from_history(history.conversation_history_snapshot().as_ref()),
GuardianContextMode::Legacy,
);
assert_eq!(
history
.conversation_history_snapshot()
.latest_compaction_model_hash(),
None
latest_hash
);
assert_eq!(
snapshot.latest_compaction_model_hash(),
Some("producer-hash")
);
assert_eq!(
GuardianContextMode::from_history(snapshot.as_ref()),
GuardianContextMode::ThreadOwned,
);
// Checkpoint replay/rollback restores the item's own provenance, not a new model's metadata.
history.replace_annotated(vec![checkpoint]);
history.restore_review_context(/*retained_context*/ None, /*checkpoint*/ None);
assert_eq!(
GuardianContextMode::from_history(history.conversation_history_snapshot().as_ref()),
GuardianContextMode::ThreadOwned,
);
assert_eq!(
history
.conversation_history_snapshot()
@@ -196,6 +222,73 @@ fn conversation_history_snapshot_binds_compaction_hash_to_the_latest_item() {
);
}
#[test_case(serde_json::json!({
"verified_answers": [], "incomplete": true
}); "missing answers")]
#[test_case(serde_json::json!({
"verified_answers": [], "incomplete": false, "next_order": 1,
"user_messages": [{
"turn_id": "turn", "message_id": "restriction",
"text": "Only publish to a private repository.", "complete": true
}]
}); "retained instructions")]
fn checkpoint_retained_evidence_prevents_legacy_downgrade(saved_context: serde_json::Value) {
let mut history = ContextManager::with_guardian_context_mode(
GuardianContextMode::ThreadOwned,
&codex_protocol::protocol::SessionSource::Cli,
);
history.replace_annotated(vec![ResponseItemEnvelope::new(
serde_json::from_value(serde_json::json!({
"type": "compaction", "id": "unknown", "encrypted_content": "opaque checkpoint"
}))
.expect("checkpoint fixture"),
)]);
let retained: RetainedContext =
serde_json::from_value(saved_context).expect("retained evidence checkpoint");
history.restore_review_context(Some(&retained), /*checkpoint*/ None);
let snapshot = history.conversation_history_snapshot();
assert_eq!(
GuardianContextMode::from_history(snapshot.as_ref()),
GuardianContextMode::ThreadOwned,
);
assert_eq!(snapshot.retained_context(), Some(&retained));
assert_eq!(snapshot.latest_compaction_model_hash(), None);
}
#[test_case(None, GuardianContextMode::Legacy; "model window")]
#[test_case(Some("Only publish privately."), GuardianContextMode::Legacy; "legacy backup")]
#[test_case(Some("Only publish."), GuardianContextMode::ThreadOwned; "shortened legacy backup")]
fn checkpoint_replayed_instructions_keep_legacy_review_when_the_source_survives(
backup_text: Option<&str>,
expected_mode: GuardianContextMode,
) {
let mut history = ContextManager::with_guardian_context_mode(
GuardianContextMode::ThreadOwned,
&codex_protocol::protocol::SessionSource::Cli,
);
history.replace_annotated(vec![ResponseItemEnvelope::new(
serde_json::from_value(serde_json::json!({
"type": "compaction", "id": "unknown", "encrypted_content": "opaque checkpoint"
}))
.expect("checkpoint fixture"),
)]);
history.restore_review_context(/*retained_context*/ None, /*checkpoint*/ None);
history.record_items(
&[user_input_text_msg("Only publish privately.")],
TruncationPolicy::Bytes(10_000),
);
let retained = history.retained_context().clone();
let backup = backup_text.map(|text| GuardianHistoryCheckpoint(vec![user_input_text_msg(text)]));
history.restore_review_context(Some(&retained), backup.as_ref());
assert_eq!(
GuardianContextMode::from_history(history.conversation_history_snapshot().as_ref()),
expected_mode,
);
assert_eq!(history.retained_context(), &retained);
}
#[test]
fn conversation_history_snapshot_excludes_contextual_user_messages() {
let contextual_message = crate::context::ContextualUserFragment::into(UserInstructions {
+4 -4
View File
@@ -469,10 +469,10 @@ async fn run_review_on_session(
.sync_session_approved_hosts_to(&review_session.session.services.network_approval)
.await;
let history = if params.parent_session.guardian_context_mode
== GuardianContextMode::ThreadOwned
{
params.parent_history.conversation_history_snapshot()
let parent_history = params.parent_history.conversation_history_snapshot();
let history = if GuardianContextMode::from_history(parent_history.as_ref())
== GuardianContextMode::ThreadOwned {
parent_history
} else {
params.parent_session.conversation_history_snapshot().await
};
@@ -30,15 +30,16 @@ impl PreparedGuardianContext {
if reset_version != history.reset_version {
history_reset.cancel();
}
let context_policy =
ReviewContextPolicy::for_context(parent.guardian_context_mode, &config.features);
let context_mode =
GuardianContextMode::from_history(history.conversation_history_snapshot().as_ref());
let context_policy = ReviewContextPolicy::for_context(context_mode, &config.features);
let root_authorization_version = context_policy.root_authorization_version(&parent).await;
let parent_compaction = context_policy.parent_compaction(history, compaction_model_hash)?;
let mut key = GuardianReviewSessionReuseKey::from_spawn_config(
&config,
parent.inherited_instructions().await,
history.history_version(),
parent.guardian_context_mode,
context_mode,
)
.with_environments(context.environments())
.with_node_repl_policy_eligibility(context.model_info.computer_use_review_required())
+6 -9
View File
@@ -24,7 +24,6 @@ use crate::config::ManagedFeatures;
use crate::config::resolve_tool_suggest_config_from_layer_stack;
use crate::context::ContextualUserFragment;
use crate::context::DeveloperInstructions;
use crate::context::GuardianContextMode;
use crate::context::GuardianPolicy;
use crate::context::ManagedDeveloperInstructions;
use crate::context::ModelSwitchInstructions;
@@ -4003,14 +4002,12 @@ impl Session {
for envelope in &mut items {
Self::assign_missing_response_item_id(&mut envelope.item);
}
if self.guardian_context_mode == GuardianContextMode::ThreadOwned
&& let Some(checkpoint) = items.iter_mut().rev().find(|envelope| {
matches!(
envelope.item,
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. }
)
})
{
if let Some(checkpoint) = items.iter_mut().rev().find(|envelope| {
matches!(
envelope.item,
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. }
)
}) {
checkpoint
.metadata
.get_or_insert_default()
+2 -4
View File
@@ -961,11 +961,9 @@ impl Session {
thread_id.to_string(),
thread_extension_init,
);
// Resolve once for live history, replay, and all reviewer consumers.
// Capture follows the flag; replay selects reviewer policy from the saved checkpoint.
let guardian_context_mode = GuardianContextMode::from_features(&config.features);
thread_extension_data.insert(crate::context::GuardianReviewEvidence::new(
guardian_context_mode,
));
thread_extension_data.insert(crate::context::GuardianReviewEvidence::default());
// Kick off independent async setup tasks in parallel to reduce startup latency.
//
// - initialize thread persistence with new or resumed session info
@@ -103,14 +103,14 @@ impl RequestUserInputHandler {
))
})?;
if turn.config.features.enabled(Feature::GuardianApproval) {
let history = session.conversation_history_snapshot().await;
session
.services
.thread_extension_data
.get_or_init(GuardianReviewEvidence::default)
.record_user_input(&call_id, &questions, &response);
.record_user_input(history.as_ref(), &call_id, &questions, &response);
}
// Capture and consumption use the same fixed thread feature setting. Legacy
// threads must not construct retained answers, persist them, or advance their revision.
// Capture follows the session flag even while an older checkpoint uses legacy review.
if turn.config.features.enabled(Feature::GuardianApproval)
&& session.guardian_context_mode == GuardianContextMode::ThreadOwned
{
@@ -117,7 +117,7 @@ async fn request_user_input_sets_non_blocking_outside_plan_mode(
session
.services
.thread_extension_data
.insert(GuardianReviewEvidence::new(session.guardian_context_mode));
.insert(GuardianReviewEvidence::default());
let original_history = session.conversation_history_snapshot().await;
*session.active_turn.lock().await = Some(ActiveTurn::default());