Account for file images in context budgets and Guardian reviews (#46072)

## Why

File images contributed zero to history and compaction token estimates and were dropped from Guardian context. This undercounted context usage and omitted image evidence from reviews.

## What changed

- Estimate file images using the fixed resized-image cost, or 10,000 patch tokens for `original` detail because file references do not expose dimensions.
- Charge file images against remote compaction and Guardian request budgets.
- Preserve file images from user messages and tool outputs through Guardian selection and delivery, and deduplicate review images by file ID.
- Apply transcript image count and byte limits to both reference types, counting file ID bytes rather than referenced file contents.

## Testing

Add coverage for file-image estimates, selection limits, delivery, and compaction retention. Extend Guardian tests to verify file-image evidence reaches reviews and uploaded original-detail images trigger reviewer-history compaction.

GitOrigin-RevId: ee024204dcbe16e277fea9347c6a4d7fc120e18d
This commit is contained in:
Krish Chainani authored and copyberry committed 2026-09-17 01:38:13 +00:00
1 parent ce03f22af6
commit b974893c90
18 files changed
+481 -199

No files matched your search

+55 -10
View File
@@ -605,11 +605,14 @@ async fn amazon_bedrock_automatic_compaction_uses_v2_responses_endpoint() -> Res
Ok(())
}
#[test_case(None; "default_trims_images")]
#[test_case(Some(false); "disabled_preserves_images")]
#[test_case(None, "image_url"; "default_trims_images")]
#[test_case(Some(false), "image_url"; "disabled_preserves_images")]
#[test_case(None, "file_id"; "default_trims_file_images")]
#[test_case(Some(false), "file_id"; "disabled_preserves_file_images")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_compact_v2_charges_retained_images_to_token_budget(
image_budget_enabled: Option<bool>,
image_field: &str,
) -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -630,6 +633,14 @@ async fn remote_compact_v2_charges_retained_images_to_token_budget(
// Each original-detail image costs 10,000 estimated patch tokens.
let image_inputs = (1..=8)
.map(|number| {
if image_field == "file_id" {
return Ok(UserInput::Image {
image: ImageReference::File {
file_id: format!("file_{number}"),
},
detail: Some(codex_protocol::models::ImageDetail::Original),
});
}
let image = image::ImageBuffer::from_pixel(
/*width*/ 3200,
/*height*/ 3200,
@@ -666,7 +677,24 @@ async fn remote_compact_v2_charges_retained_images_to_token_budget(
.await?;
wait_for_turn_complete(codex).await;
let initial_request = initial_mock.single_request();
let prepared_images = initial_request.message_input_image_urls("user");
let prepared_images = initial_request
.inputs_of_type("message")
.into_iter()
.filter(|item| item["role"] == "user")
.flat_map(|item| {
item["content"]
.as_array()
.expect("message content is an array")
.clone()
})
.filter(|item| item["type"] == "input_image")
.map(|item| {
item[image_field]
.as_str()
.expect("image input has a string reference")
.to_owned()
})
.collect::<Vec<_>>();
assert_eq!(prepared_images.len(), 7);
for cycle in 1..=2 {
@@ -717,16 +745,33 @@ async fn remote_compact_v2_charges_retained_images_to_token_budget(
};
let mut expected_images = prepared_images[dropped..].to_vec();
if cycle == 2 {
let UserInput::Image {
image: ImageReference::Inline { image_url },
..
} = &image_inputs[7]
else {
let UserInput::Image { image, .. } = &image_inputs[7] else {
unreachable!()
};
expected_images.push(image_url.clone());
expected_images.push(match image {
ImageReference::Inline { image_url } => image_url.clone(),
ImageReference::File { file_id } => file_id.clone(),
});
}
assert_eq!(follow_up.message_input_image_urls("user"), expected_images);
let retained_images = follow_up
.inputs_of_type("message")
.into_iter()
.filter(|item| item["role"] == "user")
.flat_map(|item| {
item["content"]
.as_array()
.expect("message content is an array")
.clone()
})
.filter(|item| item["type"] == "input_image")
.map(|item| {
item[image_field]
.as_str()
.expect("image input has a string reference")
.to_owned()
})
.collect::<Vec<_>>();
assert_eq!(retained_images, expected_images);
assert!(
follow_up
.message_input_texts("user")
@@ -30,8 +30,11 @@ use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use test_case::test_case;
use super::image_rollout::RecordingFileAttachmentStore;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(160_000, &[0, 0]; "complete_instructions_fit")]
#[test_case(28_000, &[0, 1]; "oversized_history_compacts_then_truncates")]
@@ -198,6 +201,7 @@ async fn review_preserves_user_instructions_until_request_budgeting(
enum ReviewerResponse {
Decision,
ToolContinuation,
FileImageContinuation,
UncompactableContinuation,
CompactionError,
NextReview,
@@ -206,6 +210,7 @@ enum ReviewerResponse {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(1, ReviewerResponse::Decision; "required_context_fails_closed")]
#[test_case(4_500, ReviewerResponse::ToolContinuation; "oversized_tool_continuation_compacts")]
#[test_case(4_500, ReviewerResponse::FileImageContinuation; "uploaded_original_image_history_compacts")]
#[test_case(4_500, ReviewerResponse::UncompactableContinuation; "ineffective_compaction_fails_closed")]
#[test_case(4_500, ReviewerResponse::CompactionError; "compaction_service_error_does_not_request_user_approval")]
#[test_case(6_000, ReviewerResponse::NextReview; "incoming_review_compacts_existing_history")]
@@ -231,6 +236,10 @@ async fn review_respects_complete_context_budget(
)
.with_model_info_override("gpt-5.6-luna", move |model| {
model.context_window = Some(window);
if matches!(reviewer_response, ReviewerResponse::FileImageContinuation) {
model.supports_image_detail_original = true;
model.use_responses_lite = false;
}
model
.model_messages
.as_mut()
@@ -268,12 +277,17 @@ async fn review_respects_complete_context_budget(
if matches!(
reviewer_response,
ReviewerResponse::ToolContinuation
| ReviewerResponse::FileImageContinuation
| ReviewerResponse::UncompactableContinuation
| ReviewerResponse::CompactionError
) {
builder = builder
.with_code_mode_host_program(codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?);
}
let image_store = Arc::new(RecordingFileAttachmentStore::default());
if matches!(reviewer_response, ReviewerResponse::FileImageContinuation) {
builder = builder.with_image_store(image_store.clone());
}
let test = builder.build_with_auto_env(&server).await?;
let command = json!({"cmd": "echo guardian-budget-test", "sandbox_permissions": "require_escalated", "justification": "Run the requested command."}).to_string();
let mut commentary =
@@ -321,12 +335,22 @@ async fn review_respects_complete_context_budget(
"exec",
"text('inspection-output'.repeat(600));",
),
// A tiny inline image fits before upload. Its opaque original-detail file
// reference must reserve 10k tokens in reviewer history and force compaction.
ReviewerResponse::FileImageContinuation => ev_custom_tool_call(
"reviewer-inspect",
"exec",
r#"image("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", "original");"#,
),
},
ev_completed("review"),
]),
);
}
if matches!(reviewer_response, ReviewerResponse::ToolContinuation) {
if matches!(
reviewer_response,
ReviewerResponse::ToolContinuation | ReviewerResponse::FileImageContinuation
) {
events.insert(
/*index*/ 2,
sse(vec![
@@ -424,18 +448,38 @@ async fn review_respects_complete_context_budget(
"expected required-evidence budget rejection: {output}"
);
} else {
let recovered = matches!(reviewer_response, ReviewerResponse::ToolContinuation);
let recovered = matches!(
reviewer_response,
ReviewerResponse::ToolContinuation | ReviewerResponse::FileImageContinuation
);
assert_eq!(requests.len(), if recovered { 4 } else { 3 });
assert_eq!(guardian_requests.len(), if recovered { 2 } else { 1 });
if recovered {
assert_eq!(compact_requests.len(), 1);
let compact = &compact_requests[0];
assert!(
compact
.body_json()
.to_string()
.contains("inspection-output")
);
if matches!(reviewer_response, ReviewerResponse::FileImageContinuation) {
assert_eq!(
image_store
.uploads
.lock()
.expect("image upload tracker lock is not poisoned")
.len(),
1
);
// The file reservation also protects the compaction request itself: an output
// larger than its window is replaced before the summary request is sent.
assert_eq!(
compact.custom_tool_call_output("reviewer-inspect")["output"],
"Output exceeded the available model context and was truncated"
);
} else {
assert!(
compact
.body_json()
.to_string()
.contains("inspection-output")
);
}
let recovered = guardian_requests[1].body_json();
assert!(
recovered["input"]
+2 -2
View File
@@ -57,8 +57,8 @@ use std::time::Duration;
const UPLOADED_FILE_ID: &str = "file_uploaded_image";
#[derive(Default)]
struct RecordingFileAttachmentStore {
uploads: Mutex<Vec<UploadRequest>>,
pub(super) struct RecordingFileAttachmentStore {
pub(super) uploads: Mutex<Vec<UploadRequest>>,
}
impl AttachmentStore for RecordingFileAttachmentStore {