Deduplicate large tool output strings in rollout traces (#62407)

## Why

Repeated tool output, such as the same image returned in several results,
can consume the trace bundle budget. When output bytes are unavailable,
the surrounding result can still carry terminal metadata and conversation
links.

## What changed

- Store JSON string values of at least 64 KiB, measured after encoding,
  separately from their tool result or runtime event. Identical encoded
  values share one record per bundle, while each occurrence retains its
  position and complete captures reconstruct the original JSON bytes.
- Keep separate compression shards open for content and surrounding
  records. Budget for the serialized event and fall back to a single
  capped or omitted payload when the split layout or its references
  exceed the applicable limit.
- Track missing values separately from literal `null` so reduction can
  preserve surviving terminal metadata and keep tool output IDs attached
  to their original items.

## Testing

Add regression tests for shared image and text payloads, byte-for-byte
reconstruction, recording completion under tight bundle limits, and
reduction with missing output.

GitOrigin-RevId: a003197ea998639b6c2ae27f408990c0186406bd
This commit is contained in:
cassirer-openai
2026-11-19 02:41:02 +00:00
committed by copyberry
parent 9274511443
commit 508a429666
18 changed files with 1072 additions and 259 deletions
@@ -327,6 +327,40 @@ fn accepted_tool_results_survive_without_inference_and_reuse_their_ids() -> anyh
Ok(())
}
#[test]
fn capped_tool_output_keeps_the_next_stripped_id_in_its_original_slot() -> anyhow::Result<()> {
let (temp, writer) =
crate::writer::capture_tests::limited_trace(/*body*/ 512, /*bundle*/ 64 << 10)?;
start_thread(&writer, "thread-root", "/root")?;
start_turn(&writer, "turn-1")?;
let request = json!({"input": [
{"type": "function_call_output", "output": "x".repeat(1024)},
{"type": "function_call_output", "output": "retained"}
]});
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: "sample".into(),
thread_id: "thread-root".into(),
codex_turn_id: "turn-1".into(),
model: "model".into(),
provider_name: "test".into(),
request_payload: writer.write_json_payload(RawPayloadKind::InferenceRequest, &request)?,
prepared_prompt_payload: writer
.write_json_payload(RawPayloadKind::PreparedPrompt, &request)?,
warmup_context_payload: None,
stripped_tool_output_ids: vec![(0, "large".into()), (1, "small".into())],
})?;
let state = replay_bundle(temp.path())?;
let ids = &state.inference_calls["sample"].request_item_ids;
assert_eq!(ids.len(), 1);
assert_eq!(
state.conversation_items[&ids[0]]
.responses_item_id
.as_deref(),
Some("small")
);
Ok(())
}
#[test]
fn injected_outputs_keep_their_request_positions_and_native_ids() -> anyhow::Result<()> {
for accept_first in [true, false] {
@@ -23,6 +23,7 @@ use crate::model::ConversationRole;
use crate::model::InferenceCallId;
use crate::model::ProducerRef;
use crate::payload::RawPayloadRef;
use crate::shard::ObservedJson;
mod normalize;
@@ -40,8 +41,8 @@ impl TraceReducer {
if self.receivable_ids.contains_key(&key) {
return Ok(());
}
let item =
normalize::normalize_model_item(&self.payload_reader.observed_json(payload)?, payload)?;
let ObservedJson { mut value, missing } = self.payload_reader.observed_json(payload)?;
let item = normalize::normalize_model_item(&mut value, payload, &missing)?;
if !item.is_delivery_or_tool_output() || item.responses_item_id.as_deref() != Some(wire_id)
{
bail!("accepted item payload does not match {wire_id}");
@@ -81,7 +82,10 @@ impl TraceReducer {
if !request_payload.capture.is_complete() {
return Ok(Vec::new());
}
let mut payload = self.payload_reader.observed_json(request_payload)?;
let ObservedJson {
value: mut payload,
missing,
} = self.payload_reader.observed_json(request_payload)?;
let Some(input) = payload.get_mut("input") else {
bail!(
"inference request payload {} did not contain input",
@@ -101,6 +105,9 @@ impl TraceReducer {
let item = request_items
.get_mut(index)
.context("stripped tool output index outside request")?;
if missing["input"][index].is_string() {
continue; // The captured request has no item to attach the history ID to.
}
if item.get("id").is_some()
|| !matches!(
item["type"].as_str(),
@@ -113,7 +120,8 @@ impl TraceReducer {
}
item["id"] = Value::String(history_id);
}
let items = normalize::normalize_model_items(request_items, request_payload)?;
let items =
normalize::normalize_model_items(request_items, request_payload, &missing["input"])?;
let previous_response_id = payload.get("previous_response_id").and_then(Value::as_str);
// After compaction, the next full request is compared against the installed replacement
@@ -203,7 +211,10 @@ impl TraceReducer {
if !response_payload.capture.is_complete() {
return Ok(Vec::new());
}
let payload = self.payload_reader.observed_json(response_payload)?;
let ObservedJson {
value: payload,
missing,
} = self.payload_reader.observed_json(response_payload)?;
let Some(output_items) = payload.get("output_items").and_then(Value::as_array) else {
bail!(
"inference response payload {} did not contain output_items",
@@ -220,7 +231,11 @@ impl TraceReducer {
bail!("inference response referenced unknown call {inference_call_id}");
};
let items = normalize::normalize_model_items(output_items, response_payload)?;
let items = normalize::normalize_model_items(
output_items,
response_payload,
&missing["output_items"],
)?;
// A later request or compaction can be recorded before this response.
// Only match items with source IDs, so retries with identical text stay distinct.
let candidates = self.rollout.threads[&thread_id]
@@ -380,12 +395,23 @@ impl TraceReducer {
checkpoint_payload: &RawPayloadRef,
) -> Result<ReducedCompactionCheckpoint> {
let (input_items, replacement_items) = if checkpoint_payload.capture.is_complete() {
let payload = self.payload_reader.observed_json(checkpoint_payload)?;
let ObservedJson {
value: payload,
missing,
} = self.payload_reader.observed_json(checkpoint_payload)?;
let input = required_array(&payload, "input_history", checkpoint_payload)?;
let replacement = required_array(&payload, "replacement_history", checkpoint_payload)?;
(
normalize::normalize_model_items(input, checkpoint_payload)?,
normalize::normalize_model_items(replacement, checkpoint_payload)?,
normalize::normalize_model_items(
input,
checkpoint_payload,
&missing["input_history"],
)?,
normalize::normalize_model_items(
replacement,
checkpoint_payload,
&missing["replacement_history"],
)?,
)
} else {
// The install event still establishes a compaction boundary.
@@ -414,6 +440,7 @@ impl TraceReducer {
Some(codex_turn_id.to_string()),
wall_time_unix_ms,
NormalizedConversationItem {
structured_output_hash: None,
responses_item_id: None,
role: ConversationRole::Assistant,
channel: None,
@@ -517,6 +544,9 @@ impl TraceReducer {
}
}
let item_id = self.next_conversation_item_id();
if let Some(hash) = item.structured_output_hash {
self.structured_output_hashes.insert(item_id.clone(), hash);
}
self.rollout.conversation_items.insert(
item_id.clone(),
ConversationItem {
@@ -566,6 +596,12 @@ impl TraceReducer {
if accepted_id.as_deref() == Some(item_id) {
*accepted_id = None;
item.body.clone_from(&normalized.body);
if let Some(hash) = normalized.structured_output_hash {
self.structured_output_hashes
.insert(item_id.to_owned(), hash);
} else {
self.structured_output_hashes.remove(item_id);
}
if normalized.agent_message.is_none() {
self.snapshot_output_anchors.insert(item_id.to_owned());
}
@@ -664,6 +700,10 @@ impl TraceReducer {
{
return false;
}
let existing_hash = self.structured_output_hashes.get(item_id);
if existing_hash.is_some() || normalized.structured_output_hash.is_some() {
return existing_hash == normalized.structured_output_hash.as_ref();
}
conversation_item_matches(item, normalized)
}
@@ -8,6 +8,7 @@ use serde::Deserialize;
use serde_json::Value;
use sha2::Digest;
use sha2::Sha256;
use std::collections::BTreeMap;
use crate::model::AgentMessageMetadata;
use crate::model::ConversationBody;
@@ -31,6 +32,7 @@ pub(super) struct NormalizedConversationItem {
pub(super) kind: ConversationItemKind,
pub(super) agent_message: Option<AgentMessageMetadata>,
pub(super) body: ConversationBody,
pub(super) structured_output_hash: Option<[u8; 32]>,
pub(super) call_id: Option<String>,
}
@@ -48,14 +50,15 @@ impl NormalizedConversationItem {
pub(super) fn normalize_model_items(
items: &[Value],
raw_payload: &RawPayloadRef,
missing: &Value,
) -> Result<Vec<NormalizedConversationItem>> {
let mut normalized_items = Vec::new();
for item in items {
for (index, item) in items.iter().enumerate() {
// Tools and reasoning settings configure inference. Their raw payload retains the control.
if matches!(
item.get("type").and_then(Value::as_str),
Some("additional_tools" | "configuration_update")
) || unavailable_ref(item, raw_payload).is_some()
) || missing[index].is_string()
{
continue;
}
@@ -64,7 +67,11 @@ pub(super) fn normalize_model_items(
if let Some(object) = model_visible_item.as_object_mut() {
object.remove("internal_chat_message_metadata_passthrough");
}
normalized_items.push(normalize_model_item(&model_visible_item, raw_payload)?);
normalized_items.push(normalize_model_item(
&mut model_visible_item,
raw_payload,
&missing[index],
)?);
}
Ok(normalized_items)
}
@@ -80,8 +87,9 @@ pub(super) fn token_usage_from_value(value: &Value) -> Option<TokenUsage> {
}
pub(super) fn normalize_model_item(
item: &Value,
item: &mut Value,
raw_payload: &RawPayloadRef,
missing: &Value,
) -> Result<NormalizedConversationItem> {
let Some(item_type) = item.get("type").and_then(Value::as_str) else {
bail!(
@@ -90,11 +98,12 @@ pub(super) fn normalize_model_item(
);
};
let mut normalized = match item_type {
"message" => normalize_message_item(item, raw_payload),
"agent_message" => normalize_agent_message_item(item, raw_payload),
"reasoning" => normalize_reasoning_item(item, raw_payload),
"message" => normalize_message_item(item, raw_payload, missing),
"agent_message" => normalize_agent_message_item(item, raw_payload, missing),
"reasoning" => normalize_reasoning_item(item, raw_payload, missing),
"function_call" => Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::FunctionCall,
@@ -107,11 +116,12 @@ pub(super) fn normalize_model_item(
}),
"function_call_output" => Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role: ConversationRole::Tool,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::FunctionCallOutput,
agent_message: None,
body: tool_output_body(item.get("output"), raw_payload)?,
body: tool_output_body(item.get("output"), raw_payload, &missing["output"])?,
call_id: item
.get("call_id")
.and_then(Value::as_str)
@@ -119,6 +129,7 @@ pub(super) fn normalize_model_item(
}),
"custom_tool_call" => Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::CustomToolCall,
@@ -131,11 +142,12 @@ pub(super) fn normalize_model_item(
}),
"custom_tool_call_output" => Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role: ConversationRole::Tool,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::CustomToolCallOutput,
agent_message: None,
body: tool_output_body(item.get("output"), raw_payload)?,
body: tool_output_body(item.get("output"), raw_payload, &missing["output"])?,
call_id: item
.get("call_id")
.and_then(Value::as_str)
@@ -144,6 +156,7 @@ pub(super) fn normalize_model_item(
"tool_search_call" | "web_search_call" | "image_generation_call" | "local_shell_call" => {
Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::FunctionCall,
@@ -155,21 +168,37 @@ pub(super) fn normalize_model_item(
.map(ToString::to_string),
})
}
"tool_search_output" | "mcp_tool_call_output" => Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Tool,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::FunctionCallOutput,
agent_message: None,
body: json_body(item, raw_payload),
call_id: item
.get("call_id")
.and_then(Value::as_str)
.map(ToString::to_string),
}),
"tool_search_output" | "mcp_tool_call_output" => {
// A preview can truncate a difference or show null for two different missing
// values. Hash the full visible JSON and the missing child IDs at their paths.
let body = json_body(item, raw_payload);
item.sort_all_objects();
let gaps: BTreeMap<_, _> = missing
.as_object()
.into_iter()
.flatten()
.filter(|(key, _)| item.get(key).is_some())
.collect();
let mut hash = Sha256::new();
serde_json::to_writer(&mut hash, &(&*item, gaps))?;
Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: Some(hash.finalize().into()),
role: ConversationRole::Tool,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::FunctionCallOutput,
agent_message: None,
body,
call_id: item
.get("call_id")
.and_then(Value::as_str)
.map(ToString::to_string),
})
}
"compaction" | "compaction_summary" | "context_compaction" => {
Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Summary),
kind: ConversationItemKind::Message,
@@ -190,6 +219,7 @@ pub(super) fn normalize_model_item(
fn normalize_message_item(
item: &Value,
raw_payload: &RawPayloadRef,
missing: &Value,
) -> Result<NormalizedConversationItem> {
let Some(role) = item.get("role").and_then(Value::as_str) else {
bail!(
@@ -205,6 +235,7 @@ fn normalize_message_item(
};
Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role,
channel: item
.get("phase")
@@ -213,7 +244,7 @@ fn normalize_message_item(
kind: ConversationItemKind::Message,
agent_message: None,
body: ConversationBody {
parts: content_parts(item.get("content"), raw_payload)?,
parts: content_parts(item.get("content"), raw_payload, &missing["content"])?,
},
call_id: None,
})
@@ -222,17 +253,20 @@ fn normalize_message_item(
fn normalize_agent_message_item(
item: &Value,
raw_payload: &RawPayloadRef,
missing: &Value,
) -> Result<NormalizedConversationItem> {
let raw_payload_id = &raw_payload.raw_payload_id;
let routing = AgentMessageMetadata::deserialize(item).with_context(|| {
format!("failed to parse agent_message routing in payload {raw_payload_id}")
})?;
let mut parts = Vec::new();
for part in item["content"]
for (index, part) in item["content"]
.as_array()
.context("expected agent_message content array")?
.iter()
.enumerate()
{
if let Some(missing) = unavailable_ref(&part["text"], raw_payload) {
if let Some(missing) = missing["content"][index]["text"].as_str() {
parts.push(payload_ref_part("text", missing));
continue;
}
@@ -252,6 +286,7 @@ fn normalize_agent_message_item(
Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Analysis),
kind: ConversationItemKind::Message,
@@ -264,6 +299,7 @@ fn normalize_agent_message_item(
fn normalize_reasoning_item(
item: &Value,
raw_payload: &RawPayloadRef,
missing: &Value,
) -> Result<NormalizedConversationItem> {
let mut parts = Vec::new();
append_reasoning_parts(
@@ -271,6 +307,7 @@ fn normalize_reasoning_item(
"content",
ReasoningPartKind::Content,
raw_payload,
missing,
&mut parts,
)?;
append_reasoning_parts(
@@ -278,6 +315,7 @@ fn normalize_reasoning_item(
"summary",
ReasoningPartKind::Summary,
raw_payload,
missing,
&mut parts,
)?;
@@ -309,6 +347,7 @@ fn normalize_reasoning_item(
Ok(NormalizedConversationItem {
responses_item_id: None,
structured_output_hash: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Analysis),
kind: ConversationItemKind::Reasoning,
@@ -329,6 +368,7 @@ fn append_reasoning_parts(
key: &str,
kind: ReasoningPartKind,
raw_payload: &RawPayloadRef,
missing: &Value,
parts: &mut Vec<ConversationPart>,
) -> Result<()> {
let Some(items) = item.get(key) else {
@@ -344,7 +384,7 @@ fn append_reasoning_parts(
);
};
for content_item in items {
for (index, content_item) in items.iter().enumerate() {
let Some(item_type) = content_item.get("type").and_then(Value::as_str) else {
bail!(
"reasoning item in payload {} had {key} entry without string type",
@@ -372,7 +412,7 @@ fn append_reasoning_parts(
}
};
if let Some(missing) = unavailable_ref(&content_item["text"], raw_payload) {
if let Some(missing) = missing[key][index]["text"].as_str() {
parts.push(payload_ref_part(expected_type, missing));
continue;
}
@@ -417,31 +457,27 @@ fn channel_from_phase(phase: &str) -> Option<ConversationChannel> {
}
}
/// Only interpret recorder-produced gaps backed by a partial reference in this payload.
fn unavailable_ref<'a>(value: &Value, root: &'a RawPayloadRef) -> Option<&'a RawPayloadRef> {
let marker = value.as_object().filter(|obj| obj.len() == 1)?;
let id = marker.get("$trace_unavailable")?.as_str()?;
root.references()
.find(|r| r.raw_payload_id == id && !r.capture.is_complete())
}
fn content_parts(
content: Option<&Value>,
raw_payload: &RawPayloadRef,
missing: &Value,
) -> Result<Vec<ConversationPart>> {
let Some(content) = content.and_then(Value::as_array) else {
return Ok(vec![payload_ref_part("content", raw_payload)]);
return Ok(vec![payload_ref_part(
"content",
&raw_payload.raw_payload_id,
)]);
};
let mut parts = Vec::new();
for part in content {
for (index, part) in content.iter().enumerate() {
match part.get("type").and_then(Value::as_str) {
Some("input_text" | "output_text" | "text") => {
if let Some(text) = part.get("text").and_then(Value::as_str) {
parts.push(ConversationPart::Text {
text: text.to_string(),
});
} else if let Some(missing) = unavailable_ref(&part["text"], raw_payload) {
} else if let Some(missing) = missing[index]["text"].as_str() {
parts.push(payload_ref_part("text", missing));
}
}
@@ -452,12 +488,16 @@ fn content_parts(
canonical.sort_all_objects();
let mut digest = Sha256::new();
serde_json::to_writer(&mut digest, &canonical)?;
let missing_image = missing[index]["image_url"].as_str();
if let Some(id) = missing_image {
digest.update([0]); // Include the shared child's identity in a partial observation.
digest.update(id.as_bytes());
}
parts.push(ConversationPart::PayloadRef {
label: other.unwrap_or("content").to_string(),
raw_payload_id: unavailable_ref(&part["image_url"], raw_payload)
.unwrap_or(raw_payload)
.raw_payload_id
.clone(),
raw_payload_id: missing_image
.unwrap_or(&raw_payload.raw_payload_id)
.to_owned(),
content_sha256: Some(format!("{:x}", digest.finalize())),
});
}
@@ -500,7 +540,7 @@ fn raw_text_or_json_body(value: Option<&Value>, raw_payload: &RawPayloadRef) ->
}
Some(value) => json_body(value, raw_payload),
None => ConversationBody {
parts: vec![payload_ref_part("payload", raw_payload)],
parts: vec![payload_ref_part("payload", &raw_payload.raw_payload_id)],
},
}
}
@@ -508,17 +548,18 @@ fn raw_text_or_json_body(value: Option<&Value>, raw_payload: &RawPayloadRef) ->
fn tool_output_body(
output: Option<&Value>,
raw_payload: &RawPayloadRef,
missing: &Value,
) -> Result<ConversationBody> {
Ok(match output {
Some(Value::String(text)) => ConversationBody {
parts: vec![ConversationPart::Text { text: text.clone() }],
},
Some(Value::Array(_)) => ConversationBody {
parts: content_parts(output, raw_payload)?,
parts: content_parts(output, raw_payload, missing)?,
},
Some(value) => json_body(value, raw_payload),
None => ConversationBody {
parts: vec![payload_ref_part("tool_output", raw_payload)],
parts: vec![payload_ref_part("tool_output", &raw_payload.raw_payload_id)],
},
})
}
@@ -550,10 +591,10 @@ fn json_body(value: &Value, raw_payload: &RawPayloadRef) -> ConversationBody {
}
}
fn payload_ref_part(label: &str, raw_payload: &RawPayloadRef) -> ConversationPart {
fn payload_ref_part(label: &str, id: &str) -> ConversationPart {
ConversationPart::PayloadRef {
label: label.to_string(),
raw_payload_id: raw_payload.raw_payload_id.clone(),
raw_payload_id: id.to_string(),
content_sha256: None,
}
}
@@ -555,6 +555,62 @@ fn request_reuses_prior_tool_outputs_with_internal_metadata() -> anyhow::Result<
Ok(())
}
#[test]
fn tool_search_outputs_keep_the_evidence_for_each_version() -> anyhow::Result<()> {
let long_text = "prefix".repeat(340);
let a = json!(format!("{long_text}A"));
let b = json!(format!("{long_text}B"));
let null = json!(null);
for body_cap in [512, 8192] {
let (root, writer) = crate::writer::capture_tests::limited_trace(body_cap, 128 << 10)?;
start_thread(&writer, ROOT_THREAD_ID, "/root")?;
let mut requests = Vec::new();
for (index, (first, second)) in [
(&a, &null),
(&b, &null),
(&b, &null),
(&null, &b),
(&null, &null),
]
.into_iter()
.enumerate()
{
let turn = format!("turn-{index}");
start_turn(&writer, &turn)?;
let mut output = json!({"type": "tool_search_output", "call_id": "search", "tools": [
{"name": "one", "text": first}, {"name": "two", "text": second}
]});
if index == 2 {
output["internal_chat_message_metadata_passthrough"] = json!({"text": a});
}
let request = writer
.write_json_payload(RawPayloadKind::InferenceRequest, &json!({"input":[output]}))?;
assert_eq!(
request.is_complete(),
body_cap > long_text.len() || index == 4
);
requests.push(request.raw_payload_id.clone());
append_inference_start(&writer, &format!("inference-{index}"), &turn, request)?;
}
drop(writer);
let rollout = replay_bundle(root.path())?;
// A changed value or a moved missing slot gets its own evidence. An exact repeat
// reuses the first sighting, and genuine JSON nulls form a distinct observation.
for (index, source) in [0, 1, 1, 3, 4].into_iter().enumerate() {
let item_id =
&rollout.inference_calls[&format!("inference-{index}")].request_item_ids[0];
let [ConversationPart::Json { raw_payload_id, .. }] =
rollout.conversation_items[item_id].body.parts.as_slice()
else {
panic!("expected JSON tool-search output");
};
assert_eq!(raw_payload_id, &requests[source]);
}
assert_eq!(rollout.conversation_items.len(), 4);
}
Ok(())
}
#[test]
fn tool_output_versions_preserve_different_nested_metadata() -> anyhow::Result<()> {
let temp = TempDir::new()?;
@@ -73,6 +73,7 @@ pub fn replay_bundle(bundle_dir: impl AsRef<Path>) -> Result<RolloutTrace> {
terminal_ids_by_process: BTreeMap::new(),
process_ids_by_terminal: BTreeMap::new(),
thread_conversation_snapshots: BTreeMap::new(),
structured_output_hashes: BTreeMap::new(),
pending_compaction_replacement_item_ids: BTreeMap::new(),
code_cell_ids_by_runtime: BTreeMap::new(),
last_thread_resume_seq: BTreeMap::new(),
@@ -220,6 +221,8 @@ struct TraceReducer {
process_ids_by_terminal: BTreeMap<String, String>,
/// Latest request and its response items, used to reconcile the next request.
thread_conversation_snapshots: BTreeMap<String, Vec<String>>,
/// Full identities for JSON tool outputs whose reduced bodies contain only a preview.
structured_output_hashes: BTreeMap<String, [u8; 32]>,
/// Replacement snapshot installed by compaction but not yet seen in a sampling request.
///
/// The first full request after compaction should compare against the installed replacement
@@ -72,7 +72,7 @@ impl TraceReducer {
tool_call_id: &str,
runtime_payload: &RawPayloadRef,
) -> Result<()> {
if !runtime_payload.capture.is_complete() {
if !runtime_payload.is_complete() {
return Ok(());
}
let kind = self
@@ -135,7 +135,7 @@ impl TraceReducer {
) -> Result<()> {
let kind = self.rollout.tool_calls[tool_call_id].kind.clone();
// MCP results are opaque evidence; they cannot describe agent interactions.
if !runtime_payload.capture.is_complete() || matches!(kind, ToolCallKind::Mcp { .. }) {
if !runtime_payload.is_complete() || matches!(kind, ToolCallKind::Mcp { .. }) {
return Ok(());
}
let runtime_payload_json = self.payload_reader.read_json(runtime_payload)?;
@@ -28,6 +28,7 @@ use crate::model::TerminalRequest;
use crate::model::TerminalResult;
use crate::model::TerminalSession;
use crate::model::ToolCallKind;
use crate::payload::RawPayloadKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawEventSeq;
use crate::reducer::TraceReducer;
@@ -93,7 +94,7 @@ impl TraceReducer {
return Ok(None);
};
if !runtime_payload.capture.is_complete() {
if !runtime_payload.is_complete() {
return Ok(None);
}
let payload = self.payload_reader.read_json(runtime_payload)?;
@@ -175,13 +176,44 @@ impl TraceReducer {
else {
bail!("terminal end referenced unknown operation {operation_id}");
};
let response = response_payload
.filter(|p| p.capture.is_complete())
.map(|payload| {
let value = self.payload_reader.read_json(payload)?;
parse_terminal_response_payload(value, &operation_kind, &payload.raw_payload_id)
})
.transpose()?;
let response = match response_payload {
Some(payload)
if payload.capture.is_complete()
&& (payload.kind == RawPayloadKind::ToolRuntimeEvent
|| payload.is_complete()) =>
{
// A retained exec-end parent still carries the exit code and process ID.
// observed_json maps an unavailable output child to null.
let value = self.payload_reader.observed_json(payload)?.value;
Some(parse_terminal_response_payload(
value,
&operation_kind,
&payload.raw_payload_id,
)?)
}
Some(payload)
if payload.capture.is_complete()
&& operation_kind == TerminalOperationKind::WriteStdin =>
{
let observed = self.payload_reader.observed_json(payload)?;
// Missing stdout has a child ID at the same path. A literal null does not.
let has_exec_output = observed.value["value"]["output"].is_string()
|| observed.missing["value"]["output"].is_string();
if has_exec_output
&& let DispatchedToolTraceResponsePayload::CodeModeResponse { value } =
serde_json::from_value(observed.value)?
{
let result: CodeModeExecResult = serde_json::from_value(value)?;
Some(ParsedTerminalResponse {
process_id: None,
result: result.into(),
})
} else {
None
}
}
_ => None,
};
let process_id = {
let Some(operation) = self.rollout.terminal_operations.get_mut(operation_id) else {
@@ -507,7 +539,7 @@ fn parse_protocol_terminal_response(payload: ExecCommandEndPayload) -> ParsedTer
process_id: payload.process_id,
result: TerminalResult {
exit_code: Some(payload.exit_code),
stdout: payload.aggregated_output,
stdout: payload.aggregated_output.unwrap_or_default(),
stderr: String::new(),
formatted_output: None,
original_token_count: None,
@@ -557,15 +589,8 @@ fn parse_dispatch_terminal_response(value: JsonValue) -> Result<ParsedTerminalRe
fn parse_code_mode_exec_result(value: JsonValue) -> TerminalResult {
match serde_json::from_value::<CodeModeExecResult>(value.clone()) {
Ok(result) => TerminalResult {
exit_code: result.exit_code,
stdout: result.output.clone(),
stderr: String::new(),
formatted_output: Some(result.output),
original_token_count: result.original_token_count,
chunk_id: result.chunk_id,
},
Err(_) => {
Ok(result) if result.output.is_some() => result.into(),
_ => {
let output = json_text_content(&value).unwrap_or_else(|| value.to_string());
TerminalResult {
exit_code: None,
@@ -614,8 +639,7 @@ struct ExecCommandBeginPayload {
#[derive(Deserialize)]
struct ExecCommandEndPayload {
process_id: Option<String>,
#[serde(default)]
aggregated_output: String,
aggregated_output: Option<String>,
exit_code: i32,
}
@@ -655,7 +679,20 @@ struct CodeModeExecResult {
chunk_id: Option<String>,
exit_code: Option<i32>,
original_token_count: Option<usize>,
output: String,
output: Option<String>,
}
impl From<CodeModeExecResult> for TerminalResult {
fn from(result: CodeModeExecResult) -> Self {
Self {
exit_code: result.exit_code,
stdout: result.output.clone().unwrap_or_default(),
stderr: String::new(),
formatted_output: result.output,
original_token_count: result.original_token_count,
chunk_id: result.chunk_id,
}
}
}
#[cfg(test)]
@@ -19,6 +19,7 @@ use crate::model::TerminalResult;
use crate::model::TerminalSession;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::payload::PayloadCapture;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::ROOT_THREAD_ID;
@@ -37,8 +38,30 @@ use crate::writer::TraceWriter;
#[test]
fn exec_tool_reduces_to_terminal_operation_and_session() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
check_exec_terminal_result("ok\n", /*exit_code*/ 0, Some("ok\n"))
}
#[test]
fn exec_end_retains_exit_code_and_session_when_output_is_omitted() -> anyhow::Result<()> {
// Numbered lines stay larger than the bundle budget even after compression.
let output = (0..32_768)
.map(|line| format!("{line}\n"))
.collect::<String>();
check_exec_terminal_result(
&output, /*exit_code*/ 17, /*expected_stdout*/ None,
)
}
fn check_exec_terminal_result(
output: &str,
exit_code: i32,
expected_stdout: Option<&str>,
) -> anyhow::Result<()> {
let (temp, writer) = crate::writer::capture_tests::limited_trace(
/*body*/ 256 << 10,
/*bundle*/ 24 << 10,
)?;
start_thread(&writer, ROOT_THREAD_ID, "/root")?;
start_turn(&writer, "turn-1")?;
append_inference_with_tool_call(&writer)?;
@@ -94,11 +117,16 @@ fn exec_tool_reduces_to_terminal_operation_and_session() -> anyhow::Result<()> {
"turn_id": "turn-1",
"command": ["cargo", "test"],
"cwd": "/repo",
"aggregated_output": "ok\n",
"exit_code": 0,
"aggregated_output": output,
"exit_code": exit_code,
"status": "completed"
}),
)?;
if expected_stdout.is_none() {
assert!(runtime_end_payload.capture.is_complete());
assert!(matches!(runtime_end_payload.parts.as_slice(), [child]
if matches!(child.capture, PayloadCapture::Omitted { .. })));
}
let runtime_end_payload_id = runtime_end_payload.raw_payload_id.clone();
let runtime_end = writer.append_with_context(
trace_context("turn-1"),
@@ -188,8 +216,8 @@ fn exec_tool_reduces_to_terminal_operation_and_session() -> anyhow::Result<()> {
max_output_tokens: None,
},
result: Some(TerminalResult {
exit_code: Some(0),
stdout: "ok\n".to_string(),
exit_code: Some(exit_code),
stdout: expected_stdout.unwrap_or_default().to_string(),
stderr: String::new(),
formatted_output: None,
original_token_count: None,
@@ -570,8 +598,91 @@ fn invalid_write_stdin_arguments_remain_failed_tool_calls() -> anyhow::Result<()
#[test]
fn code_mode_write_stdin_result_projects_structured_exec_fields() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
check_code_mode_write_stdin_result(/*body_limit*/ 128 << 10)
}
#[test]
fn capped_code_mode_write_stdin_retains_structured_exec_fields() -> anyhow::Result<()> {
check_code_mode_write_stdin_result(/*body_limit*/ 4096)
}
fn check_code_mode_write_stdin_result(body_limit: usize) -> anyhow::Result<()> {
let output = "x".repeat(80 << 10);
let response = json!({
"type": "code_mode_response",
"value": {
"chunk_id": "abc123",
"wall_time_seconds": 1.25,
"exit_code": 0,
"original_token_count": 3,
"output": output
}
});
let retained_output = (body_limit > output.len()).then_some(output);
assert_eq!(
replay_write_stdin_result(body_limit, response, ExecutionStatus::Completed)?,
Some(TerminalResult {
exit_code: Some(0),
stdout: retained_output.clone().unwrap_or_default(),
stderr: String::new(),
formatted_output: retained_output,
original_token_count: Some(3),
chunk_id: Some("abc123".to_string()),
}),
);
Ok(())
}
#[test]
fn capped_write_stdin_only_recovers_structured_output() -> anyhow::Result<()> {
let body_limit = 4 << 10;
let text = "x".repeat(80 << 10);
for (response, status) in [
(
json!({"type": "direct_response", "response_item": {"type": "function_call_output", "output": text}}),
ExecutionStatus::Completed,
),
(
json!({"type": "error", "error": text}),
ExecutionStatus::Failed,
),
// A literal null and a gap elsewhere do not identify a missing terminal output.
(
json!({"type": "code_mode_response", "value": {"output": null, "text": text}}),
ExecutionStatus::Completed,
),
] {
assert_eq!(
replay_write_stdin_result(body_limit, response, status)?,
None
);
}
let response = json!({
"type": "code_mode_response",
"value": {"output": "done", "exit_code": 17, "text": text},
});
assert_eq!(
replay_write_stdin_result(body_limit, response, ExecutionStatus::Completed)?,
Some(TerminalResult {
exit_code: Some(17),
stdout: "done".into(),
formatted_output: Some("done".into()),
stderr: String::new(),
original_token_count: None,
chunk_id: None,
})
);
Ok(())
}
fn replay_write_stdin_result(
body_limit: usize,
response: serde_json::Value,
status: ExecutionStatus,
) -> anyhow::Result<Option<TerminalResult>> {
let (temp, writer) =
crate::writer::capture_tests::limited_trace(body_limit, /*bundle*/ 1 << 20)?;
start_thread(&writer, ROOT_THREAD_ID, "/root")?;
start_turn(&writer, "turn-1")?;
let request_payload = writer.write_json_payload(
@@ -590,19 +701,6 @@ fn code_mode_write_stdin_result_projects_structured_exec_fields() -> anyhow::Res
}
}),
)?;
let response_payload = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({
"type": "code_mode_response",
"value": {
"chunk_id": "abc123",
"wall_time_seconds": 1.25,
"exit_code": 0,
"original_token_count": 3,
"output": "done\n"
}
}),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellStarted {
@@ -625,29 +723,22 @@ fn code_mode_write_stdin_result_projects_structured_exec_fields() -> anyhow::Res
invocation_payload: Some(request_payload),
},
)?;
writer.append_with_context(
writer.event_with_payload(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
RawPayloadKind::ToolResult,
&response,
move |response_payload| RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-stdin".to_string(),
status: ExecutionStatus::Completed,
status,
result_payload: Some(response_payload),
},
)?;
writer.flush()?;
let rollout = replay_bundle(temp.path())?;
assert_eq!(
rollout.terminal_operations["terminal_operation:1"].result,
Some(TerminalResult {
exit_code: Some(0),
stdout: "done\n".to_string(),
stderr: String::new(),
formatted_output: Some("done\n".to_string()),
original_token_count: Some(3),
chunk_id: Some("abc123".to_string()),
}),
);
Ok(())
Ok(rollout.terminal_operations["terminal_operation:1"]
.result
.clone())
}
fn append_inference_with_tool_call(writer: &TraceWriter) -> anyhow::Result<()> {