Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,277 @@
//! Accepted history retains original inference provenance across retries and resets.
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use super::test_support::append_completed_inference;
use super::test_support::append_inference_completion;
use super::test_support::append_inference_request;
use super::test_support::create_started_writer;
use super::test_support::message;
use super::test_support::start_thread;
use super::test_support::start_turn;
use super::test_support::start_turn_for_thread;
use super::test_support::trace_context;
use crate::ProducerRef;
use crate::RawPayloadKind;
use crate::RawTraceEventPayload;
use crate::replay_bundle;
#[test]
fn identical_text_from_a_discarded_attempt_does_not_gain_acceptance() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let input = message("user", "answer");
let mut output = message("assistant", "same text");
output["id"] = json!("discarded");
append_completed_inference(
&writer,
"thread-root",
"turn-1",
"first",
vec![input.clone()],
vec![output.clone()],
)?;
append_inference_request(&writer, "thread-root", "turn-1", "retry", vec![input])?;
output["id"] = json!("accepted");
// Acceptance can arrive before the asynchronous stream mapper's terminal record.
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::HistoryItemAccepted {
item_id: "accepted".into(),
},
)?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({"output_items": [output]}),
)?;
append_inference_completion(&writer, "retry", "resp-retry", response)?;
let trace = replay_bundle(temp.path())?;
let first = &trace.inference_calls["first"];
let retry = &trace.inference_calls["retry"];
assert_ne!(first.response_item_ids, retry.response_item_ids);
let mut expected = retry.request_item_ids.clone();
expected.extend(retry.response_item_ids.clone());
assert_eq!(trace.threads["thread-root"].conversation_item_ids, expected);
assert_eq!(
trace.conversation_items[&first.response_item_ids[0]]
.responses_item_id
.as_deref(),
Some("discarded")
);
Ok(())
}
#[test]
fn late_response_reuses_a_later_request_sighting_without_rewriting_its_snapshot()
-> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let input = message("user", "answer");
let mut output = message("assistant", "accepted");
output["id"] = json!("msg-accepted");
append_inference_request(
&writer,
"thread-root",
"turn-1",
"first",
vec![input.clone()],
)?;
let later_input = vec![input, output.clone(), message("user", "continue")];
append_inference_request(
&writer,
"thread-root",
"turn-1",
"second",
later_input.clone(),
)?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({"output_items": [output]}),
)?;
append_inference_completion(&writer, "first", "resp-first", response)?;
append_inference_request(&writer, "thread-root", "turn-1", "third", later_input)?;
let trace = replay_bundle(temp.path())?;
let second = &trace.inference_calls["second"];
assert_eq!(
trace.inference_calls["first"].response_item_ids,
vec![second.request_item_ids[1].clone()]
);
assert_eq!(
trace.inference_calls["third"].request_item_ids,
second.request_item_ids
);
assert_eq!(
trace.threads["thread-root"].conversation_item_ids,
second.request_item_ids
);
assert_eq!(
trace.conversation_items[&second.request_item_ids[1]].produced_by,
vec![ProducerRef::Inference {
inference_call_id: "first".into()
}]
);
Ok(())
}
#[test]
fn late_response_keeps_compaction_replacement_distinct() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let input = message("user", "answer");
let mut output = message("assistant", "accepted");
output["id"] = json!("msg-accepted");
append_inference_request(
&writer,
"thread-root",
"turn-1",
"first",
vec![input.clone()],
)?;
let checkpoint = writer.write_json_payload(
RawPayloadKind::CompactionCheckpoint,
&json!({
"input_history": [input, output], "replacement_history": [output]
}),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CompactionInstalled {
compaction_id: "reset".into(),
checkpoint_payload: checkpoint,
},
)?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({"output_items": [output]}),
)?;
append_inference_completion(&writer, "first", "resp-first", response)?;
append_inference_request(&writer, "thread-root", "turn-1", "second", vec![output])?;
let trace = replay_bundle(temp.path())?;
let checkpoint = &trace.compactions["reset"];
assert_eq!(
trace.inference_calls["first"].response_item_ids,
vec![checkpoint.input_item_ids[1].clone()]
);
assert_eq!(
trace.inference_calls["second"].request_item_ids,
checkpoint.replacement_item_ids
);
assert_ne!(
checkpoint.input_item_ids[1],
checkpoint.replacement_item_ids[0]
);
assert_eq!(
trace.conversation_items[&checkpoint.replacement_item_ids[0]].produced_by,
vec![ProducerRef::Compaction {
compaction_id: "reset".into()
}]
);
let mut expected = checkpoint.input_item_ids.clone();
expected.push(checkpoint.marker_item_id.clone());
expected.extend(checkpoint.replacement_item_ids.clone());
assert_eq!(trace.threads["thread-root"].conversation_item_ids, expected);
Ok(())
}
#[test]
fn inherited_output_is_child_prefill_without_copying_parent_sampling_provenance()
-> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-parent")?;
let mut output = message("assistant", "inherited");
output["id"] = json!("msg-parent");
append_completed_inference(
&writer,
"thread-root",
"turn-parent",
"parent",
vec![message("user", "answer")],
vec![output.clone()],
)?;
start_thread(&writer, "child", "/root/child")?;
start_turn_for_thread(&writer, "child", "turn-child")?;
append_inference_request(&writer, "child", "turn-child", "child", vec![output])?;
let trace = replay_bundle(temp.path())?;
let parent = &trace.inference_calls["parent"];
let child = &trace.inference_calls["child"];
assert_ne!(child.request_item_ids, parent.response_item_ids);
assert_eq!(
trace.threads["child"].conversation_item_ids,
child.request_item_ids
);
assert_eq!(
trace.conversation_items[&child.request_item_ids[0]].produced_by,
Vec::<ProducerRef>::new()
);
// A sighting in the child must not imply acceptance in the parent's history.
assert_eq!(
trace.threads["thread-root"].conversation_item_ids,
parent.request_item_ids
);
let accepted = RawTraceEventPayload::HistoryItemAccepted {
item_id: "msg-parent".into(),
};
let context = trace_context("turn-parent");
let first = writer.append_with_context(context.clone(), accepted.clone())?;
let mut duplicate = writer.append_with_context(context, accepted)?;
drop(writer);
// Give the later event an earlier clock reading: sequence determines which pair wins.
let path = temp.path().join("trace.jsonl");
let original = serde_json::to_string(&duplicate)?;
duplicate.wall_time_unix_ms = first.wall_time_unix_ms - 1;
let events = std::fs::read_to_string(&path)?;
assert!(events.contains(&original));
std::fs::write(
path,
events.replace(&original, &serde_json::to_string(&duplicate)?),
)?;
let replayed = replay_bundle(temp.path())?;
let local = &replayed.conversation_items[&parent.response_item_ids[0]];
let inherited = &replayed.conversation_items[&child.request_item_ids[0]];
assert_eq!(
(local.accepted_at_unix_ms, local.accepted_seq),
(Some(first.wall_time_unix_ms), Some(first.seq))
);
assert_eq!(
(inherited.accepted_at_unix_ms, inherited.accepted_seq),
(None, None)
);
Ok(())
}
#[test]
fn legacy_bundles_cannot_claim_accepted_history() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
append_completed_inference(
&writer,
"thread-root",
"turn-1",
"call",
vec![message("user", "answer")],
vec![message("assistant", "unproven")],
)?;
let manifest_path = temp.path().join("manifest.json");
let mut manifest: serde_json::Value =
serde_json::from_reader(std::fs::File::open(&manifest_path)?)?;
manifest["schema_version"] = json!(1);
std::fs::write(manifest_path, serde_json::to_vec(&manifest)?)?;
assert!(
replay_bundle(temp.path())
.unwrap_err()
.to_string()
.contains("cannot establish accepted history")
);
Ok(())
}

View File

@@ -0,0 +1,771 @@
//! Code-mode reduction.
//!
//! A code cell is the runtime parent for model-authored `exec`
//! JavaScript. Nested tools, waits, and terminal operations hang off this
//! object so viewers can inspect runtime work without flattening it into the
//! model-visible conversation.
//!
//! The reducer has to reconcile two clocks:
//! - model-visible items come from inference request/response payloads;
//! - runtime work starts as soon as Codex dispatches the tool.
//!
//! In real traces `CodeCellStarted` can arrive before the inference completion
//! payload that contains the `custom_tool_call` item. We therefore queue starts
//! until their source conversation item exists, then attach runtime edges.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde_json::Value;
use super::TraceReducer;
use crate::model::CodeCell;
use crate::model::CodeCellId;
use crate::model::CodeCellRuntimeStatus;
use crate::model::ConversationItemKind;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::model::ProducerRef;
use crate::model::ToolCallId;
use crate::model::ToolCallRequester;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawEventSeq;
use crate::raw_event::RawToolCallRequester;
/// Runtime start payload for one model-authored code-mode exec call.
///
/// The reduced id is already derived from the model-visible call id before this
/// reaches the code-cell reducer, so the reducer can reconcile runtime lifecycle
/// events against a stable graph identity.
pub(super) struct StartedCodeCell {
pub(super) code_cell_id: CodeCellId,
pub(super) runtime_cell_id: String,
pub(super) model_visible_call_id: crate::model::ModelVisibleCallId,
pub(super) source_js: String,
}
/// Queued code-cell start waiting for its model-visible source item.
///
/// Code execution can begin before inference stream completion records the
/// custom-tool call item that authored it. This wrapper keeps the original
/// event timing intact until that source item exists.
pub(super) struct PendingCodeCellStart {
pub(super) seq: RawEventSeq,
pub(super) wall_time_unix_ms: i64,
pub(super) thread_id: String,
pub(super) codex_turn_id: Option<String>,
pub(super) started: StartedCodeCell,
}
/// Lifecycle event observed before a queued code cell has materialized.
///
/// These events are replayed after the start is resolved so failed or very fast
/// cells do not lose runtime status while preserving source-item ownership.
pub(super) struct PendingCodeCellLifecycleEvent {
pub(super) seq: RawEventSeq,
pub(super) wall_time_unix_ms: i64,
pub(super) kind: PendingCodeCellLifecycleEventKind,
}
/// Runtime lifecycle transitions that can arrive while a code-cell start is queued.
pub(super) enum PendingCodeCellLifecycleEventKind {
InitialResponse {
runtime_cell_id: String,
status: CodeCellRuntimeStatus,
response_payload: Option<RawPayloadRef>,
},
Ended {
status: CodeCellRuntimeStatus,
response_payload: Option<RawPayloadRef>,
},
}
impl TraceReducer {
/// Starts a code cell once its model-visible source item exists.
///
/// Runtime events are allowed to arrive before stream completion has
/// reduced the model output that requested `exec`. Queueing preserves the
/// event order while still requiring every final `CodeCell` to point at the
/// exact conversation item that authored its JavaScript.
pub(super) fn start_or_queue_code_cell(&mut self, pending: PendingCodeCellStart) -> Result<()> {
let code_cell_id = pending.started.code_cell_id.clone();
if self
.source_item_id_for_pending_code_cell(&pending)?
.is_none()
{
if self.rollout.code_cells.contains_key(&code_cell_id)
|| self.pending_code_cell_starts.contains_key(&code_cell_id)
{
bail!("duplicate code cell start for {code_cell_id}");
}
self.pending_code_cell_starts.insert(code_cell_id, pending);
return Ok(());
}
self.start_code_cell(pending)
}
/// Materializes any queued code-cell starts unlocked by newly reduced conversation items.
///
/// This is called after inference and compaction conversation reduction,
/// because those are the only paths that create model-visible items today.
pub(super) fn flush_pending_code_cell_starts(&mut self) -> Result<()> {
let mut ready_ids = Vec::new();
for (code_cell_id, pending) in &self.pending_code_cell_starts {
if self
.source_item_id_for_pending_code_cell(pending)?
.is_some()
{
ready_ids.push(code_cell_id.clone());
}
}
for code_cell_id in ready_ids {
let Some(pending) = self.pending_code_cell_starts.remove(&code_cell_id) else {
continue;
};
self.start_code_cell(pending)?;
}
Ok(())
}
/// Inserts the reduced `CodeCell` once source ownership can be proven.
fn start_code_cell(&mut self, pending: PendingCodeCellStart) -> Result<()> {
let PendingCodeCellStart {
seq,
wall_time_unix_ms,
thread_id,
codex_turn_id,
started,
} = pending;
if self.rollout.code_cells.contains_key(&started.code_cell_id) {
bail!("duplicate code cell start for {}", started.code_cell_id);
}
let Some(codex_turn_id) = codex_turn_id else {
bail!(
"code cell start {} did not include a Codex turn id",
started.code_cell_id
);
};
self.validate_code_cell_turn(&thread_id, &codex_turn_id)?;
let source_item_id = self.source_item_id_for_code_cell_start(
&thread_id,
&started.code_cell_id,
&started.model_visible_call_id,
)?;
let output_item_ids = self.model_visible_code_cell_item_ids(
&thread_id,
&started.model_visible_call_id,
ConversationItemKind::CustomToolCallOutput,
);
// Runtime events may also have arrived while the start was queued.
// Seed these reverse links from already-reduced tool calls so replay is
// order-insensitive within the known trace causality.
let requester = ToolCallRequester::CodeCell {
code_cell_id: started.code_cell_id.clone(),
};
let nested_tool_call_ids = self
.rollout
.tool_calls
.values()
.filter(|tool_call| tool_call.requester == requester)
.map(|tool_call| tool_call.tool_call_id.clone())
.collect();
self.rollout.code_cells.insert(
started.code_cell_id.clone(),
CodeCell {
code_cell_id: started.code_cell_id.clone(),
model_visible_call_id: started.model_visible_call_id,
thread_id: thread_id.clone(),
codex_turn_id,
source_item_id,
output_item_ids: output_item_ids.clone(),
runtime_cell_id: Some(started.runtime_cell_id),
execution: ExecutionWindow {
started_at_unix_ms: wall_time_unix_ms,
started_seq: seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
runtime_status: CodeCellRuntimeStatus::Starting,
initial_response_at_unix_ms: None,
initial_response_seq: None,
initial_response_status: None,
raw_initial_response_payload_id: None,
raw_result_payload_id: None,
yielded_at_unix_ms: None,
yielded_seq: None,
source_js: started.source_js,
nested_tool_call_ids,
wait_tool_call_ids: Vec::new(),
},
);
self.thread_mut(&thread_id)?;
for item_id in output_item_ids {
self.add_code_cell_output_item(&started.code_cell_id, &item_id)?;
}
self.flush_pending_code_cell_lifecycle_events(&started.code_cell_id)?;
Ok(())
}
/// Returns the source item if the model-visible `exec` call has been reduced.
fn source_item_id_for_pending_code_cell(
&self,
pending: &PendingCodeCellStart,
) -> Result<Option<String>> {
Ok(self
.model_visible_code_cell_item_ids(
&pending.thread_id,
&pending.started.model_visible_call_id,
ConversationItemKind::CustomToolCall,
)
.into_iter()
.next())
}
/// Records the runtime's first response for a code cell, or waits for its source item.
///
/// Code-mode execution can start and fail before the inference response payload
/// that introduced the model-visible `exec` call has been reduced. In that
/// case the cell start is already pending; keep the lifecycle event beside it
/// instead of weakening the invariant that every reduced cell has a source
/// conversation item.
pub(super) fn record_or_queue_code_cell_initial_response(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
code_cell_id: CodeCellId,
runtime_cell_id: String,
status: CodeCellRuntimeStatus,
response_payload: Option<RawPayloadRef>,
) -> Result<()> {
if !self.rollout.code_cells.contains_key(&code_cell_id) {
if self.pending_code_cell_starts.contains_key(&code_cell_id) {
self.queue_code_cell_lifecycle_event(
code_cell_id,
PendingCodeCellLifecycleEvent {
seq,
wall_time_unix_ms,
kind: PendingCodeCellLifecycleEventKind::InitialResponse {
runtime_cell_id,
status,
response_payload,
},
},
);
return Ok(());
}
bail!("code cell initial response referenced unknown cell {code_cell_id}");
}
self.record_code_cell_initial_response(
seq,
wall_time_unix_ms,
code_cell_id,
runtime_cell_id,
status,
response_payload,
)
}
fn record_code_cell_initial_response(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
code_cell_id: CodeCellId,
runtime_cell_id: String,
status: CodeCellRuntimeStatus,
response_payload: Option<RawPayloadRef>,
) -> Result<()> {
let Some(cell) = self.rollout.code_cells.get_mut(&code_cell_id) else {
bail!("code cell initial response referenced unknown cell {code_cell_id}");
};
cell.runtime_cell_id = Some(runtime_cell_id);
if cell.initial_response_status.is_none() {
cell.initial_response_at_unix_ms = Some(wall_time_unix_ms);
cell.initial_response_seq = Some(seq);
cell.initial_response_status = Some(status.clone());
cell.raw_initial_response_payload_id = response_payload.map(|p| p.raw_payload_id);
}
if status == CodeCellRuntimeStatus::Yielded {
cell.yielded_at_unix_ms = Some(wall_time_unix_ms);
cell.yielded_seq = Some(seq);
}
cell.runtime_status = status;
Ok(())
}
/// Ends a code cell, or waits until its queued start can materialize.
///
/// This mirrors `record_or_queue_code_cell_initial_response`: the reducer is
/// strict about unknown cells, but a cell whose start is pending on the
/// model-visible source item is known and just needs its lifecycle replayed
/// after the source item appears.
pub(super) fn end_or_queue_code_cell(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
code_cell_id: CodeCellId,
status: CodeCellRuntimeStatus,
response_payload: Option<RawPayloadRef>,
) -> Result<()> {
if !self.rollout.code_cells.contains_key(&code_cell_id) {
if self.pending_code_cell_starts.contains_key(&code_cell_id) {
self.queue_code_cell_lifecycle_event(
code_cell_id,
PendingCodeCellLifecycleEvent {
seq,
wall_time_unix_ms,
kind: PendingCodeCellLifecycleEventKind::Ended {
status,
response_payload,
},
},
);
return Ok(());
}
bail!("code cell end referenced unknown cell {code_cell_id}");
}
self.end_code_cell(
seq,
wall_time_unix_ms,
code_cell_id,
status,
response_payload,
)
}
fn end_code_cell(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
code_cell_id: CodeCellId,
status: CodeCellRuntimeStatus,
response_payload: Option<RawPayloadRef>,
) -> Result<()> {
let Some(cell) = self.rollout.code_cells.get_mut(&code_cell_id) else {
bail!("code cell end referenced unknown cell {code_cell_id}");
};
if cell.initial_response_at_unix_ms.is_none() {
cell.initial_response_at_unix_ms = Some(wall_time_unix_ms);
cell.initial_response_seq = Some(seq);
}
cell.raw_result_payload_id = response_payload.map(|p| p.raw_payload_id);
cell.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
cell.execution.ended_seq = Some(seq);
cell.execution.status = execution_status_for_code_cell(&status);
cell.runtime_status = status;
Ok(())
}
/// Closes unfinished code cells when their owning turn is interrupted.
///
/// A yielded code cell can outlive a completed turn and be resumed by a
/// later `wait`, so normal turn completion must not imply cell completion.
/// Cancellation/failure is different: the model-visible JS frame has been
/// abandoned even if nested terminal work reports late runtime events. In
/// that case leaving the cell `running` makes a completed trace look live.
pub(super) fn terminate_running_code_cells_for_turn_end(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
codex_turn_id: &str,
turn_status: &ExecutionStatus,
) -> Result<()> {
let runtime_status = match turn_status {
ExecutionStatus::Running | ExecutionStatus::Completed => return Ok(()),
ExecutionStatus::Failed => CodeCellRuntimeStatus::Failed,
ExecutionStatus::Cancelled | ExecutionStatus::Aborted => {
CodeCellRuntimeStatus::Terminated
}
};
let code_cell_ids: Vec<_> = self
.rollout
.code_cells
.values()
.filter(|cell| {
cell.codex_turn_id == codex_turn_id
&& cell.execution.status == ExecutionStatus::Running
})
.map(|cell| cell.code_cell_id.clone())
.collect();
for code_cell_id in code_cell_ids {
self.end_code_cell(
seq,
wall_time_unix_ms,
code_cell_id,
runtime_status.clone(),
/*response_payload*/ None,
)?;
}
Ok(())
}
fn queue_code_cell_lifecycle_event(
&mut self,
code_cell_id: CodeCellId,
event: PendingCodeCellLifecycleEvent,
) {
let events = self
.pending_code_cell_lifecycle_events
.entry(code_cell_id)
.or_default();
events.push(event);
events.sort_by_key(|event| event.seq);
}
fn flush_pending_code_cell_lifecycle_events(&mut self, code_cell_id: &str) -> Result<()> {
let Some(events) = self.pending_code_cell_lifecycle_events.remove(code_cell_id) else {
return Ok(());
};
for event in events {
match event.kind {
PendingCodeCellLifecycleEventKind::InitialResponse {
runtime_cell_id,
status,
response_payload,
} => self.record_code_cell_initial_response(
event.seq,
event.wall_time_unix_ms,
code_cell_id.to_string(),
runtime_cell_id,
status,
response_payload,
)?,
PendingCodeCellLifecycleEventKind::Ended {
status,
response_payload,
} => self.end_code_cell(
event.seq,
event.wall_time_unix_ms,
code_cell_id.to_string(),
status,
response_payload,
)?,
}
}
Ok(())
}
/// Links a nested tool call back to its parent code cell.
///
/// If the parent cell is still queued, the link is recovered later from already
/// reduced tool calls when the cell materializes.
pub(super) fn link_tool_call_to_code_cell(
&mut self,
tool_call_id: &ToolCallId,
requester: &ToolCallRequester,
) -> Result<()> {
let ToolCallRequester::CodeCell { code_cell_id } = requester else {
return Ok(());
};
let Some(cell) = self.rollout.code_cells.get_mut(code_cell_id) else {
// The cell start may still be queued behind the inference payload
// that contains its model-visible source item. `start_code_cell`
// backfills these already-reduced nested calls once the source
// ownership can be proven.
return Ok(());
};
push_unique(&mut cell.nested_tool_call_ids, tool_call_id);
Ok(())
}
/// Records that a model-visible wait call is waiting on a runtime code cell.
///
/// Wait calls are not nested JavaScript tools, so the relationship is inferred
/// from the runtime cell id inside the function arguments.
pub(super) fn link_wait_tool_call_from_request_payload(
&mut self,
thread_id: &str,
tool_call_id: &ToolCallId,
request_payload: Option<&RawPayloadRef>,
) -> Result<()> {
let Some(request_payload) = request_payload else {
return Ok(());
};
let payload = self.read_payload_json(request_payload)?;
if payload.get("tool_name").and_then(Value::as_str) != Some("wait") {
return Ok(());
}
// `wait` is a normal model-visible function call, not a nested JS tool
// request. The only stable edge back to the code cell is the runtime
// `cell_id` inside the function arguments.
let Some(arguments) = payload
.get("payload")
.and_then(|payload| payload.get("arguments"))
.and_then(Value::as_str)
else {
bail!(
"wait tool request payload {} did not contain function arguments",
request_payload.raw_payload_id
);
};
let arguments: Value = serde_json::from_str(arguments).with_context(|| {
format!(
"wait tool request payload {} had invalid JSON arguments",
request_payload.raw_payload_id
)
})?;
let Some(runtime_cell_id) = arguments.get("cell_id").and_then(Value::as_str) else {
bail!(
"wait tool request payload {} did not contain cell_id",
request_payload.raw_payload_id
);
};
let Some(code_cell_id) =
self.code_cell_id_for_runtime_cell_id_if_known(thread_id, runtime_cell_id)
else {
return Ok(());
};
let Some(cell) = self.rollout.code_cells.get_mut(&code_cell_id) else {
return Ok(());
};
push_unique(&mut cell.wait_tool_call_ids, tool_call_id);
Ok(())
}
/// Attaches a later-observed model-visible output item to its code cell.
///
/// This is used when an inference request carries a custom-tool output after
/// the runtime cell already exists.
pub(super) fn attach_model_visible_code_cell_item(
&mut self,
item_id: &str,
call_id: Option<&str>,
kind: &ConversationItemKind,
) -> Result<()> {
let Some(call_id) = call_id else {
return Ok(());
};
if *kind != ConversationItemKind::CustomToolCallOutput {
return Ok(());
}
// The output item can be observed after the CodeCell was created, e.g.
// when a later inference request carries the custom-tool result back to
// the model. Add the reverse ProducerRef at that later observation
// point instead of copying runtime bytes into the conversation model.
let code_cell_id = Self::reduced_code_cell_id_for_model_visible_call(call_id);
if !self.rollout.code_cells.contains_key(&code_cell_id) {
return Ok(());
}
self.add_code_cell_output_item(&code_cell_id, item_id)
}
/// Resolves the owning thread for a code-cell runtime event.
///
/// Runtime events should carry a thread id, but older/raw paths may only have
/// the turn id. The fallback keeps replay strict while avoiding duplicate logic
/// in every code-cell event arm.
pub(super) fn code_cell_event_thread_id(
&self,
thread_id: Option<String>,
codex_turn_id: Option<&str>,
runtime_cell_id: &str,
event_name: &str,
) -> Result<String> {
if let Some(thread_id) = thread_id {
return Ok(thread_id);
}
let Some(codex_turn_id) = codex_turn_id else {
bail!("{event_name} {runtime_cell_id} did not include a thread id");
};
self.rollout
.codex_turns
.get(codex_turn_id)
.map(|turn| turn.thread_id.clone())
.with_context(|| {
format!(
"{event_name} {runtime_cell_id} referenced unknown Codex turn {codex_turn_id}"
)
})
}
/// Derives the stable reduced code-cell id from the model-visible exec call id.
pub(super) fn reduced_code_cell_id_for_model_visible_call(
model_visible_call_id: &str,
) -> CodeCellId {
// The model-visible `exec` call is the durable source identity. The
// runtime `cell_id` is only a thread-local handle used for later waits
// and nested tool calls.
format!("code_cell:{model_visible_call_id}")
}
/// Records the thread-local runtime cell id to reduced code-cell id mapping.
///
/// Runtime ids can repeat across threads, so callers must provide the owning
/// thread id when creating or resolving this bridge.
pub(super) fn record_runtime_code_cell_id(
&mut self,
thread_id: &str,
runtime_cell_id: &str,
code_cell_id: &str,
) -> Result<()> {
let key = runtime_code_cell_key(thread_id, runtime_cell_id);
if let Some(existing) = self.code_cell_ids_by_runtime.get(&key) {
if existing == code_cell_id {
return Ok(());
}
bail!(
"runtime code cell {runtime_cell_id} in thread {thread_id} mapped to both \
{existing} and {code_cell_id}"
);
}
self.code_cell_ids_by_runtime
.insert(key, code_cell_id.to_string());
Ok(())
}
/// Resolves a runtime cell id to the reduced code-cell id for the given thread.
pub(super) fn code_cell_id_for_runtime_cell_id(
&self,
thread_id: &str,
runtime_cell_id: &str,
event_name: &str,
) -> Result<CodeCellId> {
self.code_cell_id_for_runtime_cell_id_if_known(thread_id, runtime_cell_id)
.with_context(|| {
format!(
"{event_name} referenced unknown runtime cell {runtime_cell_id} \
in thread {thread_id}"
)
})
}
fn code_cell_id_for_runtime_cell_id_if_known(
&self,
thread_id: &str,
runtime_cell_id: &str,
) -> Option<CodeCellId> {
self.code_cell_ids_by_runtime
.get(&runtime_code_cell_key(thread_id, runtime_cell_id))
.cloned()
}
/// Converts a raw tool requester into the reduced graph requester.
///
/// Code-mode tool requests arrive with a runtime cell id, so this method is
/// the boundary that turns that runtime handle into a stable code-cell anchor.
pub(super) fn reduce_tool_call_requester(
&self,
thread_id: &str,
requester: RawToolCallRequester,
) -> Result<ToolCallRequester> {
match requester {
RawToolCallRequester::Model => Ok(ToolCallRequester::Model),
RawToolCallRequester::CodeCell { runtime_cell_id } => Ok(ToolCallRequester::CodeCell {
code_cell_id: self.code_cell_id_for_runtime_cell_id(
thread_id,
&runtime_cell_id,
"code-mode nested tool",
)?,
}),
}
}
fn validate_code_cell_turn(&self, thread_id: &str, codex_turn_id: &str) -> Result<()> {
if !self.rollout.threads.contains_key(thread_id) {
bail!("code cell start referenced unknown thread {thread_id}");
}
let Some(turn) = self.rollout.codex_turns.get(codex_turn_id) else {
bail!("code cell start referenced unknown Codex turn {codex_turn_id}");
};
if turn.thread_id != thread_id {
bail!(
"code cell start used thread {thread_id}, but Codex turn {codex_turn_id} belongs \
to {}",
turn.thread_id
);
}
Ok(())
}
fn model_visible_code_cell_item_ids(
&self,
thread_id: &str,
call_id: &str,
kind: ConversationItemKind,
) -> Vec<String> {
self.rollout
.threads
.get(thread_id)
.into_iter()
.flat_map(|thread| &thread.conversation_item_ids)
.map(|item_id| &self.rollout.conversation_items[item_id])
.filter(|item| item.call_id.as_deref() == Some(call_id) && item.kind == kind)
.map(|item| item.item_id.clone())
.collect()
}
fn source_item_id_for_code_cell_start(
&self,
thread_id: &str,
code_cell_id: &str,
model_visible_call_id: &str,
) -> Result<String> {
self.model_visible_code_cell_item_ids(
thread_id,
model_visible_call_id,
ConversationItemKind::CustomToolCall,
)
.into_iter()
.next()
.with_context(|| {
format!(
"code cell {code_cell_id} referenced model-visible call {model_visible_call_id}, \
but no custom tool call item was observed"
)
})
}
fn add_code_cell_output_item(&mut self, code_cell_id: &str, item_id: &str) -> Result<()> {
let Some(cell) = self.rollout.code_cells.get_mut(code_cell_id) else {
bail!("code cell {code_cell_id} disappeared during output linking");
};
push_unique(&mut cell.output_item_ids, item_id);
let Some(item) = self.rollout.conversation_items.get_mut(item_id) else {
bail!("conversation item {item_id} disappeared during code-cell output linking");
};
let producer = ProducerRef::CodeCell {
code_cell_id: code_cell_id.to_string(),
};
if !item.produced_by.contains(&producer) {
item.produced_by.push(producer);
}
Ok(())
}
}
fn execution_status_for_code_cell(status: &CodeCellRuntimeStatus) -> ExecutionStatus {
match status {
CodeCellRuntimeStatus::Starting
| CodeCellRuntimeStatus::Running
| CodeCellRuntimeStatus::Yielded => ExecutionStatus::Running,
CodeCellRuntimeStatus::Completed => ExecutionStatus::Completed,
CodeCellRuntimeStatus::Failed => ExecutionStatus::Failed,
CodeCellRuntimeStatus::Terminated => ExecutionStatus::Cancelled,
}
}
fn push_unique(items: &mut Vec<String>, item_id: &str) {
if !items.iter().any(|existing| existing == item_id) {
items.push(item_id.to_string());
}
}
fn runtime_code_cell_key(thread_id: &str, runtime_cell_id: &str) -> (String, String) {
(thread_id.to_string(), runtime_cell_id.to_string())
}
#[cfg(test)]
#[path = "code_cell_tests.rs"]
mod tests;

View File

@@ -0,0 +1,537 @@
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::model::CodeCellRuntimeStatus;
use crate::model::ConversationItemKind;
use crate::model::ExecutionStatus;
use crate::model::ProducerRef;
use crate::model::RolloutStatus;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawToolCallRequester;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::append_inference_request;
use crate::reducer::test_support::create_started_writer;
use crate::reducer::test_support::generic_summary;
use crate::reducer::test_support::message;
use crate::reducer::test_support::start_turn;
use crate::reducer::test_support::start_turn_for_thread;
use crate::reducer::test_support::trace_context;
use crate::reducer::test_support::trace_context_for_thread;
use crate::replay_bundle;
#[test]
fn code_cell_lifecycle_links_nested_tools_waits_and_outputs() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"input": [message("user", "count files")]
}),
)?;
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: "inference-1".to_string(),
thread_id: "thread-root".to_string(),
codex_turn_id: "turn-1".to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload: request,
})?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": "resp-1",
"output_items": [{
"type": "custom_tool_call",
"name": "exec",
"call_id": "call-code",
"input": "text('hi')"
}]
}),
)?;
// Runtime tool dispatch starts before the stream-completion hook has
// reduced the model response that requested `exec`.
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id: "1".to_string(),
model_visible_call_id: "call-code".to_string(),
source_js: "text('hi')".to_string(),
},
)?;
writer.append(RawTraceEventPayload::InferenceCompleted {
inference_call_id: "inference-1".to_string(),
response_id: Some("resp-1".to_string()),
upstream_request_id: None,
response_payload: response,
})?;
let initial_response = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({"response": "initial caller result"}),
)?;
let final_response = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({"response": "later runtime result"}),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellInitialResponse {
runtime_cell_id: "1".to_string(),
status: CodeCellRuntimeStatus::Yielded,
response_payload: Some(initial_response.clone()),
},
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "nested-tool-1".to_string(),
model_visible_call_id: None,
code_mode_runtime_tool_id: Some("tool-1".to_string()),
requester: RawToolCallRequester::CodeCell {
runtime_cell_id: "1".to_string(),
},
kind: ToolCallKind::ExecCommand,
summary: ToolCallSummary::Generic {
label: "exec_command".to_string(),
input_preview: Some("pwd".to_string()),
output_preview: None,
},
invocation_payload: None,
},
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "nested-tool-1".to_string(),
status: ExecutionStatus::Completed,
result_payload: None,
},
)?;
start_turn(&writer, "turn-2")?;
let followup = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"previous_response_id": "resp-1",
"input": [{
"type": "custom_tool_call_output",
"call_id": "call-code",
"output": "Script running with cell ID 1"
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: "inference-2".to_string(),
thread_id: "thread-root".to_string(),
codex_turn_id: "turn-2".to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload: followup,
})?;
let wait_request = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "wait",
"tool_namespace": null,
"payload": {
"type": "function",
"arguments": "{\"cell_id\":\"1\"}"
}
}),
)?;
writer.append_with_context(
trace_context("turn-2"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "wait-tool-1".to_string(),
model_visible_call_id: Some("wait-call".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::Other {
name: "wait".to_string(),
},
summary: ToolCallSummary::Generic {
label: "wait".to_string(),
input_preview: Some("{\"cell_id\":\"1\"}".to_string()),
output_preview: None,
},
invocation_payload: Some(wait_request),
},
)?;
writer.append_with_context(
trace_context("turn-2"),
RawTraceEventPayload::CodeCellEnded {
runtime_cell_id: "1".to_string(),
status: CodeCellRuntimeStatus::Completed,
response_payload: Some(final_response.clone()),
},
)?;
let rollout = replay_bundle(temp.path())?;
let code_cell_id = test_reduced_code_cell_id("call-code");
let cell = &rollout.code_cells[&code_cell_id];
let output_item_id = rollout.inference_calls["inference-2"]
.request_item_ids
.last()
.expect("exec output item");
assert_eq!(
(
&cell.initial_response_status,
&cell.raw_initial_response_payload_id,
&cell.raw_result_payload_id,
),
(
&Some(CodeCellRuntimeStatus::Yielded),
&Some(initial_response.raw_payload_id),
&Some(final_response.raw_payload_id),
)
);
assert_eq!(cell.thread_id, "thread-root");
assert_eq!(cell.runtime_status, CodeCellRuntimeStatus::Completed);
assert_eq!(cell.execution.status, ExecutionStatus::Completed);
assert_eq!(cell.runtime_cell_id, Some("1".to_string()));
assert_eq!(cell.nested_tool_call_ids, vec!["nested-tool-1"]);
assert_eq!(cell.wait_tool_call_ids, vec!["wait-tool-1"]);
assert_eq!(cell.output_item_ids, vec![output_item_id.clone()]);
assert_eq!(
rollout.conversation_items[output_item_id].produced_by,
vec![ProducerRef::CodeCell {
code_cell_id: code_cell_id.clone(),
}]
);
assert_eq!(
rollout.conversation_items[&cell.source_item_id].kind,
ConversationItemKind::CustomToolCall,
);
Ok(())
}
#[test]
fn fast_code_cell_lifecycle_waits_for_source_item() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
// Put outputs on either side of ordinal 10, where map-key order differs from history order.
let mut input: Vec<_> = (0..7)
.map(|index| message("user", &format!("context {index}")))
.collect();
for (dispatch_id, call_id) in [("outer", "call-code"), ("no-cell", "other-exec")] {
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: dispatch_id.into(),
model_visible_call_id: Some(call_id.into()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::Other {
name: "exec".into(),
},
summary: generic_summary("exec"),
invocation_payload: None,
},
)?;
}
append_inference_request(
&writer,
"thread-root",
"turn-1",
"inference-1",
input.clone(),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id: "1".to_string(),
model_visible_call_id: "call-code".to_string(),
source_js: "not valid js".to_string(),
},
)?;
let initial_response = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({"response": "initial caller result"}),
)?;
let final_response = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({"response": "later runtime result"}),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellInitialResponse {
runtime_cell_id: "1".to_string(),
status: CodeCellRuntimeStatus::Failed,
response_payload: Some(initial_response.clone()),
},
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellEnded {
runtime_cell_id: "1".to_string(),
status: CodeCellRuntimeStatus::Failed,
response_payload: Some(final_response.clone()),
},
)?;
let call = json!({
"type": "custom_tool_call",
"name": "exec",
"call_id": "call-code",
"input": "not valid js"
});
// Compaction exposes the source and original output before the response is recorded.
// Its replacement output must be appended before the queued cell is materialized.
input.push(call.clone());
input.push(json!({
"type": "custom_tool_call_output", "call_id": "call-code", "output": "initial caller result"
}));
let checkpoint = writer.write_json_payload(
RawPayloadKind::CompactionCheckpoint,
&json!({
"input_history": input,
"replacement_history": [call, {
"type": "custom_tool_call_output", "call_id": "call-code", "output": "later runtime result"
}]
}),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CompactionInstalled {
compaction_id: "compaction-1".to_string(),
checkpoint_payload: checkpoint,
},
)?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": "resp-1",
"output_items": [call]
}),
)?;
writer.append(RawTraceEventPayload::InferenceCompleted {
inference_call_id: "inference-1".to_string(),
response_id: Some("resp-1".to_string()),
upstream_request_id: None,
response_payload: response,
})?;
let rollout = replay_bundle(temp.path())?;
let code_cell_id = test_reduced_code_cell_id("call-code");
let cell = &rollout.code_cells[&code_cell_id];
assert_eq!(
rollout.tool_calls["outer"].started_code_cell_id.as_ref(),
Some(&cell.code_cell_id)
);
assert_eq!(rollout.tool_calls["no-cell"].started_code_cell_id, None);
assert_eq!(
cell.output_item_ids,
vec!["conversation_item:9", "conversation_item:12"]
);
assert_eq!(
(
&cell.initial_response_status,
&cell.raw_initial_response_payload_id,
&cell.raw_result_payload_id,
),
(
&Some(CodeCellRuntimeStatus::Failed),
&Some(initial_response.raw_payload_id),
&Some(final_response.raw_payload_id),
)
);
assert_eq!(cell.thread_id, "thread-root");
assert_eq!(cell.runtime_status, CodeCellRuntimeStatus::Failed);
assert_eq!(cell.execution.status, ExecutionStatus::Failed);
assert_eq!(cell.runtime_cell_id, Some("1".to_string()));
assert_eq!(
rollout.conversation_items[&cell.source_item_id].kind,
ConversationItemKind::CustomToolCall,
);
Ok(())
}
#[test]
fn cancelled_turn_terminates_unfinished_code_cell() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"input": [message("user", "count files")]
}),
)?;
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: "inference-1".to_string(),
thread_id: "thread-root".to_string(),
codex_turn_id: "turn-1".to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload: request,
})?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": "resp-1",
"output_items": [{
"type": "custom_tool_call",
"name": "exec",
"call_id": "call-code",
"input": "await tools.exec_command({cmd: 'slow'});"
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceCompleted {
inference_call_id: "inference-1".to_string(),
response_id: Some("resp-1".to_string()),
upstream_request_id: None,
response_payload: response,
})?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id: "1".to_string(),
model_visible_call_id: "call-code".to_string(),
source_js: "await tools.exec_command({cmd: 'slow'});".to_string(),
},
)?;
let turn_end = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodexTurnEnded {
codex_turn_id: "turn-1".to_string(),
status: ExecutionStatus::Cancelled,
},
)?;
let rollout = replay_bundle(temp.path())?;
let code_cell_id = test_reduced_code_cell_id("call-code");
let cell = &rollout.code_cells[&code_cell_id];
assert_eq!(cell.runtime_status, CodeCellRuntimeStatus::Terminated);
assert_eq!(cell.execution.status, ExecutionStatus::Cancelled);
assert_eq!(cell.execution.ended_seq, Some(turn_end.seq));
Ok(())
}
#[test]
fn runtime_code_cell_ids_can_repeat_across_threads_and_after_resume() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
writer.append(RawTraceEventPayload::ThreadStarted {
thread_id: "thread-child".to_string(),
agent_path: "/root/child".to_string(),
metadata_payload: None,
})?;
for (thread_id, turn_id, inference_call_id, call_id) in [
("thread-root", "turn-root", "inference-root", "call-root"),
(
"thread-child",
"turn-child",
"inference-child",
"call-child",
),
(
"thread-child",
"turn-resumed",
"inference-resumed",
"call-resumed",
),
] {
if turn_id == "turn-resumed" {
writer.append(RawTraceEventPayload::ThreadEnded {
thread_id: thread_id.to_string(),
status: RolloutStatus::Completed,
})?;
writer.append(RawTraceEventPayload::ThreadResumed {
thread_id: thread_id.to_string(),
})?;
}
start_turn_for_thread(&writer, thread_id, turn_id)?;
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"input": [message("user", "run code")]
}),
)?;
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: inference_call_id.to_string(),
thread_id: thread_id.to_string(),
codex_turn_id: turn_id.to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload: request,
})?;
writer.append_with_context(
trace_context_for_thread(thread_id, turn_id),
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id: "1".to_string(),
model_visible_call_id: call_id.to_string(),
source_js: "text('hi')".to_string(),
},
)?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": format!("resp-{turn_id}"),
"output_items": [{
"type": "custom_tool_call",
"name": "exec",
"call_id": call_id,
"input": "text('hi')"
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceCompleted {
inference_call_id: inference_call_id.to_string(),
response_id: Some(format!("resp-{turn_id}")),
upstream_request_id: None,
response_payload: response,
})?;
writer.append_with_context(
trace_context_for_thread(thread_id, turn_id),
RawTraceEventPayload::CodeCellEnded {
runtime_cell_id: "1".to_string(),
status: CodeCellRuntimeStatus::Completed,
response_payload: None,
},
)?;
}
let rollout = replay_bundle(temp.path())?;
let root_cell_id = test_reduced_code_cell_id("call-root");
let child_cell_id = test_reduced_code_cell_id("call-child");
let resumed_cell_id = test_reduced_code_cell_id("call-resumed");
assert_eq!(rollout.code_cells[&root_cell_id].thread_id, "thread-root");
assert_eq!(rollout.code_cells[&child_cell_id].thread_id, "thread-child");
assert_eq!(
rollout.code_cells[&resumed_cell_id].thread_id,
"thread-child"
);
assert_eq!(
rollout.code_cells[&root_cell_id].runtime_cell_id,
Some("1".to_string())
);
assert_eq!(
rollout.code_cells[&child_cell_id].runtime_cell_id,
Some("1".to_string())
);
assert_eq!(
rollout.code_cells[&resumed_cell_id].runtime_cell_id,
Some("1".to_string())
);
Ok(())
}
fn test_reduced_code_cell_id(model_visible_call_id: &str) -> String {
format!("code_cell:{model_visible_call_id}")
}

View File

@@ -0,0 +1,183 @@
//! Reducer support for the remote compaction lifecycle.
//!
//! This module owns request/checkpoint bookkeeping. Conversation item reconciliation stays in
//! `conversation` because it depends on the same normalization and reuse invariants as inference
//! requests.
use anyhow::Result;
use anyhow::bail;
use super::TraceReducer;
use crate::model::Compaction;
use crate::model::CompactionRequest;
use crate::model::CompactionRequestId;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawEventSeq;
impl TraceReducer {
/// Starts one upstream request attempt for a compaction operation.
pub(super) fn start_compaction_request(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
started: StartedCompactionRequest,
) -> Result<()> {
if self
.rollout
.compaction_requests
.contains_key(&started.compaction_request_id)
{
bail!(
"duplicate compaction request start for {}",
started.compaction_request_id
);
}
self.thread_mut(&started.thread_id)?;
let Some(turn) = self.rollout.codex_turns.get(&started.codex_turn_id) else {
bail!(
"compaction request {} referenced unknown codex turn {}",
started.compaction_request_id,
started.codex_turn_id
);
};
if turn.thread_id != started.thread_id {
bail!(
"compaction request {} used thread {}, but codex turn {} belongs to {}",
started.compaction_request_id,
started.thread_id,
started.codex_turn_id,
turn.thread_id
);
}
self.rollout.compaction_requests.insert(
started.compaction_request_id.clone(),
CompactionRequest {
compaction_request_id: started.compaction_request_id,
compaction_id: started.compaction_id,
thread_id: started.thread_id,
codex_turn_id: started.codex_turn_id,
execution: ExecutionWindow {
started_at_unix_ms: wall_time_unix_ms,
started_seq: seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
model: started.model,
provider_name: started.provider_name,
raw_request_payload_id: started.request_payload.raw_payload_id,
raw_response_payload_id: None,
},
);
Ok(())
}
/// Completes an upstream compaction request attempt without modifying conversation history.
///
/// The request/response payloads are evidence for the remote call. The live
/// conversation changes only when a separate install event provides the checkpoint.
pub(super) fn complete_compaction_request(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
compaction_id: String,
compaction_request_id: CompactionRequestId,
status: ExecutionStatus,
response_payload: Option<RawPayloadRef>,
) -> Result<()> {
let Some(request) = self
.rollout
.compaction_requests
.get_mut(&compaction_request_id)
else {
bail!(
"compaction request completion referenced unknown request {compaction_request_id}"
);
};
if request.compaction_id != compaction_id {
bail!(
"compaction request {compaction_request_id} completion used compaction {compaction_id}, but start used {}",
request.compaction_id
);
}
request.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
request.execution.ended_seq = Some(seq);
request.execution.status = status;
request.raw_response_payload_id = response_payload.map(|payload| payload.raw_payload_id);
Ok(())
}
/// Installs a compaction checkpoint into the reduced conversation graph.
///
/// This is the semantic boundary where replacement history becomes the live
/// thread history; request attempts alone do not imply that change.
pub(super) fn reduce_compaction_installed_event(
&mut self,
wall_time_unix_ms: i64,
thread_id: String,
codex_turn_id: String,
compaction_id: String,
checkpoint_payload: RawPayloadRef,
) -> Result<()> {
if self.rollout.compactions.contains_key(&compaction_id) {
bail!("duplicate compaction install for {compaction_id}");
}
self.thread_mut(&thread_id)?;
let Some(turn) = self.rollout.codex_turns.get(&codex_turn_id) else {
bail!(
"compaction install {compaction_id} referenced unknown codex turn {codex_turn_id}"
);
};
if turn.thread_id != thread_id {
bail!(
"compaction install {compaction_id} used thread {thread_id}, but codex turn {codex_turn_id} belongs to {}",
turn.thread_id
);
}
let checkpoint = self.reduce_compaction_checkpoint(
wall_time_unix_ms,
&thread_id,
codex_turn_id.as_str(),
&compaction_id,
&checkpoint_payload,
)?;
let request_ids = self
.rollout
.compaction_requests
.values()
.filter(|request| request.compaction_id == compaction_id)
.map(|request| request.compaction_request_id.clone())
.collect();
self.pending_compaction_replacement_item_ids
.insert(thread_id.clone(), checkpoint.replacement_item_ids.clone());
self.rollout.compactions.insert(
compaction_id.clone(),
Compaction {
compaction_id,
thread_id,
codex_turn_id,
installed_at_unix_ms: wall_time_unix_ms,
marker_item_id: checkpoint.marker_item_id,
request_ids,
input_item_ids: checkpoint.input_item_ids,
replacement_item_ids: checkpoint.replacement_item_ids,
},
);
Ok(())
}
}
/// Raw compaction-request start fields after dispatch has stripped the event envelope.
pub(super) struct StartedCompactionRequest {
pub(super) compaction_id: String,
pub(super) compaction_request_id: String,
pub(super) thread_id: String,
pub(super) codex_turn_id: String,
pub(super) model: String,
pub(super) provider_name: String,
pub(super) request_payload: RawPayloadRef,
}

View File

@@ -0,0 +1,765 @@
//! Conversation reduction from model-facing payload snapshots.
//!
//! Replay retains all observed items, then selects accepted history using
//! request inputs, compaction checkpoints, and harness acceptance events.
//! Tool messages use the content sent to the model in subsequent requests.
use std::collections::HashSet;
use anyhow::Context;
use anyhow::Ok;
use anyhow::Result;
use anyhow::bail;
use serde_json::Value;
use self::normalize::NormalizedConversationItem;
use super::TraceReducer;
use crate::model::CompactionId;
use crate::model::ConversationBody;
use crate::model::ConversationItem;
use crate::model::ConversationItemKind;
use crate::model::ConversationPart;
use crate::model::ConversationRole;
use crate::model::InferenceCallId;
use crate::model::ProducerRef;
use crate::payload::RawPayloadRef;
mod normalize;
impl TraceReducer {
/// Reduces an inference request input snapshot into model-visible conversation items.
///
/// Full snapshots reuse matching items even if the prompt builder reorders them.
/// Incremental requests append to the referenced response's context.
pub(super) fn reduce_inference_request(
&mut self,
wall_time_unix_ms: i64,
inference_call_id: &InferenceCallId,
thread_id: &str,
codex_turn_id: &str,
request_payload: &RawPayloadRef,
) -> Result<Vec<String>> {
let payload = self.read_payload_json(request_payload)?;
let Some(input) = payload.get("input") else {
bail!(
"inference request payload {} did not contain input",
request_payload.raw_payload_id
);
};
let Some(request_items) = input.as_array() else {
bail!(
"inference request payload {} had non-array input",
request_payload.raw_payload_id
);
};
let items = normalize::normalize_model_items(request_items, request_payload)?;
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
// history, not the pre-compaction prompt. Any repeated developer/context prefix that Codex
// reinjects must therefore become a fresh post-compaction conversation item.
let post_compaction_snapshot = if previous_response_id.is_none() {
self.pending_compaction_replacement_item_ids
.get(thread_id)
.cloned()
} else {
None
};
let request_item_ids = if let Some(previous_response_id) = previous_response_id {
// Streaming follow-up requests can send only the new input plus a
// `previous_response_id`. The trace model still exposes the full
// model-visible input, so rebuild the omitted prefix from the
// previous request and response before reducing this delta.
let previous_items = self
.rollout
.inference_calls
.values()
.find(|inference| {
inference.thread_id == thread_id
&& inference.response_id.as_deref() == Some(previous_response_id)
})
.map(|inference| {
let mut ids = inference.request_item_ids.clone();
ids.extend(inference.response_item_ids.clone());
ids
});
let Some(mut item_ids) = previous_items else {
bail!(
"incremental inference request {inference_call_id} referenced unknown previous_response_id {previous_response_id}"
);
};
let delta_item_ids = self.reconcile_conversation_items(
items,
ReconcileItems {
thread_id,
codex_turn_id,
wall_time_unix_ms,
produced_by: Vec::new(),
start_index: item_ids.len(),
mode: ReconcileMode::AppendOnly,
snapshot_override: None,
},
)?;
item_ids.extend(delta_item_ids);
item_ids
} else {
self.reconcile_conversation_items(
items,
ReconcileItems {
thread_id,
codex_turn_id,
wall_time_unix_ms,
produced_by: Vec::new(),
start_index: 0,
mode: ReconcileMode::FullSnapshot,
snapshot_override: post_compaction_snapshot.as_deref(),
},
)?
};
self.append_thread_conversation_items(thread_id, &request_item_ids)?;
if post_compaction_snapshot.is_some() {
self.pending_compaction_replacement_item_ids
.remove(thread_id);
}
self.thread_conversation_snapshots
.insert(thread_id.to_string(), request_item_ids.clone());
Ok(request_item_ids)
}
/// Reduces an inference response payload into conversation items produced by the call.
pub(super) fn reduce_inference_response(
&mut self,
wall_time_unix_ms: i64,
inference_call_id: &InferenceCallId,
response_payload: &RawPayloadRef,
) -> Result<Vec<String>> {
let payload = self.read_payload_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",
response_payload.raw_payload_id
);
};
let Some((thread_id, codex_turn_id)) = self
.rollout
.inference_calls
.get(inference_call_id)
.map(|inference| (inference.thread_id.clone(), inference.codex_turn_id.clone()))
else {
bail!("inference response referenced unknown call {inference_call_id}");
};
let items = normalize::normalize_model_items(output_items, response_payload)?;
// 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]
.conversation_item_ids
.iter()
.filter(|id| {
let source_id = &self.rollout.conversation_items[*id].responses_item_id;
source_id.is_some()
&& items
.iter()
.any(|item| &item.responses_item_id == source_id)
})
.cloned()
.collect::<Vec<_>>();
let response_item_ids = self.reconcile_detached_conversation_items(
items,
DetachedReconcileItems {
thread_id: &thread_id,
codex_turn_id: &codex_turn_id,
wall_time_unix_ms,
produced_by: vec![ProducerRef::Inference {
inference_call_id: inference_call_id.clone(),
}],
candidates,
},
)?;
self.append_thread_conversation_items(&thread_id, &response_item_ids)?;
let inference = &self.rollout.inference_calls[inference_call_id];
let latest = self
.rollout
.inference_calls
.values()
.filter(|call| call.thread_id == thread_id)
.max_by_key(|call| call.execution.started_seq);
// A late response must not replace a newer request or compaction snapshot.
if latest.is_some_and(|call| call.inference_call_id == *inference_call_id)
&& !self
.pending_compaction_replacement_item_ids
.contains_key(&thread_id)
{
let mut snapshot = inference.request_item_ids.clone();
snapshot.extend(response_item_ids.clone());
self.thread_conversation_snapshots
.insert(thread_id, snapshot);
}
if let Some(usage) = payload
.get("token_usage")
.and_then(normalize::token_usage_from_value)
&& let Some(inference) = self.rollout.inference_calls.get_mut(inference_call_id)
{
inference.usage = Some(usage);
}
Ok(response_item_ids)
}
fn reconcile_conversation_items(
&mut self,
items: Vec<NormalizedConversationItem>,
context: ReconcileItems<'_>,
) -> Result<Vec<String>> {
let previous_snapshot = context.snapshot_override.map_or_else(
|| {
self.thread_conversation_snapshots
.get(context.thread_id)
.cloned()
.unwrap_or_default()
},
<[_]>::to_vec,
);
let mut item_ids = Vec::with_capacity(items.len());
let mut used_item_ids = HashSet::with_capacity(items.len());
for (offset, item) in items.into_iter().enumerate() {
let index = context.start_index + offset;
let tool_link_item = item.clone();
self.ensure_call_id_consistency(context.thread_id, &item)?;
let item_id = if let Some(previous_item_id) = previous_snapshot.get(index) {
if !used_item_ids.contains(previous_item_id)
&& self.item_matches(previous_item_id, &item)
{
previous_item_id.clone()
} else if matches!(context.mode, ReconcileMode::FullSnapshot) {
self.find_matching_snapshot_item(&previous_snapshot, &used_item_ids, &item)
.unwrap_or_else(|| {
self.create_conversation_item(
context.thread_id,
Some(context.codex_turn_id.to_string()),
context.wall_time_unix_ms,
item,
context.produced_by.clone(),
)
})
} else {
let codex_turn_id = context.codex_turn_id;
let thread_id = context.thread_id;
bail!(
"model conversation mismatch while reducing turn {codex_turn_id} for \
thread {thread_id} at item index {index}: existing item \
{previous_item_id} does not match the current model payload item"
);
}
} else if matches!(context.mode, ReconcileMode::FullSnapshot) {
self.find_matching_snapshot_item(&previous_snapshot, &used_item_ids, &item)
.unwrap_or_else(|| {
self.create_conversation_item(
context.thread_id,
Some(context.codex_turn_id.to_string()),
context.wall_time_unix_ms,
item,
context.produced_by.clone(),
)
})
} else {
self.create_conversation_item(
context.thread_id,
Some(context.codex_turn_id.to_string()),
context.wall_time_unix_ms,
item,
context.produced_by.clone(),
)
};
self.update_conversation_item_from_sighting(
&item_id,
&tool_link_item,
&context.produced_by,
)?;
self.attach_model_visible_tool_item(
&item_id,
tool_link_item.call_id.as_deref(),
&tool_link_item.kind,
)?;
self.attach_model_visible_code_cell_item(
&item_id,
tool_link_item.call_id.as_deref(),
&tool_link_item.kind,
)?;
self.resolve_pending_agent_edges_for_item(&item_id)?;
used_item_ids.insert(item_id.clone());
item_ids.push(item_id);
}
Ok(item_ids)
}
/// Reduces a compaction checkpoint payload into installed replacement history.
///
/// The returned ids let the compaction reducer record both the boundary marker
/// and the snapshot that future full requests should reconcile against.
pub(super) fn reduce_compaction_checkpoint(
&mut self,
wall_time_unix_ms: i64,
thread_id: &str,
codex_turn_id: &str,
compaction_id: &CompactionId,
checkpoint_payload: &RawPayloadRef,
) -> Result<ReducedCompactionCheckpoint> {
let payload = self.read_payload_json(checkpoint_payload)?;
let input_history = required_array(&payload, "input_history", checkpoint_payload)?;
let replacement_history =
required_array(&payload, "replacement_history", checkpoint_payload)?;
let input_items = normalize::normalize_model_items(input_history, checkpoint_payload)?;
let replacement_items =
normalize::normalize_model_items(replacement_history, checkpoint_payload)?;
let input_candidates = self
.thread_conversation_snapshots
.get(thread_id)
.cloned()
.unwrap_or_default();
let input_item_ids = self.reconcile_detached_conversation_items(
input_items,
DetachedReconcileItems {
thread_id,
codex_turn_id,
wall_time_unix_ms,
produced_by: Vec::new(),
candidates: input_candidates,
},
)?;
// A compaction checkpoint has two transcript effects. First, record the structural
// boundary where old live history ended. Then append the replacement items, including
// the provider-visible summary item if the compact endpoint returned one.
let marker_item_id = self.create_conversation_item(
thread_id,
Some(codex_turn_id.to_string()),
wall_time_unix_ms,
NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Assistant,
channel: None,
kind: ConversationItemKind::CompactionMarker,
agent_message: None,
// The summary is a separate model/provider-visible item. Keep the marker body
// empty so transcript renderers cannot mistake the boundary for prompt content.
body: ConversationBody { parts: Vec::new() },
call_id: None,
},
vec![ProducerRef::Compaction {
compaction_id: compaction_id.clone(),
}],
);
let replacement_item_ids = self.reconcile_detached_conversation_items(
replacement_items,
DetachedReconcileItems {
thread_id,
codex_turn_id,
wall_time_unix_ms,
produced_by: vec![ProducerRef::Compaction {
compaction_id: compaction_id.clone(),
}],
// Replacement history is a rewrite boundary. Even if the compact endpoint emits
// text that matches old history, the installed item is a new post-compaction
// conversation item and should not reuse a pre-compaction ID.
candidates: Vec::new(),
},
)?;
self.append_thread_conversation_items(thread_id, &input_item_ids)?;
self.append_thread_conversation_items(thread_id, std::slice::from_ref(&marker_item_id))?;
self.append_thread_conversation_items(thread_id, &replacement_item_ids)?;
Ok(ReducedCompactionCheckpoint {
input_item_ids,
marker_item_id,
replacement_item_ids,
})
}
fn reconcile_detached_conversation_items(
&mut self,
items: Vec<NormalizedConversationItem>,
context: DetachedReconcileItems<'_>,
) -> Result<Vec<String>> {
let mut item_ids = Vec::with_capacity(items.len());
let mut used_item_ids = HashSet::with_capacity(items.len());
for item in items {
let tool_link_item = item.clone();
self.ensure_call_id_consistency(context.thread_id, &item)?;
let item_id = self
.find_matching_snapshot_item(&context.candidates, &used_item_ids, &item)
.unwrap_or_else(|| {
self.create_conversation_item(
context.thread_id,
Some(context.codex_turn_id.to_string()),
context.wall_time_unix_ms,
item,
context.produced_by.clone(),
)
});
self.update_conversation_item_from_sighting(
&item_id,
&tool_link_item,
&context.produced_by,
)?;
self.attach_model_visible_tool_item(
&item_id,
tool_link_item.call_id.as_deref(),
&tool_link_item.kind,
)?;
self.attach_model_visible_code_cell_item(
&item_id,
tool_link_item.call_id.as_deref(),
&tool_link_item.kind,
)?;
self.resolve_pending_agent_edges_for_item(&item_id)?;
used_item_ids.insert(item_id.clone());
item_ids.push(item_id);
}
Ok(item_ids)
}
fn create_conversation_item(
&mut self,
thread_id: &str,
codex_turn_id: Option<String>,
first_seen_at_unix_ms: i64,
item: NormalizedConversationItem,
produced_by: Vec<ProducerRef>,
) -> String {
let item_id = self.next_conversation_item_id();
self.rollout.conversation_items.insert(
item_id.clone(),
ConversationItem {
item_id: item_id.clone(),
responses_item_id: item.responses_item_id,
accepted_at_unix_ms: None,
accepted_seq: None,
thread_id: thread_id.to_string(),
codex_turn_id,
first_seen_at_unix_ms,
role: item.role,
channel: item.channel,
kind: item.kind,
agent_message: item.agent_message,
body: item.body,
call_id: item.call_id,
produced_by,
},
);
item_id
}
fn update_conversation_item_from_sighting(
&mut self,
item_id: &str,
normalized: &NormalizedConversationItem,
produced_by: &[ProducerRef],
) -> Result<()> {
let Some(item) = self.rollout.conversation_items.get_mut(item_id) else {
bail!("conversation item {item_id} was referenced before it was created");
};
if item.responses_item_id.is_none() {
item.responses_item_id
.clone_from(&normalized.responses_item_id);
}
if item.kind == ConversationItemKind::Reasoning {
merge_reasoning_body(&mut item.body, &normalized.body)?;
}
for producer in produced_by {
if !item.produced_by.contains(producer) {
item.produced_by.push(producer.clone());
}
}
Ok(())
}
fn append_thread_conversation_items(
&mut self,
thread_id: &str,
item_ids: &[String],
) -> Result<()> {
let thread = self.thread_mut(thread_id)?;
for item_id in item_ids {
if !thread.conversation_item_ids.contains(item_id) {
thread.conversation_item_ids.push(item_id.clone());
}
}
Ok(())
}
fn find_matching_snapshot_item(
&self,
previous_snapshot: &[String],
used_item_ids: &HashSet<String>,
normalized: &NormalizedConversationItem,
) -> Option<String> {
previous_snapshot
.iter()
.find(|item_id| {
!used_item_ids.contains(*item_id) && self.item_matches(item_id, normalized)
})
.cloned()
}
fn ensure_call_id_consistency(
&self,
thread_id: &str,
normalized: &NormalizedConversationItem,
) -> Result<()> {
// One call can emit several outputs, and history trimming can rewrite
// them. Keep distinct outputs as separate items; only the invocation
// itself must remain consistent.
if !matches!(
normalized.kind,
ConversationItemKind::FunctionCall | ConversationItemKind::CustomToolCall
) {
return Ok(());
}
let Some(call_id) = normalized.call_id.as_deref() else {
return Ok(());
};
for item in self.rollout.conversation_items.values() {
if item.thread_id == thread_id
&& item.call_id.as_deref() == Some(call_id)
&& item.kind == normalized.kind
&& !conversation_item_matches(item, normalized)
{
bail!("model-visible call id {call_id} was reused with different content");
}
}
Ok(())
}
fn item_matches(&self, item_id: &str, normalized: &NormalizedConversationItem) -> bool {
let Some(item) = self.rollout.conversation_items.get(item_id) else {
return false;
};
if let (Some(existing), Some(incoming)) =
(&item.responses_item_id, &normalized.responses_item_id)
&& existing != incoming
{
return false;
}
conversation_item_matches(item, normalized)
}
fn next_conversation_item_id(&mut self) -> String {
let ordinal = self.next_conversation_item_ordinal;
self.next_conversation_item_ordinal += 1;
format!("conversation_item:{ordinal}")
}
}
#[derive(Clone, Copy)]
enum ReconcileMode {
/// Full model requests are authoritative snapshots of the live context. The
/// prompt builder can reorder already-observed items or replace history
/// with synthetic summary messages. Reuse matching content at most once
/// per snapshot, respecting supplied item IDs without requiring the same position.
FullSnapshot,
/// Incremental request deltas append to a known prefix.
/// A mismatch at an occupied position means our reconstructed prefix is
/// wrong and should fail replay.
AppendOnly,
}
struct ReconcileItems<'a> {
thread_id: &'a str,
codex_turn_id: &'a str,
wall_time_unix_ms: i64,
produced_by: Vec<ProducerRef>,
start_index: usize,
mode: ReconcileMode,
snapshot_override: Option<&'a [String]>,
}
struct DetachedReconcileItems<'a> {
thread_id: &'a str,
codex_turn_id: &'a str,
wall_time_unix_ms: i64,
produced_by: Vec<ProducerRef>,
candidates: Vec<String>,
}
/// Conversation ids produced when a compaction checkpoint is installed.
///
/// The marker item records the boundary, while replacement items are the live
/// history that subsequent full requests should treat as their baseline.
pub(super) struct ReducedCompactionCheckpoint {
pub(super) input_item_ids: Vec<String>,
pub(super) marker_item_id: String,
pub(super) replacement_item_ids: Vec<String>,
}
fn required_array<'a>(
payload: &'a Value,
key: &str,
raw_payload: &RawPayloadRef,
) -> Result<&'a Vec<Value>> {
payload.get(key).and_then(Value::as_array).with_context(|| {
format!(
"compaction checkpoint payload {} did not contain array {key}",
raw_payload.raw_payload_id
)
})
}
fn conversation_item_matches(
item: &ConversationItem,
normalized: &NormalizedConversationItem,
) -> bool {
let body_matches = if item.kind == ConversationItemKind::Reasoning
&& normalized.kind == ConversationItemKind::Reasoning
{
reasoning_body_matches(&item.body, &normalized.body)
} else {
conversation_body_matches(&item.body, &normalized.body)
};
item.role == normalized.role
&& item.channel == normalized.channel
&& item.kind == normalized.kind
&& item.agent_message == normalized.agent_message
&& body_matches
&& item.call_id == normalized.call_id
}
fn conversation_body_matches(left: &ConversationBody, right: &ConversationBody) -> bool {
left.parts.len() == right.parts.len()
&& left
.parts
.iter()
.zip(&right.parts)
.all(|(left, right)| match (left, right) {
(
ConversationPart::Json {
summary: left_summary,
raw_payload_id: _,
},
ConversationPart::Json {
summary: right_summary,
raw_payload_id: _,
},
) => left_summary == right_summary,
(
ConversationPart::PayloadRef {
content_sha256: Some(left_hash),
..
},
ConversationPart::PayloadRef {
content_sha256: Some(right_hash),
..
},
) => left_hash == right_hash,
_ => left == right,
})
}
fn reasoning_body_matches(left: &ConversationBody, right: &ConversationBody) -> bool {
if conversation_body_matches(left, right) {
return true;
}
// The Responses API may return readable reasoning on completion, but later
// request snapshots often replay only the encrypted blob. Treat the blob as
// stable model-visible identity and merge readable text as best-effort
// evidence, because request/response serialization can observe different
// readable forms for the same encrypted reasoning item.
let Some(left_encoded) = reasoning_encoded_part(left) else {
return false;
};
let Some(right_encoded) = reasoning_encoded_part(right) else {
return false;
};
left_encoded == right_encoded
}
fn merge_reasoning_body(
existing: &mut ConversationBody,
incoming: &ConversationBody,
) -> Result<()> {
if conversation_body_matches(existing, incoming) {
return Ok(());
}
if !reasoning_body_matches(existing, incoming) {
bail!("reasoning item merge attempted with different encrypted_content identity");
}
let existing_text_parts = reasoning_text_parts(existing);
let existing_summary_parts = reasoning_summary_parts(existing);
if !existing_text_parts.is_empty() && !existing_summary_parts.is_empty() {
return Ok(());
}
let incoming_text_parts = reasoning_text_parts(incoming);
let incoming_summary_parts = reasoning_summary_parts(incoming);
let text_parts = if !existing_text_parts.is_empty() {
existing_text_parts
} else {
incoming_text_parts
};
let summary_parts = if !existing_summary_parts.is_empty() {
existing_summary_parts
} else {
incoming_summary_parts
};
// We already know that the encoded part exist (and matches).
let encoded_parts = reasoning_encoded_parts(existing);
existing.parts = text_parts
.into_iter()
.cloned()
.chain(summary_parts.into_iter().cloned())
.chain(encoded_parts.into_iter().cloned())
.collect();
Ok(())
}
fn reasoning_text_parts(body: &ConversationBody) -> Vec<&ConversationPart> {
body.parts
.iter()
.filter(|part| matches!(part, ConversationPart::Text { .. }))
.collect()
}
fn reasoning_summary_parts(body: &ConversationBody) -> Vec<&ConversationPart> {
body.parts
.iter()
.filter(|part| matches!(part, ConversationPart::Summary { .. }))
.collect()
}
fn reasoning_encoded_parts(body: &ConversationBody) -> Vec<&ConversationPart> {
body.parts
.iter()
.filter(|part| matches!(part, ConversationPart::Encoded { .. }))
.collect()
}
fn reasoning_encoded_part(body: &ConversationBody) -> Option<(&str, &str)> {
body.parts.iter().find_map(|part| {
if let ConversationPart::Encoded { label, value } = part {
Some((label.as_str(), value.as_str()))
} else {
None
}
})
}
#[cfg(test)]
#[path = "conversation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,547 @@
//! Normalization from Responses-shaped JSON items into conversation item data.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_protocol::models::AgentMessageInputContent;
use codex_protocol::models::ResponseItem;
use serde_json::Value;
use sha2::Digest;
use sha2::Sha256;
use crate::model::AgentMessageMetadata;
use crate::model::ConversationBody;
use crate::model::ConversationChannel;
use crate::model::ConversationItemKind;
use crate::model::ConversationPart;
use crate::model::ConversationRole;
use crate::model::TokenUsage;
use crate::payload::RawPayloadRef;
/// Conversation fields parsed from one Responses item before trace identity.
///
/// IDs and provenance are assigned after positional reconciliation. Keeping the
/// normalized data separate from `ConversationItem` makes reuse vs insertion a
/// single reducer decision instead of something the parser has to know about.
#[derive(Clone)]
pub(super) struct NormalizedConversationItem {
pub(super) responses_item_id: Option<String>,
pub(super) role: ConversationRole,
pub(super) channel: Option<ConversationChannel>,
pub(super) kind: ConversationItemKind,
pub(super) agent_message: Option<AgentMessageMetadata>,
pub(super) body: ConversationBody,
pub(super) call_id: Option<String>,
}
pub(super) fn normalize_model_items(
items: &[Value],
raw_payload: &RawPayloadRef,
) -> Result<Vec<NormalizedConversationItem>> {
let mut normalized_items = Vec::new();
for item in items {
if item.get("type").and_then(Value::as_str) == Some("additional_tools") {
continue;
}
let mut model_visible_item = item.clone();
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)?);
}
Ok(normalized_items)
}
pub(super) fn token_usage_from_value(value: &Value) -> Option<TokenUsage> {
Some(TokenUsage {
input_tokens: u64_field(value, "input_tokens")?,
cached_input_tokens: u64_field(value, "cached_input_tokens")?,
cache_write_input_tokens: u64_field(value, "cache_write_input_tokens").unwrap_or(0),
output_tokens: u64_field(value, "output_tokens")?,
reasoning_output_tokens: u64_field(value, "reasoning_output_tokens")?,
})
}
fn normalize_model_item(
item: &Value,
raw_payload: &RawPayloadRef,
) -> Result<NormalizedConversationItem> {
let Some(item_type) = item.get("type").and_then(Value::as_str) else {
bail!(
"model item in payload {} did not contain a string type",
raw_payload.raw_payload_id
);
};
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),
"function_call" => Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::FunctionCall,
agent_message: None,
body: raw_text_or_json_body(item.get("arguments"), raw_payload),
call_id: item
.get("call_id")
.and_then(Value::as_str)
.map(ToString::to_string),
}),
"function_call_output" => Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Tool,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::FunctionCallOutput,
agent_message: None,
body: tool_output_body(item.get("output"), raw_payload)?,
call_id: item
.get("call_id")
.and_then(Value::as_str)
.map(ToString::to_string),
}),
"custom_tool_call" => Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::CustomToolCall,
agent_message: None,
body: custom_tool_call_body(item, raw_payload),
call_id: item
.get("call_id")
.and_then(Value::as_str)
.map(ToString::to_string),
}),
"custom_tool_call_output" => Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Tool,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::CustomToolCallOutput,
agent_message: None,
body: tool_output_body(item.get("output"), raw_payload)?,
call_id: item
.get("call_id")
.and_then(Value::as_str)
.map(ToString::to_string),
}),
"tool_search_call" | "web_search_call" | "image_generation_call" | "local_shell_call" => {
Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Commentary),
kind: ConversationItemKind::FunctionCall,
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" => 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),
}),
"compaction" | "compaction_summary" | "context_compaction" => {
Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Summary),
kind: ConversationItemKind::Message,
agent_message: None,
body: compaction_body(item, raw_payload)?,
call_id: None,
})
}
_ => bail!(
"unsupported model item type {item_type} in payload {}",
raw_payload.raw_payload_id
),
}?;
normalized.responses_item_id = item.get("id").and_then(Value::as_str).map(str::to_string);
Ok(normalized)
}
fn normalize_message_item(
item: &Value,
raw_payload: &RawPayloadRef,
) -> Result<NormalizedConversationItem> {
let Some(role) = item.get("role").and_then(Value::as_str) else {
bail!(
"message item in payload {} did not contain a string role",
raw_payload.raw_payload_id
);
};
let Some(role) = role_from_str(role) else {
bail!(
"unsupported message role {role} in payload {}",
raw_payload.raw_payload_id
);
};
Ok(NormalizedConversationItem {
responses_item_id: None,
role,
channel: item
.get("phase")
.and_then(Value::as_str)
.and_then(channel_from_phase),
kind: ConversationItemKind::Message,
agent_message: None,
body: ConversationBody {
parts: content_parts(item.get("content"), raw_payload)?,
},
call_id: None,
})
}
fn normalize_agent_message_item(
item: &Value,
raw_payload: &RawPayloadRef,
) -> Result<NormalizedConversationItem> {
let raw_payload_id = &raw_payload.raw_payload_id;
let response_item =
serde_json::from_value::<ResponseItem>(item.clone()).with_context(|| {
format!("failed to parse agent_message item in payload {raw_payload_id}")
})?;
let ResponseItem::AgentMessage {
author,
recipient,
content,
..
} = response_item
else {
bail!("item in payload {raw_payload_id} was not an agent_message");
};
let parts = content
.into_iter()
.map(|content| match content {
AgentMessageInputContent::InputText { text } => ConversationPart::Text { text },
AgentMessageInputContent::EncryptedContent { encrypted_content } => {
ConversationPart::Encoded {
label: "encrypted_content".to_string(),
value: encrypted_content,
}
}
})
.collect::<Vec<_>>();
if parts.is_empty() {
bail!("agent_message item in payload {raw_payload_id} contained no content");
}
Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Analysis),
kind: ConversationItemKind::Message,
agent_message: Some(AgentMessageMetadata { author, recipient }),
body: ConversationBody { parts },
call_id: None,
})
}
fn normalize_reasoning_item(
item: &Value,
raw_payload: &RawPayloadRef,
) -> Result<NormalizedConversationItem> {
let mut parts = Vec::new();
append_reasoning_parts(
item,
"content",
ReasoningPartKind::Content,
raw_payload,
&mut parts,
)?;
append_reasoning_parts(
item,
"summary",
ReasoningPartKind::Summary,
raw_payload,
&mut parts,
)?;
if let Some(encrypted_content) = item.get("encrypted_content") {
let encrypted_content = match encrypted_content {
Value::Null => None,
Value::String(encrypted_content) => Some(encrypted_content),
_ => {
bail!(
"reasoning item in payload {} had non-string encrypted_content",
raw_payload.raw_payload_id
);
}
};
if let Some(encrypted_content) = encrypted_content {
parts.push(ConversationPart::Encoded {
label: "encrypted_content".to_string(),
value: encrypted_content.to_string(),
});
}
}
if parts.is_empty() {
bail!(
"reasoning item in payload {} contained no content, summary, or encrypted_content",
raw_payload.raw_payload_id
);
}
Ok(NormalizedConversationItem {
responses_item_id: None,
role: ConversationRole::Assistant,
channel: Some(ConversationChannel::Analysis),
kind: ConversationItemKind::Reasoning,
agent_message: None,
body: ConversationBody { parts },
call_id: None,
})
}
#[derive(Clone, Copy)]
enum ReasoningPartKind {
Content,
Summary,
}
fn append_reasoning_parts(
item: &Value,
key: &str,
kind: ReasoningPartKind,
raw_payload: &RawPayloadRef,
parts: &mut Vec<ConversationPart>,
) -> Result<()> {
let Some(items) = item.get(key) else {
return Ok(());
};
if matches!((kind, items), (ReasoningPartKind::Content, Value::Null)) {
return Ok(());
}
let Some(items) = items.as_array() else {
bail!(
"reasoning item in payload {} had non-array {key}",
raw_payload.raw_payload_id
);
};
for content_item in items {
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",
raw_payload.raw_payload_id
);
};
let expected_type = match kind {
ReasoningPartKind::Content => {
if !matches!(item_type, "reasoning_text" | "text") {
bail!(
"reasoning item in payload {} had unsupported content type {item_type}",
raw_payload.raw_payload_id
);
}
"content"
}
ReasoningPartKind::Summary => {
if item_type != "summary_text" {
bail!(
"reasoning item in payload {} had unsupported summary type {item_type}",
raw_payload.raw_payload_id
);
}
"summary"
}
};
let Some(text) = content_item.get("text").and_then(Value::as_str) else {
bail!(
"reasoning item in payload {} had {expected_type} entry without string text",
raw_payload.raw_payload_id
);
};
match kind {
ReasoningPartKind::Content => parts.push(ConversationPart::Text {
text: text.to_string(),
}),
ReasoningPartKind::Summary => parts.push(ConversationPart::Summary {
text: text.to_string(),
}),
}
}
Ok(())
}
fn role_from_str(role: &str) -> Option<ConversationRole> {
match role {
"system" => Some(ConversationRole::System),
"developer" => Some(ConversationRole::Developer),
"user" => Some(ConversationRole::User),
"assistant" => Some(ConversationRole::Assistant),
"tool" => Some(ConversationRole::Tool),
_ => None,
}
}
fn channel_from_phase(phase: &str) -> Option<ConversationChannel> {
match phase {
"commentary" => Some(ConversationChannel::Commentary),
// Both answer phases are Harmony final-channel text; only the latter
// declares a terminal answer.
"partial_answer" | "final_answer" => Some(ConversationChannel::Final),
"summary" => Some(ConversationChannel::Summary),
_ => None,
}
}
fn content_parts(
content: Option<&Value>,
raw_payload: &RawPayloadRef,
) -> Result<Vec<ConversationPart>> {
let Some(content) = content.and_then(Value::as_array) else {
return Ok(vec![payload_ref_part("content", raw_payload)]);
};
let mut parts = Vec::new();
for part in content {
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(),
});
}
}
other => {
// Repeated images live in different request payloads. Compare their
// content without copying large image bodies into the reduced graph.
let mut canonical = part.clone();
canonical.sort_all_objects();
let mut digest = Sha256::new();
serde_json::to_writer(&mut digest, &canonical)?;
parts.push(ConversationPart::PayloadRef {
label: other.unwrap_or("content").to_string(),
raw_payload_id: raw_payload.raw_payload_id.clone(),
content_sha256: Some(format!("{:x}", digest.finalize())),
});
}
}
}
Ok(parts)
}
fn custom_tool_call_body(item: &Value, raw_payload: &RawPayloadRef) -> ConversationBody {
let Some(input) = item.get("input").and_then(Value::as_str) else {
return json_body(item, raw_payload);
};
if item.get("name").and_then(Value::as_str) == Some("exec") {
ConversationBody {
parts: vec![ConversationPart::Code {
language: "javascript".to_string(),
source: input.to_string(),
}],
}
} else {
ConversationBody {
parts: vec![ConversationPart::Text {
text: input.to_string(),
}],
}
}
}
fn raw_text_or_json_body(value: Option<&Value>, raw_payload: &RawPayloadRef) -> ConversationBody {
match value {
Some(Value::String(text)) => {
if let Ok(json) = serde_json::from_str::<Value>(text) {
json_body(&json, raw_payload)
} else {
ConversationBody {
parts: vec![ConversationPart::Text { text: text.clone() }],
}
}
}
Some(value) => json_body(value, raw_payload),
None => ConversationBody {
parts: vec![payload_ref_part("payload", raw_payload)],
},
}
}
fn tool_output_body(
output: Option<&Value>,
raw_payload: &RawPayloadRef,
) -> 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)?,
},
Some(value) => json_body(value, raw_payload),
None => ConversationBody {
parts: vec![payload_ref_part("tool_output", raw_payload)],
},
})
}
fn compaction_body(item: &Value, raw_payload: &RawPayloadRef) -> Result<ConversationBody> {
let Some(encrypted_content) = item.get("encrypted_content").and_then(Value::as_str) else {
bail!(
"compaction item in payload {} did not contain string encrypted_content",
raw_payload.raw_payload_id
);
};
// `type: "compaction"` is the remote-compaction summary that later re-enters model requests.
// The structural "history was cut here" marker is inserted separately when the checkpoint is
// installed; payload refs are observation-local, so the encoded summary itself is identity.
Ok(ConversationBody {
parts: vec![ConversationPart::Encoded {
label: "encrypted_content".to_string(),
value: encrypted_content.to_string(),
}],
})
}
fn json_body(value: &Value, raw_payload: &RawPayloadRef) -> ConversationBody {
ConversationBody {
parts: vec![ConversationPart::Json {
summary: summarize_json(value),
raw_payload_id: raw_payload.raw_payload_id.clone(),
}],
}
}
fn payload_ref_part(label: &str, raw_payload: &RawPayloadRef) -> ConversationPart {
ConversationPart::PayloadRef {
label: label.to_string(),
raw_payload_id: raw_payload.raw_payload_id.clone(),
content_sha256: None,
}
}
fn summarize_json(value: &Value) -> String {
const MAX_JSON_SUMMARY_LEN: usize = 240;
let mut summary =
serde_json::to_string(value).unwrap_or_else(|_| "<unserializable json>".to_string());
if summary.len() > MAX_JSON_SUMMARY_LEN {
summary.truncate(summary.floor_char_boundary(MAX_JSON_SUMMARY_LEN));
summary.push_str("...");
}
summary
}
fn u64_field(value: &Value, field: &str) -> Option<u64> {
value
.get(field)
.and_then(Value::as_i64)
.map(|value| value.max(0) as u64)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,231 @@
//! Inference call lifecycle reduction.
//!
//! Conversation request/response normalization lives in the conversation module;
//! this module owns the runtime envelope around those model-facing payloads.
use anyhow::Result;
use anyhow::bail;
use super::TraceReducer;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::model::InferenceCall;
use crate::model::InferenceCallId;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawEventSeq;
use crate::raw_event::RawTraceEventPayload;
/// Raw inference-start fields after dispatch has stripped the common event envelope.
///
/// Keeping this as one argument prevents callsites from passing a long list of
/// adjacent strings whose ordering is easy to mix up.
pub(super) struct StartedInferenceCall {
pub(super) inference_call_id: InferenceCallId,
pub(super) thread_id: String,
pub(super) codex_turn_id: String,
pub(super) model: String,
pub(super) provider_name: String,
pub(super) request_payload: RawPayloadRef,
}
impl TraceReducer {
/// Starts an inference call and reduces its request payload into conversation items.
///
/// Requests are model-visible transcript evidence, so the inference object is only
/// inserted after the request snapshot has been normalized and linked to the turn.
pub(super) fn start_inference_call(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
started: StartedInferenceCall,
) -> Result<()> {
if self
.rollout
.inference_calls
.contains_key(&started.inference_call_id)
{
bail!(
"duplicate inference start for {}",
started.inference_call_id
);
}
let inference_call_id = started.inference_call_id.clone();
let thread_id = started.thread_id.clone();
let codex_turn_id = started.codex_turn_id.clone();
let request_payload = started.request_payload.clone();
let Some(turn) = self.rollout.codex_turns.get(&codex_turn_id) else {
bail!(
"inference start {inference_call_id} referenced unknown codex turn {codex_turn_id}"
);
};
if turn.thread_id != thread_id {
bail!(
"inference start {inference_call_id} used thread {thread_id}, \
but codex turn {codex_turn_id} belongs to {}",
turn.thread_id
);
}
let request_item_ids = self.reduce_inference_request(
wall_time_unix_ms,
&inference_call_id,
&thread_id,
&codex_turn_id,
&request_payload,
)?;
self.thread_mut(&thread_id)?;
self.rollout.inference_calls.insert(
inference_call_id.clone(),
InferenceCall {
inference_call_id,
thread_id,
codex_turn_id,
execution: ExecutionWindow {
started_at_unix_ms: wall_time_unix_ms,
started_seq: seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
model: started.model,
provider_name: started.provider_name,
response_id: None,
upstream_request_id: None,
request_item_ids,
response_item_ids: Vec::new(),
tool_call_ids_started_by_response: Vec::new(),
usage: None,
raw_request_payload_id: started.request_payload.raw_payload_id,
raw_response_payload_id: None,
},
);
Ok(())
}
/// Closes any inference streams that are still live when the owning turn ends.
///
/// Normal completion events close the active inference before the turn ends.
/// If a call is still `Running`, Codex stopped observing that provider stream
/// earlier and the reduced graph should not present it as live.
pub(super) fn close_running_inference_calls_for_turn_end(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
codex_turn_id: &str,
turn_status: &ExecutionStatus,
) {
let inference_status = match turn_status {
ExecutionStatus::Running => return,
ExecutionStatus::Completed | ExecutionStatus::Cancelled => ExecutionStatus::Cancelled,
ExecutionStatus::Failed => ExecutionStatus::Failed,
ExecutionStatus::Aborted => ExecutionStatus::Aborted,
};
for inference in self.rollout.inference_calls.values_mut() {
if inference.codex_turn_id == codex_turn_id
&& inference.execution.status == ExecutionStatus::Running
{
inference.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
inference.execution.ended_seq = Some(seq);
inference.execution.status = inference_status.clone();
}
}
}
/// Completes an inference call and, when present, reduces response output items.
pub(super) fn complete_inference_call(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
payload: RawTraceEventPayload,
) -> Result<()> {
let (inference_call_id, status, response_id, upstream_request_id, response_payload) =
match payload {
RawTraceEventPayload::InferenceCompleted {
inference_call_id,
response_id,
upstream_request_id,
response_payload,
} => (
inference_call_id,
ExecutionStatus::Completed,
response_id,
upstream_request_id,
Some(response_payload),
),
RawTraceEventPayload::InferenceFailed {
inference_call_id,
upstream_request_id,
partial_response_payload,
..
} => (
inference_call_id,
ExecutionStatus::Failed,
None,
upstream_request_id,
partial_response_payload,
),
RawTraceEventPayload::InferenceCancelled {
inference_call_id,
upstream_request_id,
partial_response_payload,
..
} => (
inference_call_id,
ExecutionStatus::Cancelled,
None,
upstream_request_id,
partial_response_payload,
),
_ => bail!("complete_inference_call received a non-terminal inference event"),
};
if !self
.rollout
.inference_calls
.contains_key(&inference_call_id)
{
bail!("inference completion referenced unknown call {inference_call_id}");
}
let response_item_ids = response_payload
.as_ref()
.map(|payload| {
self.reduce_inference_response(wall_time_unix_ms, &inference_call_id, payload)
})
.transpose()?;
{
let Some(inference) = self.rollout.inference_calls.get_mut(&inference_call_id) else {
bail!("inference call {inference_call_id} disappeared during response reduction");
};
inference.response_id = response_id;
// Turn-end cleanup can close a stream before the async mapper observes
// cancellation. Preserve that terminal status while still retaining any
// late partial response evidence from the mapper.
if inference.execution.status == ExecutionStatus::Running {
inference.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
inference.execution.ended_seq = Some(seq);
inference.execution.status = status;
}
// Turn-end cleanup can mark an inference terminal before the stream
// mapper records its late partial payload. Keep the server request
// id from that late payload even when the status is already closed.
if let Some(upstream_request_id) = upstream_request_id {
inference.upstream_request_id = Some(upstream_request_id);
}
if let Some(response_payload) = response_payload {
inference.raw_response_payload_id = Some(response_payload.raw_payload_id);
}
if let Some(response_item_ids) = response_item_ids {
inference.response_item_ids = response_item_ids;
}
}
Ok(())
}
}
#[cfg(test)]
#[path = "inference_tests.rs"]
mod tests;

View File

@@ -0,0 +1,172 @@
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::model::ConversationItemKind;
use crate::model::ExecutionStatus;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::append_inference_start;
use crate::reducer::test_support::create_started_writer;
use crate::reducer::test_support::message;
use crate::reducer::test_support::start_turn;
use crate::reducer::test_support::trace_context;
use crate::replay_bundle;
#[test]
fn cancelled_inference_retains_accepted_partial_output() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"input": [message("user", "draft")]
}),
)?;
append_inference_start(&writer, "inference-1", "turn-1", request)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::HistoryItemAccepted {
item_id: "msg-partial".into(),
},
)?;
let partial_response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": null,
"token_usage": null,
"output_items": [{
"type": "message",
"id": "msg-partial",
"role": "assistant",
"content": [{"type": "output_text", "text": "partial"}]
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceCancelled {
inference_call_id: "inference-1".to_string(),
upstream_request_id: Some("req-cancelled".to_string()),
reason: "test interruption".to_string(),
partial_response_payload: Some(partial_response),
})?;
let rollout = replay_bundle(temp.path())?;
let inference = &rollout.inference_calls["inference-1"];
let response_item_id = &inference.response_item_ids[0];
assert_eq!(inference.execution.status, ExecutionStatus::Cancelled);
assert_eq!(
inference.upstream_request_id,
Some("req-cancelled".to_string()),
);
assert_eq!(inference.response_item_ids.len(), 1);
assert_eq!(
rollout.conversation_items[response_item_id].kind,
ConversationItemKind::Message,
);
assert_eq!(
rollout.conversation_items[response_item_id].produced_by,
vec![crate::model::ProducerRef::Inference {
inference_call_id: "inference-1".to_string(),
}],
);
let mut expected = inference.request_item_ids.clone();
expected.extend(inference.response_item_ids.clone());
assert_eq!(
rollout.threads["thread-root"].conversation_item_ids,
expected
);
Ok(())
}
#[test]
fn cancelled_turn_closes_running_inference_call() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"input": [message("user", "wait")]
}),
)?;
append_inference_start(&writer, "inference-1", "turn-1", request)?;
let turn_end = writer.append(RawTraceEventPayload::CodexTurnEnded {
codex_turn_id: "turn-1".to_string(),
status: ExecutionStatus::Cancelled,
})?;
let rollout = replay_bundle(temp.path())?;
let inference = &rollout.inference_calls["inference-1"];
assert_eq!(inference.execution.status, ExecutionStatus::Cancelled);
assert_eq!(inference.execution.ended_seq, Some(turn_end.seq));
Ok(())
}
#[test]
fn late_cancelled_inference_preserves_turn_end_status() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"input": [message("user", "interrupt")]
}),
)?;
append_inference_start(&writer, "inference-1", "turn-1", request)?;
let turn_end = writer.append(RawTraceEventPayload::CodexTurnEnded {
codex_turn_id: "turn-1".to_string(),
status: ExecutionStatus::Failed,
})?;
let partial_response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": null,
"token_usage": null,
"output_items": [{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "late partial"}]
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceCancelled {
inference_call_id: "inference-1".to_string(),
upstream_request_id: Some("req-late-cancelled".to_string()),
reason: "stream mapper noticed cancellation after turn end".to_string(),
partial_response_payload: Some(partial_response.clone()),
})?;
let rollout = replay_bundle(temp.path())?;
let inference = &rollout.inference_calls["inference-1"];
assert_eq!(inference.execution.status, ExecutionStatus::Failed);
assert_eq!(inference.execution.ended_seq, Some(turn_end.seq));
assert_eq!(
inference.raw_response_payload_id,
Some(partial_response.raw_payload_id),
);
assert_eq!(
inference.upstream_request_id,
Some("req-late-cancelled".to_string()),
);
assert_eq!(inference.response_item_ids.len(), 1);
let response_item_id = &inference.response_item_ids[0];
assert_eq!(
rollout.conversation_items[response_item_id].body.parts,
vec![crate::model::ConversationPart::Text {
text: "late partial".to_string(),
}],
);
Ok(())
}

View File

@@ -0,0 +1,639 @@
//! Deterministic replay from raw trace events to `RolloutTrace`.
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use anyhow::ensure;
use serde::de::IgnoredAny;
use serde_json::Value;
use crate::bundle::MANIFEST_FILE_NAME;
use crate::bundle::RAW_EVENT_LOG_FILE_NAME;
use crate::bundle::REDUCED_TRACE_SCHEMA_VERSION;
use crate::bundle::TRACE_MANIFEST_SCHEMA_VERSION;
use crate::bundle::TraceBundleManifest;
use crate::model::ExecutionStatus;
use crate::model::RolloutTrace;
use crate::payload::RawPayloadRef;
use crate::raw_event::RAW_TRACE_EVENT_SCHEMA_VERSION;
use crate::raw_event::RawTraceEvent;
use crate::raw_event::RawTraceEventPayload;
mod code_cell;
mod compaction;
mod conversation;
mod inference;
#[cfg(test)]
pub(crate) mod test_support;
mod thread;
mod tool;
#[cfg(test)]
#[path = "acceptance_tests.rs"]
mod acceptance_tests;
use self::code_cell::PendingCodeCellLifecycleEvent;
use self::code_cell::PendingCodeCellStart;
use self::code_cell::StartedCodeCell;
use self::compaction::StartedCompactionRequest;
use self::inference::StartedInferenceCall;
use self::tool::ObservedAgentResultEdge;
use self::tool::PendingAgentInteractionEdge;
use self::tool::ToolCallStarted;
/// Replays a local trace bundle into a reduced rollout graph.
/// A valid prefix has `recording_complete = false`; malformed events or missing
/// or invalid referenced payloads return an error.
pub fn replay_bundle(bundle_dir: impl AsRef<Path>) -> Result<RolloutTrace> {
let bundle_dir = bundle_dir.as_ref();
let manifest: TraceBundleManifest =
serde_json::from_reader(File::open(bundle_dir.join(MANIFEST_FILE_NAME))?)
.with_context(|| format!("read {}", bundle_dir.join(MANIFEST_FILE_NAME).display()))?;
// Earlier bundles cannot distinguish accepted output from transport output.
ensure!(
manifest.schema_version == TRACE_MANIFEST_SCHEMA_VERSION,
"trace schema {} cannot establish accepted history; use its matching reducer or record a new bundle",
manifest.schema_version
);
let mut reducer = TraceReducer {
rollout: RolloutTrace::new(
REDUCED_TRACE_SCHEMA_VERSION,
manifest.trace_id,
manifest.rollout_id,
manifest.root_thread_id,
manifest.started_at_unix_ms,
),
bundle_dir: bundle_dir.to_path_buf(),
next_conversation_item_ordinal: 1,
next_terminal_operation_ordinal: 1,
terminal_ids_by_process: BTreeMap::new(),
process_ids_by_terminal: BTreeMap::new(),
thread_conversation_snapshots: BTreeMap::new(),
pending_compaction_replacement_item_ids: BTreeMap::new(),
code_cell_ids_by_runtime: BTreeMap::new(),
pending_code_cell_starts: BTreeMap::new(),
pending_code_cell_lifecycle_events: BTreeMap::new(),
pending_agent_interaction_edges: Vec::new(),
first_acceptances: BTreeMap::new(),
};
let event_log_path = bundle_dir.join(RAW_EVENT_LOG_FILE_NAME);
let event_log = File::open(&event_log_path)
.with_context(|| format!("open trace event log {}", event_log_path.display()))?;
let mut event_log = BufReader::new(event_log);
let mut event_count = 0;
let mut line = String::new();
for line_number in 1.. {
line.clear();
if event_log
.read_line(&mut line)
.with_context(|| format!("read trace event line {line_number}"))?
== 0
{
break;
}
if line.trim().is_empty() {
continue;
}
ensure!(
!reducer.rollout.recording_complete,
"trace event after recording completed"
);
let event: RawTraceEvent = serde_json::from_str(&line)
.with_context(|| format!("parse trace event line {line_number}"))?;
ensure!(
event.schema_version == RAW_TRACE_EVENT_SCHEMA_VERSION,
"unsupported trace event schema {} at line {line_number}",
event.schema_version,
);
event_count += 1;
ensure!(
event.seq == event_count,
"missing or reordered trace event {event_count}"
);
ensure!(
event.rollout_id == reducer.rollout.rollout_id,
"trace event belongs to another rollout"
);
// A short write or copy can leave the entire marker except its final newline.
// Only the writer's complete record establishes clean closure.
if matches!(event.payload, RawTraceEventPayload::RecordingCompleted)
&& !line.ends_with('\n')
{
break;
}
reducer.apply_event(event)?;
}
for payload in reducer.rollout.raw_payloads.values() {
// IgnoredAny checks JSON structure but skips UTF-8 validation inside strings.
// Read one body as text so opaque payloads get both checks without a JSON tree.
let body = std::fs::read_to_string(reducer.bundle_dir.join(&payload.path))
.with_context(|| format!("read payload {}", payload.raw_payload_id))?;
serde_json::from_str::<IgnoredAny>(&body)
.with_context(|| format!("invalid payload {}", payload.raw_payload_id))?;
}
// Spawn edges prefer the child task message as their target, but a child can
// fail before that message is ever reduced. Only after replaying the whole
// bundle do we know which spawn deliveries need the child-thread fallback.
reducer.resolve_pending_spawn_edge_fallbacks()?;
// Cell starts can be queued until their model output arrives. Link only
// materialized cells, after both sides of the dispatch have been replayed.
for tool in reducer.rollout.tool_calls.values_mut() {
if tool.requester == crate::ToolCallRequester::Model
&& matches!(&tool.kind, crate::ToolCallKind::Other { name } if name == codex_code_mode::PUBLIC_TOOL_NAME)
&& let Some(call_id) = &tool.model_visible_call_id
&& let Some(cell) = reducer.rollout.code_cells.get(
&TraceReducer::reduced_code_cell_id_for_model_visible_call(call_id),
)
&& cell.thread_id == tool.thread_id
&& tool
.started_by_codex_turn_id
.as_ref()
.is_none_or(|turn| turn == &cell.codex_turn_id)
{
tool.started_code_cell_id = Some(cell.code_cell_id.clone());
}
}
// Acceptance and response records can arrive in either order. Select history
// after replay, retaining discarded attempts elsewhere in the graph.
// Request/checkpoint items include inherited context without local acceptance.
for item in reducer.rollout.conversation_items.values_mut() {
if let Some(&(at_unix_ms, seq)) = item
.responses_item_id
.as_ref()
.and_then(|id| reducer.first_acceptances.get(&item.thread_id)?.get(id))
{
item.accepted_at_unix_ms = Some(at_unix_ms);
item.accepted_seq = Some(seq);
}
}
let context_item_ids: BTreeSet<_> = reducer
.rollout
.inference_calls
.values()
.flat_map(|call| call.request_item_ids.iter())
.chain(reducer.rollout.compactions.values().flat_map(|checkpoint| {
checkpoint
.input_item_ids
.iter()
.chain(&checkpoint.replacement_item_ids)
.chain(std::iter::once(&checkpoint.marker_item_id))
}))
.collect();
for thread in reducer.rollout.threads.values_mut() {
let accepted_ids = reducer
.first_acceptances
.remove(&thread.thread_id)
.unwrap_or_default();
thread.conversation_item_ids.retain(|id| {
let item = &reducer.rollout.conversation_items[id];
context_item_ids.contains(id)
|| item
.responses_item_id
.as_ref()
.is_some_and(|source_id| accepted_ids.contains_key(source_id))
});
}
Ok(reducer.rollout)
}
struct TraceReducer {
rollout: RolloutTrace,
bundle_dir: PathBuf,
/// First (wall time, sequence) by receiving thread and Responses item ID.
first_acceptances: BTreeMap<String, BTreeMap<String, (i64, crate::RawEventSeq)>>,
next_conversation_item_ordinal: u64,
next_terminal_operation_ordinal: u64,
/// Latest session for each thread-local runtime handle; each exec replaces it.
terminal_ids_by_process: BTreeMap<(String, String), String>,
/// Retains the begin/end consistency check when a handle is later reused.
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>>,
/// 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
/// history, not against the pre-compaction request. That keeps repeated prefix/context messages
/// as fresh post-compaction conversation items while still reusing the summary/replacement
/// items that actually became live history.
pending_compaction_replacement_item_ids: BTreeMap<String, Vec<String>>,
/// Runtime cell ids indexed by thread-local code-mode handle.
///
/// Reduced `CodeCellId`s are based on the model-visible `exec` call id
/// because that is the durable source identity. Runtime lifecycle, nested
/// tools, and `wait` calls arrive with the runtime-local `cell_id`, so this
/// index is the one intentional bridge between those namespaces.
code_cell_ids_by_runtime: BTreeMap<(String, String), String>,
/// Code-cell starts whose model-visible `custom_tool_call` item has not
/// been reduced yet.
///
/// Core begins executing tools before the stream-completion hook records
/// the response payload that requested them. Queueing keeps replay strict
/// about eventual source-item ownership without requiring trace producers
/// to reorder runtime events behind inference completion.
pending_code_cell_starts: BTreeMap<String, PendingCodeCellStart>,
/// Initial/end events that arrived while the matching start was queued.
///
/// Fast cells can return before the inference response payload that proves
/// the model-visible `exec` source item has been reduced. The start remains
/// queued for ownership validation; these lifecycle events wait with it and
/// are replayed in raw sequence order once the cell materializes.
pending_code_cell_lifecycle_events: BTreeMap<String, Vec<PendingCodeCellLifecycleEvent>>,
/// Multi-agent deliveries whose recipient-side transcript item has not been observed yet.
///
/// V2 agent tools enqueue mailbox messages in the target thread. The trace event for the
/// sending tool arrives before the recipient inference request materializes that mailbox item
/// as a `ConversationItem`, so the reducer keeps the delivery edge pending until it can point
/// at the exact model-visible item instead of a coarse thread.
pending_agent_interaction_edges: Vec<PendingAgentInteractionEdge>,
}
impl TraceReducer {
fn read_payload_json(&self, payload: &RawPayloadRef) -> Result<Value> {
// Reducers keep raw bodies out of the graph, but typed replay sometimes
// needs a small subset of fields to build semantic objects.
let payload_path = self.bundle_dir.join(&payload.path);
let file = File::open(&payload_path)
.with_context(|| format!("open payload {}", payload.raw_payload_id))?;
serde_json::from_reader(BufReader::new(file))
.with_context(|| format!("parse payload {}", payload.raw_payload_id))
}
fn apply_event(&mut self, event: RawTraceEvent) -> Result<()> {
// Raw payload refs are reducer-wide evidence, not owned by a single
// semantic arm. Keep this bookkeeping separate so typed reduction can
// stay strict without duplicating payload insertion in every case.
for payload in event.payload.raw_payload_refs() {
self.insert_raw_payload(payload);
}
match event.payload {
RawTraceEventPayload::RecordingCompleted => {
self.rollout.recording_complete = true;
}
RawTraceEventPayload::RolloutStarted {
trace_id,
root_thread_id,
} => {
self.rollout.trace_id = trace_id;
self.rollout.root_thread_id = root_thread_id;
}
RawTraceEventPayload::RolloutEnded { status } => {
self.rollout.status = status;
self.rollout.ended_at_unix_ms = Some(event.wall_time_unix_ms);
}
RawTraceEventPayload::ThreadStarted {
thread_id,
agent_path,
metadata_payload,
} => {
self.start_thread(
event.seq,
event.wall_time_unix_ms,
thread_id,
agent_path,
metadata_payload,
)?;
}
RawTraceEventPayload::ThreadEnded { thread_id, status } => {
self.end_thread(event.seq, event.wall_time_unix_ms, thread_id, status)?;
}
RawTraceEventPayload::ThreadResumed { thread_id } => {
self.resume_thread(&thread_id)?;
}
RawTraceEventPayload::CodexTurnStarted {
codex_turn_id,
thread_id,
} => {
self.start_codex_turn(
event.seq,
event.wall_time_unix_ms,
codex_turn_id,
thread_id,
)?;
}
RawTraceEventPayload::CodexTurnEnded {
codex_turn_id,
status,
} => {
self.end_codex_turn(
event.seq,
event.wall_time_unix_ms,
event.thread_id,
codex_turn_id,
status,
)?;
}
RawTraceEventPayload::HistoryItemAccepted { item_id } => {
let thread_id = event
.thread_id
.context("history acceptance has no thread")?;
self.thread_mut(&thread_id)?;
self.first_acceptances
.entry(thread_id)
.or_default()
.entry(item_id)
.or_insert((event.wall_time_unix_ms, event.seq));
}
RawTraceEventPayload::InferenceStarted {
inference_call_id,
thread_id,
codex_turn_id,
model,
provider_name,
request_payload,
} => {
self.start_inference_call(
event.seq,
event.wall_time_unix_ms,
StartedInferenceCall {
inference_call_id,
thread_id,
codex_turn_id,
model,
provider_name,
request_payload,
},
)?;
}
payload @ (RawTraceEventPayload::InferenceCompleted { .. }
| RawTraceEventPayload::InferenceFailed { .. }
| RawTraceEventPayload::InferenceCancelled { .. }) => {
self.complete_inference_call(event.seq, event.wall_time_unix_ms, payload)?;
}
RawTraceEventPayload::ProtocolEventObserved { .. } => {
// Protocol wrappers are raw debug breadcrumbs. Typed hooks own
// the reduced graph, so these payload refs are retained without
// creating semantic objects.
}
RawTraceEventPayload::ToolCallStarted {
tool_call_id,
model_visible_call_id,
code_mode_runtime_tool_id,
requester,
kind,
summary,
invocation_payload,
} => {
self.start_tool_call(
event.seq,
event.wall_time_unix_ms,
event.thread_id,
event.codex_turn_id,
ToolCallStarted {
tool_call_id,
model_visible_call_id,
code_mode_runtime_tool_id,
requester,
kind,
summary,
invocation_payload,
},
)?;
}
RawTraceEventPayload::McpToolCallCorrelationAssigned {
tool_call_id,
mcp_call_id,
} => {
self.assign_mcp_tool_call_correlation(tool_call_id, mcp_call_id)?;
}
RawTraceEventPayload::StdinTargetResolved {
tool_call_id,
exec_tool_call_id,
} => {
self.resolve_stdin_target(&tool_call_id, &exec_tool_call_id)?;
}
RawTraceEventPayload::ToolCallRuntimeStarted {
tool_call_id,
kind,
runtime_payload,
} => {
self.start_tool_runtime_observation(
event.seq,
event.wall_time_unix_ms,
tool_call_id,
kind,
runtime_payload,
)?;
}
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id,
status,
runtime_payload,
} => {
self.end_tool_runtime_observation(
event.seq,
event.wall_time_unix_ms,
tool_call_id,
status,
runtime_payload,
)?;
}
RawTraceEventPayload::ToolCallEnded {
tool_call_id,
status,
result_payload,
} => {
self.end_tool_call(
event.seq,
event.wall_time_unix_ms,
tool_call_id,
status,
result_payload,
)?;
}
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id,
model_visible_call_id,
source_js,
} => {
let thread_id = self.code_cell_event_thread_id(
event.thread_id,
event.codex_turn_id.as_deref(),
&runtime_cell_id,
"code cell start",
)?;
let reduced_code_cell_id =
Self::reduced_code_cell_id_for_model_visible_call(&model_visible_call_id);
self.record_runtime_code_cell_id(
&thread_id,
&runtime_cell_id,
&reduced_code_cell_id,
)?;
self.start_or_queue_code_cell(PendingCodeCellStart {
seq: event.seq,
wall_time_unix_ms: event.wall_time_unix_ms,
thread_id,
codex_turn_id: event.codex_turn_id,
started: StartedCodeCell {
code_cell_id: reduced_code_cell_id,
runtime_cell_id,
model_visible_call_id,
source_js,
},
})?;
}
RawTraceEventPayload::CodeCellInitialResponse {
runtime_cell_id,
status,
response_payload,
} => {
let thread_id = self.code_cell_event_thread_id(
event.thread_id,
event.codex_turn_id.as_deref(),
&runtime_cell_id,
"code cell initial response",
)?;
let code_cell_id = self.code_cell_id_for_runtime_cell_id(
&thread_id,
&runtime_cell_id,
"code cell initial response",
)?;
self.record_or_queue_code_cell_initial_response(
event.seq,
event.wall_time_unix_ms,
code_cell_id,
runtime_cell_id,
status,
response_payload,
)?;
}
RawTraceEventPayload::CodeCellEnded {
runtime_cell_id,
status,
response_payload,
} => {
let thread_id = self.code_cell_event_thread_id(
event.thread_id,
event.codex_turn_id.as_deref(),
&runtime_cell_id,
"code cell end",
)?;
let code_cell_id = self.code_cell_id_for_runtime_cell_id(
&thread_id,
&runtime_cell_id,
"code cell end",
)?;
self.end_or_queue_code_cell(
event.seq,
event.wall_time_unix_ms,
code_cell_id,
status,
response_payload,
)?;
}
RawTraceEventPayload::CompactionRequestStarted {
compaction_id,
compaction_request_id,
thread_id,
codex_turn_id,
model,
provider_name,
request_payload,
} => {
self.start_compaction_request(
event.seq,
event.wall_time_unix_ms,
StartedCompactionRequest {
compaction_id,
compaction_request_id,
thread_id,
codex_turn_id,
model,
provider_name,
request_payload,
},
)?;
}
RawTraceEventPayload::CompactionRequestCompleted {
compaction_id,
compaction_request_id,
response_payload,
} => {
self.complete_compaction_request(
event.seq,
event.wall_time_unix_ms,
compaction_id,
compaction_request_id,
ExecutionStatus::Completed,
Some(response_payload),
)?;
}
RawTraceEventPayload::CompactionRequestFailed {
compaction_id,
compaction_request_id,
..
} => {
self.complete_compaction_request(
event.seq,
event.wall_time_unix_ms,
compaction_id,
compaction_request_id,
ExecutionStatus::Failed,
/*response_payload*/ None,
)?;
}
RawTraceEventPayload::CompactionInstalled {
compaction_id,
checkpoint_payload,
} => {
let Some(thread_id) = event.thread_id else {
bail!("compaction installed event {compaction_id} did not include a thread id");
};
let Some(codex_turn_id) = event.codex_turn_id else {
bail!(
"compaction installed event {compaction_id} did not include a codex turn id"
);
};
self.reduce_compaction_installed_event(
event.wall_time_unix_ms,
thread_id,
codex_turn_id,
compaction_id,
checkpoint_payload,
)?;
}
RawTraceEventPayload::AgentResultObserved {
edge_id,
child_thread_id,
child_codex_turn_id,
parent_thread_id,
message,
carried_payload,
} => {
self.queue_agent_result_interaction_edge(ObservedAgentResultEdge {
wall_time_unix_ms: event.wall_time_unix_ms,
edge_id,
child_thread_id,
child_codex_turn_id,
parent_thread_id,
message,
carried_payload,
})?;
}
RawTraceEventPayload::Other { .. } => {
bail!("raw trace event has no reducer implementation");
}
}
// Compaction appends input and replacement histories separately. Pending cells
// must see both before finding their source and outputs in the ordered history.
self.flush_pending_code_cell_starts()
}
fn insert_raw_payload(&mut self, payload: &RawPayloadRef) {
self.rollout
.raw_payloads
.insert(payload.raw_payload_id.clone(), payload.clone());
}
}

View File

@@ -0,0 +1,202 @@
//! Shared reducer test fixtures.
//!
//! These helpers only write common trace scaffolding. Scenario-specific event
//! sequences stay in each test so the behavior under test remains visible.
use serde_json::json;
use tempfile::TempDir;
use crate::model::ToolCallSummary;
use crate::payload::RawPayloadKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawTraceEventContext;
use crate::raw_event::RawTraceEventPayload;
use crate::replay_bundle;
use crate::writer::TraceWriter;
pub(crate) const ROOT_THREAD_ID: &str = "thread-root";
pub(crate) const AGENT_ROOT_THREAD_ID: &str = "019d0000-0000-7000-8000-000000000001";
pub(crate) fn message(role: &str, text: &str) -> serde_json::Value {
json!({
"type": "message",
"role": role,
"content": [{"type": "input_text", "text": text}]
})
}
pub(crate) fn generic_summary(label: &str) -> ToolCallSummary {
ToolCallSummary::Generic {
label: label.to_string(),
input_preview: None,
output_preview: None,
}
}
pub(crate) fn create_started_writer(temp: &TempDir) -> anyhow::Result<TraceWriter> {
create_started_writer_for_thread(temp, ROOT_THREAD_ID, "/root")
}
pub(crate) fn create_started_agent_writer(temp: &TempDir) -> anyhow::Result<TraceWriter> {
create_started_writer_for_thread(temp, AGENT_ROOT_THREAD_ID, "/root")
}
pub(crate) fn create_started_writer_for_thread(
temp: &TempDir,
thread_id: &str,
agent_path: &str,
) -> anyhow::Result<TraceWriter> {
let writer = TraceWriter::create(
temp.path(),
"trace-1".to_string(),
"rollout-1".to_string(),
thread_id.to_string(),
)?;
start_thread(&writer, thread_id, agent_path)?;
Ok(writer)
}
pub(crate) fn start_thread(
writer: &TraceWriter,
thread_id: &str,
agent_path: &str,
) -> anyhow::Result<()> {
writer.append(RawTraceEventPayload::ThreadStarted {
thread_id: thread_id.to_string(),
agent_path: agent_path.to_string(),
metadata_payload: None,
})?;
Ok(())
}
pub(crate) fn start_turn(writer: &TraceWriter, turn_id: &str) -> anyhow::Result<()> {
start_turn_for_thread(writer, ROOT_THREAD_ID, turn_id)
}
pub(crate) fn start_agent_turn(writer: &TraceWriter, turn_id: &str) -> anyhow::Result<()> {
start_turn_for_thread(writer, AGENT_ROOT_THREAD_ID, turn_id)
}
pub(crate) fn start_turn_for_thread(
writer: &TraceWriter,
thread_id: &str,
turn_id: &str,
) -> anyhow::Result<()> {
writer.append(RawTraceEventPayload::CodexTurnStarted {
codex_turn_id: turn_id.to_string(),
thread_id: thread_id.to_string(),
})?;
Ok(())
}
pub(crate) fn trace_context(turn_id: &str) -> RawTraceEventContext {
trace_context_for_thread(ROOT_THREAD_ID, turn_id)
}
pub(crate) fn trace_context_for_agent(turn_id: &str) -> RawTraceEventContext {
trace_context_for_thread(AGENT_ROOT_THREAD_ID, turn_id)
}
pub(crate) fn trace_context_for_thread(thread_id: &str, turn_id: &str) -> RawTraceEventContext {
RawTraceEventContext {
thread_id: Some(thread_id.to_string()),
codex_turn_id: Some(turn_id.to_string()),
}
}
pub(crate) fn append_inference_start(
writer: &TraceWriter,
inference_call_id: &str,
codex_turn_id: &str,
request_payload: RawPayloadRef,
) -> anyhow::Result<()> {
append_inference_start_for_thread(
writer,
ROOT_THREAD_ID,
codex_turn_id,
inference_call_id,
request_payload,
)
}
pub(crate) fn append_inference_start_for_thread(
writer: &TraceWriter,
thread_id: &str,
codex_turn_id: &str,
inference_call_id: &str,
request_payload: RawPayloadRef,
) -> anyhow::Result<()> {
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: inference_call_id.to_string(),
thread_id: thread_id.to_string(),
codex_turn_id: codex_turn_id.to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload,
})?;
Ok(())
}
pub(crate) fn append_inference_completion(
writer: &TraceWriter,
inference_call_id: &str,
response_id: &str,
response_payload: RawPayloadRef,
) -> anyhow::Result<()> {
writer.append(RawTraceEventPayload::InferenceCompleted {
inference_call_id: inference_call_id.to_string(),
response_id: Some(response_id.to_string()),
upstream_request_id: None,
response_payload,
})?;
Ok(())
}
pub(crate) fn append_inference_request(
writer: &TraceWriter,
thread_id: &str,
turn_id: &str,
inference_id: &str,
input: Vec<serde_json::Value>,
) -> anyhow::Result<()> {
let request =
writer.write_json_payload(RawPayloadKind::InferenceRequest, &json!({ "input": input }))?;
append_inference_start_for_thread(writer, thread_id, turn_id, inference_id, request)
}
pub(crate) fn append_completed_inference(
writer: &TraceWriter,
thread_id: &str,
turn_id: &str,
inference_id: &str,
input: Vec<serde_json::Value>,
output_items: Vec<serde_json::Value>,
) -> anyhow::Result<()> {
append_inference_request(writer, thread_id, turn_id, inference_id, input)?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": format!("resp-{inference_id}"),
"output_items": output_items,
}),
)?;
writer.append_with_context(
trace_context_for_thread(thread_id, turn_id),
RawTraceEventPayload::InferenceCompleted {
inference_call_id: inference_id.to_string(),
response_id: Some(format!("resp-{inference_id}")),
upstream_request_id: None,
response_payload: response,
},
)?;
Ok(())
}
pub(crate) fn expect_replay_error(temp: &TempDir, expected: &str) -> anyhow::Result<()> {
let Err(err) = replay_bundle(temp.path()) else {
panic!("expected replay error containing {expected}");
};
let message = err.to_string();
assert!(message.contains(expected), "unexpected error: {message}");
Ok(())
}

View File

@@ -0,0 +1,294 @@
//! Thread and turn reduction.
//!
//! Threads are the container that every other reducer module links into. This
//! module owns the identity metadata parsing as well, so the central dispatcher
//! does not need to know the shape of multi-agent session-source payloads.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use anyhow::ensure;
use serde::Deserialize;
use serde_json::Value;
use super::TraceReducer;
use super::tool::spawn_edge_id;
use crate::model::AgentOrigin;
use crate::model::AgentThread;
use crate::model::CodexTurn;
use crate::model::CodexTurnId;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::model::RolloutStatus;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawEventSeq;
impl TraceReducer {
/// Inserts a thread and derives its multi-agent identity from optional metadata.
///
/// The raw event carries a denormalized agent path; when v2 subagent metadata is
/// present, that metadata is authoritative because it also drives spawn edges and task names.
pub(super) fn start_thread(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: String,
agent_path: String,
metadata_payload: Option<RawPayloadRef>,
) -> Result<()> {
if self.rollout.threads.contains_key(&thread_id) {
bail!("duplicate thread start for {thread_id}");
}
let metadata = metadata_payload
.as_ref()
.map(|payload| self.thread_started_metadata(payload))
.transpose()?;
let spawn = metadata
.as_ref()
.and_then(ThreadStartedMetadata::thread_spawn);
// The v2 SessionSource is the authoritative child identity record.
// Prefer its nested agent_path over the denormalized event field so
// task derivation and the spawn edge are based on the same metadata.
let agent_path = spawn
.as_ref()
.and_then(|spawn| spawn.agent_path.clone())
.or_else(|| {
metadata
.as_ref()
.and_then(|metadata| metadata.agent_path.clone())
})
.unwrap_or(agent_path);
let nickname = metadata
.as_ref()
.and_then(|metadata| metadata.nickname.clone());
let default_model = metadata
.as_ref()
.and_then(|metadata| metadata.model.clone());
let origin = if let Some(spawn) = spawn {
let edge_id = spawn_edge_id(&spawn.parent_thread_id, &thread_id);
let task_name = spawn
.task_name
.clone()
.unwrap_or_else(|| task_name_from_agent_path(&agent_path));
let agent_role = spawn.agent_role.clone().unwrap_or_default();
AgentOrigin::Spawned {
parent_thread_id: spawn.parent_thread_id,
spawn_edge_id: edge_id,
task_name,
agent_role,
}
} else {
AgentOrigin::Root
};
self.rollout.threads.insert(
thread_id.clone(),
AgentThread {
thread_id,
agent_path,
nickname,
origin,
execution: ExecutionWindow {
started_at_unix_ms: wall_time_unix_ms,
started_seq: seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
default_model,
conversation_item_ids: Vec::new(),
},
);
Ok(())
}
/// Reopens a known thread after eviction, preserving its identity and history.
pub(super) fn resume_thread(&mut self, thread_id: &str) -> Result<()> {
let thread = self.thread_mut(thread_id).with_context(|| {
format!(
"cannot resume thread {thread_id}: it was not started in this trace; resuming threads from an earlier trace is not supported"
)
})?;
ensure!(
thread.execution.ended_seq.is_some(),
"resumed thread {thread_id} has not ended"
);
thread.execution.ended_at_unix_ms = None;
thread.execution.ended_seq = None;
thread.execution.status = ExecutionStatus::Running;
// Reload creates fresh cell and process namespaces. Historical objects
// remain, but their runtime handles must not resolve in the new session.
self.code_cell_ids_by_runtime
.retain(|(owner, _), _| owner != thread_id);
self.terminal_ids_by_process
.retain(|(owner, _), _| owner != thread_id);
Ok(())
}
/// Marks a thread terminal without treating child shutdown as rollout completion.
pub(super) fn end_thread(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: String,
status: RolloutStatus,
) -> Result<()> {
let thread = self.thread_mut(&thread_id)?;
thread.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
thread.execution.ended_seq = Some(seq);
thread.execution.status = match status {
RolloutStatus::Running => ExecutionStatus::Running,
RolloutStatus::Completed => ExecutionStatus::Completed,
RolloutStatus::Failed => ExecutionStatus::Failed,
RolloutStatus::Aborted => ExecutionStatus::Aborted,
};
Ok(())
}
/// Starts a Codex turn inside an existing thread.
pub(super) fn start_codex_turn(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
codex_turn_id: CodexTurnId,
thread_id: String,
) -> Result<()> {
if self.rollout.codex_turns.contains_key(&codex_turn_id) {
bail!("duplicate codex turn start for {codex_turn_id}");
}
self.thread_mut(&thread_id)?;
self.rollout.codex_turns.insert(
codex_turn_id.clone(),
CodexTurn {
codex_turn_id,
thread_id,
execution: ExecutionWindow {
started_at_unix_ms: wall_time_unix_ms,
started_seq: seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
input_item_ids: Vec::new(),
},
);
Ok(())
}
/// Marks a Codex turn terminal and validates any thread id carried by the raw event.
pub(super) fn end_codex_turn(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: Option<String>,
codex_turn_id: CodexTurnId,
status: ExecutionStatus,
) -> Result<()> {
if let Some(event_thread_id) = thread_id.as_deref()
&& let Some(turn) = self.rollout.codex_turns.get(&codex_turn_id)
&& turn.thread_id != event_thread_id
{
bail!(
"codex turn end for {codex_turn_id} used thread {event_thread_id}, \
but the turn belongs to {}",
turn.thread_id
);
}
let Some(turn) = self.rollout.codex_turns.get_mut(&codex_turn_id) else {
bail!("codex turn end referenced unknown turn {codex_turn_id}");
};
turn.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
turn.execution.ended_seq = Some(seq);
turn.execution.status = status.clone();
self.terminate_running_code_cells_for_turn_end(
seq,
wall_time_unix_ms,
&codex_turn_id,
&status,
)?;
self.close_running_inference_calls_for_turn_end(
seq,
wall_time_unix_ms,
&codex_turn_id,
&status,
);
Ok(())
}
/// Returns a mutable thread or reports a reducer error tied to the unknown id.
pub(super) fn thread_mut(&mut self, thread_id: &str) -> Result<&mut AgentThread> {
self.rollout
.threads
.get_mut(thread_id)
.with_context(|| format!("trace event referenced unknown thread {thread_id}"))
}
fn thread_started_metadata(
&self,
metadata_payload: &RawPayloadRef,
) -> Result<ThreadStartedMetadata> {
let value = self.read_payload_json(metadata_payload)?;
serde_json::from_value(value)
.with_context(|| format!("parse thread metadata {}", metadata_payload.raw_payload_id))
}
}
#[derive(Deserialize)]
struct ThreadStartedMetadata {
agent_path: Option<String>,
task_name: Option<String>,
nickname: Option<String>,
agent_role: Option<String>,
model: Option<String>,
session_source: Option<Value>,
}
impl ThreadStartedMetadata {
fn thread_spawn(&self) -> Option<ThreadSpawnMetadata> {
let spawn = self
.session_source
.as_ref()?
.get("subagent")?
.get("thread_spawn")?;
let agent_path = spawn
.get("agent_path")
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| self.agent_path.clone());
Some(ThreadSpawnMetadata {
parent_thread_id: spawn.get("parent_thread_id")?.as_str()?.to_string(),
agent_path: agent_path.clone(),
task_name: spawn
.get("task_name")
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| self.task_name.clone())
.or_else(|| agent_path.as_deref().map(task_name_from_agent_path)),
agent_role: spawn
.get("agent_role")
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| self.agent_role.clone()),
})
}
}
struct ThreadSpawnMetadata {
parent_thread_id: String,
agent_path: Option<String>,
task_name: Option<String>,
agent_role: Option<String>,
}
fn task_name_from_agent_path(agent_path: &str) -> String {
agent_path
.rsplit('/')
.find(|segment| !segment.is_empty())
.unwrap_or(agent_path)
.to_string()
}

View File

@@ -0,0 +1,521 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use super::TraceReducer;
use crate::model::CodeModeRuntimeToolId;
use crate::model::ConversationItemKind;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::model::McpCallId;
use crate::model::ModelVisibleCallId;
use crate::model::ProducerRef;
use crate::model::ToolCall;
use crate::model::ToolCallId;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawEventSeq;
use crate::raw_event::RawToolCallRequester;
mod agents;
mod terminal;
#[cfg(test)]
#[path = "tool/mcp_tests.rs"]
mod mcp_tests;
pub(super) use agents::ObservedAgentResultEdge;
pub(super) use agents::PendingAgentInteractionEdge;
pub(super) use agents::spawn_edge_id;
/// Raw tool-start fields after dispatch has stripped the common event envelope.
///
/// Tool starts carry several optional identity namespaces: model-visible calls,
/// code-mode runtime tools, and canonical invocation payloads. Grouping them keeps
/// the reducer callsite readable and avoids positional argument mistakes.
pub(super) struct ToolCallStarted {
pub(super) tool_call_id: ToolCallId,
pub(super) model_visible_call_id: Option<ModelVisibleCallId>,
pub(super) code_mode_runtime_tool_id: Option<CodeModeRuntimeToolId>,
pub(super) requester: RawToolCallRequester,
pub(super) kind: ToolCallKind,
pub(super) summary: ToolCallSummary,
pub(super) invocation_payload: Option<RawPayloadRef>,
}
impl TraceReducer {
/// Starts a tool call and links it to model-visible items or runtime parents when available.
///
/// Some tools also create richer domain objects, such as terminal operations, from
/// the same invocation payload. The generic ToolCall remains the common index.
pub(super) fn start_tool_call(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: Option<String>,
codex_turn_id: Option<String>,
started: ToolCallStarted,
) -> Result<()> {
let tool_call_id = started.tool_call_id.clone();
if self.rollout.tool_calls.contains_key(&tool_call_id) {
bail!("duplicate tool call start for {tool_call_id}");
}
self.ensure_unique_model_visible_tool_call(
started.model_visible_call_id.as_deref(),
&tool_call_id,
)?;
let thread_id = self.tool_thread_id(thread_id, codex_turn_id.as_deref())?;
self.validate_tool_turn(&thread_id, codex_turn_id.as_deref())?;
let model_visible_call_id = started.model_visible_call_id.clone();
let requester = self.reduce_tool_call_requester(&thread_id, started.requester.clone())?;
let model_visible_call_item_ids = model_visible_call_id
.as_deref()
.map(|call_id| {
self.model_visible_tool_item_ids(
&thread_id,
call_id,
&[
ConversationItemKind::FunctionCall,
ConversationItemKind::CustomToolCall,
],
)
})
.unwrap_or_default();
let model_visible_output_item_ids = model_visible_call_id
.as_deref()
.map(|call_id| {
self.model_visible_tool_item_ids(
&thread_id,
call_id,
&[
ConversationItemKind::FunctionCallOutput,
ConversationItemKind::CustomToolCallOutput,
],
)
})
.unwrap_or_default();
self.thread_mut(&thread_id)?;
// write_stdin has no protocol runtime-begin event, so its request comes
// from the canonical invocation. Runtime resolution can refine its session link.
let terminal_operation_id = self.start_terminal_operation_from_invocation(
seq,
wall_time_unix_ms,
&thread_id,
&tool_call_id,
&started.kind,
started.invocation_payload.as_ref(),
)?;
// Terminal-backed tools should render through the richer terminal
// operation instead of the generic tool summary captured by producers.
let summary = terminal_operation_id
.as_ref()
.map(|operation_id| ToolCallSummary::Terminal {
operation_id: operation_id.clone(),
})
.unwrap_or(started.summary);
let raw_invocation_payload_id = started
.invocation_payload
.as_ref()
.map(|payload| payload.raw_payload_id.clone());
self.link_wait_tool_call_from_request_payload(
&thread_id,
&tool_call_id,
started.invocation_payload.as_ref(),
)?;
self.rollout.tool_calls.insert(
tool_call_id.clone(),
ToolCall {
tool_call_id: tool_call_id.clone(),
mcp_call_id: None,
model_visible_call_id,
code_mode_runtime_tool_id: started.code_mode_runtime_tool_id,
started_code_cell_id: None,
thread_id,
started_by_codex_turn_id: codex_turn_id,
execution: ExecutionWindow {
started_at_unix_ms: wall_time_unix_ms,
started_seq: seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
requester: requester.clone(),
kind: started.kind,
model_visible_call_item_ids,
model_visible_output_item_ids: Vec::new(),
terminal_operation_id,
summary,
raw_invocation_payload_id,
raw_result_payload_id: None,
raw_runtime_payload_ids: Vec::new(),
},
);
self.link_tool_call_to_code_cell(&tool_call_id, &requester)?;
self.link_tool_to_inference_response(&tool_call_id);
// Output items need the reverse ProducerRef edge as well, so attach
// them after insertion through the same helper used by the transcript
// reducer when the output is observed after the tool start.
for item_id in model_visible_output_item_ids {
self.add_tool_output_item(&tool_call_id, &item_id)?;
}
// The call/output items may have been observed before this tool start.
// Re-sync after insertion so terminal observations get both directions
// of the model-visible link.
self.sync_terminal_model_observation(&tool_call_id)?;
Ok(())
}
/// Attaches the bridge-visible MCP UUID after the generic tool call exists.
pub(super) fn assign_mcp_tool_call_correlation(
&mut self,
tool_call_id: ToolCallId,
mcp_call_id: McpCallId,
) -> Result<()> {
let Some(tool_call) = self.rollout.tool_calls.get_mut(&tool_call_id) else {
bail!("MCP correlation referenced unknown tool call {tool_call_id}");
};
if tool_call.mcp_call_id.replace(mcp_call_id).is_some() {
bail!("duplicate MCP correlation for tool call {tool_call_id}");
}
Ok(())
}
/// Completes the canonical tool call and any terminal operation driven by dispatch output.
///
/// Protocol-backed terminal tools end from runtime events; direct tools
/// may only have the canonical result payload, so this method handles both paths.
pub(super) fn end_tool_call(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
tool_call_id: ToolCallId,
status: ExecutionStatus,
result_payload: Option<RawPayloadRef>,
) -> Result<()> {
let (terminal_operation_id, thread_id, end_terminal_from_result) = {
let Some(tool_call) = self.rollout.tool_calls.get_mut(&tool_call_id) else {
bail!("tool call end referenced unknown call {tool_call_id}");
};
tool_call.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
tool_call.execution.ended_seq = Some(seq);
tool_call.execution.status = status.clone();
tool_call.raw_result_payload_id = result_payload
.as_ref()
.map(|payload| payload.raw_payload_id.clone());
(
tool_call.terminal_operation_id.clone(),
tool_call.thread_id.clone(),
// Protocol-backed tools end terminal operations from
// runtime observations. Dispatch result payloads are still kept
// on ToolCall, but they are caller-facing and may be transformed
// relative to the raw terminal output.
tool_call.raw_runtime_payload_ids.is_empty(),
)
};
if end_terminal_from_result && let Some(operation_id) = terminal_operation_id {
self.end_terminal_operation(
seq,
wall_time_unix_ms,
&thread_id,
&operation_id,
status,
result_payload.as_ref(),
)?;
}
self.attach_agent_interaction_tool_result(&tool_call_id, result_payload.as_ref())?;
Ok(())
}
/// Records a runtime-begin observation for an already started tool call.
///
/// Runtime observations enrich the generic tool with protocol facts and may
/// create domain-specific children such as terminal operations or agent edges.
pub(super) fn start_tool_runtime_observation(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
tool_call_id: ToolCallId,
kind: ToolCallKind,
runtime_payload: RawPayloadRef,
) -> Result<()> {
let (thread_id, existing_terminal_operation_id) = {
let Some(tool_call) = self.rollout.tool_calls.get_mut(&tool_call_id) else {
bail!("tool runtime start referenced unknown call {tool_call_id}");
};
// Interception and MCP aliases can route a callable to a different handler.
// Keep its original summary/invocation, but classify execution by that handler.
tool_call.kind = kind.clone();
push_unique(
&mut tool_call.raw_runtime_payload_ids,
&runtime_payload.raw_payload_id,
);
(
tool_call.thread_id.clone(),
tool_call.terminal_operation_id.clone(),
)
};
if existing_terminal_operation_id.is_some()
&& matches!(kind, ToolCallKind::ExecCommand | ToolCallKind::WriteStdin)
{
bail!("tool runtime start would create a second terminal operation for {tool_call_id}");
}
// Protocol begin events carry runtime facts such as process ids and
// cwd. These facts should create terminal rows, but they must not
// replace the canonical invocation payload captured at dispatch.
let terminal_operation_id = self.start_terminal_operation_from_runtime(
seq,
wall_time_unix_ms,
&thread_id,
&tool_call_id,
&kind,
&runtime_payload,
)?;
if let Some(operation_id) = &terminal_operation_id {
let Some(tool_call) = self.rollout.tool_calls.get_mut(&tool_call_id) else {
bail!("tool call {tool_call_id} disappeared during runtime start reduction");
};
if tool_call.terminal_operation_id.is_none() {
tool_call.terminal_operation_id = Some(operation_id.clone());
tool_call.summary = ToolCallSummary::Terminal {
operation_id: operation_id.clone(),
};
}
}
if terminal_operation_id.is_some() {
self.sync_terminal_model_observation(&tool_call_id)?;
}
self.start_agent_interaction_from_runtime(&tool_call_id, &runtime_payload)?;
Ok(())
}
/// Records a runtime-end observation for an already started tool call.
pub(super) fn end_tool_runtime_observation(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
tool_call_id: ToolCallId,
status: ExecutionStatus,
runtime_payload: RawPayloadRef,
) -> Result<()> {
let (thread_id, terminal_operation_id) = {
let Some(tool_call) = self.rollout.tool_calls.get_mut(&tool_call_id) else {
bail!("tool runtime end referenced unknown call {tool_call_id}");
};
push_unique(
&mut tool_call.raw_runtime_payload_ids,
&runtime_payload.raw_payload_id,
);
(
tool_call.thread_id.clone(),
tool_call.terminal_operation_id.clone(),
)
};
if let Some(operation_id) = terminal_operation_id {
self.end_terminal_operation(
seq,
wall_time_unix_ms,
&thread_id,
&operation_id,
status,
Some(&runtime_payload),
)?;
}
self.end_agent_interaction_from_runtime(
wall_time_unix_ms,
&tool_call_id,
&runtime_payload,
)?;
Ok(())
}
/// Attaches a conversation item observed after the tool call was reduced.
///
/// Inference request/response ordering can expose call/output items after the
/// runtime tool object exists, so transcript reduction calls back here to add
/// reverse links without duplicating matching logic.
pub(super) fn attach_model_visible_tool_item(
&mut self,
item_id: &str,
call_id: Option<&str>,
kind: &ConversationItemKind,
) -> Result<()> {
let Some(call_id) = call_id else {
return Ok(());
};
match kind {
ConversationItemKind::FunctionCall | ConversationItemKind::CustomToolCall => {
if let Some(tool_call_id) = self.single_tool_for_model_visible_call(call_id)? {
self.add_tool_call_item(&tool_call_id, item_id)?;
self.link_tool_to_inference_response(&tool_call_id);
self.sync_terminal_model_observation(&tool_call_id)?;
}
}
ConversationItemKind::FunctionCallOutput
| ConversationItemKind::CustomToolCallOutput => {
if let Some(tool_call_id) = self.single_tool_for_model_visible_call(call_id)? {
self.add_tool_output_item(&tool_call_id, item_id)?;
self.sync_terminal_model_observation(&tool_call_id)?;
}
}
ConversationItemKind::Message
| ConversationItemKind::Reasoning
| ConversationItemKind::CompactionMarker => {}
}
Ok(())
}
fn tool_thread_id(
&self,
thread_id: Option<String>,
codex_turn_id: Option<&str>,
) -> Result<String> {
if let Some(thread_id) = thread_id {
return Ok(thread_id);
}
let Some(codex_turn_id) = codex_turn_id else {
bail!("tool call start did not include thread or Codex turn context");
};
self.rollout
.codex_turns
.get(codex_turn_id)
.map(|turn| turn.thread_id.clone())
.with_context(|| {
format!("tool call start referenced unknown Codex turn {codex_turn_id}")
})
}
fn validate_tool_turn(&self, thread_id: &str, codex_turn_id: Option<&str>) -> Result<()> {
if !self.rollout.threads.contains_key(thread_id) {
bail!("tool call start referenced unknown thread {thread_id}");
}
if let Some(codex_turn_id) = codex_turn_id {
let Some(turn) = self.rollout.codex_turns.get(codex_turn_id) else {
bail!("tool call start referenced unknown Codex turn {codex_turn_id}");
};
if turn.thread_id != thread_id {
bail!(
"tool call start used thread {thread_id}, but Codex turn {codex_turn_id} \
belongs to {}",
turn.thread_id
);
}
}
Ok(())
}
fn ensure_unique_model_visible_tool_call(
&self,
model_visible_call_id: Option<&str>,
tool_call_id: &str,
) -> Result<()> {
let Some(model_visible_call_id) = model_visible_call_id else {
return Ok(());
};
if let Some(existing) = self.single_tool_for_model_visible_call(model_visible_call_id)?
&& existing != tool_call_id
{
bail!("duplicate tool call for model-visible call id {model_visible_call_id}");
}
Ok(())
}
fn single_tool_for_model_visible_call(
&self,
model_visible_call_id: &str,
) -> Result<Option<ToolCallId>> {
let mut matching = self
.rollout
.tool_calls
.values()
.filter(|tool| tool.model_visible_call_id.as_deref() == Some(model_visible_call_id))
.map(|tool| tool.tool_call_id.clone());
let first = matching.next();
if matching.next().is_some() {
bail!("multiple tool calls matched model-visible call id {model_visible_call_id}");
}
Ok(first)
}
fn model_visible_tool_item_ids(
&self,
thread_id: &str,
call_id: &str,
kinds: &[ConversationItemKind],
) -> Vec<String> {
// A late tool-start event must link outputs in history order, not map-key order.
self.rollout.threads[thread_id]
.conversation_item_ids
.iter()
.map(|item_id| &self.rollout.conversation_items[item_id])
.filter(|item| item.call_id.as_deref() == Some(call_id) && kinds.contains(&item.kind))
.map(|item| item.item_id.clone())
.collect::<Vec<_>>()
}
fn add_tool_call_item(&mut self, tool_call_id: &str, item_id: &str) -> Result<()> {
let Some(tool_call) = self.rollout.tool_calls.get_mut(tool_call_id) else {
bail!("tool call {tool_call_id} disappeared during conversation linking");
};
push_unique(&mut tool_call.model_visible_call_item_ids, item_id);
Ok(())
}
fn add_tool_output_item(&mut self, tool_call_id: &str, item_id: &str) -> Result<()> {
let Some(tool_call) = self.rollout.tool_calls.get_mut(tool_call_id) else {
bail!("tool call {tool_call_id} disappeared during output linking");
};
push_unique(&mut tool_call.model_visible_output_item_ids, item_id);
let Some(item) = self.rollout.conversation_items.get_mut(item_id) else {
bail!("conversation item {item_id} disappeared during output linking");
};
let producer = ProducerRef::Tool {
tool_call_id: tool_call_id.to_string(),
};
if !item.produced_by.contains(&producer) {
item.produced_by.push(producer);
}
Ok(())
}
fn link_tool_to_inference_response(&mut self, tool_call_id: &str) {
let Some(tool_call) = self.rollout.tool_calls.get(tool_call_id) else {
return;
};
let call_item_ids = tool_call.model_visible_call_item_ids.clone();
if call_item_ids.is_empty() {
return;
}
for inference in self.rollout.inference_calls.values_mut() {
if inference
.response_item_ids
.iter()
.any(|item_id| call_item_ids.contains(item_id))
&& !inference
.tool_call_ids_started_by_response
.contains(&tool_call_id.to_string())
{
inference
.tool_call_ids_started_by_response
.push(tool_call_id.to_string());
}
}
}
}
fn push_unique(items: &mut Vec<String>, item_id: &str) {
if !items.iter().any(|existing| existing == item_id) {
items.push(item_id.to_string());
}
}

View File

@@ -0,0 +1,814 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_protocol::protocol::CollabAgentInteractionBeginEvent;
use codex_protocol::protocol::CollabAgentInteractionEndEvent;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::CollabCloseBeginEvent;
use codex_protocol::protocol::CollabCloseEndEvent;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::SubAgentActivityEvent;
use codex_protocol::protocol::SubAgentActivityKind;
use serde::Deserialize;
use serde_json::Value;
use super::super::TraceReducer;
use crate::model::ConversationItem;
use crate::model::ConversationItemKind;
use crate::model::ConversationPart;
use crate::model::ConversationRole;
use crate::model::InteractionEdge;
use crate::model::InteractionEdgeKind;
use crate::model::ToolCallKind;
use crate::model::TraceAnchor;
use crate::payload::RawPayloadRef;
/// Agent delivery edge waiting for the recipient-side conversation item.
///
/// Multi-agent v2 records the sender tool before the target thread necessarily
/// includes the delivered mailbox message in a model-visible request. The edge
/// stays pending so it can target that exact conversation item when possible.
pub(in crate::reducer) struct PendingAgentInteractionEdge {
pub(in crate::reducer) edge_id: String,
pub(in crate::reducer) kind: InteractionEdgeKind,
pub(in crate::reducer) source: TraceAnchor,
pub(in crate::reducer) target_thread_id: String,
pub(in crate::reducer) message_author: String,
pub(in crate::reducer) message_content: String,
/// Spawn-only fallback for children that fail before their task message is model-visible.
pub(in crate::reducer) unresolved_spawn_thread_id: Option<String>,
pub(in crate::reducer) started_at_unix_ms: i64,
pub(in crate::reducer) ended_at_unix_ms: Option<i64>,
pub(in crate::reducer) carried_raw_payload_ids: Vec<String>,
}
/// Typed reducer input for a multi-agent v2 child completion notification.
///
/// Child results are observed outside the normal tool lifecycle, but they still
/// carry a parent-thread notification. This wrapper keeps the dispatcher from
/// passing a positional bundle of thread and turn ids.
pub(in crate::reducer) struct ObservedAgentResultEdge {
pub(in crate::reducer) wall_time_unix_ms: i64,
pub(in crate::reducer) edge_id: String,
pub(in crate::reducer) child_thread_id: String,
pub(in crate::reducer) child_codex_turn_id: String,
pub(in crate::reducer) parent_thread_id: String,
pub(in crate::reducer) message: String,
pub(in crate::reducer) carried_payload: Option<RawPayloadRef>,
}
#[derive(Deserialize)]
struct AgentMessageInvocationArgs {
message: String,
}
/// Builds the stable edge id for the spawn relationship between two threads.
pub(in crate::reducer) fn spawn_edge_id(parent_thread_id: &str, child_thread_id: &str) -> String {
format!("edge:spawn:{parent_thread_id}:{child_thread_id}")
}
impl TraceReducer {
/// Starts a multi-agent edge from a runtime begin payload, when the tool kind supports one.
pub(super) fn start_agent_interaction_from_runtime(
&mut self,
tool_call_id: &str,
runtime_payload: &RawPayloadRef,
) -> Result<()> {
let kind = self
.rollout
.tool_calls
.get(tool_call_id)
.with_context(|| format!("agent edge referenced unknown tool call {tool_call_id}"))?
.kind
.clone();
match kind {
ToolCallKind::AssignAgentTask => {
let payload: CollabAgentInteractionBeginEvent =
serde_json::from_value(self.read_payload_json(runtime_payload)?)?;
self.queue_message_agent_interaction(
tool_call_id,
InteractionEdgeKind::AssignAgentTask,
payload.receiver_thread_id.to_string(),
payload.prompt,
/*ended_at_unix_ms*/ None,
)
}
ToolCallKind::SendMessage => {
let payload: CollabAgentInteractionBeginEvent =
serde_json::from_value(self.read_payload_json(runtime_payload)?)?;
self.queue_message_agent_interaction(
tool_call_id,
InteractionEdgeKind::SendMessage,
payload.receiver_thread_id.to_string(),
payload.prompt,
/*ended_at_unix_ms*/ None,
)
}
ToolCallKind::CloseAgent => {
let payload: CollabCloseBeginEvent =
serde_json::from_value(self.read_payload_json(runtime_payload)?)?;
self.upsert_close_agent_interaction(
tool_call_id,
payload.receiver_thread_id.to_string(),
/*ended_at_unix_ms*/ None,
)
}
ToolCallKind::ExecCommand
| ToolCallKind::WriteStdin
| ToolCallKind::ApplyPatch
| ToolCallKind::Mcp { .. }
| ToolCallKind::Web
| ToolCallKind::ImageGeneration
| ToolCallKind::SpawnAgent
| ToolCallKind::WaitAgent
| ToolCallKind::Other { .. } => Ok(()),
}
}
/// Ends or enriches a multi-agent edge from a runtime end payload.
pub(super) fn end_agent_interaction_from_runtime(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
runtime_payload: &RawPayloadRef,
) -> Result<()> {
let kind = self.rollout.tool_calls[tool_call_id].kind.clone();
// MCP results are opaque evidence; they cannot describe agent interactions.
if matches!(kind, ToolCallKind::Mcp { .. }) {
return Ok(());
}
let runtime_payload_json = self.read_payload_json(runtime_payload)?;
if runtime_payload_json.get("agent_thread_id").is_some() {
let payload: SubAgentActivityEvent = serde_json::from_value(runtime_payload_json)?;
return self.end_sub_agent_activity(wall_time_unix_ms, tool_call_id, &kind, &payload);
}
match kind {
ToolCallKind::SpawnAgent => {
let payload: CollabAgentSpawnEndEvent =
serde_json::from_value(runtime_payload_json)?;
self.end_spawn_agent_interaction(wall_time_unix_ms, tool_call_id, &payload)
}
ToolCallKind::AssignAgentTask => {
let payload: CollabAgentInteractionEndEvent =
serde_json::from_value(runtime_payload_json)?;
self.end_message_agent_interaction(
wall_time_unix_ms,
tool_call_id,
InteractionEdgeKind::AssignAgentTask,
&payload,
)
}
ToolCallKind::SendMessage => {
let payload: CollabAgentInteractionEndEvent =
serde_json::from_value(runtime_payload_json)?;
self.end_message_agent_interaction(
wall_time_unix_ms,
tool_call_id,
InteractionEdgeKind::SendMessage,
&payload,
)
}
ToolCallKind::CloseAgent => {
let payload: CollabCloseEndEvent = serde_json::from_value(runtime_payload_json)?;
self.upsert_close_agent_interaction(
tool_call_id,
payload.receiver_thread_id.to_string(),
Some(wall_time_unix_ms),
)
}
ToolCallKind::ExecCommand
| ToolCallKind::WriteStdin
| ToolCallKind::ApplyPatch
| ToolCallKind::Mcp { .. }
| ToolCallKind::Web
| ToolCallKind::ImageGeneration
| ToolCallKind::WaitAgent
| ToolCallKind::Other { .. } => Ok(()),
}
}
fn end_sub_agent_activity(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
tool_kind: &ToolCallKind,
payload: &SubAgentActivityEvent,
) -> Result<()> {
let target_thread_id = payload.agent_thread_id.to_string();
match (tool_kind, &payload.kind) {
(ToolCallKind::SpawnAgent, SubAgentActivityKind::Started) => {
let parent_thread_id = self
.rollout
.tool_calls
.get(tool_call_id)
.with_context(|| {
format!("agent activity referenced unknown tool call {tool_call_id}")
})?
.thread_id
.clone();
self.queue_sub_agent_activity_message_edge(
wall_time_unix_ms,
tool_call_id,
spawn_edge_id(&parent_thread_id, &target_thread_id),
InteractionEdgeKind::SpawnAgent,
target_thread_id.clone(),
Some(target_thread_id),
)
}
(ToolCallKind::AssignAgentTask, SubAgentActivityKind::Interacted) => self
.queue_sub_agent_activity_message_edge(
wall_time_unix_ms,
tool_call_id,
tool_edge_id(tool_call_id),
InteractionEdgeKind::AssignAgentTask,
target_thread_id,
/*unresolved_spawn_thread_id*/ None,
),
(ToolCallKind::SendMessage, SubAgentActivityKind::Interacted) => self
.queue_sub_agent_activity_message_edge(
wall_time_unix_ms,
tool_call_id,
tool_edge_id(tool_call_id),
InteractionEdgeKind::SendMessage,
target_thread_id,
/*unresolved_spawn_thread_id*/ None,
),
(ToolCallKind::CloseAgent, SubAgentActivityKind::Interrupted) => self
.upsert_close_agent_interaction(
tool_call_id,
target_thread_id,
Some(wall_time_unix_ms),
),
(_, SubAgentActivityKind::Completed) => Ok(()),
_ => bail!(
"sub-agent activity {:?} does not match tool call kind {tool_kind:?}",
payload.kind
),
}
}
fn queue_sub_agent_activity_message_edge(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
edge_id: String,
edge_kind: InteractionEdgeKind,
target_thread_id: String,
unresolved_spawn_thread_id: Option<String>,
) -> Result<()> {
let tool_call = self.rollout.tool_calls.get(tool_call_id).with_context(|| {
format!("agent activity referenced unknown tool call {tool_call_id}")
})?;
let started_at_unix_ms = tool_call.execution.started_at_unix_ms;
let message_author = self.agent_path_for_thread(&tool_call.thread_id)?;
let message_content = self.agent_message_content_from_invocation(tool_call_id)?;
let carried_raw_payload_ids = self.agent_tool_payload_ids(tool_call_id)?;
self.queue_or_resolve_agent_interaction_edge(PendingAgentInteractionEdge {
edge_id,
kind: edge_kind,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
},
target_thread_id,
message_author,
message_content,
unresolved_spawn_thread_id,
started_at_unix_ms,
ended_at_unix_ms: Some(wall_time_unix_ms),
carried_raw_payload_ids,
})
}
fn agent_message_content_from_invocation(&self, tool_call_id: &str) -> Result<String> {
let tool_call = self.rollout.tool_calls.get(tool_call_id).with_context(|| {
format!("agent activity referenced unknown tool call {tool_call_id}")
})?;
let invocation_payload_id = tool_call
.raw_invocation_payload_id
.as_deref()
.with_context(|| {
format!("agent activity tool call {tool_call_id} missing invocation payload")
})?;
let invocation_payload = self
.rollout
.raw_payloads
.get(invocation_payload_id)
.with_context(|| {
format!(
"agent activity tool call {tool_call_id} referenced missing invocation payload {invocation_payload_id}"
)
})?;
let invocation = self.read_payload_json(invocation_payload)?;
let arguments = invocation
.get("payload")
.and_then(|payload| payload.get("arguments"))
.and_then(Value::as_str)
.with_context(|| {
format!("agent activity tool call {tool_call_id} missing function arguments")
})?;
let args: AgentMessageInvocationArgs = serde_json::from_str(arguments)
.with_context(|| format!("parse agent activity tool call {tool_call_id} arguments"))?;
Ok(args.message)
}
/// Adds the canonical tool result payload to an already reduced multi-agent edge.
pub(super) fn attach_agent_interaction_tool_result(
&mut self,
tool_call_id: &str,
result_payload: Option<&RawPayloadRef>,
) -> Result<()> {
let Some(result_payload) = result_payload else {
return Ok(());
};
if let Some(edge) = self
.rollout
.interaction_edges
.values_mut()
.find(|edge| tool_call_source_matches(&edge.source, tool_call_id))
{
push_unique(
&mut edge.carried_raw_payload_ids,
&result_payload.raw_payload_id,
);
return Ok(());
}
// Agent delivery edges intentionally wait for the recipient-side
// conversation item. Tool end can arrive before that item is
// reduced, so preserve the response payload on the pending edge rather
// than dropping evidence until the delivery materializes.
if let Some(pending) = self
.pending_agent_interaction_edges
.iter_mut()
.find(|pending| tool_call_source_matches(&pending.source, tool_call_id))
{
push_unique(
&mut pending.carried_raw_payload_ids,
&result_payload.raw_payload_id,
);
}
Ok(())
}
fn end_spawn_agent_interaction(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
payload: &CollabAgentSpawnEndEvent,
) -> Result<()> {
let Some(child_thread_id) = payload.new_thread_id else {
return Ok(());
};
let tool_call = &self.rollout.tool_calls[tool_call_id];
let child_thread_id = child_thread_id.to_string();
let edge_id = spawn_edge_id(&payload.sender_thread_id.to_string(), &child_thread_id);
let message_author = self.agent_path_for_thread(&tool_call.thread_id)?;
self.queue_or_resolve_agent_interaction_edge(PendingAgentInteractionEdge {
edge_id,
kind: InteractionEdgeKind::SpawnAgent,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
},
target_thread_id: child_thread_id.clone(),
message_author,
message_content: payload.prompt.clone(),
unresolved_spawn_thread_id: Some(child_thread_id),
started_at_unix_ms: tool_call.execution.started_at_unix_ms,
ended_at_unix_ms: Some(wall_time_unix_ms),
carried_raw_payload_ids: self.agent_tool_payload_ids(tool_call_id)?,
})
}
fn end_message_agent_interaction(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
edge_kind: InteractionEdgeKind,
payload: &CollabAgentInteractionEndEvent,
) -> Result<()> {
self.queue_message_agent_interaction(
tool_call_id,
edge_kind,
payload.receiver_thread_id.to_string(),
payload.prompt.clone(),
Some(wall_time_unix_ms),
)
}
fn queue_message_agent_interaction(
&mut self,
tool_call_id: &str,
kind: InteractionEdgeKind,
target_thread_id: String,
message_content: String,
ended_at_unix_ms: Option<i64>,
) -> Result<()> {
let tool_call = &self.rollout.tool_calls[tool_call_id];
let message_author = self.agent_path_for_thread(&tool_call.thread_id)?;
self.queue_or_resolve_agent_interaction_edge(PendingAgentInteractionEdge {
edge_id: tool_edge_id(tool_call_id),
kind,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
},
target_thread_id,
message_author,
message_content,
unresolved_spawn_thread_id: None,
started_at_unix_ms: tool_call.execution.started_at_unix_ms,
ended_at_unix_ms,
carried_raw_payload_ids: self.agent_tool_payload_ids(tool_call_id)?,
})
}
fn agent_tool_payload_ids(&self, tool_call_id: &str) -> Result<Vec<String>> {
let tool_call =
self.rollout.tool_calls.get(tool_call_id).with_context(|| {
format!("agent edge referenced unknown tool call {tool_call_id}")
})?;
let mut payload_ids = Vec::new();
if let Some(payload_id) = &tool_call.raw_invocation_payload_id {
push_unique(&mut payload_ids, payload_id);
}
for payload_id in &tool_call.raw_runtime_payload_ids {
push_unique(&mut payload_ids, payload_id);
}
if let Some(payload_id) = &tool_call.raw_result_payload_id {
push_unique(&mut payload_ids, payload_id);
}
Ok(payload_ids)
}
fn upsert_close_agent_interaction(
&mut self,
tool_call_id: &str,
target_thread_id: String,
ended_at_unix_ms: Option<i64>,
) -> Result<()> {
if !self.rollout.threads.contains_key(&target_thread_id) {
// A failed close can name a thread that never participated in this
// trace. Keep that evidence on the ToolCall raw payloads rather
// than creating an anchor to a non-existent reduced object.
return Ok(());
}
let started_at_unix_ms = self
.rollout
.tool_calls
.get(tool_call_id)
.with_context(|| format!("close edge referenced unknown tool call {tool_call_id}"))?
.execution
.started_at_unix_ms;
let carried_raw_payload_ids = self.agent_tool_payload_ids(tool_call_id)?;
self.upsert_interaction_edge(InteractionEdge {
edge_id: tool_edge_id(tool_call_id),
kind: InteractionEdgeKind::CloseAgent,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
},
target: TraceAnchor::Thread {
thread_id: target_thread_id,
},
started_at_unix_ms,
ended_at_unix_ms,
carried_item_ids: Vec::new(),
carried_raw_payload_ids,
})
}
/// Queues or resolves the edge from a child completion to its parent notification.
pub(in crate::reducer) fn queue_agent_result_interaction_edge(
&mut self,
observed: ObservedAgentResultEdge,
) -> Result<()> {
let message_author = self.agent_path_for_thread(&observed.child_thread_id)?;
let source = if let Some(source_item_id) = self.latest_assistant_message_item_for_turn(
&observed.child_thread_id,
&observed.child_codex_turn_id,
) {
TraceAnchor::ConversationItem {
item_id: source_item_id,
}
} else {
// Child completion is delivered from AgentStatus, not from transcript
// content. Failed or cancelled children can therefore notify the parent
// without producing a final assistant message. Anchor those edges to
// the child thread so the trace keeps the valid delivery instead of
// inventing a missing conversation item.
TraceAnchor::Thread {
thread_id: observed.child_thread_id,
}
};
self.queue_or_resolve_agent_interaction_edge(PendingAgentInteractionEdge {
edge_id: observed.edge_id,
kind: InteractionEdgeKind::AgentResult,
source,
target_thread_id: observed.parent_thread_id,
message_author,
message_content: observed.message,
unresolved_spawn_thread_id: None,
started_at_unix_ms: observed.wall_time_unix_ms,
ended_at_unix_ms: Some(observed.wall_time_unix_ms),
carried_raw_payload_ids: observed
.carried_payload
.map(|payload| vec![payload.raw_payload_id])
.unwrap_or_default(),
})
}
/// Resolves pending agent edges whose target is the newly reduced conversation item.
pub(in crate::reducer) fn resolve_pending_agent_edges_for_item(
&mut self,
item_id: &str,
) -> Result<()> {
if self.is_interaction_edge_target_item(item_id) {
return Ok(());
}
let Some((thread_id, message_author, message_content)) =
self.inter_agent_message_item(item_id)
else {
return Ok(());
};
let Some(pending_index) = self
.pending_agent_interaction_edges
.iter()
.position(|pending| {
pending.target_thread_id == thread_id
&& pending.message_author == message_author
&& pending.message_content == message_content
})
else {
return Ok(());
};
let pending = self.pending_agent_interaction_edges.remove(pending_index);
self.upsert_agent_interaction_edge_for_item(pending, item_id.to_string())
}
fn queue_or_resolve_agent_interaction_edge(
&mut self,
pending: PendingAgentInteractionEdge,
) -> Result<()> {
if let Some(item_id) = self.find_unlinked_inter_agent_message_item(
&pending.target_thread_id,
&pending.message_author,
&pending.message_content,
) {
return self.upsert_agent_interaction_edge_for_item(pending, item_id);
}
if let Some(existing) = self
.pending_agent_interaction_edges
.iter_mut()
.find(|existing| existing.edge_id == pending.edge_id)
{
if existing.kind != pending.kind
|| existing.source != pending.source
|| existing.target_thread_id != pending.target_thread_id
|| existing.message_author != pending.message_author
|| existing.message_content != pending.message_content
|| existing.unresolved_spawn_thread_id != pending.unresolved_spawn_thread_id
{
bail!(
"pending interaction edge {} was observed with conflicting delivery data",
pending.edge_id
);
}
existing.started_at_unix_ms =
existing.started_at_unix_ms.min(pending.started_at_unix_ms);
existing.ended_at_unix_ms = match (existing.ended_at_unix_ms, pending.ended_at_unix_ms)
{
(Some(existing_ended), Some(pending_ended)) => {
Some(existing_ended.max(pending_ended))
}
(None, ended) | (ended, None) => ended,
};
extend_unique(
&mut existing.carried_raw_payload_ids,
pending.carried_raw_payload_ids,
);
return Ok(());
}
self.pending_agent_interaction_edges.push(pending);
Ok(())
}
/// Materializes unresolved spawn edges that have a valid child-thread fallback target.
pub(in crate::reducer) fn resolve_pending_spawn_edge_fallbacks(&mut self) -> Result<()> {
let pending_edges = std::mem::take(&mut self.pending_agent_interaction_edges);
for pending in pending_edges {
let Some(child_thread_id) = pending.unresolved_spawn_thread_id else {
continue;
};
if pending.kind != InteractionEdgeKind::SpawnAgent {
bail!(
"non-spawn interaction edge {} carried a spawn fallback target",
pending.edge_id
);
}
if !self.rollout.threads.contains_key(&child_thread_id) {
continue;
}
// Spawn normally resolves to the child task message because that is
// where the delegated work first becomes model-visible. A child can
// fail before that transcript item exists, but the spawned thread is
// still real and the spawning tool still created it. Preserve that
// relationship with the thread fallback instead of dropping the edge.
self.upsert_interaction_edge(InteractionEdge {
edge_id: pending.edge_id,
kind: pending.kind,
source: pending.source,
target: TraceAnchor::Thread {
thread_id: child_thread_id,
},
started_at_unix_ms: pending.started_at_unix_ms,
ended_at_unix_ms: pending.ended_at_unix_ms,
carried_item_ids: Vec::new(),
carried_raw_payload_ids: pending.carried_raw_payload_ids,
})?;
}
Ok(())
}
fn upsert_agent_interaction_edge_for_item(
&mut self,
pending: PendingAgentInteractionEdge,
target_item_id: String,
) -> Result<()> {
self.upsert_interaction_edge(InteractionEdge {
edge_id: pending.edge_id,
kind: pending.kind,
source: pending.source,
target: TraceAnchor::ConversationItem {
item_id: target_item_id.clone(),
},
started_at_unix_ms: pending.started_at_unix_ms,
ended_at_unix_ms: pending.ended_at_unix_ms,
carried_item_ids: vec![target_item_id],
carried_raw_payload_ids: pending.carried_raw_payload_ids,
})
}
fn upsert_interaction_edge(&mut self, edge: InteractionEdge) -> Result<()> {
if let Some(existing) = self.rollout.interaction_edges.get_mut(&edge.edge_id) {
if existing.kind != edge.kind
|| existing.source != edge.source
|| existing.target != edge.target
{
bail!(
"interaction edge {} was observed with conflicting endpoints",
edge.edge_id
);
}
existing.started_at_unix_ms = existing.started_at_unix_ms.min(edge.started_at_unix_ms);
existing.ended_at_unix_ms = match (existing.ended_at_unix_ms, edge.ended_at_unix_ms) {
(Some(existing_ended), Some(edge_ended)) => Some(existing_ended.max(edge_ended)),
(None, ended) | (ended, None) => ended,
};
extend_unique(&mut existing.carried_item_ids, edge.carried_item_ids);
extend_unique(
&mut existing.carried_raw_payload_ids,
edge.carried_raw_payload_ids,
);
return Ok(());
}
self.rollout
.interaction_edges
.insert(edge.edge_id.clone(), edge);
Ok(())
}
fn find_unlinked_inter_agent_message_item(
&self,
thread_id: &str,
message_author: &str,
message_content: &str,
) -> Option<String> {
self.rollout
.threads
.get(thread_id)?
.conversation_item_ids
.iter()
.find(|item_id| {
!self.is_interaction_edge_target_item(item_id)
&& self
.inter_agent_message_item(item_id)
.is_some_and(|(_, author, content)| {
author == message_author && content == message_content
})
})
.cloned()
}
fn inter_agent_message_item(&self, item_id: &str) -> Option<(String, String, String)> {
let item = self.rollout.conversation_items.get(item_id)?;
let (author_agent_path, recipient_agent_path, message_content) =
inter_agent_message_fields(item)?;
let thread = self.rollout.threads.get(&item.thread_id)?;
if recipient_agent_path != thread.agent_path {
return None;
}
Some((item.thread_id.clone(), author_agent_path, message_content))
}
fn agent_path_for_thread(&self, thread_id: &str) -> Result<String> {
self.rollout
.threads
.get(thread_id)
.map(|thread| thread.agent_path.clone())
.with_context(|| format!("agent edge referenced unknown thread {thread_id}"))
}
fn is_interaction_edge_target_item(&self, item_id: &str) -> bool {
self.rollout
.interaction_edges
.values()
.any(|edge| matches!(&edge.target, TraceAnchor::ConversationItem { item_id: target } if target == item_id))
}
fn latest_assistant_message_item_for_turn(
&self,
thread_id: &str,
codex_turn_id: &str,
) -> Option<String> {
self.rollout
.conversation_items
.values()
.filter(|item| {
item.thread_id == thread_id
&& item.codex_turn_id.as_deref() == Some(codex_turn_id)
&& item.role == ConversationRole::Assistant
&& item.kind == ConversationItemKind::Message
&& item.agent_message.is_none()
})
.max_by_key(|item| item.first_seen_at_unix_ms)
.map(|item| item.item_id.clone())
}
}
fn extend_unique(items: &mut Vec<String>, new_items: Vec<String>) {
for item in new_items {
if !items.iter().any(|existing| existing == &item) {
items.push(item);
}
}
}
fn tool_edge_id(tool_call_id: &str) -> String {
format!("edge:tool:{tool_call_id}")
}
fn tool_call_source_matches(anchor: &TraceAnchor, tool_call_id: &str) -> bool {
matches!(anchor, TraceAnchor::ToolCall { tool_call_id: source } if source == tool_call_id)
}
fn push_unique(items: &mut Vec<String>, item: &str) {
if !items.iter().any(|existing| existing == item) {
items.push(item.to_string());
}
}
fn inter_agent_message_fields(item: &ConversationItem) -> Option<(String, String, String)> {
if item.role != ConversationRole::Assistant || item.kind != ConversationItemKind::Message {
return None;
}
if let Some(agent_message) = &item.agent_message {
let message_content = match item.body.parts.as_slice() {
[ConversationPart::Text { text }] => text,
[ConversationPart::Encoded { label, value }] if label == "encrypted_content" => value,
[
ConversationPart::Text { .. },
ConversationPart::Encoded { label, value },
] if label == "encrypted_content" => value,
_ => return None,
};
return Some((
agent_message.author.clone(),
agent_message.recipient.clone(),
message_content.clone(),
));
}
// Older traces store multi-agent v2 deliveries as assistant messages whose
// text is serialized `InterAgentCommunication`. Treat only that exact
// transport shape as an edge target; ordinary assistant JSON must not be
// mistaken for cross-thread delivery.
let [ConversationPart::Text { text }] = item.body.parts.as_slice() else {
return None;
};
let communication = serde_json::from_str::<InterAgentCommunication>(text).ok()?;
Some((
communication.author.to_string(),
communication.recipient.to_string(),
communication
.encrypted_content
.unwrap_or(communication.content),
))
}
#[cfg(test)]
#[path = "agents_tests.rs"]
mod tests;

View File

@@ -0,0 +1,994 @@
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::model::AgentOrigin;
use crate::model::ExecutionStatus;
use crate::model::InteractionEdgeKind;
use crate::model::RolloutStatus;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::model::TraceAnchor;
use crate::payload::RawPayloadKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawToolCallRequester;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::append_completed_inference;
use crate::reducer::test_support::append_inference_request;
use crate::reducer::test_support::create_started_agent_writer;
use crate::reducer::test_support::message;
use crate::reducer::test_support::start_agent_turn;
use crate::reducer::test_support::start_thread;
use crate::reducer::test_support::start_turn_for_thread;
use crate::reducer::test_support::trace_context_for_agent;
use crate::reducer::test_support::trace_context_for_thread;
use crate::replay_bundle;
use crate::writer::TraceWriter;
#[test]
fn child_thread_metadata_creates_spawn_origin_without_delivery_edge() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = TraceWriter::create(
temp.path(),
"trace-1".to_string(),
"rollout-1".to_string(),
"019d0000-0000-7000-8000-000000000002".to_string(),
)?;
let metadata = writer.write_json_payload(
RawPayloadKind::SessionMetadata,
&json!({
"nickname": "James",
"agent_role": "explorer",
"task_name": "repo_file_counter",
"model": "gpt-test",
"session_source": {
"subagent": {
"thread_spawn": {
"parent_thread_id": "019d0000-0000-7000-8000-000000000001",
"agent_path": "/root/repo_file_counter",
"agent_nickname": "James",
"agent_role": "explorer"
}
}
}
}),
)?;
writer.append(RawTraceEventPayload::ThreadStarted {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
agent_path: "/root/repo_file_counter".to_string(),
metadata_payload: Some(metadata),
})?;
let replayed = replay_bundle(temp.path())?;
let thread = &replayed.threads["019d0000-0000-7000-8000-000000000002"];
assert_eq!(thread.nickname, Some("James".to_string()));
assert_eq!(thread.default_model, Some("gpt-test".to_string()));
assert_eq!(
thread.origin,
AgentOrigin::Spawned {
parent_thread_id: "019d0000-0000-7000-8000-000000000001".to_string(),
spawn_edge_id: "edge:spawn:019d0000-0000-7000-8000-000000000001:019d0000-0000-7000-8000-000000000002".to_string(),
task_name: "repo_file_counter".to_string(),
agent_role: "explorer".to_string(),
}
);
assert!(
!replayed.interaction_edges.contains_key(
"edge:spawn:019d0000-0000-7000-8000-000000000001:019d0000-0000-7000-8000-000000000002"
),
"spawn metadata identifies the child, but the delivery edge waits for the recipient \
conversation item"
);
Ok(())
}
#[test]
fn spawn_runtime_payload_targets_delivered_child_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let spawn_payloads = append_spawn_agent_tool_lifecycle(&writer, "turn-1")?;
// Then record the child-side model-visible task message. This is the
// preferred target because it pinpoints where the delegated work entered
// the child timeline.
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/repo_file_counter",
)?;
start_turn_for_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
)?;
let delivered = inter_agent_message(
"/root",
"/root/repo_file_counter",
"count",
/*trigger_turn*/ true,
);
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
"inference-child-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:spawn:019d0000-0000-7000-8000-000000000001:019d0000-0000-7000-8000-000000000002"];
assert_eq!(edge.kind, InteractionEdgeKind::SpawnAgent);
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-spawn".to_string()
}
);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
"019d0000-0000-7000-8000-000000000002"
);
assert_eq!(
edge.carried_raw_payload_ids,
vec![
spawn_payloads.invocation.raw_payload_id,
spawn_payloads.begin.raw_payload_id,
spawn_payloads.end.raw_payload_id,
spawn_payloads.result.raw_payload_id,
]
);
Ok(())
}
#[test]
fn spawn_runtime_payload_falls_back_to_child_thread_without_delivery_item() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let spawn_payloads = append_spawn_agent_tool_lifecycle(&writer, "turn-1")?;
// Deliberately start the child thread without appending an inference
// request containing the inter-agent task message. This reproduces the
// failure path where the child aborts before the reducer can target the
// precise child-side ConversationItem.
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/repo_file_counter",
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:spawn:019d0000-0000-7000-8000-000000000001:019d0000-0000-7000-8000-000000000002"];
assert_eq!(edge.kind, InteractionEdgeKind::SpawnAgent);
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-spawn".to_string()
}
);
assert_eq!(
edge.target,
TraceAnchor::Thread {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string()
}
);
// No transcript item carried the task, so the fallback edge should not
// claim one. The raw payloads still preserve the tool evidence.
assert!(edge.carried_item_ids.is_empty());
assert_eq!(
edge.carried_raw_payload_ids,
vec![
spawn_payloads.invocation.raw_payload_id,
spawn_payloads.begin.raw_payload_id,
spawn_payloads.end.raw_payload_id,
spawn_payloads.result.raw_payload_id,
]
);
Ok(())
}
#[test]
fn sub_agent_started_activity_creates_spawn_edge() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let child_thread_id = "019d0000-0000-7000-8000-000000000002";
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "spawn_agent",
"payload": {
"type": "function",
"arguments": "{\"message\":\"review this\",\"task_name\":\"reviewer\"}"
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-spawn-v2".to_string(),
model_visible_call_id: Some("call-spawn-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::SpawnAgent,
summary: ToolCallSummary::Generic {
label: "spawn_agent".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload.clone()),
},
)?;
let activity_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"event_id": "call-spawn-v2",
"occurred_at_ms": 1234,
"agent_thread_id": child_thread_id,
"agent_path": "/root/reviewer",
"kind": "started"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-spawn-v2".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
)?;
start_thread(&writer, child_thread_id, "/root/reviewer")?;
start_turn_for_thread(&writer, child_thread_id, "turn-child-1")?;
append_inference_request(
&writer,
child_thread_id,
"turn-child-1",
"inference-child-1",
vec![json!({
"type": "agent_message",
"author": "/root",
"recipient": "/root/reviewer",
"content": [
{
"type": "input_text",
"text": "Message Type: NEW_TASK\nTask name: /root/reviewer\nSender: /root\nPayload:\n"
},
{"type": "encrypted_content", "encrypted_content": "review this"}
]
})],
)?;
let replayed = replay_bundle(temp.path())?;
let edge_id = format!("edge:spawn:019d0000-0000-7000-8000-000000000001:{child_thread_id}");
let edge = &replayed.interaction_edges[&edge_id];
assert_eq!(edge.kind, InteractionEdgeKind::SpawnAgent);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
child_thread_id
);
assert_eq!(
edge.carried_raw_payload_ids,
vec![
invocation_payload.raw_payload_id,
activity_payload.raw_payload_id,
]
);
Ok(())
}
#[test]
fn send_message_runtime_payload_targets_delivered_child_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "send_message",
"payload": {
"type": "function",
"arguments": "{\"target\":\"/root/child\",\"message\":\"hello\"}"
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-send".to_string(),
model_visible_call_id: Some("call-send".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::SendMessage,
summary: ToolCallSummary::Generic {
label: "send_message".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload),
},
)?;
let begin_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-send",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"receiver_thread_id": "019d0000-0000-7000-8000-000000000002",
"prompt": "hello",
"status": "running"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::SendMessage,
tool_call_id: "call-send".to_string(),
runtime_payload: begin_payload,
},
)?;
let end_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-send",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"receiver_thread_id": "019d0000-0000-7000-8000-000000000002",
"prompt": "hello",
"status": "running"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-send".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: end_payload,
},
)?;
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/child",
)?;
start_turn_for_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
)?;
let delivered =
inter_agent_message("/root", "/root/child", "hello", /*trigger_turn*/ false);
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
"inference-child-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:tool:call-send"];
assert_eq!(edge.kind, InteractionEdgeKind::SendMessage);
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-send".to_string()
}
);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
"019d0000-0000-7000-8000-000000000002"
);
assert!(edge.ended_at_unix_ms.is_some());
Ok(())
}
#[test]
fn send_message_activity_targets_delivered_child_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let child_thread_id = "019d0000-0000-7000-8000-000000000002";
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "send_message",
"payload": {
"type": "function",
"arguments": "{\"target\":\"/root/child\",\"message\":\"hello again\"}"
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-send-v2".to_string(),
model_visible_call_id: Some("call-send-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::SendMessage,
summary: ToolCallSummary::Generic {
label: "send_message".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload.clone()),
},
)?;
let activity_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"event_id": "call-send-v2",
"occurred_at_ms": 1234,
"agent_thread_id": child_thread_id,
"agent_path": "/root/child",
"kind": "interacted"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-send-v2".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
)?;
start_thread(&writer, child_thread_id, "/root/child")?;
start_turn_for_thread(&writer, child_thread_id, "turn-child-1")?;
let delivered = inter_agent_message(
"/root",
"/root/child",
"hello again",
/*trigger_turn*/ false,
);
append_inference_request(
&writer,
child_thread_id,
"turn-child-1",
"inference-child-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:tool:call-send-v2"];
assert_eq!(edge.kind, InteractionEdgeKind::SendMessage);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
child_thread_id
);
assert_eq!(
edge.carried_raw_payload_ids,
vec![
invocation_payload.raw_payload_id,
activity_payload.raw_payload_id,
]
);
Ok(())
}
#[test]
fn followup_activity_targets_delivered_child_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let child_thread_id = "019d0000-0000-7000-8000-000000000002";
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "followup_task",
"payload": {
"type": "function",
"arguments": "{\"target\":\"/root/child\",\"message\":\"continue\"}"
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-followup-v2".to_string(),
model_visible_call_id: Some("call-followup-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::AssignAgentTask,
summary: ToolCallSummary::Generic {
label: "followup_task".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload.clone()),
},
)?;
let activity_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"event_id": "call-followup-v2",
"occurred_at_ms": 1234,
"agent_thread_id": child_thread_id,
"agent_path": "/root/child",
"kind": "interacted"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-followup-v2".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
)?;
start_thread(&writer, child_thread_id, "/root/child")?;
start_turn_for_thread(&writer, child_thread_id, "turn-child-1")?;
let delivered = inter_agent_message(
"/root",
"/root/child",
"continue",
/*trigger_turn*/ true,
);
append_inference_request(
&writer,
child_thread_id,
"turn-child-1",
"inference-child-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:tool:call-followup-v2"];
assert_eq!(edge.kind, InteractionEdgeKind::AssignAgentTask);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
child_thread_id
);
assert_eq!(
edge.carried_raw_payload_ids,
vec![
invocation_payload.raw_payload_id,
activity_payload.raw_payload_id,
]
);
Ok(())
}
#[test]
fn close_agent_runtime_payload_targets_thread() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/child",
)?;
start_agent_turn(&writer, "turn-1")?;
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "close_agent",
"payload": {
"type": "function",
"arguments": r#"{"target":"/root/child"}"#
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-close".to_string(),
model_visible_call_id: Some("call-close".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::CloseAgent,
summary: ToolCallSummary::Generic {
label: "close_agent".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload.clone()),
},
)?;
let begin_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-close",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"receiver_thread_id": "019d0000-0000-7000-8000-000000000002"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::CloseAgent,
tool_call_id: "call-close".to_string(),
runtime_payload: begin_payload.clone(),
},
)?;
let end_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-close",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"receiver_thread_id": "019d0000-0000-7000-8000-000000000002",
"receiver_agent_nickname": "Scout",
"receiver_agent_role": "explorer",
"status": "running"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-close".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: end_payload.clone(),
},
)?;
let result_payload = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({"previous_status": "running"}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "call-close".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(result_payload.clone()),
},
)?;
writer.append(RawTraceEventPayload::ThreadEnded {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
status: RolloutStatus::Completed,
})?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:tool:call-close"];
assert_eq!(edge.kind, InteractionEdgeKind::CloseAgent);
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-close".to_string()
}
);
assert_eq!(
edge.target,
TraceAnchor::Thread {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string()
}
);
assert!(edge.carried_item_ids.is_empty());
assert_eq!(
edge.carried_raw_payload_ids,
vec![
invocation_payload.raw_payload_id,
begin_payload.raw_payload_id,
end_payload.raw_payload_id,
result_payload.raw_payload_id,
]
);
assert_eq!(
replayed.threads["019d0000-0000-7000-8000-000000000002"]
.execution
.status,
ExecutionStatus::Completed
);
assert_eq!(replayed.status, RolloutStatus::Running);
Ok(())
}
#[test]
fn agent_result_edge_links_child_result_to_parent_notification() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/child",
)?;
start_turn_for_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
)?;
append_completed_inference(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
"inference-child-1",
vec![message("assistant", "task")],
vec![message("assistant", "done")],
)?;
let notification = "<subagent_notification>{\"agent_path\":\"/root/child\",\"status\":{\"completed\":\"done\"}}</subagent_notification>";
let carried_payload = writer.write_json_payload(
RawPayloadKind::AgentResult,
&json!({
"child_agent_path": "/root/child",
"message": notification,
"status": {"completed": "done"}
}),
)?;
writer.append_with_context(
trace_context_for_thread("019d0000-0000-7000-8000-000000000002", "turn-child-1"),
RawTraceEventPayload::AgentResultObserved {
edge_id: "edge:agent_result:thread-child:turn-child-1:thread-root".to_string(),
child_thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
child_codex_turn_id: "turn-child-1".to_string(),
parent_thread_id: "019d0000-0000-7000-8000-000000000001".to_string(),
message: notification.to_string(),
carried_payload: Some(carried_payload.clone()),
},
)?;
start_agent_turn(&writer, "turn-root-1")?;
let delivered = inter_agent_message(
"/root/child",
"/root",
notification,
/*trigger_turn*/ false,
);
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000001",
"turn-root-1",
"inference-root-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge =
&replayed.interaction_edges["edge:agent_result:thread-child:turn-child-1:thread-root"];
assert_eq!(edge.kind, InteractionEdgeKind::AgentResult);
let TraceAnchor::ConversationItem {
item_id: source_item_id,
} = &edge.source
else {
panic!("expected child result conversation item source");
};
assert_eq!(
text_body(&replayed.conversation_items[source_item_id]),
"done"
);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
"019d0000-0000-7000-8000-000000000001"
);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
edge.carried_raw_payload_ids,
vec![carried_payload.raw_payload_id]
);
Ok(())
}
#[test]
fn agent_result_edge_falls_back_to_child_thread_without_result_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
// The child received its task but produced no assistant output. Failed
// child tasks can still notify the parent through AgentStatus, so the
// inbound task must not be mistaken for the child's result.
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/child",
)?;
start_turn_for_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
)?;
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
"inference-child-1",
vec![json!({
"type": "agent_message",
"author": "/root",
"recipient": "/root/child",
"content": [{"type": "input_text", "text": "do the task"}]
})],
)?;
let notification = r#"<subagent_notification>{"agent_path":"/root/child","status":{"failed":"boom"}}</subagent_notification>"#;
let carried_payload = writer.write_json_payload(
RawPayloadKind::AgentResult,
&json!({
"child_agent_path": "/root/child",
"message": notification,
"status": {"failed": "boom"}
}),
)?;
writer.append_with_context(
trace_context_for_thread("019d0000-0000-7000-8000-000000000002", "turn-child-1"),
RawTraceEventPayload::AgentResultObserved {
edge_id: "edge:agent_result:thread-child:turn-child-1:thread-root".to_string(),
child_thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
child_codex_turn_id: "turn-child-1".to_string(),
parent_thread_id: "019d0000-0000-7000-8000-000000000001".to_string(),
message: notification.to_string(),
carried_payload: Some(carried_payload.clone()),
},
)?;
// The parent does receive the failure notification as a model-visible
// mailbox item. The target should remain that precise parent-side
// ConversationItem even though the source falls back to the child thread.
start_agent_turn(&writer, "turn-root-1")?;
let delivered = inter_agent_message(
"/root/child",
"/root",
notification,
/*trigger_turn*/ false,
);
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000001",
"turn-root-1",
"inference-root-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge =
&replayed.interaction_edges["edge:agent_result:thread-child:turn-child-1:thread-root"];
assert_eq!(edge.kind, InteractionEdgeKind::AgentResult);
assert_eq!(
edge.source,
TraceAnchor::Thread {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
}
);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
"019d0000-0000-7000-8000-000000000001"
);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
edge.carried_raw_payload_ids,
vec![carried_payload.raw_payload_id]
);
Ok(())
}
struct SpawnAgentToolPayloads {
invocation: RawPayloadRef,
begin: RawPayloadRef,
end: RawPayloadRef,
result: RawPayloadRef,
}
fn append_spawn_agent_tool_lifecycle(
writer: &TraceWriter,
turn_id: &str,
) -> anyhow::Result<SpawnAgentToolPayloads> {
// Keep the parent-side tool lifecycle in one place so the spawn tests can
// focus on the child-side event that decides the edge target.
let invocation = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "spawn_agent",
"payload": {
"type": "function",
"arguments": r#"{"task_name":"repo_file_counter","message":"count"}"#
}
}),
)?;
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-spawn".to_string(),
model_visible_call_id: Some("call-spawn".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::SpawnAgent,
summary: ToolCallSummary::Generic {
label: "spawn_agent".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation.clone()),
},
)?;
let begin = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-spawn",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"prompt": "count"
}),
)?;
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::SpawnAgent,
tool_call_id: "call-spawn".to_string(),
runtime_payload: begin.clone(),
},
)?;
let end = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-spawn",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"new_thread_id": "019d0000-0000-7000-8000-000000000002",
"prompt": "count",
"model": "gpt-test",
"reasoning_effort": "medium",
"status": "running"
}),
)?;
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-spawn".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: end.clone(),
},
)?;
let result = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({"task_name": "/root/repo_file_counter"}),
)?;
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "call-spawn".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(result.clone()),
},
)?;
Ok(SpawnAgentToolPayloads {
invocation,
begin,
end,
result,
})
}
fn inter_agent_message(author: &str, recipient: &str, content: &str, trigger_turn: bool) -> String {
json!({
"author": author,
"recipient": recipient,
"other_recipients": [],
"content": content,
"trigger_turn": trigger_turn,
})
.to_string()
}
fn target_conversation_item_id(anchor: &TraceAnchor) -> &String {
let TraceAnchor::ConversationItem { item_id } = anchor else {
panic!("expected conversation item target");
};
item_id
}
fn text_body(item: &crate::model::ConversationItem) -> &str {
let [crate::model::ConversationPart::Text { text }] = item.body.parts.as_slice() else {
panic!("expected single text part");
};
text
}

View File

@@ -0,0 +1,131 @@
//! MCP identity regressions for callable aliases and backend names.
use std::sync::Arc;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::ToolDispatchInvocation;
use crate::ToolDispatchPayload;
use crate::ToolDispatchRequester;
use crate::model::ToolCallKind;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::ROOT_THREAD_ID;
use crate::reducer::test_support::append_completed_inference;
use crate::reducer::test_support::create_started_writer;
use crate::reducer::test_support::start_turn;
use crate::reducer::test_support::trace_context;
use crate::replay_bundle;
use crate::tool_dispatch::ToolDispatchTraceContext;
#[test]
fn mcp_calls_keep_callable_identity_and_classify_the_backend() -> anyhow::Result<()> {
// Both naming styles are aliases: neither the namespace nor the callable
// tool name determines the backend identity. All test data is invented.
for (namespace, tool_name, arguments) in [
("mcp__catalog", "lookup", "{}"),
("catalog_alias", "lookup", "{}"),
("catalog_alias", "exec_command", "{}"),
("catalog_alias", "send_message", "{}"),
("catalog_alias", "spawn_agent", "{}"),
("mcp__catalog", "write_stdin", "{}"),
("catalog_alias", "write_stdin", r#"{"session_id":123}"#),
] {
let temp = TempDir::new()?;
let writer = Arc::new(create_started_writer(&temp)?);
start_turn(&writer, "turn-1")?;
append_completed_inference(
&writer,
ROOT_THREAD_ID,
"turn-1",
"inference-1",
vec![],
vec![json!({
"type": "custom_tool_call", "name": "exec",
"call_id": "call-cell", "input": "await tools.call({})"
})],
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id: "cell-1".to_string(),
model_visible_call_id: "call-cell".to_string(),
source_js: "await tools.call({})".to_string(),
},
)?;
let _dispatch = ToolDispatchTraceContext::start(
Arc::clone(&writer),
ToolDispatchInvocation {
thread_id: ROOT_THREAD_ID.to_string(),
codex_turn_id: "turn-1".to_string(),
tool_call_id: "call-mcp".to_string(),
tool_name: tool_name.to_string(),
tool_namespace: Some(namespace.to_string()),
requester: ToolDispatchRequester::CodeCell {
runtime_cell_id: "cell-1".to_string(),
runtime_tool_call_id: "runtime-tool-1".to_string(),
},
payload: ToolDispatchPayload::Function {
arguments: arguments.to_string(),
},
},
);
let before = replay_bundle(temp.path())?;
// Namespaced write_stdin calls must neither require terminal arguments
// nor create terminal sessions when those arguments happen to be valid.
assert!(before.terminal_operations.is_empty());
assert!(before.terminal_sessions.is_empty());
let mut expected = before.tool_calls["call-mcp"].clone();
expected.kind = ToolCallKind::Mcp {
server: "inventory_service".to_string(),
tool: "find_item".to_string(),
};
let invocation = json!({
"server": "inventory_service", "tool": "find_item",
"arguments": serde_json::from_str::<serde_json::Value>(arguments)?
});
let begin = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-mcp", "turn_id": "turn-1", "invocation": invocation
}),
)?;
writer.append(RawTraceEventPayload::ToolCallRuntimeStarted {
kind: expected.kind.clone(),
tool_call_id: "call-mcp".to_string(),
runtime_payload: begin.clone(),
})?;
expected.raw_runtime_payload_ids.push(begin.raw_payload_id);
// A live prefix must already have backend identity. Everything else,
// including the callable label, invocation reference and parent, stays.
assert_eq!(replay_bundle(temp.path())?.tool_calls["call-mcp"], expected);
// The producer emits the runtime begin before assigning its MCP
// correlation ID, even when the callable name matches a built-in.
writer.append(RawTraceEventPayload::McpToolCallCorrelationAssigned {
tool_call_id: "call-mcp".to_string(),
mcp_call_id: "mcp-correlation-1".to_string(),
})?;
expected.mcp_call_id = Some("mcp-correlation-1".to_string());
let end = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-mcp", "turn_id": "turn-1", "invocation": invocation,
"duration": {"secs": 0, "nanos": 1}, "result": {"Ok": {"content": []}}
}),
)?;
writer.append(RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-mcp".to_string(),
status: crate::ExecutionStatus::Completed,
runtime_payload: end.clone(),
})?;
expected.raw_runtime_payload_ids.push(end.raw_payload_id);
// MCP completion must not overwrite the outer dispatch lifecycle.
assert_eq!(replay_bundle(temp.path())?.tool_calls["call-mcp"], expected);
}
Ok(())
}

View File

@@ -0,0 +1,660 @@
//! Terminal reduction for exec-like tool calls.
//!
//! The raw trace records terminal activity as normal tool lifecycle events.
//! Protocol-backed exec events carry `ExecCommand*` payloads with the richest
//! runtime details. Direct tools without protocol observations, such as
//! `write_stdin`, can still form a terminal row from the canonical dispatch
//! invocation/result payloads when those payloads carry the session join key.
//! Runtime process handles are recyclable and thread-local. Each exec creates a
//! distinct reduced session; stdin uses the runtime's resolved exec when recorded,
//! falling back to the latest session for its handle in older traces.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde::Deserialize;
use serde_json::Value as JsonValue;
use super::push_unique;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::model::TerminalModelObservation;
use crate::model::TerminalObservationSource;
use crate::model::TerminalOperation;
use crate::model::TerminalOperationId;
use crate::model::TerminalOperationKind;
use crate::model::TerminalRequest;
use crate::model::TerminalResult;
use crate::model::TerminalSession;
use crate::model::ToolCallKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawEventSeq;
use crate::reducer::TraceReducer;
impl TraceReducer {
/// Starts a terminal operation from a canonical dispatch invocation payload.
///
/// This is currently needed for direct tools such as write-stdin that do not
/// emit a richer protocol runtime-begin event with the terminal join key.
pub(in crate::reducer) fn start_terminal_operation_from_invocation(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &str,
tool_call_id: &str,
kind: &ToolCallKind,
invocation_payload: Option<&RawPayloadRef>,
) -> Result<Option<TerminalOperationId>> {
if !matches!(kind, ToolCallKind::WriteStdin) {
return Ok(None);
}
let operation_kind = TerminalOperationKind::WriteStdin;
let Some(invocation_payload) = invocation_payload else {
// Payload writes are best-effort in the live recorder. If the
// canonical invocation is missing, keep the ToolCall but avoid
// fabricating a lossy terminal row.
return Ok(None);
};
let payload = self.read_payload_json(invocation_payload)?;
let Some(request) = parse_dispatch_terminal_request(payload).with_context(|| {
format!(
"parse terminal invocation payload {} as dispatch payload",
invocation_payload.raw_payload_id
)
})?
else {
return Ok(None);
};
self.insert_terminal_operation(TerminalOperationStart {
seq,
wall_time_unix_ms,
thread_id,
tool_call_id,
operation_kind,
raw_payload: invocation_payload,
request,
})
}
/// Starts a terminal operation from a protocol runtime-begin payload.
pub(in crate::reducer) fn start_terminal_operation_from_runtime(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &str,
tool_call_id: &str,
kind: &ToolCallKind,
runtime_payload: &RawPayloadRef,
) -> Result<Option<TerminalOperationId>> {
let Some(operation_kind) = terminal_operation_kind(kind) else {
return Ok(None);
};
let payload = self.read_payload_json(runtime_payload)?;
let payload: ExecCommandBeginPayload =
serde_json::from_value(payload).with_context(|| {
format!(
"parse terminal runtime start payload {}",
runtime_payload.raw_payload_id
)
})?;
let request = parse_protocol_terminal_request(payload, &operation_kind);
self.insert_terminal_operation(TerminalOperationStart {
seq,
wall_time_unix_ms,
thread_id,
tool_call_id,
operation_kind,
raw_payload: runtime_payload,
request,
})
}
fn insert_terminal_operation(
&mut self,
start: TerminalOperationStart<'_>,
) -> Result<Option<TerminalOperationId>> {
let operation_id = self.next_terminal_operation_id();
let ParsedTerminalRequest {
process_id,
request,
} = start.request;
self.rollout.terminal_operations.insert(
operation_id.clone(),
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: None,
tool_call_id: start.tool_call_id.to_string(),
kind: start.operation_kind,
execution: ExecutionWindow {
started_at_unix_ms: start.wall_time_unix_ms,
started_seq: start.seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
request,
result: None,
model_observations: Vec::new(),
raw_payload_ids: vec![start.raw_payload.raw_payload_id.clone()],
},
);
if let Some(process_id) = process_id {
self.attach_terminal_session(start.thread_id, &process_id, &operation_id)?;
}
Ok(Some(operation_id))
}
/// Completes the terminal operation associated with a tool call, if one exists.
///
/// Non-terminal tools flow through the same generic tool lifecycle, so callers
/// may invoke this unconditionally and receive Ok for unrelated tool kinds.
pub(in crate::reducer) fn end_terminal_operation(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &str,
operation_id: &str,
status: ExecutionStatus,
response_payload: Option<&RawPayloadRef>,
) -> Result<()> {
let Some(operation_kind) = self
.rollout
.terminal_operations
.get(operation_id)
.map(|operation| operation.kind.clone())
else {
bail!("terminal end referenced unknown operation {operation_id}");
};
let response = response_payload
.map(|payload| {
let value = self.read_payload_json(payload)?;
let response = parse_terminal_response_payload(
value,
&operation_kind,
&payload.raw_payload_id,
)?;
Ok::<_, anyhow::Error>((payload.raw_payload_id.clone(), response))
})
.transpose()?;
let process_id = {
let Some(operation) = self.rollout.terminal_operations.get_mut(operation_id) else {
bail!("terminal end referenced unknown operation {operation_id}");
};
operation.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
operation.execution.ended_seq = Some(seq);
operation.execution.status = status;
if let Some((raw_payload_id, response)) = response {
push_unique(&mut operation.raw_payload_ids, &raw_payload_id);
operation.result = Some(response.result);
response.process_id
} else {
None
}
};
if let Some(process_id) = process_id {
self.attach_terminal_session(thread_id, &process_id, operation_id)?;
}
Ok(())
}
fn attach_terminal_session(
&mut self,
thread_id: &str,
process_id: &str,
operation_id: &str,
) -> Result<()> {
let Some(operation) = self.rollout.terminal_operations.get_mut(operation_id) else {
bail!("terminal session referenced unknown operation {operation_id}");
};
if let Some(terminal_id) = &operation.terminal_id {
let existing = &self.process_ids_by_terminal[terminal_id];
if existing != process_id {
bail!(
"terminal operation {operation_id} changed process id from {existing} to {process_id}"
);
}
return Ok(());
}
let key = (thread_id.to_string(), process_id.to_string());
let existing = match operation.kind {
TerminalOperationKind::ExecCommand => None,
TerminalOperationKind::WriteStdin => self.terminal_ids_by_process.get(&key).cloned(),
};
let terminal_id = existing.unwrap_or_else(|| format!("terminal_session:{operation_id}"));
let session = self
.rollout
.terminal_sessions
.entry(terminal_id.clone())
.or_insert_with(|| TerminalSession {
terminal_id: terminal_id.clone(),
thread_id: thread_id.to_string(),
created_by_operation_id: operation_id.to_string(),
operation_ids: Vec::new(),
execution: ExecutionWindow {
started_at_unix_ms: operation.execution.started_at_unix_ms,
started_seq: operation.execution.started_seq,
// Raw events do not report session release: buffered output
// can still be collected after the process exits.
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
});
push_unique(&mut session.operation_ids, operation_id);
operation.terminal_id = Some(terminal_id.clone());
self.process_ids_by_terminal
.insert(terminal_id.clone(), process_id.to_string());
self.terminal_ids_by_process.insert(key, terminal_id);
Ok(())
}
/// Replaces the provisional handle-based join with the runtime's actual target.
pub(in crate::reducer) fn resolve_stdin_target(
&mut self,
tool_call_id: &str,
exec_tool_call_id: &str,
) -> Result<()> {
let stdin = self
.rollout
.tool_calls
.get(tool_call_id)
.with_context(|| format!("stdin target referenced unknown call {tool_call_id}"))?;
let exec = self
.rollout
.tool_calls
.get(exec_tool_call_id)
.with_context(|| format!("stdin target referenced unknown exec {exec_tool_call_id}"))?;
let (Some(operation_id), Some(exec_operation_id)) =
(&stdin.terminal_operation_id, &exec.terminal_operation_id)
else {
// A failed payload write can leave either call without a terminal projection.
return Ok(());
};
let Some(terminal_id) = self.rollout.terminal_operations[exec_operation_id]
.terminal_id
.clone()
else {
return Ok(());
};
let operation = self
.rollout
.terminal_operations
.get_mut(operation_id)
.with_context(|| format!("stdin target referenced unknown operation {operation_id}"))?;
if operation.terminal_id.as_ref() == Some(&terminal_id) {
return Ok(());
}
// Move this operation without rewinding the handle lookup: a newer exec
// may already own that handle by the time resolution is recorded.
if let Some(previous) = operation.terminal_id.replace(terminal_id.clone()) {
let session = self
.rollout
.terminal_sessions
.get_mut(&previous)
.with_context(|| format!("stdin target referenced unknown session {previous}"))?;
session.operation_ids.retain(|id| id != operation_id);
if session.operation_ids.is_empty() {
self.rollout.terminal_sessions.remove(&previous);
self.process_ids_by_terminal.remove(&previous);
}
}
self.rollout
.terminal_sessions
.get_mut(&terminal_id)
.with_context(|| format!("stdin target referenced unknown session {terminal_id}"))?
.operation_ids
.push(operation_id.clone());
Ok(())
}
/// Mirrors model-visible tool items onto the terminal observation view.
///
/// Runtime terminal rows are useful on their own, but the model-visible call
/// and output item ids let viewers jump between transcript and terminal timelines.
pub(in crate::reducer) fn sync_terminal_model_observation(
&mut self,
tool_call_id: &str,
) -> Result<()> {
let Some(tool_call) = self.rollout.tool_calls.get(tool_call_id) else {
bail!("tool call {tool_call_id} disappeared during terminal observation linking");
};
let Some(operation_id) = tool_call.terminal_operation_id.clone() else {
return Ok(());
};
let call_item_ids = tool_call.model_visible_call_item_ids.clone();
let output_item_ids = tool_call.model_visible_output_item_ids.clone();
if call_item_ids.is_empty() && output_item_ids.is_empty() {
return Ok(());
}
let Some(operation) = self.rollout.terminal_operations.get_mut(&operation_id) else {
bail!("terminal operation {operation_id} disappeared during observation linking");
};
// A terminal result and a model-visible tool output are intentionally
// separate: the former is what the runtime saw, the latter is what later
// inference payloads prove was shown back to the model.
if let Some(observation) = operation
.model_observations
.iter_mut()
.find(|observation| observation.source == TerminalObservationSource::DirectToolCall)
{
observation.call_item_ids = call_item_ids;
observation.output_item_ids = output_item_ids;
} else {
operation.model_observations.push(TerminalModelObservation {
call_item_ids,
output_item_ids,
source: TerminalObservationSource::DirectToolCall,
});
}
Ok(())
}
fn next_terminal_operation_id(&mut self) -> TerminalOperationId {
let ordinal = self.next_terminal_operation_ordinal;
self.next_terminal_operation_ordinal += 1;
format!("terminal_operation:{ordinal}")
}
}
fn terminal_operation_kind(kind: &ToolCallKind) -> Option<TerminalOperationKind> {
match kind {
ToolCallKind::ExecCommand => Some(TerminalOperationKind::ExecCommand),
ToolCallKind::WriteStdin => Some(TerminalOperationKind::WriteStdin),
ToolCallKind::ApplyPatch
| ToolCallKind::Mcp { .. }
| ToolCallKind::Web
| ToolCallKind::ImageGeneration
| ToolCallKind::SpawnAgent
| ToolCallKind::AssignAgentTask
| ToolCallKind::SendMessage
| ToolCallKind::WaitAgent
| ToolCallKind::CloseAgent
| ToolCallKind::Other { .. } => None,
}
}
struct TerminalOperationStart<'a> {
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &'a str,
tool_call_id: &'a str,
operation_kind: TerminalOperationKind,
raw_payload: &'a RawPayloadRef,
request: ParsedTerminalRequest,
}
struct ParsedTerminalRequest {
process_id: Option<String>,
request: TerminalRequest,
}
struct ParsedTerminalResponse {
process_id: Option<String>,
result: TerminalResult,
}
fn parse_protocol_terminal_request(
payload: ExecCommandBeginPayload,
operation_kind: &TerminalOperationKind,
) -> ParsedTerminalRequest {
// Startup/poll paths usually include a process id at begin time, but plain
// exec starts may only learn it in the matching end event.
let process_id = payload.process_id.clone();
let request = match operation_kind {
TerminalOperationKind::ExecCommand => TerminalRequest::ExecCommand {
display_command: payload.command.join(" "),
command: payload.command,
cwd: payload.cwd,
yield_time_ms: None,
max_output_tokens: None,
},
TerminalOperationKind::WriteStdin => TerminalRequest::WriteStdin {
stdin: payload.interaction_input.unwrap_or_default(),
yield_time_ms: None,
max_output_tokens: None,
},
};
ParsedTerminalRequest {
process_id,
request,
}
}
fn parse_dispatch_terminal_request(value: JsonValue) -> Result<Option<ParsedTerminalRequest>> {
let payload: DispatchedToolTraceRequestPayload = serde_json::from_value(value)?;
// Recorded kinds are name-based. Only the built-in write_stdin owns terminal
// sessions; core records its default namespace as None. Namespaced aliases
// must wait for runtime classification, even if their arguments look native.
if payload.tool_namespace.is_some() {
return Ok(None);
}
if payload.tool_name != "write_stdin" {
bail!(
"dispatch terminal request is for {}, not write_stdin",
payload.tool_name
);
}
if payload.payload.kind != "function" {
bail!(
"write_stdin dispatch payload used unsupported {} payload",
payload.payload.kind
);
}
let arguments = payload
.payload
.arguments
.context("write_stdin dispatch payload omitted function arguments")?;
// Invalid model arguments are a tool failure, not a corrupt trace. Keep the
// generic call and its error without inventing a terminal operation.
let Ok(args) = serde_json::from_str::<DispatchedWriteStdinArgs>(&arguments) else {
return Ok(None);
};
let Some(process_id) = process_id_from_json(&args.session_id) else {
return Ok(None);
};
Ok(Some(ParsedTerminalRequest {
process_id: Some(process_id),
request: TerminalRequest::WriteStdin {
stdin: args.chars,
yield_time_ms: args.yield_time_ms,
max_output_tokens: args.max_output_tokens,
},
}))
}
fn parse_terminal_response_payload(
value: JsonValue,
operation_kind: &TerminalOperationKind,
raw_payload_id: &str,
) -> Result<ParsedTerminalResponse> {
match operation_kind {
TerminalOperationKind::ExecCommand => {
let payload = serde_json::from_value::<ExecCommandEndPayload>(value)
.with_context(|| format!("parse exec terminal response {raw_payload_id}"))?;
Ok(parse_protocol_terminal_response(payload))
}
TerminalOperationKind::WriteStdin => {
match serde_json::from_value::<ExecCommandEndPayload>(value.clone()) {
Ok(payload) => Ok(parse_protocol_terminal_response(payload)),
Err(protocol_err) => parse_dispatch_terminal_response(value).with_context(|| {
format!(
"parse write_stdin terminal response {raw_payload_id} as protocol payload \
({protocol_err}) or dispatch payload"
)
}),
}
}
}
}
fn parse_protocol_terminal_response(payload: ExecCommandEndPayload) -> ParsedTerminalResponse {
ParsedTerminalResponse {
process_id: payload.process_id,
result: TerminalResult {
exit_code: Some(payload.exit_code),
stdout: payload.aggregated_output,
stderr: String::new(),
formatted_output: None,
original_token_count: None,
chunk_id: None,
},
}
}
fn parse_dispatch_terminal_response(value: JsonValue) -> Result<ParsedTerminalResponse> {
let payload: DispatchedToolTraceResponsePayload = serde_json::from_value(value)?;
let result = match payload {
DispatchedToolTraceResponsePayload::DirectResponse { response_item } => {
let output = response_item
.get("output")
.and_then(json_text_content)
.unwrap_or_else(|| response_item.to_string());
TerminalResult {
exit_code: None,
stdout: output.clone(),
stderr: String::new(),
formatted_output: Some(output),
original_token_count: None,
chunk_id: None,
}
}
DispatchedToolTraceResponsePayload::CodeModeResponse { value } => {
// Code-mode returns the JavaScript-facing tool value, not the text
// shown to the model. For write_stdin that value is the structured
// unified-exec result, so keep ToolCall.raw_result_payload_id as the
// raw boundary while projecting terminal-specific fields here.
parse_code_mode_exec_result(value)
}
DispatchedToolTraceResponsePayload::Error { error } => TerminalResult {
exit_code: None,
stdout: String::new(),
stderr: error.clone(),
formatted_output: Some(error),
original_token_count: None,
chunk_id: None,
},
};
Ok(ParsedTerminalResponse {
process_id: None,
result,
})
}
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(_) => {
let output = json_text_content(&value).unwrap_or_else(|| value.to_string());
TerminalResult {
exit_code: None,
stdout: output.clone(),
stderr: String::new(),
formatted_output: Some(output),
original_token_count: None,
chunk_id: None,
}
}
}
}
fn json_text_content(value: &JsonValue) -> Option<String> {
match value {
JsonValue::String(text) => Some(text.clone()),
JsonValue::Array(items) => {
let text = items
.iter()
.filter_map(|item| item.get("text").and_then(JsonValue::as_str))
.collect::<Vec<_>>()
.join("\n");
(!text.is_empty()).then_some(text)
}
JsonValue::Null => None,
other => Some(other.to_string()),
}
}
fn process_id_from_json(value: &JsonValue) -> Option<String> {
match value {
JsonValue::String(value) if !value.is_empty() => Some(value.clone()),
JsonValue::Number(value) => Some(value.to_string()),
_ => None,
}
}
#[derive(Deserialize)]
struct ExecCommandBeginPayload {
process_id: Option<String>,
command: Vec<String>,
cwd: String,
interaction_input: Option<String>,
}
#[derive(Deserialize)]
struct ExecCommandEndPayload {
process_id: Option<String>,
#[serde(default)]
aggregated_output: String,
exit_code: i32,
}
#[derive(Deserialize)]
struct DispatchedToolTraceRequestPayload {
tool_name: String,
tool_namespace: Option<String>,
payload: DispatchedToolPayload,
}
#[derive(Deserialize)]
struct DispatchedToolPayload {
#[serde(rename = "type")]
kind: String,
arguments: Option<String>,
}
#[derive(Deserialize)]
struct DispatchedWriteStdinArgs {
session_id: JsonValue,
#[serde(default)]
chars: String,
yield_time_ms: Option<u64>,
max_output_tokens: Option<usize>,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
enum DispatchedToolTraceResponsePayload {
DirectResponse { response_item: JsonValue },
CodeModeResponse { value: JsonValue },
Error { error: String },
}
#[derive(Deserialize)]
struct CodeModeExecResult {
chunk_id: Option<String>,
exit_code: Option<i32>,
original_token_count: Option<usize>,
output: String,
}
#[cfg(test)]
#[path = "terminal_tests.rs"]
mod tests;

View File

@@ -0,0 +1,708 @@
use std::sync::Arc;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::ToolDispatchInvocation;
use crate::ToolDispatchPayload;
use crate::ToolDispatchRequester;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::model::RolloutStatus;
use crate::model::TerminalModelObservation;
use crate::model::TerminalObservationSource;
use crate::model::TerminalOperation;
use crate::model::TerminalOperationKind;
use crate::model::TerminalRequest;
use crate::model::TerminalResult;
use crate::model::TerminalSession;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::ROOT_THREAD_ID;
use crate::reducer::test_support::create_started_writer;
use crate::reducer::test_support::generic_summary;
use crate::reducer::test_support::message;
use crate::reducer::test_support::start_thread;
use crate::reducer::test_support::start_turn;
use crate::reducer::test_support::start_turn_for_thread;
use crate::reducer::test_support::trace_context;
use crate::reducer::test_support::trace_context_for_thread;
use crate::replay_bundle;
use crate::tool_dispatch::ToolDispatchTraceContext;
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)?;
start_turn(&writer, "turn-1")?;
append_inference_with_tool_call(&writer)?;
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "exec_command",
"tool_namespace": null,
"payload": {
"type": "function",
"arguments": "{\"cmd\":\"cargo test\"}"
}
}),
)?;
let invocation_payload_id = invocation_payload.raw_payload_id.clone();
let _tool_start = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-1".to_string(),
model_visible_call_id: Some("call-1".to_string()),
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
kind: ToolCallKind::ExecCommand,
summary: generic_summary("exec_command"),
invocation_payload: Some(invocation_payload),
},
)?;
let runtime_start_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "tool-1",
"turn_id": "turn-1",
"command": ["cargo", "test"],
"cwd": "/repo"
}),
)?;
let runtime_start_payload_id = runtime_start_payload.raw_payload_id.clone();
let runtime_start = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::ExecCommand,
tool_call_id: "tool-1".to_string(),
runtime_payload: runtime_start_payload,
},
)?;
let runtime_end_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "tool-1",
"process_id": "pty-1",
"turn_id": "turn-1",
"command": ["cargo", "test"],
"cwd": "/repo",
"aggregated_output": "ok\n",
"exit_code": 0,
"status": "completed"
}),
)?;
let runtime_end_payload_id = runtime_end_payload.raw_payload_id.clone();
let runtime_end = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "tool-1".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: runtime_end_payload,
},
)?;
let result_payload = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({
"type": "direct_response",
"response_item": {
"type": "function_call_output",
"call_id": "call-1",
"output": "ok\n"
}
}),
)?;
let result_payload_id = result_payload.raw_payload_id.clone();
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-1".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(result_payload),
},
)?;
start_turn(&writer, "turn-2")?;
append_followup_with_tool_output(&writer)?;
let rollout = replay_bundle(temp.path())?;
let operation_id = "terminal_operation:1".to_string();
let output_item_id = rollout.inference_calls["inference-2"]
.request_item_ids
.last()
.expect("tool output item")
.clone();
assert_eq!(
rollout.tool_calls["tool-1"].terminal_operation_id,
Some(operation_id.clone()),
);
assert_eq!(
rollout.tool_calls["tool-1"].raw_invocation_payload_id,
Some(invocation_payload_id),
);
assert_eq!(
rollout.tool_calls["tool-1"].raw_result_payload_id,
Some(result_payload_id),
);
assert_eq!(
rollout.tool_calls["tool-1"].raw_runtime_payload_ids,
vec![
runtime_start_payload_id.clone(),
runtime_end_payload_id.clone()
],
);
assert_eq!(
rollout.tool_calls["tool-1"].summary,
ToolCallSummary::Terminal {
operation_id: operation_id.clone(),
},
);
assert_eq!(
rollout.terminal_operations[&operation_id],
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: Some("terminal_session:terminal_operation:1".to_string()),
tool_call_id: "tool-1".to_string(),
kind: TerminalOperationKind::ExecCommand,
execution: ExecutionWindow {
started_at_unix_ms: runtime_start.wall_time_unix_ms,
started_seq: runtime_start.seq,
ended_at_unix_ms: Some(runtime_end.wall_time_unix_ms),
ended_seq: Some(runtime_end.seq),
status: ExecutionStatus::Completed,
},
request: TerminalRequest::ExecCommand {
command: vec!["cargo".to_string(), "test".to_string()],
display_command: "cargo test".to_string(),
cwd: "/repo".to_string(),
yield_time_ms: None,
max_output_tokens: None,
},
result: Some(TerminalResult {
exit_code: Some(0),
stdout: "ok\n".to_string(),
stderr: String::new(),
formatted_output: None,
original_token_count: None,
chunk_id: None,
}),
model_observations: vec![TerminalModelObservation {
call_item_ids: rollout.inference_calls["inference-1"]
.response_item_ids
.clone(),
output_item_ids: vec![output_item_id],
source: TerminalObservationSource::DirectToolCall,
}],
raw_payload_ids: vec![runtime_start_payload_id, runtime_end_payload_id],
},
);
assert_eq!(
rollout.terminal_sessions["terminal_session:terminal_operation:1"],
TerminalSession {
terminal_id: "terminal_session:terminal_operation:1".to_string(),
thread_id: "thread-root".to_string(),
created_by_operation_id: operation_id.clone(),
operation_ids: vec![operation_id],
execution: ExecutionWindow {
started_at_unix_ms: runtime_start.wall_time_unix_ms,
started_seq: runtime_start.seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
},
);
Ok(())
}
#[test]
fn reused_process_ids_keep_sessions_and_stdin_joins_distinct() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
start_thread(&writer, "child", "/root/child")?;
start_turn_for_thread(&writer, "child", "child-turn")?;
let mut reused_stdin = None;
// Real rollouts reuse process IDs both across threads and after an exec
// finishes. Polls must stay with the corresponding exec, not the last
// occurrence of the process number anywhere in the rollout.
for (index, (thread, turn, kind)) in [
("thread-root", "turn-1", ToolCallKind::ExecCommand),
("child", "child-turn", ToolCallKind::ExecCommand),
("thread-root", "turn-1", ToolCallKind::WriteStdin),
("child", "child-turn", ToolCallKind::WriteStdin),
("thread-root", "turn-1", ToolCallKind::ExecCommand),
("thread-root", "turn-1", ToolCallKind::WriteStdin),
("child", "resumed-turn", ToolCallKind::WriteStdin),
]
.into_iter()
.enumerate()
{
if turn == "resumed-turn" {
writer.append(RawTraceEventPayload::ThreadEnded {
thread_id: thread.to_string(),
status: RolloutStatus::Completed,
})?;
writer.append(RawTraceEventPayload::ThreadResumed {
thread_id: thread.to_string(),
})?;
start_turn_for_thread(&writer, thread, turn)?;
}
if index == 4 {
let response = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({"process_id": "123", "exit_code": 0}),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "tool-0".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: response,
},
)?;
}
let tool_call_id = format!("tool-{index}");
writer.append_with_context(
trace_context_for_thread(thread, turn),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: tool_call_id.clone(),
model_visible_call_id: None,
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
kind: kind.clone(),
summary: generic_summary("terminal"),
invocation_payload: None,
},
)?;
let request = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"process_id": "123",
"command": ["bash"],
"cwd": "/repo",
"interaction_input": (index == 5).then_some("echo hi\n"),
}),
)?;
let request_id = request.raw_payload_id.clone();
let runtime_start = writer.append_with_context(
trace_context_for_thread(thread, turn),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind,
tool_call_id,
runtime_payload: request,
},
)?;
if index == 5 {
reused_stdin = Some((runtime_start, request_id));
}
}
let rollout = replay_bundle(temp.path())?;
let groups = rollout
.terminal_sessions
.values()
.map(|session| {
let calls = session
.operation_ids
.iter()
.map(|id| {
let operation = &rollout.terminal_operations[id];
assert_eq!(operation.terminal_id.as_ref(), Some(&session.terminal_id));
operation.tool_call_id.as_str()
})
.collect::<Vec<_>>();
(session.thread_id.as_str(), calls)
})
.collect::<Vec<_>>();
assert_eq!(
groups,
vec![
("thread-root", vec!["tool-0", "tool-2"]),
("child", vec!["tool-1", "tool-3"]),
("thread-root", vec!["tool-4", "tool-5"]),
("child", vec!["tool-6"]),
],
);
let (runtime_start, request_id) = reused_stdin.unwrap();
assert_eq!(
rollout.terminal_operations["terminal_operation:6"],
TerminalOperation {
operation_id: "terminal_operation:6".to_string(),
terminal_id: Some("terminal_session:terminal_operation:5".to_string()),
tool_call_id: "tool-5".to_string(),
kind: TerminalOperationKind::WriteStdin,
execution: ExecutionWindow {
started_at_unix_ms: runtime_start.wall_time_unix_ms,
started_seq: runtime_start.seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
request: TerminalRequest::WriteStdin {
stdin: "echo hi\n".to_string(),
yield_time_ms: None,
max_output_tokens: None,
},
result: None,
model_observations: Vec::new(),
raw_payload_ids: vec![request_id],
},
);
// Stdin started while tool-0 owned the handle, but dispatch was delayed
// until tool-4 replaced it. Only its session membership should change.
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::StdinTargetResolved {
tool_call_id: "tool-2".to_string(),
exec_tool_call_id: "tool-4".to_string(),
},
)?;
let mut expected = rollout;
let previous = "terminal_session:terminal_operation:1";
let resolved = "terminal_session:terminal_operation:5";
expected
.terminal_sessions
.get_mut(previous)
.unwrap()
.operation_ids = vec!["terminal_operation:1".to_string()];
expected
.terminal_sessions
.get_mut(resolved)
.unwrap()
.operation_ids
.push("terminal_operation:3".to_string());
expected
.terminal_operations
.get_mut("terminal_operation:3")
.unwrap()
.terminal_id = Some(resolved.to_string());
assert_eq!(replay_bundle(temp.path())?, expected);
Ok(())
}
#[test]
fn dispatch_write_stdin_payload_reduces_to_terminal_operation() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "write_stdin",
"tool_namespace": null,
"payload": {
"type": "function",
"arguments": json!({
"session_id": 123,
"chars": "echo hi\n",
"yield_time_ms": 250,
"max_output_tokens": 2000
}).to_string()
}
}),
)?;
let request_payload_id = request_payload.raw_payload_id.clone();
let tool_start = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-stdin".to_string(),
model_visible_call_id: Some("call-stdin".to_string()),
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
kind: ToolCallKind::WriteStdin,
summary: generic_summary("write_stdin"),
invocation_payload: Some(request_payload),
},
)?;
let response_payload = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({
"type": "direct_response",
"response_item": {
"type": "function_call_output",
"call_id": "call-stdin",
"output": "hi\n"
}
}),
)?;
let response_payload_id = response_payload.raw_payload_id.clone();
let tool_end = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-stdin".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(response_payload),
},
)?;
let rollout = replay_bundle(temp.path())?;
let operation_id = "terminal_operation:1".to_string();
assert_eq!(
rollout.tool_calls["tool-stdin"].terminal_operation_id,
Some(operation_id.clone()),
);
assert_eq!(
rollout.tool_calls["tool-stdin"].summary,
ToolCallSummary::Terminal {
operation_id: operation_id.clone(),
},
);
assert_eq!(
rollout.terminal_operations[&operation_id],
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: Some("terminal_session:terminal_operation:1".to_string()),
tool_call_id: "tool-stdin".to_string(),
kind: TerminalOperationKind::WriteStdin,
execution: ExecutionWindow {
started_at_unix_ms: tool_start.wall_time_unix_ms,
started_seq: tool_start.seq,
ended_at_unix_ms: Some(tool_end.wall_time_unix_ms),
ended_seq: Some(tool_end.seq),
status: ExecutionStatus::Completed,
},
request: TerminalRequest::WriteStdin {
stdin: "echo hi\n".to_string(),
yield_time_ms: Some(250),
max_output_tokens: Some(2000),
},
result: Some(TerminalResult {
exit_code: None,
stdout: "hi\n".to_string(),
stderr: String::new(),
formatted_output: Some("hi\n".to_string()),
original_token_count: None,
chunk_id: None,
}),
model_observations: Vec::new(),
raw_payload_ids: vec![request_payload_id, response_payload_id],
},
);
assert_eq!(
rollout.terminal_sessions["terminal_session:terminal_operation:1"],
TerminalSession {
terminal_id: "terminal_session:terminal_operation:1".to_string(),
thread_id: "thread-root".to_string(),
created_by_operation_id: operation_id.clone(),
operation_ids: vec![operation_id],
execution: ExecutionWindow {
started_at_unix_ms: tool_start.wall_time_unix_ms,
started_seq: tool_start.seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
},
);
Ok(())
}
#[test]
fn invalid_write_stdin_arguments_remain_failed_tool_calls() -> anyhow::Result<()> {
for arguments in [r#"{"session_id": "#, "{}", r#"{"session_id": null}"#] {
let temp = TempDir::new()?;
let writer = Arc::new(create_started_writer(&temp)?);
start_turn(&writer, "turn-1")?;
let dispatch = ToolDispatchTraceContext::start(
Arc::clone(&writer),
ToolDispatchInvocation {
thread_id: ROOT_THREAD_ID.to_string(),
codex_turn_id: "turn-1".to_string(),
tool_call_id: "call-stdin".to_string(),
tool_name: "write_stdin".to_string(),
tool_namespace: None,
requester: ToolDispatchRequester::Model {
model_visible_call_id: "call-stdin".to_string(),
},
payload: ToolDispatchPayload::Function {
arguments: arguments.to_string(),
},
},
);
dispatch.record_failed("invalid arguments");
let rollout = replay_bundle(temp.path())?;
let call = &rollout.tool_calls["call-stdin"];
assert_eq!(call.execution.status, ExecutionStatus::Failed);
assert_eq!(call.terminal_operation_id, None);
assert!(rollout.terminal_operations.is_empty());
assert!(rollout.terminal_sessions.is_empty());
// The failed call still retains its original arguments and error.
for (id, expected) in [
(
call.raw_invocation_payload_id.as_ref().unwrap(),
json!({"tool_name": "write_stdin", "tool_namespace": null,
"payload": {"type": "function", "arguments": arguments}}),
),
(
call.raw_result_payload_id.as_ref().unwrap(),
json!({"type": "error", "error": "invalid arguments"}),
),
] {
let payload = std::fs::read(temp.path().join(&rollout.raw_payloads[id].path))?;
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&payload)?,
expected
);
}
}
Ok(())
}
#[test]
fn code_mode_write_stdin_result_projects_structured_exec_fields() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "write_stdin",
"tool_namespace": null,
"payload": {
"type": "function",
"arguments": json!({
"session_id": 456,
"chars": "",
"yield_time_ms": 1000,
"max_output_tokens": 4000
}).to_string()
}
}),
)?;
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 {
runtime_cell_id: "cell-1".to_string(),
model_visible_call_id: "call-code".to_string(),
source_js: "await tools.write_stdin({ chars: '' })".to_string(),
},
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-stdin".to_string(),
model_visible_call_id: None,
code_mode_runtime_tool_id: Some("runtime-tool-1".to_string()),
requester: crate::raw_event::RawToolCallRequester::CodeCell {
runtime_cell_id: "cell-1".to_string(),
},
kind: ToolCallKind::WriteStdin,
summary: generic_summary("write_stdin"),
invocation_payload: Some(request_payload),
},
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-stdin".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(response_payload),
},
)?;
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(())
}
fn append_inference_with_tool_call(writer: &TraceWriter) -> anyhow::Result<()> {
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"input": [message("user", "run tests")]
}),
)?;
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: "inference-1".to_string(),
thread_id: "thread-root".to_string(),
codex_turn_id: "turn-1".to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload: request,
})?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": "resp-1",
"output_items": [{
"type": "function_call",
"name": "exec_command",
"arguments": "{\"cmd\":\"cargo test\"}",
"call_id": "call-1"
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceCompleted {
inference_call_id: "inference-1".to_string(),
response_id: Some("resp-1".to_string()),
upstream_request_id: None,
response_payload: response,
})?;
Ok(())
}
fn append_followup_with_tool_output(writer: &TraceWriter) -> anyhow::Result<()> {
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"previous_response_id": "resp-1",
"input": [{
"type": "function_call_output",
"call_id": "call-1",
"output": "ok\n"
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: "inference-2".to_string(),
thread_id: "thread-root".to_string(),
codex_turn_id: "turn-2".to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload: request,
})?;
Ok(())
}