Preserve Guardian evidence during checkpoint migration (#45789)

## Why

A checkpoint produced by a previous model may be incompatible with the selected Guardian reviewer. Legacy review must retain user restrictions and verified answers across compaction and restart until a compatible checkpoint is available.

## What changed

- Expose retained user evidence independently of whether Guardian reviews the legacy transcript or parent context.
- Resolve the selected reviewer's compaction compatibility hash during resume and remote compaction. Preserve the legacy transcript when checkpoint compatibility is unknown or mismatched.
- Activate parent-context review immediately after compatible compaction and invalidate pending reviews bound to the previous evidence policy. Ordinary compaction preserves pending reviews.
- Keep strict compatibility checks for previously migrated checkpoints whose complete legacy transcript is no longer available.

## Testing

Add coverage for mismatched checkpoint hashes, retained evidence during legacy review, and pending-review cancellation on migration. Add a request-history scenario covering a model switch, incompatible automatic compaction, restart, and compatible manual compaction with preserved user restrictions and verified answers.

GitOrigin-RevId: b52bfd7c21ce7ebed482174c8d7c327e50b1ada8
This commit is contained in:
felixxia-oai authored and copyberry committed 2026-09-15 20:41:39 +00:00
1 parent 0c3a14bbc2
commit c51cb968e4
22 files changed
+841 -281

No files matched your search

@@ -159,12 +159,6 @@ 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,
+2
View File
@@ -86,6 +86,7 @@ pub(crate) struct CompactedHistoryMetadata {
pub(crate) window_ids: AutoCompactWindowIds,
pub(crate) compaction_response_id: Option<String>,
pub(crate) compaction_model_hash: Option<String>,
pub(crate) reviewer_compaction_hash: Option<String>,
}
pub(crate) async fn build_compaction_initial_context(
@@ -388,6 +389,7 @@ async fn run_compact_task_inner_impl(
window_ids,
compaction_response_id: Some(compaction_response_id),
compaction_model_hash: turn_context.model_info().comp_hash.clone(),
reviewer_compaction_hash: None,
},
)
.await;
+16
View File
@@ -337,6 +337,21 @@ async fn run_remote_compact_task_inner_impl(
replacement_history: &replacement_history,
});
}
let reviewer_compaction_hash = if sess.enabled(Feature::GuardianThreadContext)
&& crate::context::GuardianContextMode::from_history(
sess.conversation_history_snapshot().await.as_ref(),
) == crate::context::GuardianContextMode::Legacy
&& let Some(review_turn) = sess.turn_context_for_sub_id(&turn_context.sub_id).await
{
// Previous-model compaction must remain compatible with the continuing turn's
// reviewer, including model changes accepted while compaction was running.
let mut review_context = crate::guardian::GuardianReviewContext::from(&review_turn);
review_context.model_info = review_turn.capture_current_model_info();
let (_, reviewer) = crate::guardian::resolve_review_model(sess, &review_context).await;
reviewer.comp_hash.clone()
} else {
None
};
sess.replace_compacted_history(
new_history,
reference_context_item,
@@ -347,6 +362,7 @@ async fn run_remote_compact_task_inner_impl(
window_ids: new_window_ids,
compaction_response_id: Some(compaction_response_id),
compaction_model_hash: compaction_turn_context.model_info().comp_hash.clone(),
reviewer_compaction_hash,
},
)
.await;
@@ -1,5 +1,5 @@
//! Session capture policy and the reviewer policy carried by each history snapshot.
//! Older checkpoints keep legacy review while its transcript preserves the retained evidence.
//! Unknown or incompatible checkpoints keep legacy review alongside retained user evidence.
use codex_extension_api::ConversationHistorySnapshot;
use codex_features::Feature;
@@ -18,7 +18,7 @@ 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() {
if history.uses_parent_context_for_review() {
Self::ThreadOwned
} else {
Self::Legacy
@@ -33,23 +33,29 @@ impl GuardianContextMode {
}
}
pub(crate) fn for_checkpoint(self, items: &[ResponseItemEnvelope]) -> Self {
pub(crate) fn for_checkpoint(
self,
items: &[ResponseItemEnvelope],
reviewer_compaction_hash: Option<&str>,
) -> Self {
let checkpoint = items.iter().rev().find(|envelope| {
matches!(
envelope.item,
ResponseItem::Compaction { .. } | ResponseItem::ContextCompaction { .. }
)
});
if checkpoint.is_some_and(|checkpoint| {
checkpoint
if checkpoint.is_none_or(|checkpoint| {
let producer_hash = checkpoint
.metadata
.as_ref()
.and_then(|metadata| metadata.compaction_model_hash.as_deref())
.is_none_or(str::is_empty)
.and_then(|metadata| metadata.compaction_model_hash.as_deref());
producer_hash
.zip(reviewer_compaction_hash)
.is_some_and(|(producer, reviewer)| !producer.is_empty() && producer == reviewer)
}) {
Self::Legacy
} else {
self
} else {
Self::Legacy
}
}
}
@@ -1,6 +1,6 @@
//! 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.
//! Retained answers survive restart even while incompatible checkpoints use legacy review.
//! Sessions without retained capture continue using the bounded runtime buffer.
use std::collections::BTreeSet;
use std::collections::VecDeque;
@@ -18,7 +18,6 @@ use codex_protocol::request_user_input::RequestUserInputResponse;
use serde_json::json;
use super::ContextualUserFragment;
use super::GuardianContextMode;
use crate::codex_thread::GuardianAuthorizationVersion;
use crate::codex_thread::GuardianRootMessage;
use crate::guardian::guardian_truncate_text;
@@ -63,7 +62,7 @@ impl GuardianReviewEvidence {
questions: &[RequestUserInputQuestion],
response: &RequestUserInputResponse,
) {
if GuardianContextMode::from_history(history) != GuardianContextMode::Legacy {
if history.retained_context().is_some() {
return;
}
let fragment = questions
@@ -115,24 +114,20 @@ impl GuardianReviewEvidence {
&self,
history: &dyn ConversationHistorySnapshot,
) -> GuardianUserInputSnapshot {
match GuardianContextMode::from_history(history) {
GuardianContextMode::ThreadOwned => {
let answers = history
.retained_context()
.map(codex_guardian_context::render_verified_answers);
match history.retained_context() {
Some(context) => {
let answers = codex_guardian_context::render_verified_answers(context);
let authorization_version = GuardianAuthorizationVersion {
user_message_revision: history.user_message_revision(),
user_input_response_count: 0,
retained_context_complete: answers
.as_ref()
.is_none_or(|answers| answers.complete),
retained_context_complete: answers.complete,
};
GuardianUserInputSnapshot {
fragments: answers.map(|answers| answers.fragments).unwrap_or_default(),
fragments: answers.fragments,
authorization_version,
}
}
GuardianContextMode::Legacy => {
None => {
let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
let fragments = state
.user_inputs
@@ -168,13 +163,12 @@ impl GuardianReviewEvidence {
history: &dyn ConversationHistorySnapshot,
call_id: &str,
) -> Option<String> {
match GuardianContextMode::from_history(history) {
GuardianContextMode::ThreadOwned => history
.retained_context()?
match history.retained_context() {
Some(context) => context
.verified_answers()
.find(|answer| answer.call_id == call_id)
.and_then(codex_guardian_context::render_verified_answer),
GuardianContextMode::Legacy => self
None => self
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
+90 -53
View File
@@ -1,5 +1,6 @@
//! Parent model history and bounded host-owned context facts.
//! Compaction replaces only the model window. Snapshots include retained facts atomically;
//! Compaction replaces the model window and can activate thread-owned Guardian review.
//! Snapshots include reviewer policy and retained facts atomically;
//! checkpoint replay and source-call rollback share their live lifecycle.
//! Token estimates charge item content rather than transport metadata.
//! Oversized instructions keep an incomplete excerpt for bounded root review, including
@@ -75,7 +76,7 @@ pub(crate) struct ContextManager {
/// The oldest items are at the beginning of the vector. Snapshots share the vector until a
/// caller needs to mutate it, avoiding deep copies for read-only history consumers.
items: Arc<Vec<ResponseItemEnvelope>>,
/// Legacy-only history, started at first compaction. Thread-owned mode reads parent context.
/// Legacy-only history preserved across compaction and resume. Thread-owned review uses parent context.
review_history: Option<TranscriptHistory>,
/// Host facts independent of the model window; snapshots share immutable state.
retained_context: Arc<RetainedContext>,
@@ -111,12 +112,15 @@ struct SharedConversationHistory {
review_history: Option<TranscriptHistory>,
retained_context: Arc<RetainedContext>,
guardian_context_mode: GuardianContextMode,
guardian_review_mode: GuardianContextMode,
history_version: u64,
user_message_revision: u64,
}
pub(crate) enum HistoryReplacement {
Compaction,
Compaction {
reviewer_compaction_hash: Option<String>,
},
Reset,
}
@@ -140,6 +144,10 @@ impl ConversationHistorySnapshot for SharedConversationHistory {
.then_some(&self.retained_context)
}
fn uses_parent_context_for_review(&self) -> bool {
self.guardian_review_mode == GuardianContextMode::ThreadOwned
}
fn review_items(&self) -> Box<dyn Iterator<Item = &ResponseItem> + Send + '_> {
match &self.review_history {
Some(history) => history.items(),
@@ -202,7 +210,8 @@ 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_review_mode,
guardian_context_mode: self.guardian_context_mode,
guardian_review_mode: self.guardian_review_mode,
history_version: self.history_version,
user_message_revision: self.user_message_revision,
})
@@ -251,54 +260,54 @@ impl ContextManager {
&mut self,
retained_context: Option<&RetainedContext>,
checkpoint: Option<&GuardianHistoryCheckpoint>,
reviewer_compaction_hash: Option<&str>,
) {
// 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 {
// A previously promoted checkpoint may have discarded the only complete transcript.
// Keep requiring parent context in that case; a compatibility failure must not turn
// a partial model window into a legacy fallback. Migrating checkpoints keep a backup
// and can expose retained facts independently of which transcript review uses.
let requires_parent_context = checkpoint.is_none()
&& retained_context.is_some_and(|context| {
!context.verified_answers_complete()
|| context.ordered_entries().any(|(_, entry)| match entry {
RetainedContextEntry::VerifiedAnswer(_) => true,
RetainedContextEntry::UserMessage(message) => {
!self.raw_items().any(|item| {
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
})
}
})
});
self.guardian_review_mode = if requires_parent_context {
self.guardian_context_mode
} else {
self.guardian_context_mode.for_checkpoint(&self.items)
self.guardian_context_mode
.for_checkpoint(&self.items, reviewer_compaction_hash)
};
self.restore_retained_context(retained_context);
if self.guardian_review_mode == GuardianContextMode::ThreadOwned {
if self.guardian_context_mode == GuardianContextMode::ThreadOwned {
// Older retained checkpoints cleared oversized instructions. Recover their
// bounded root excerpts before discarding the legacy source transcript.
let items = &self.items;
@@ -317,6 +326,10 @@ impl ContextManager {
guardian_truncate_text(&original.message(), GUARDIAN_MAX_ROOT_MESSAGE_TOKENS).0,
)
});
}
if self.guardian_review_mode == GuardianContextMode::ThreadOwned
|| (self.guardian_context_mode == GuardianContextMode::Legacy && checkpoint.is_none())
{
self.review_history = None;
return;
}
@@ -325,11 +338,17 @@ impl ContextManager {
.as_ref()
.map_or(self.history_version, TranscriptHistory::generation)
.saturating_add(1);
self.review_history = checkpoint.map(|checkpoint| {
let mut history = TranscriptHistory::new(generation);
let mut history = TranscriptHistory::new(generation);
if let Some(checkpoint) = checkpoint {
history.reset(checkpoint.0.iter());
history
});
} else {
// Retain the legacy window through replay, including answers captured in its suffix.
history.reset(self.raw_items().filter(|item| {
!matches!(item, ResponseItem::Message { role, content, .. }
if role == "user" && is_contextual_user_message_content(content))
}));
}
self.review_history = Some(history);
}
pub(crate) fn token_info(&self) -> Option<TokenUsageInfo> {
@@ -555,8 +574,22 @@ impl ContextManager {
self.world_state_baseline = None;
}
/// Compaction changes the model's history without changing the user's authorization.
pub(crate) fn replace_compacted(&mut self, items: Vec<ResponseItemEnvelope>) {
/// Returns whether compaction changed Guardian's evidence policy, invalidating older reviews.
pub(crate) fn replace_compacted(
&mut self,
items: Vec<ResponseItemEnvelope>,
reviewer_compaction_hash: Option<&str>,
) -> bool {
let promoted = self.guardian_review_mode == GuardianContextMode::Legacy
&& self
.guardian_context_mode
.for_checkpoint(&items, reviewer_compaction_hash)
== GuardianContextMode::ThreadOwned;
if promoted {
self.guardian_review_mode = GuardianContextMode::ThreadOwned;
self.review_history = None;
self.user_message_revision = self.user_message_revision.saturating_add(/*rhs*/ 1);
}
if self.guardian_review_mode == GuardianContextMode::Legacy && self.review_history.is_none()
{
let mut retained = TranscriptHistory::new(self.history_version.saturating_add(1));
@@ -570,7 +603,11 @@ impl ContextManager {
}
self.items = Arc::new(items);
self.history_version = self.history_version.saturating_add(1);
if promoted {
self.reset_version = self.history_version;
}
self.world_state_baseline = None;
promoted
}
/// Drop the last `num_turns` instruction turns from this history.
@@ -156,6 +156,7 @@ fn conversation_history_snapshot_shares_response_items_until_history_changes() {
#[test_case(None; "missing hash")]
#[test_case(Some(""); "empty hash")]
#[test_case(Some("other-producer"); "incompatible hash")]
fn conversation_history_snapshot_binds_review_mode_and_hash_to_the_latest_item(
latest_hash: Option<&str>,
) {
@@ -174,7 +175,11 @@ fn conversation_history_snapshot_binds_review_mode_and_hash_to_the_latest_item(
&codex_protocol::protocol::SessionSource::Cli,
);
history.replace_annotated(vec![checkpoint.clone()]);
history.restore_review_context(/*retained_context*/ None, /*checkpoint*/ None);
history.restore_review_context(
/*retained_context*/ None,
/*checkpoint*/ None,
Some("producer-hash"),
);
let snapshot = history.conversation_history_snapshot();
let mut unknown = checkpoint.clone();
unknown.metadata = latest_hash.map(|hash| CodexHarnessMetadata {
@@ -188,7 +193,11 @@ fn conversation_history_snapshot_binds_review_mode_and_hash_to_the_latest_item(
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);
history.restore_review_context(
Some(&legacy_context),
/*checkpoint*/ None,
Some("producer-hash"),
);
assert_eq!(
GuardianContextMode::from_history(history.conversation_history_snapshot().as_ref()),
GuardianContextMode::Legacy,
@@ -209,7 +218,11 @@ fn conversation_history_snapshot_binds_review_mode_and_hash_to_the_latest_item(
);
// 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);
history.restore_review_context(
/*retained_context*/ None,
/*checkpoint*/ None,
Some("producer-hash"),
);
assert_eq!(
GuardianContextMode::from_history(history.conversation_history_snapshot().as_ref()),
GuardianContextMode::ThreadOwned,
@@ -232,7 +245,7 @@ fn conversation_history_snapshot_binds_review_mode_and_hash_to_the_latest_item(
"text": "Only publish to a private repository.", "complete": true
}]
}); "retained instructions")]
fn checkpoint_retained_evidence_prevents_legacy_downgrade(saved_context: serde_json::Value) {
fn checkpoint_retained_evidence_survives_legacy_review(saved_context: serde_json::Value) {
let mut history = ContextManager::with_guardian_context_mode(
GuardianContextMode::ThreadOwned,
&codex_protocol::protocol::SessionSource::Cli,
@@ -245,24 +258,28 @@ fn checkpoint_retained_evidence_prevents_legacy_downgrade(saved_context: serde_j
)]);
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);
for (checkpoint, expected_mode) in [
(None, GuardianContextMode::ThreadOwned),
(
Some(GuardianHistoryCheckpoint(vec![assistant_msg(
"Original transcript",
)])),
GuardianContextMode::Legacy,
),
] {
history.restore_review_context(Some(&retained), checkpoint.as_ref(), Some("reviewer"));
let snapshot = history.conversation_history_snapshot();
assert_eq!(
GuardianContextMode::from_history(snapshot.as_ref()),
expected_mode
);
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,
) {
#[test]
fn checkpoint_replayed_instructions_keep_legacy_review_when_the_source_survives() {
let mut history = ContextManager::with_guardian_context_mode(
GuardianContextMode::ThreadOwned,
&codex_protocol::protocol::SessionSource::Cli,
@@ -273,18 +290,24 @@ fn checkpoint_replayed_instructions_keep_legacy_review_when_the_source_survives(
}))
.expect("checkpoint fixture"),
)]);
history.restore_review_context(/*retained_context*/ None, /*checkpoint*/ None);
history.restore_review_context(
/*retained_context*/ None, /*checkpoint*/ None,
/*reviewer_compaction_hash*/ 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());
history.restore_review_context(
Some(&retained),
/*checkpoint*/ None,
/*reviewer_compaction_hash*/ None,
);
assert_eq!(
GuardianContextMode::from_history(history.conversation_history_snapshot().as_ref()),
expected_mode,
GuardianContextMode::Legacy,
);
assert_eq!(history.retained_context(), &retained);
}
@@ -1415,7 +1438,7 @@ fn drop_last_n_user_turns_preserves_prefix() {
}
}
history.drop_last_n_user_turns(/*num_turns*/ 1);
history.replace_compacted(Vec::new());
history.replace_compacted(Vec::new(), /*reviewer_compaction_hash*/ None);
let retained = history.retained_context();
assert!(retained.user_messages_complete());
assert!(retained.verified_answers_complete());
+1
View File
@@ -18,6 +18,7 @@ pub(crate) use request_budget::observe as observe_guardian_request;
mod review;
mod review_session;
mod reviewer_config;
pub(crate) use reviewer_config::resolve_review_model;
mod runtime;
#[cfg(test)]
pub(crate) mod test_host;
+2 -33
View File
@@ -134,39 +134,8 @@ pub(super) async fn guardian_review_session_config(
Some(network_proxy) => Some(network_proxy.proxy().current_cfg().await?),
None => None,
};
let available_models = session
.services
.models_manager
.list_models(
codex_models_manager::manager::RefreshStrategy::Offline,
turn.config.http_client_factory(),
)
.await;
let default_review_model_id = turn.provider.approval_review_preferred_model();
let review_model = codex_guardian_reviewer::select_review_model(
&context.model_info,
context.reasoning_effort.as_ref(),
default_review_model_id,
&available_models,
);
// Resolve a separate reviewer against the current catalog on every attempt.
// Parent fallback must retain the action's metadata even after a catalog refresh.
let guardian_model_info =
if !review_model.catalog_contains_auto_review && !review_model.model_overridden {
Arc::clone(&context.model_info)
} else {
Arc::new(
session
.services
.models_manager
.get_model_info(
review_model.model.as_str(),
&turn.config.to_models_manager_config(),
)
.await,
)
};
let (review_model, guardian_model_info) =
super::reviewer_config::resolve_review_model(session, context).await;
let reviewer_config = session
.services
.thread_extension_data
@@ -87,16 +87,10 @@ impl ReviewContextPolicy {
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
}),
GuardianContextMode::ThreadOwned
.for_checkpoint(history.annotated_items(), reviewer_compaction_hash)
== GuardianContextMode::ThreadOwned,
"parent compaction checkpoint is incompatible with the Guardian review model or its compatibility is unknown"
);
}
@@ -91,6 +91,7 @@ async fn run_review_preserves_evidence_during_parent_compaction() {
window_ids,
compaction_response_id: None,
compaction_model_hash: Some("matching".to_owned()),
reviewer_compaction_hash: Some("matching".to_owned()),
},
)
.await;
+47 -1
View File
@@ -1,6 +1,8 @@
//! Adds model, policy context and live network state to the extension's reviewer configuration.
//! Resolves reviewer models and adds policy context and live network state to reviewer configuration.
//! Both prewarming and reviews finish this setup before context preparation and reuse checks.
use std::sync::Arc;
use codex_protocol::models::BaseInstructionsProvenance;
use codex_protocol::openai_models::ModelMessages;
@@ -53,3 +55,47 @@ pub fn build_guardian_review_session_config(
}
Ok(guardian_config)
}
/// Resolves the same catalog-backed reviewer for approval and checkpoint migration.
pub(crate) async fn resolve_review_model(
session: &crate::session::session::Session,
context: &super::GuardianReviewContext,
) -> (
codex_guardian_reviewer::ReviewModel,
Arc<codex_protocol::openai_models::ModelInfo>,
) {
let turn = context.turn();
let available_models = session
.services
.models_manager
.list_models(
codex_models_manager::manager::RefreshStrategy::Offline,
turn.config.http_client_factory(),
)
.await;
let default_review_model_id = turn.provider.approval_review_preferred_model();
let review_model = codex_guardian_reviewer::select_review_model(
&context.model_info,
context.reasoning_effort.as_ref(),
default_review_model_id,
&available_models,
);
// Resolve a separate reviewer against the current catalog on every attempt.
// Parent fallback must retain the action's metadata even after a catalog refresh.
let guardian_model_info =
if !review_model.catalog_contains_auto_review && !review_model.model_overridden {
Arc::clone(&context.model_info)
} else {
Arc::new(
session
.services
.models_manager
.get_model_info(
review_model.model.as_str(),
&turn.config.to_models_manager_config(),
)
.await,
)
};
(review_model, guardian_model_info)
}
+18 -5
View File
@@ -1678,7 +1678,7 @@ impl Session {
)]
async fn apply_rollout_reconstruction(
&self,
turn_context: &TurnContext,
turn_context: &Arc<TurnContext>,
rollout_items: &[RolloutItem],
) -> Option<PreviousTurnSettings> {
let rollout_reconstruction::RolloutReconstruction {
@@ -1720,6 +1720,14 @@ impl Session {
.zip(metadata)
.map(|(item, metadata)| ResponseItemEnvelope { item, metadata })
.collect();
let reviewer_compaction_hash =
if self.guardian_context_mode == crate::context::GuardianContextMode::ThreadOwned {
let context = crate::guardian::GuardianReviewContext::from(turn_context);
let (_, reviewer) = crate::guardian::resolve_review_model(self, &context).await;
reviewer.comp_hash.clone()
} else {
None
};
{
let mut state = self.state.lock().await;
state.replace_annotated_history(
@@ -1727,9 +1735,11 @@ impl Session {
reference_context_item,
HistoryReplacement::Reset,
);
state
.history
.restore_review_context(Some(&retained_context), guardian_history.as_ref());
state.history.restore_review_context(
Some(&retained_context),
guardian_history.as_ref(),
reviewer_compaction_hash.as_deref(),
);
if let Some(world_state) = world_state_baseline {
state.history.set_world_state_baseline(world_state);
}
@@ -4039,7 +4049,9 @@ impl Session {
state.replace_annotated_history(
items,
reference_context_item.clone(),
HistoryReplacement::Compaction,
HistoryReplacement::Compaction {
reviewer_compaction_hash: metadata.reviewer_compaction_hash,
},
);
compacted_item.guardian_history = state.history.guardian_history_checkpoint();
compacted_item.retained_context = Some(state.history.retained_context().clone());
@@ -4501,6 +4513,7 @@ impl Session {
window_ids,
compaction_response_id: None,
compaction_model_hash: None,
reviewer_compaction_hash: None,
},
)
.await;
@@ -351,6 +351,9 @@ impl Session {
history.restore_review_context(
checkpoint.compacted.retained_context.as_ref(),
checkpoint.compacted.guardian_history.as_ref(),
// Keep the backup during replay; the installing session resolves its reviewer.
/*reviewer_compaction_hash*/
None,
);
}
// Materialize exact history semantics from the replay-derived suffix. The eventual lazy
+1
View File
@@ -5428,6 +5428,7 @@ async fn settings_checkpoint_waits_for_accepted_settings_persistence() {
window_ids,
compaction_response_id: None,
compaction_model_hash: None,
reviewer_compaction_hash: None,
},
),
));
+11 -4
View File
@@ -73,7 +73,7 @@ pub(crate) struct SessionState {
/// Persisted origin of the session base instructions, when known.
pub(crate) base_instructions_provenance: Option<BaseInstructionsProvenance>,
pub(crate) history: ContextManager,
/// Cancels work bound to discarded history. Appends and compaction preserve it.
/// Cancels work bound to discarded history or a superseded Guardian evidence policy.
pub(crate) history_reset: CancellationToken,
pub(crate) latest_rate_limits: Option<RateLimitSnapshot>,
pub(crate) latest_token_usage_record: Option<TokenUsageRecord>,
@@ -191,12 +191,19 @@ impl SessionState {
reference_context_item: Option<TurnContextItem>,
replacement: HistoryReplacement,
) {
match replacement {
HistoryReplacement::Compaction => self.history.replace_compacted(items),
let invalidate_reviews = match replacement {
HistoryReplacement::Compaction {
reviewer_compaction_hash,
} => self
.history
.replace_compacted(items, reviewer_compaction_hash.as_deref()),
HistoryReplacement::Reset => {
self.history.replace_annotated(items);
std::mem::take(&mut self.history_reset).cancel();
true
}
};
if invalidate_reviews {
std::mem::take(&mut self.history_reset).cancel();
}
self.history
.set_reference_context_item(reference_context_item);