Trim Guardian evidence by serialized JSON size (#65352)

## Why

JSON escaping can make a shorter tool output field consume more of the
evidence byte budget than a longer field. Ranking by raw string length
can truncate the build log while preserving a quote-heavy field that
takes up more space.

## What changed

When a Guardian response item exceeds the evidence budget, trim its
text fields in descending order of serialized JSON byte size.

## Testing

Extend the inbox truncation test to verify that a quote-heavy tool
result field is truncated while the build log and error summary stay
intact.

GitOrigin-RevId: de78c768e54e0fb020205aa5be14a9b6b3e8c1c9
This commit is contained in:
felixxia-oai
2026-12-02 22:57:17 +00:00
committed by copyberry
parent d374369121
commit 411e0f6235
2 changed files with 9 additions and 5 deletions
+6 -4
View File
@@ -88,14 +88,16 @@ fn fit_record(original: &RawValue, budget: usize) -> anyhow::Result<Value> {
&& record["type"] == "response_item"
{
let mut bytes = serialized_json_bytes(&record)?;
let mut texts = text_fields(&mut record["payload"]);
let mut texts = text_fields(&mut record["payload"])
.into_iter()
.map(|text| Ok((serialized_json_bytes(text)?, text)))
.collect::<serde_json::Result<Vec<_>>>()?;
// Sort references so smaller parts can stay intact and retain their positions.
texts.sort_by_key(|text| Reverse(text.len()));
for text in texts {
texts.sort_by_key(|(size, _)| Reverse(*size));
for (size, text) in texts {
if bytes <= budget {
break;
}
let size = serialized_json_bytes(text)?;
if size > MARKER.len() + 2 {
let target = size.saturating_sub(bytes - budget).max(MARKER.len() + 2);
*text = fit_text(text, target)?;
+3 -1
View File
@@ -507,7 +507,7 @@ async fn committed_posts_reach_current_subscribers_once_across_channel_retries()
}
#[test]
fn inbox_trims_only_the_large_text_in_tool_calls_and_results() -> anyhow::Result<()> {
fn inbox_trims_only_the_largest_serialized_text_in_tool_calls_and_results() -> anyhow::Result<()> {
use codex_protocol::protocol::TruncationPolicy;
use serde_json::json;
@@ -516,9 +516,11 @@ fn inbox_trims_only_the_large_text_in_tool_calls_and_results() -> anyhow::Result
"type": "function_call", "call_id": "build", "name": "shell",
"arguments": json!({"cmd": log}).to_string()
});
// The quotes are shorter than the build log in memory but larger after JSON escaping.
let result = json!({
"type": "function_call_output", "call_id": "build", "output": [
{"type": "input_text", "text": "Build failed with exit code 1"},
{"type": "input_text", "text": "\"".repeat(1000)},
{"type": "input_text", "text": log}
]
});