Make thread-owned Guardian context always enabled (#47686)

## What changed

- Deprecate and ignore `features.guardianv2.thread_context`, including profile overrides, with a migration notice. Ignore managed requirements for the removed flag with a warning.
- Preserve surviving legacy root instructions across compaction and resume when retained instructions are incomplete. Include unmatched instructions in worker authorization context with an explicit unknown-ordering notice, without replacing newer retained facts or expanding the reviewer's model window.
- Use surviving source calls to roll back verified answers from older checkpoints that lack acceptance-order metadata.

## Testing

Add regression coverage for legacy instruction recovery, compaction and resume, source matching, and answer rollback around same-turn user input. Update configuration and Guardian review tests to verify that the deprecated opt-out still uses thread-owned context and rejects incompatible compaction evidence.

GitOrigin-RevId: a65936c9e0b912e7667d1385a2ec53df726565de
This commit is contained in:
felixxia-oai
2026-09-23 22:44:59 +00:00
committed by copyberry
parent ab7439231c
commit a6df7385e6
17 changed files with 410 additions and 151 deletions
+54 -16
View File
@@ -2,6 +2,9 @@
//! 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.
//! Root checkpoints keep compatibility transcripts while retained instructions are incomplete;
//! thread-owned reviewers still use only the parent model window.
//! Old text checkpoints can seed that backup from their surviving plaintext instructions.
//! Token estimates charge item content rather than transport metadata.
//! Oversized instructions keep an incomplete excerpt for bounded root review, including
//! sources recovered from legacy Guardian checkpoints before their raw history is dropped.
@@ -77,7 +80,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 preserved across compaction and resume. Thread-owned review uses parent context.
/// Compatibility history for legacy review and missing root instructions.
review_history: Option<TranscriptHistory>,
/// Host facts independent of the model window; snapshots share immutable state.
retained_context: Arc<RetainedContext>,
@@ -140,16 +143,22 @@ impl ConversationHistorySnapshot for SharedConversationHistory {
}
fn review_items(&self) -> Box<dyn Iterator<Item = &ResponseItem> + Send + '_> {
match &self.review_history {
Some(history) => history.items(),
None => self.items(),
if self.guardian_review_mode == GuardianContextMode::Legacy
&& let Some(history) = &self.review_history
{
return history.items();
}
self.items()
}
fn review_history_version(&self) -> u64 {
self.review_history
.as_ref()
.map_or(self.history_version, TranscriptHistory::generation)
if self.guardian_review_mode == GuardianContextMode::Legacy {
return self
.review_history
.as_ref()
.map_or(self.history_version, TranscriptHistory::generation);
}
self.history_version
}
fn history_version(&self) -> u64 {
@@ -238,13 +247,16 @@ impl ContextManager {
true
}
/// Original checkpoint evidence, independent of the selected review window.
pub(crate) fn guardian_history_items(
&self,
) -> Option<Box<dyn Iterator<Item = &ResponseItem> + Send + '_>> {
self.review_history.as_ref().map(SectionHistory::items)
}
pub(crate) fn guardian_history_checkpoint(&self) -> Option<GuardianHistoryCheckpoint> {
if self.guardian_review_mode == GuardianContextMode::ThreadOwned {
return None;
}
self.review_history
.as_ref()
.map(|history| GuardianHistoryCheckpoint(history.items().cloned().collect()))
self.guardian_history_items()
.map(|items| GuardianHistoryCheckpoint(items.cloned().collect()))
}
pub(crate) fn restore_review_context(
@@ -328,7 +340,15 @@ impl ContextManager {
)
});
}
if self.guardian_review_mode == GuardianContextMode::ThreadOwned
let retain_legacy_authorization = self.retain_inherited_user_messages
&& self.retained_context.has_missing_user_messages()
&& (checkpoint.is_some()
// A text checkpoint can predate both retained facts and Guardian backups.
// Preserve its surviving instructions without treating an opaque checkpoint's
// partial model window as a complete compatibility transcript.
|| codex_history::CompactionCheckpoint::latest(&self.items).is_none());
if (self.guardian_review_mode == GuardianContextMode::ThreadOwned
&& !retain_legacy_authorization)
|| (self.guardian_context_mode == GuardianContextMode::Legacy && checkpoint.is_none())
{
self.review_history = None;
@@ -350,6 +370,11 @@ impl ContextManager {
}));
}
self.review_history = Some(history);
if self.guardian_review_mode == GuardianContextMode::ThreadOwned
&& !self.has_legacy_user_messages()
{
self.review_history = None;
}
}
pub(crate) fn token_info(&self) -> Option<TokenUsageInfo> {
@@ -594,9 +619,15 @@ impl ContextManager {
== 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::ThreadOwned
&& (!self.retain_inherited_user_messages
|| !self.retained_context.has_missing_user_messages()
|| !self.has_legacy_user_messages())
{
self.review_history = None;
}
if self.guardian_review_mode == GuardianContextMode::Legacy && self.review_history.is_none()
{
let mut retained = TranscriptHistory::new(self.history_version.saturating_add(1));
@@ -711,7 +742,14 @@ impl ContextManager {
.iter()
.filter_map(|item| item.turn_id())
.collect::<Vec<_>>();
if self.guardian_context_mode == GuardianContextMode::ThreadOwned {
// Old checkpoints lack an accepted-input boundary. Their answers still follow
// the original source calls, even after the capture opt-out has been retired.
if source == RetainedInputSource::Inherited
|| source.acceptance_order().is_some()
|| retained_context
.ordered_entries()
.any(|(_, entry)| matches!(entry, RetainedContextEntry::UserMessage(_)))
{
Arc::make_mut(&mut retained_context).rollback(
&removed_turns,
first_removed_message_id,
@@ -331,6 +331,129 @@ fn checkpoint_replayed_messages_keep_legacy_review_when_the_source_survives() {
assert_eq!(history.retained_context(), &retained);
}
#[test_case(None; "no retained checkpoint")]
#[test_case(Some(serde_json::json!({
"verified_answers": [], "incomplete": false
})); "legacy retained checkpoint without instructions")]
fn plaintext_checkpoint_without_backup_preserves_root_instructions(
saved_context: Option<serde_json::Value>,
) {
let instruction = serde_json::from_value(serde_json::json!({
"type": "message", "id": "original-restriction", "role": "user",
"content": [{"type": "input_text", "text": "Only publish privately."}]
}))
.expect("old instruction without ordering metadata");
let saved_context: Option<RetainedContext> =
saved_context.map(|value| serde_json::from_value(value).expect("legacy retained context"));
let mut history = ContextManager::with_guardian_context_mode(
GuardianContextMode::ThreadOwned,
&SessionSource::Cli,
);
history.replace(vec![instruction]);
history.restore_review_context(
saved_context.as_ref(),
/*checkpoint*/ None,
Some("reviewer"),
);
// Compaction removes the only plaintext copy. Resume must keep it available
// to worker authorization without adding it back to the reviewer's model window.
let compacted = vec![ResponseItemEnvelope {
item: serde_json::from_value(serde_json::json!({
"type": "compaction", "id": "new-checkpoint", "encrypted_content": "opaque"
}))
.expect("new checkpoint"),
metadata: Some(CodexHarnessMetadata {
compaction_model_hash: Some("reviewer".to_owned()),
..Default::default()
}),
}];
history.replace_compacted(compacted.clone(), Some("reviewer"));
let mut resumed = ContextManager::with_guardian_context_mode(
GuardianContextMode::ThreadOwned,
&SessionSource::Cli,
);
resumed.replace_annotated(compacted.clone());
resumed.restore_review_context(
Some(history.retained_context()),
history.guardian_history_checkpoint().as_ref(),
Some("reviewer"),
);
let snapshot = resumed.conversation_history_snapshot();
assert_eq!(
(
GuardianContextMode::from_history(snapshot.as_ref()),
snapshot.review_items().cloned().collect::<Vec<_>>(),
resumed
.legacy_user_messages()
.map(|message| message.text)
.collect::<Vec<_>>(),
),
(
GuardianContextMode::ThreadOwned,
compacted
.into_iter()
.map(|envelope| envelope.item)
.collect::<Vec<_>>(),
vec!["Only publish privately.".to_owned()],
),
);
}
#[test]
fn legacy_checkpoint_rollback_keeps_answers_before_a_same_turn_steer() {
let mut checkpoint: codex_history::CompactedItem = serde_json::from_value(serde_json::json!({
"message": "Legacy checkpoint without accepted-input metadata.",
"replacement_history": [
{"type": "message", "id": "initial", "role": "user",
"content": [{"type": "input_text", "text": "Inspect the release."}]},
{"type": "function_call", "call_id": "before", "name": "request_user_input", "arguments": "{}"},
{"type": "message", "id": "steer", "role": "user",
"content": [{"type": "input_text", "text": "Inspect the README too."}]},
{"type": "function_call", "call_id": "after", "name": "request_user_input", "arguments": "{}"}
],
"retained_context": {"verified_answers": [
{"turn_id": "shared-turn", "call_id": "before",
"questions": [{"question": "Publish?", "answer": "Only privately."}]},
{"turn_id": "shared-turn", "call_id": "after",
"questions": [{"question": "Publish the README?", "answer": "Never."}]}
], "incomplete": false}
})).expect("legacy checkpoint");
for envelope in checkpoint.replacement_history.as_mut().unwrap() {
envelope.item.set_turn_id_if_missing("shared-turn");
}
let expected = checkpoint
.retained_context
.as_ref()
.unwrap()
.verified_answers()
.cloned()
.collect::<Vec<_>>();
let mut history = ContextManager::with_guardian_context_mode(
GuardianContextMode::ThreadOwned,
&SessionSource::Cli,
);
history.replace_annotated(checkpoint.replacement_history.take().unwrap());
history.restore_review_context(
checkpoint.retained_context.as_ref(),
/*checkpoint*/ None,
/*reviewer_compaction_hash*/ None,
);
// The old checkpoint has no acceptance order; use the surviving source calls
// to remove only the answer belonging to each rolled-back input.
for remaining in [1, 0] {
history.drop_last_n_user_turns(/*num_turns*/ 1);
assert_eq!(
history
.retained_context()
.verified_answers()
.cloned()
.collect::<Vec<_>>(),
expected[..remaining],
);
}
}
#[test]
fn conversation_history_snapshot_excludes_contextual_user_messages() {
let contextual_message = crate::context::ContextualUserFragment::into(UserInstructions {
@@ -6,13 +6,18 @@
use std::sync::Arc;
use super::ContextManager;
use crate::compact::is_summary_message;
use crate::context::GuardianContextMode;
use crate::context::is_contextual_user_fragment;
use crate::event_mapping::parse_turn_item;
use crate::guardian::GUARDIAN_MAX_ROOT_MESSAGE_TOKENS;
use crate::guardian::guardian_truncate_text;
use codex_history::CodexHarnessMetadata;
use codex_history::ReconciledRetainedContext;
use codex_history::RetainedContext;
use codex_history::RetainedInputSource;
use codex_history::RetainedUserMessage;
use codex_protocol::items::TurnItem;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
@@ -23,6 +28,42 @@ pub(super) enum RetainedMessageSource {
}
impl ContextManager {
pub(super) fn has_legacy_user_messages(&self) -> bool {
ReconciledRetainedContext::new(Some(&self.retained_context), std::iter::empty())
.unmatched_user_messages(self.legacy_user_messages())
.next()
.is_some()
}
/// Bounded instruction candidates from the legacy backup; their ordering is unknown.
pub(crate) fn legacy_user_messages(&self) -> impl Iterator<Item = RetainedUserMessage> + '_ {
self.guardian_history_items()
.into_iter()
.flatten()
.filter_map(move |item| {
if !crate::context::is_user_authorization_message(item) {
return None;
}
let Some(TurnItem::UserMessage(message)) = parse_turn_item(item) else {
return None;
};
let text = message.message();
if is_summary_message(&text)
|| text.trim_start().starts_with("<user_action>")
|| is_contextual_user_fragment(&ContentItem::InputText { text: text.clone() })
{
return None;
}
let text = guardian_truncate_text(&text, GUARDIAN_MAX_ROOT_MESSAGE_TOKENS).0;
Some(RetainedUserMessage {
turn_id: item.turn_id().unwrap_or_default().to_owned(),
message_id: item.id().map(|id| id.as_str().to_owned()),
text,
complete: false,
})
})
}
pub(crate) fn restore_retained_context(&mut self, checkpoint: Option<&RetainedContext>) {
Arc::make_mut(&mut self.retained_context).restore(checkpoint, &self.items);
if self.guardian_context_mode == GuardianContextMode::ThreadOwned {