Preserve Guardian authorization evidence until request budgeting (#44570)

## Why

Transcript limits could shorten user instructions or omit later messages before Guardian evaluated the complete request budget, losing restrictions or prior approvals even when they would fit.

## What changed

- Keep user messages and manual approvals complete and in source order through transcript collection and retention.
- Preserve historical instructions while synchronous review can still compact history. If the final request still cannot fit, discard optional evidence before shortening older historical entries with truncation markers, preserving later restrictions where possible.
- Warn that shortened instructions and approvals are incomplete and that missing evidence does not authorize actions.
- Let asynchronous review defer to synchronous review when complete instructions exceed its budget.

## Testing

Add coverage for complete instruction retention, approval and restriction ordering, marked truncation of oversized Unicode text, compaction before truncation, and asynchronous fallback when instructions do not fit.

GitOrigin-RevId: e6159e876231347986b937ee7e07f944b83bfbe6
This commit is contained in:
felixxia-oai authored and copyberry committed 2026-09-10 16:02:36 +00:00
1 parent 9c4879f3a5
commit 287e4f7dbf
21 files changed
+575 -335

No files matched your search

@@ -1,6 +1,7 @@
//! Contributor integration tests use the normal catalog-backed lifecycle setup.
use super::*;
use crate::async_scorer::authorization::ScoreAuthorization;
use pretty_assertions::assert_eq;
#[derive(Clone, Copy)]
@@ -63,6 +64,7 @@ async fn catalog_budget_fixture(base_url: String, window: i64) -> Result<Guardia
enum BudgetEvidence {
Checkpoint,
Image,
UserInstructions,
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -77,11 +79,18 @@ async fn contributor_preserves_optional_evidence_or_defers_to_sync() -> Result<(
assert_catalog_budget(BudgetEvidence::Image).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn contributor_preserves_complete_user_instructions_or_defers_to_sync() -> Result<()> {
skip_if_no_network!(Ok(()));
assert_catalog_budget(BudgetEvidence::UserInstructions).await
}
async fn assert_catalog_budget(evidence: BudgetEvidence) -> Result<()> {
let windows = match evidence {
BudgetEvidence::Checkpoint => [18_000, 32_000],
// In the smaller window the text fits, but the 10K image reservation cannot.
BudgetEvidence::Image => [14_000, 40_000],
BudgetEvidence::UserInstructions => [18_000, 50_000],
};
for (window, outcome) in windows
.into_iter()
@@ -97,8 +106,18 @@ async fn assert_catalog_budget(evidence: BudgetEvidence) -> Result<()> {
]),
)
.await;
let instruction = "Inspect README.md; do not change files.";
let mut user = user_instruction(instruction);
let instruction = if matches!(evidence, BudgetEvidence::UserInstructions) {
let padding = "é🙂 ".repeat(/*n*/ 3_500);
format!("{padding}You may edit files only in the scratch directory.{padding}")
} else {
"Inspect README.md; do not change files.".to_owned()
};
let restriction = "Revoke permission to edit files. Only read README.md.";
let approval = format!(
"{}\nApproved action: read_file README.md",
codex_guardian_context::MANUAL_APPROVAL_DEVELOPER_PREFIX
);
let mut user = user_instruction(&instruction);
let (checkpoint, commentary) = match evidence {
BudgetEvidence::Checkpoint => (
Some(ResponseItem::ContextCompaction {
@@ -125,9 +144,22 @@ async fn assert_catalog_budget(evidence: BudgetEvidence) -> Result<()> {
});
(None, vec!["optional old commentary ".repeat(/*n*/ 500)])
}
BudgetEvidence::UserInstructions => (None, Vec::new()),
};
let mut history = checkpoint.iter().cloned().collect::<Vec<_>>();
history.push(user);
if matches!(evidence, BudgetEvidence::UserInstructions) {
history.push(ResponseItem::Message {
id: None,
role: "developer".to_owned(),
content: vec![ContentItem::InputText {
text: approval.clone(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
});
history.push(user_instruction(restriction));
}
history.extend(commentary.into_iter().map(|text| ResponseItem::Message {
id: None,
role: "assistant".to_owned(),
@@ -146,9 +178,32 @@ async fn assert_catalog_budget(evidence: BudgetEvidence) -> Result<()> {
current: TestConversationHistory(history),
compaction_model_hash: Some("budget-checkpoint".to_owned()),
}),
BudgetEvidence::Image => fixture.test.codex.conversation_history_snapshot().await,
BudgetEvidence::Image | BudgetEvidence::UserInstructions => {
fixture.test.codex.conversation_history_snapshot().await
}
};
let thread_store = fixture.test.codex.thread_extension_data();
if matches!(evidence, BudgetEvidence::UserInstructions) {
thread_store.insert(SecurityRiskScore {
scores: BTreeMap::from([("action_risk".to_owned(), 0.25)]),
call_id: None,
action: None,
sampled_at: None,
});
let progress = thread_store.get::<GuardianV2ScoreProgress>().unwrap();
let authorization = ScoreAuthorization::current(&fixture.test.codex).await;
*progress.authorization.lock().unwrap() = Some(authorization);
assert_eq!(
cached_approval(
&fixture.registry,
thread_store,
"review action",
/*metrics*/ None
)
.await,
Some(ReviewDecision::Approved)
);
}
let turn_store = ExtensionData::new("turn-1");
let tool_name = ToolName::plain("read_file");
let payload = ToolPayload::Function {
@@ -192,16 +247,22 @@ async fn assert_catalog_budget(evidence: BudgetEvidence) -> Result<()> {
}
})
.await?;
let request = response.single_request().body_json();
let request = response.single_request();
let text = request.message_input_texts("user").concat();
let request = request.body_json();
let input = request["input"].to_string();
if let Some(checkpoint) = checkpoint {
assert_eq!(request["input"][2], serde_json::to_value(checkpoint)?);
assert!(input.contains("commentary 0:"));
} else {
} else if matches!(evidence, BudgetEvidence::Image) {
assert!(input.contains("input_image"));
assert!(input.contains("optional old commentary"));
} else {
assert!(text.contains(&format!(
"[1] user: {instruction}\n[2] developer: {approval}\n[3] user: {restriction}\n"
)));
}
assert!(input.contains(instruction));
assert!(text.contains(&instruction));
assert!(input.contains("read_file"));
assert_eq!(
cached_approval(
@@ -2825,9 +2825,12 @@ async fn contributor_sends_compacted_conversation_history_to_luna() -> Result<()
.filter_map(|entry| entry["text"].as_str())
.collect::<Vec<_>>();
assert!(entries.iter().any(|entry| entry.contains("user turn 0:")));
assert!(entries.iter().any(|entry| entry.contains("user turn 7:")));
assert!(!entries.iter().any(|entry| entry.contains("user turn 1:")));
for index in 0..8 {
assert!(entries.iter().any(|entry| entry.contains(&format!(
"user turn {index}: {}",
"authorization ".repeat(/*n*/ 1_000)
))));
}
assert!(
entries
.iter()
@@ -2876,6 +2879,9 @@ async fn contributor_sends_compacted_conversation_history_to_luna() -> Result<()
for entry in entries.into_iter().filter(|entry| entry.starts_with('[')) {
let (label, text) = entry.split_once(": ").expect("numbered transcript entry");
if label.ends_with(" user") {
continue;
}
let max_tokens = if label.contains("tool ") {
MAX_TOOL_ENTRY_TOKENS
} else {
@@ -222,7 +222,7 @@ fn transcript_keeps_conversation_and_configured_sources() {
}
#[test]
fn transcript_truncates_oversized_entries_without_splitting_characters() {
fn transcript_truncates_oversized_assistant_entries_without_splitting_characters() {
let prefix = "start é";
let suffix = "é end";
let oversized_message = format!(
@@ -231,24 +231,8 @@ fn transcript_truncates_oversized_entries_without_splitting_characters() {
);
let original_bytes = oversized_message.len();
let items = vec![
ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: oversized_message,
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
},
ResponseItem::Message {
id: None,
role: "assistant".to_string(),
content: vec![ContentItem::OutputText {
text: "latest response".to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
},
assistant_message(oversized_message, MessagePhase::FinalAnswer),
assistant_message("latest response", MessagePhase::FinalAnswer),
];
let mut rendered = TranscriptConfig::default()
@@ -268,14 +252,14 @@ fn transcript_truncates_oversized_entries_without_splitting_characters() {
let transcript = rendered.transcript_entries();
assert_eq!(transcript.len(), 2);
let user_entry = &transcript[0];
assert!(user_entry.starts_with(&format!("[1] user: {prefix}")));
assert!(user_entry.contains("<truncated omitted_approx_tokens=\""));
assert!(user_entry.ends_with(&format!("{suffix}\n")));
let entry = &transcript[0];
assert!(entry.starts_with(&format!("[1] assistant: {prefix}")));
assert!(entry.contains("<truncated omitted_approx_tokens=\""));
assert!(entry.ends_with(&format!("{suffix}\n")));
assert!(
user_entry.len()
entry.len()
<= TruncationPolicy::Tokens(MAX_MESSAGE_ENTRY_TOKENS).byte_budget()
+ "[1] user: \n".len()
+ "[1] assistant: \n".len()
);
assert_eq!(transcript[1], "[2] assistant: latest response\n");
assert_eq!(
@@ -288,81 +272,13 @@ fn transcript_truncates_oversized_entries_without_splitting_characters() {
))
.collect::<Vec<_>>(),
vec![(
"transcript_user",
"transcript_message",
original_bytes,
user_entry.len() - "[1] user: \n".len()
entry.len() - "[1] assistant: \n".len()
)]
);
}
#[test]
fn transcript_preserves_first_and_latest_user_messages_and_recent_history() {
let oversized_user_message = "authorization ".repeat(1_000);
let mut items = (0..8)
.map(|index| ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: format!("user turn {index}: {oversized_user_message}"),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
})
.collect::<Vec<_>>();
items.push(ResponseItem::Message {
id: None,
role: "assistant".to_string(),
content: vec![ContentItem::OutputText {
text: "Most recent assistant context.".to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
});
let transcript = TranscriptConfig::default()
.build_context(ContextInput {
target: ContextTarget::Async,
history: &TestConversationHistory(&items),
root_conversation: &[],
trusted_user_answers: &[],
planned_action: None,
previous_reviews: None,
trusted_tool: None,
trusted_skill_paths: &[],
node_repl_images: None,
})
.expect("collect transcript")
.transcript_entries();
assert!(transcript[0].starts_with("[1] user: user turn 0:"));
assert!(
transcript
.iter()
.any(|entry| entry.starts_with("[8] user: user turn 7:"))
);
assert!(
!transcript
.iter()
.any(|entry| entry.contains("user turn 1:"))
);
assert!(
transcript
.iter()
.any(|entry| entry.contains("user turn 6:"))
);
assert_eq!(
transcript.last().map(String::as_str),
Some("[9] assistant: Most recent assistant context.\n")
);
assert!(
transcript
.iter()
.map(|entry| TruncationPolicy::Bytes(entry.len()).token_budget())
.sum::<usize>()
<= MAX_MESSAGE_TRANSCRIPT_TOKENS
);
}
#[test]
fn transcript_preserves_user_restrictions_before_final_assistant_messages() {
let first_user_entry = "[1] user: Find a flight to New York.\n";
@@ -1190,62 +1106,52 @@ fn transcript_preserves_outputs_with_call_ids_or_explicit_names() {
#[test]
fn configured_reasoning_counts_against_message_budget() {
let mut items = (0..8)
.map(|index| ResponseItem::Message {
for (repeats, include_reasoning) in [(200, true), (1_000, false)] {
let mut expected = Vec::new();
let mut items = (0..8)
.map(|index| {
let text = format!("user turn {index}: {}", "authorization ".repeat(repeats));
expected.push(format!("[{}] user: {text}\n", index + 1));
ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText { text }],
phase: None,
internal_chat_message_metadata_passthrough: None,
}
})
.collect::<Vec<_>>();
items.push(ResponseItem::Reasoning {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: format!("user turn {index}: {}", "authorization ".repeat(1_000)),
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "Recent reasoning evidence.".to_string(),
}],
phase: None,
content: None,
encrypted_content: None,
internal_chat_message_metadata_passthrough: None,
});
if include_reasoning {
expected.push("[9] reasoning: Recent reasoning evidence.\n".to_owned());
}
let transcript = TranscriptConfig {
sources: vec![TranscriptSource::Reasoning],
..TranscriptConfig::default()
}
.build_context(ContextInput {
target: ContextTarget::Async,
history: &TestConversationHistory(&items),
root_conversation: &[],
trusted_user_answers: &[],
planned_action: None,
previous_reviews: None,
trusted_tool: None,
trusted_skill_paths: &[],
node_repl_images: None,
})
.collect::<Vec<_>>();
items.push(ResponseItem::Reasoning {
id: None,
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "Recent reasoning evidence.".to_string(),
}],
content: None,
encrypted_content: None,
internal_chat_message_metadata_passthrough: None,
});
let transcript = TranscriptConfig {
sources: vec![TranscriptSource::Reasoning],
..TranscriptConfig::default()
.expect("collect transcript")
.transcript_entries();
assert_eq!(transcript, expected);
}
.build_context(ContextInput {
target: ContextTarget::Async,
history: &TestConversationHistory(&items),
root_conversation: &[],
trusted_user_answers: &[],
planned_action: None,
previous_reviews: None,
trusted_tool: None,
trusted_skill_paths: &[],
node_repl_images: None,
})
.expect("collect transcript")
.transcript_entries();
assert!(transcript[0].contains("user turn 0:"));
assert!(
transcript
.iter()
.any(|entry| entry.contains("user turn 7:"))
);
assert_eq!(
transcript.last().map(String::as_str),
Some("[9] reasoning: Recent reasoning evidence.\n")
);
assert!(
transcript
.iter()
.map(|entry| TruncationPolicy::Bytes(entry.len()).token_budget())
.sum::<usize>()
<= MAX_MESSAGE_TRANSCRIPT_TOKENS
);
}
#[test]