aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "rollout-trace",
crate_name = "akode_rollout_trace",
)

View File

@@ -0,0 +1,28 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-rollout-trace"
version.workspace = true
[lib]
doctest = false
name = "akode_rollout_trace"
path = "src/lib.rs"
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
akode-code-mode = { workspace = true }
akode-protocol = { workspace = true }
http = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sha2 = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true, features = ["v4"] }
[dev-dependencies]
pretty_assertions = { workspace = true }
tempfile = { workspace = true }

View File

@@ -0,0 +1,215 @@
# Rollout Trace
> **Privacy:** Rollout tracing is not telemetry. Codex does **not** upload or
> report these traces; it writes local bundles only when
> `AKODE_ROLLOUT_TRACE_ROOT` is set. Those local bundles can contain prompts,
> responses, tool inputs/outputs, terminal output, and paths, so treat them as
> sensitive.
Rollout tracing is an opt-in diagnostic path for understanding what happened
during a Codex session. It records raw runtime evidence into a local bundle on
disk, then replays that bundle into a semantic graph that a debugger or UI can
inspect.
The key design choice is: **observe first, interpret later**.
Hot-path Codex code does not try to build the final graph while the session is
running. It writes ordered raw events and payload references. The offline reducer
then decides which events became model-visible conversation, which events were
runtime work, and how information moved between threads, tools, code cells, and
terminal sessions.
## What This Gives Us
Rollout traces make failures debuggable when the normal transcript is not enough.
They preserve enough evidence to answer questions like:
- Which model request produced this tool call?
- Did this output come from the model-visible transcript, a code-mode runtime
value, a terminal operation, or an agent notification?
- Which code-mode `exec` cell issued a nested tool call?
- Which terminal operation created or reused a running process?
- Which multi-agent v2 tool call spawned, messaged, received from, or closed a
child thread?
The reduced `state.json` is intentionally not just a transcript. It is a graph of
model-visible conversation plus the runtime objects that explain how Codex got
there.
## System Shape
```mermaid
flowchart TD
subgraph Runtime["akode-core runtime"]
Protocol["protocol lifecycle\nthread start/end, turn start/end"]
Inference["inference + compaction\nrequests, responses, checkpoints"]
Tools["tool dispatch\ndirect model tools + code-mode nested tools"]
CodeMode["code-mode runtime\nexec cells, yields, waits, termination"]
Terminal["terminal runtime\nexec_command / write_stdin operations"]
Agents["multi_agent_v2\nspawn, task delivery, result, close"]
end
Context["ThreadTraceContext\nroot/child no-op-capable producer"]
Writer["TraceWriter\nassigns seq and writes payloads before events"]
subgraph Bundle["trace bundle"]
Manifest["manifest.json\ntrace_id, rollout_id, root_thread_id"]
Events["trace.jsonl\nordered raw event spine"]
Payloads["payloads/*.json\nlarge raw evidence"]
end
Reducer["replay_bundle\ndeterministic offline reducer"]
subgraph State["state.json"]
Threads["threads + turns"]
Conversation["conversation_items\nwhat the model saw"]
RuntimeObjects["inference_calls, tool_calls,\ncode_cells, terminals, compactions"]
Edges["interaction_edges\nspawn, task, result, close"]
RawRefs["raw_payload refs"]
end
Protocol --> Context
Inference --> Context
Tools --> Context
CodeMode --> Context
Terminal --> Context
Agents --> Context
Context --> Writer
Writer --> Manifest
Writer --> Payloads
Writer --> Events
Manifest --> Reducer
Events --> Reducer
Payloads --> Reducer
Reducer --> Threads
Reducer --> Conversation
Reducer --> RuntimeObjects
Reducer --> Edges
Reducer --> RawRefs
```
The thread context is deliberately small and no-op capable. A root session starts
one from `AKODE_ROLLOUT_TRACE_ROOT`; fresh spawned child threads derive their
own context from the parent's context so the whole rollout tree shares one
writer. Disabled contexts accept the same calls and record nothing.
When tracing is enabled, a thread can start or resume only if its recorder
initializes successfully. A later write failure stops recording. Partial
bundles remain available for replay. The reducer sets `recording_complete` in
`state.json` when it reads the closing record written by the last trace handle,
including when the recorded task was interrupted.
## Bundle Layout
A trace bundle contains:
- `manifest.json`: trace identity and bundle metadata.
- `trace.jsonl`: append-only raw events ordered by writer-assigned `seq`.
- `payloads/*.json`: raw requests, responses, tool inputs/results, runtime
events, terminal output, compaction data, and protocol snapshots.
- `state.json`: optional reducer output written by `akode debug trace-reduce`.
`trace_id` identifies this diagnostic artifact. `rollout_id` identifies the
Codex rollout/session being observed. Keeping those separate lets us reason about
the stored trace without confusing it with the product-level session identity.
To reduce a bundle:
```bash
codex debug trace-reduce <trace-bundle>
```
By default this writes `<trace-bundle>/state.json`. Rust callers can also call
`akode_rollout_trace::replay_bundle` directly.
## Raw Evidence vs Reduced Graph
```mermaid
flowchart LR
Model["model-visible payloads\nrequests and response output items"]
Runtime["runtime observations\ntool dispatch, terminal output, code-mode JSON"]
RawPayloads["payloads/*.json\nexact evidence"]
Reducer["reducer"]
Conversation["ConversationItem\nwhat the model saw"]
ToolCall["ToolCall\nruntime tool boundary"]
CodeCell["CodeCell\nmodel-authored exec cell"]
TerminalOperation["TerminalOperation\ncommand/write/poll"]
InteractionEdge["InteractionEdge\ninformation flow"]
Model --> RawPayloads
Runtime --> RawPayloads
RawPayloads --> Reducer
Reducer --> Conversation
Reducer --> ToolCall
Reducer --> CodeCell
Reducer --> TerminalOperation
Reducer --> InteractionEdge
CodeCell --> ToolCall
ToolCall --> TerminalOperation
ToolCall --> InteractionEdge
Conversation --> InteractionEdge
```
This distinction is the reason the model has both raw payload references and
semantic objects. A code-mode nested tool call, for example, has JSON input and
output at the JavaScript runtime boundary, but the model-visible transcript only
contains the surrounding `exec` custom tool call and its eventual output.
The reducer keeps those facts separate:
- `ConversationItem` records what appeared in model-facing requests/responses.
- `ToolCall`, `CodeCell`, `TerminalOperation`, `InferenceCall`, and
`Compaction` record runtime/debug boundaries.
- `InteractionEdge` records information flow between objects, such as a
`spawn_agent` tool call delivering a task into a child thread.
- `RawPayloadRef` points back to exact evidence when a viewer needs more detail
than the reduced graph stores inline.
## Multi-Agent v2
Multi-agent v2 child threads share the root trace writer. That means one root
bundle reduces into one graph containing the parent thread, child threads, and
the edges between them.
```mermaid
flowchart LR
RootTool["root ToolCall\nspawn_agent / followup_task / send_message"]
ChildInput["child ConversationItem\ninjected task/message"]
ChildThread["child AgentThread"]
ChildResult["child assistant ConversationItem\nresult message"]
RootNotice["root ConversationItem\nsubagent notification"]
CloseTool["root ToolCall\nclose_agent"]
TargetThread["target AgentThread"]
RootTool -- "spawn/task edge" --> ChildInput
ChildInput --> ChildThread
ChildThread --> ChildResult
ChildResult -- "agent_result edge" --> RootNotice
CloseTool -- "close_agent edge" --> TargetThread
```
Top-level independent threads still get independent bundles. Spawned child
threads are different: they are part of the same rollout tree, so they belong in
the same raw event log, payload directory, and reduced `state.json`.
## Reducer Invariants
The reducer is strict where the raw evidence should be self-consistent:
- raw events are replayed in `seq` order;
- payload files must exist before events refer to them;
- reduced object IDs are stable within one replay;
- runtime events may be queued until the model-visible source or delivery target
has been observed;
- model-visible conversation is derived from model-facing payloads, not from
runtime convenience output;
- runtime payloads are evidence, not proof that the model saw the same bytes.
Those invariants let the reduced graph stay small while preserving a path back
to the original evidence whenever a debugger needs to explain why an object or
edge exists.

View File

@@ -0,0 +1,49 @@
//! Trace bundle manifest and local layout constants.
use serde::Deserialize;
use serde::Serialize;
use crate::model::AgentThreadId;
pub(crate) const MANIFEST_FILE_NAME: &str = "manifest.json";
pub(crate) const RAW_EVENT_LOG_FILE_NAME: &str = "trace.jsonl";
pub(crate) const PAYLOADS_DIR_NAME: &str = "payloads";
/// Conventional file name for a reducer-written `RolloutTrace` cache.
pub const REDUCED_STATE_FILE_NAME: &str = "state.json";
pub(crate) const TRACE_MANIFEST_SCHEMA_VERSION: u32 = 2;
pub(crate) const REDUCED_TRACE_SCHEMA_VERSION: u32 = 2;
/// Manifest stored at the root of a trace bundle.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct TraceBundleManifest {
pub(crate) schema_version: u32,
pub(crate) trace_id: String,
pub(crate) rollout_id: String,
/// Root thread for the recorded rollout. Replay should fail rather than
/// inventing a placeholder, because every reduced object is scoped back to
/// this thread tree.
pub(crate) root_thread_id: AgentThreadId,
pub(crate) started_at_unix_ms: i64,
pub(crate) raw_event_log: String,
pub(crate) payloads_dir: String,
}
impl TraceBundleManifest {
/// Builds a manifest that uses the standard local bundle layout.
pub(crate) fn new(
trace_id: String,
rollout_id: String,
root_thread_id: AgentThreadId,
started_at_unix_ms: i64,
) -> Self {
Self {
schema_version: TRACE_MANIFEST_SCHEMA_VERSION,
trace_id,
rollout_id,
root_thread_id,
started_at_unix_ms,
raw_event_log: RAW_EVENT_LOG_FILE_NAME.to_string(),
payloads_dir: PAYLOADS_DIR_NAME.to_string(),
}
}
}

View File

@@ -0,0 +1,185 @@
//! Hot-path helpers for recording code-mode runtime cell lifecycles.
//!
//! The public `exec` tool is reduced as a first-class `CodeCell` instead of a
//! generic tool call. This module keeps the runtime response serialization and
//! lifecycle event policy inside the trace crate while core carries a compact,
//! no-op capable handle through execution and waits.
use std::sync::Arc;
use akode_code_mode::RuntimeResponse;
use serde::Serialize;
use tracing::warn;
use crate::model::AgentThreadId;
use crate::model::CodeCellRuntimeStatus;
use crate::model::CodexTurnId;
use crate::model::ModelVisibleCallId;
use crate::payload::RawPayloadKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawTraceEventContext;
use crate::raw_event::RawTraceEventPayload;
use crate::writer::TraceWriter;
/// No-op capable trace handle for one code-mode runtime cell.
#[derive(Clone, Debug)]
pub struct CodeCellTraceContext {
state: CodeCellTraceContextState,
}
#[derive(Clone, Debug)]
enum CodeCellTraceContextState {
Disabled,
Enabled(EnabledCodeCellTraceContext),
}
#[derive(Clone, Debug)]
struct EnabledCodeCellTraceContext {
writer: Arc<TraceWriter>,
thread_id: AgentThreadId,
codex_turn_id: CodexTurnId,
runtime_cell_id: String,
}
/// Raw code-mode response captured at the runtime boundary.
///
/// This is not the model-visible custom-tool output. The reducer links that
/// output through `CodeCell.output_item_ids` once the conversation item appears.
/// Keeping the raw runtime payload here preserves stored-value and lifecycle
/// evidence without duplicating the model-facing transcript.
#[derive(Serialize)]
struct CodeCellResponseTracePayload<'a> {
response: &'a RuntimeResponse,
}
impl CodeCellTraceContext {
/// Builds a context that accepts trace calls and records nothing.
pub(crate) fn disabled() -> Self {
Self {
state: CodeCellTraceContextState::Disabled,
}
}
/// Builds a context for an already-known code-mode runtime cell.
pub(crate) fn enabled(
writer: Arc<TraceWriter>,
thread_id: impl Into<AgentThreadId>,
codex_turn_id: impl Into<CodexTurnId>,
runtime_cell_id: impl Into<String>,
) -> Self {
Self {
state: CodeCellTraceContextState::Enabled(EnabledCodeCellTraceContext {
writer,
thread_id: thread_id.into(),
codex_turn_id: codex_turn_id.into(),
runtime_cell_id: runtime_cell_id.into(),
}),
}
}
/// Records the parent runtime object before JavaScript can issue nested tool calls.
pub fn record_started(
&self,
model_visible_call_id: impl Into<ModelVisibleCallId>,
source_js: impl Into<String>,
) {
let CodeCellTraceContextState::Enabled(context) = &self.state else {
return;
};
append_with_context_best_effort(
context,
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id: context.runtime_cell_id.clone(),
model_visible_call_id: model_visible_call_id.into(),
source_js: source_js.into(),
},
);
}
/// Records the first response returned by the public code-mode `exec` tool.
///
/// A yielded response returns control to the model while the cell keeps
/// running. Terminal initial responses should be followed by `record_ended`
/// by the caller so the reducer can distinguish model-visible output from
/// runtime completion.
pub fn record_initial_response(&self, response: &RuntimeResponse) {
let CodeCellTraceContextState::Enabled(context) = &self.state else {
return;
};
append_with_context_best_effort(
context,
RawTraceEventPayload::CodeCellInitialResponse {
runtime_cell_id: context.runtime_cell_id.clone(),
status: code_cell_status_for_runtime_response(response),
response_payload: code_cell_response_payload(context, response),
},
);
}
/// Records the terminal lifecycle point for a code-mode runtime cell.
pub fn record_ended(&self, response: &RuntimeResponse) {
let CodeCellTraceContextState::Enabled(context) = &self.state else {
return;
};
append_with_context_best_effort(
context,
RawTraceEventPayload::CodeCellEnded {
runtime_cell_id: context.runtime_cell_id.clone(),
status: code_cell_status_for_runtime_response(response),
response_payload: code_cell_response_payload(context, response),
},
);
}
}
fn code_cell_status_for_runtime_response(response: &RuntimeResponse) -> CodeCellRuntimeStatus {
match response {
RuntimeResponse::Yielded { .. } => CodeCellRuntimeStatus::Yielded,
RuntimeResponse::Terminated { .. } => CodeCellRuntimeStatus::Terminated,
RuntimeResponse::Result { error_text, .. } => {
if error_text.is_some() {
CodeCellRuntimeStatus::Failed
} else {
CodeCellRuntimeStatus::Completed
}
}
}
}
fn code_cell_response_payload(
context: &EnabledCodeCellTraceContext,
response: &RuntimeResponse,
) -> Option<RawPayloadRef> {
write_json_payload_best_effort(
&context.writer,
RawPayloadKind::ToolResult,
&CodeCellResponseTracePayload { response },
)
}
fn write_json_payload_best_effort(
writer: &TraceWriter,
kind: RawPayloadKind,
payload: &impl Serialize,
) -> Option<RawPayloadRef> {
match writer.write_json_payload(kind, payload) {
Ok(payload_ref) => Some(payload_ref),
Err(err) => {
warn!("failed to write rollout trace payload: {err:#}");
None
}
}
}
fn append_with_context_best_effort(
context: &EnabledCodeCellTraceContext,
payload: RawTraceEventPayload,
) {
let event_context = RawTraceEventContext {
thread_id: Some(context.thread_id.clone()),
codex_turn_id: Some(context.codex_turn_id.clone()),
};
if let Err(err) = context.writer.append_with_context(event_context, payload) {
warn!("failed to append rollout trace event: {err:#}");
}
}

View File

@@ -0,0 +1,283 @@
//! Hot-path helpers for recording upstream remote compaction attempts.
//!
//! Remote compaction is a model-facing request with a different semantic role
//! from normal sampling. Keeping the no-op capable trace handle in this crate
//! lets `akode-core` record exact endpoint payloads without owning trace schema
//! details.
use std::fmt::Display;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use akode_protocol::models::ResponseItem;
use serde::Serialize;
use tracing::warn;
use crate::inference::TraceResponseItems;
use crate::model::AgentThreadId;
use crate::model::CodexTurnId;
use crate::model::CompactionId;
use crate::model::CompactionRequestId;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventContext;
use crate::raw_event::RawTraceEventPayload;
use crate::writer::TraceWriter;
static NEXT_COMPACTION_REQUEST: AtomicU64 = AtomicU64::new(1);
/// Turn-local remote compaction tracing context.
///
/// A compaction can retry its upstream request before installing one checkpoint. The context
/// owns the stable checkpoint ID; each request attempt gets a separate request ID.
#[derive(Clone, Debug)]
pub struct CompactionTraceContext {
state: CompactionTraceContextState,
}
#[derive(Clone, Debug)]
enum CompactionTraceContextState {
Disabled,
Enabled(EnabledCompactionTraceContext),
}
#[derive(Clone, Debug)]
struct EnabledCompactionTraceContext {
writer: Arc<TraceWriter>,
thread_id: AgentThreadId,
codex_turn_id: CodexTurnId,
compaction_id: CompactionId,
model: String,
provider_name: String,
}
/// One upstream request attempt made while computing a compaction checkpoint.
#[derive(Clone, Debug)]
pub struct CompactionTraceAttempt {
state: CompactionTraceAttemptState,
}
#[derive(Clone, Debug)]
enum CompactionTraceAttemptState {
Disabled,
Enabled(EnabledCompactionTraceAttempt),
}
#[derive(Clone, Debug)]
struct EnabledCompactionTraceAttempt {
context: EnabledCompactionTraceContext,
compaction_request_id: CompactionRequestId,
}
#[derive(Serialize)]
struct TracedCompactionCompleted<'a> {
output_items: TraceResponseItems<'a>,
}
/// History replacement checkpoint persisted when compaction installs new live history.
///
/// The checkpoint keeps compaction separate from ordinary sampling snapshots:
/// `input_history` is the live thread history selected for compaction, while
/// `replacement_history` is what future prompts may carry after the checkpoint.
#[derive(Serialize)]
pub struct CompactionCheckpointTracePayload<'a> {
pub input_history: &'a [ResponseItem],
pub replacement_history: &'a [ResponseItem],
}
impl CompactionTraceContext {
/// Builds a context that accepts trace calls and records nothing.
pub fn disabled() -> Self {
Self {
state: CompactionTraceContextState::Disabled,
}
}
/// Builds an enabled context for upstream attempts that compute one checkpoint.
pub fn enabled(
writer: Arc<TraceWriter>,
thread_id: AgentThreadId,
codex_turn_id: CodexTurnId,
compaction_id: CompactionId,
model: String,
provider_name: String,
) -> Self {
Self {
state: CompactionTraceContextState::Enabled(EnabledCompactionTraceContext {
writer,
thread_id,
codex_turn_id,
compaction_id,
model,
provider_name,
}),
}
}
/// Returns whether this context records compaction traces.
pub fn is_enabled(&self) -> bool {
matches!(self.state, CompactionTraceContextState::Enabled(_))
}
/// Starts a new upstream attempt and records the exact compact endpoint request.
pub fn start_attempt(&self, request: &impl Serialize) -> CompactionTraceAttempt {
let CompactionTraceContextState::Enabled(context) = &self.state else {
return CompactionTraceAttempt::disabled();
};
let attempt = CompactionTraceAttempt {
state: CompactionTraceAttemptState::Enabled(EnabledCompactionTraceAttempt {
context: context.clone(),
compaction_request_id: next_compaction_request_id(),
}),
};
attempt.record_started(request);
attempt
}
/// Records the point where compacted history becomes the live thread history.
///
/// The checkpoint belongs to the same semantic compaction lifecycle as the
/// compact endpoint attempts, so the context reuses its stable compaction ID.
pub fn record_installed(&self, checkpoint: &CompactionCheckpointTracePayload<'_>) {
let CompactionTraceContextState::Enabled(context) = &self.state else {
return;
};
let checkpoint_payload = match context
.writer
.write_json_payload(RawPayloadKind::CompactionCheckpoint, checkpoint)
{
Ok(payload_ref) => payload_ref,
Err(err) => {
warn!("failed to write rollout trace payload: {err:#}");
return;
}
};
let event_context = RawTraceEventContext {
thread_id: Some(context.thread_id.clone()),
codex_turn_id: Some(context.codex_turn_id.clone()),
};
if let Err(err) = context.writer.append_with_context(
event_context,
RawTraceEventPayload::CompactionInstalled {
compaction_id: context.compaction_id.clone(),
checkpoint_payload,
},
) {
warn!("failed to append rollout trace event: {err:#}");
}
}
}
impl CompactionTraceAttempt {
/// Builds an attempt that records nothing.
fn disabled() -> Self {
Self {
state: CompactionTraceAttemptState::Disabled,
}
}
fn record_started(&self, request: &impl Serialize) {
let CompactionTraceAttemptState::Enabled(attempt) = &self.state else {
return;
};
let Some(request_payload) = write_json_payload_best_effort(
&attempt.context.writer,
RawPayloadKind::CompactionRequest,
request,
) else {
return;
};
append_with_context_best_effort(
&attempt.context,
RawTraceEventPayload::CompactionRequestStarted {
compaction_id: attempt.context.compaction_id.clone(),
compaction_request_id: attempt.compaction_request_id.clone(),
thread_id: attempt.context.thread_id.clone(),
codex_turn_id: attempt.context.codex_turn_id.clone(),
model: attempt.context.model.clone(),
provider_name: attempt.context.provider_name.clone(),
request_payload,
},
);
}
/// Records the non-streaming compact endpoint response payload.
///
/// Compaction responses use the same response-item preservation rules as
/// inference streams: traces are evidence, while normal ResponseItem
/// serialization is shaped for future request construction.
pub fn record_completed(&self, output_items: &[ResponseItem]) {
let CompactionTraceAttemptState::Enabled(attempt) = &self.state else {
return;
};
let response_payload = TracedCompactionCompleted {
output_items: TraceResponseItems(output_items),
};
let Some(response_payload) = write_json_payload_best_effort(
&attempt.context.writer,
RawPayloadKind::CompactionResponse,
&response_payload,
) else {
return;
};
append_with_context_best_effort(
&attempt.context,
RawTraceEventPayload::CompactionRequestCompleted {
compaction_id: attempt.context.compaction_id.clone(),
compaction_request_id: attempt.compaction_request_id.clone(),
response_payload,
},
);
}
/// Records the compact endpoint result without forcing callers to branch on trace events.
pub fn record_result<E: Display>(&self, result: Result<&[ResponseItem], E>) {
match result {
Ok(output_items) => self.record_completed(output_items),
Err(err) => self.record_failed(err),
}
}
/// Records pre-response failures from the compact endpoint.
pub fn record_failed(&self, error: impl Display) {
let CompactionTraceAttemptState::Enabled(attempt) = &self.state else {
return;
};
append_with_context_best_effort(
&attempt.context,
RawTraceEventPayload::CompactionRequestFailed {
compaction_id: attempt.context.compaction_id.clone(),
compaction_request_id: attempt.compaction_request_id.clone(),
error: error.to_string(),
},
);
}
}
fn next_compaction_request_id() -> CompactionRequestId {
let ordinal = NEXT_COMPACTION_REQUEST.fetch_add(1, Ordering::Relaxed);
format!("compaction_request:{ordinal}")
}
fn write_json_payload_best_effort(
writer: &TraceWriter,
kind: RawPayloadKind,
payload: &impl Serialize,
) -> Option<crate::RawPayloadRef> {
writer.write_json_payload(kind, payload).ok()
}
fn append_with_context_best_effort(
context: &EnabledCompactionTraceContext,
payload: RawTraceEventPayload,
) {
let event_context = RawTraceEventContext {
thread_id: Some(context.thread_id.clone()),
codex_turn_id: Some(context.codex_turn_id.clone()),
};
let _ = context.writer.append_with_context(event_context, payload);
}

View File

@@ -0,0 +1,538 @@
//! Hot-path helpers for recording upstream inference attempts.
//!
//! A disabled context records nothing, which keeps one-shot HTTP calls,
//! WebSocket reuse, and retry/fallback attempts on the same lifecycle path.
//! Transport callers can check whether terminal records need output items
//! before retaining them.
use std::fmt::Display;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use akode_protocol::models::ResponseItem;
use akode_protocol::protocol::TokenUsage;
use http::HeaderMap;
use http::HeaderValue;
use serde::Serialize;
use serde::Serializer;
use serde::ser::Error;
use serde::ser::SerializeSeq;
use serde_json::Value as JsonValue;
use uuid::Uuid;
use crate::model::AgentThreadId;
use crate::model::CodexTurnId;
use crate::model::InferenceCallId;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventContext;
use crate::raw_event::RawTraceEventPayload;
use crate::writer::TraceWriter;
const INFERENCE_CALL_ID_HEADER: &str = "x-codex-inference-call-id";
/// Turn-local inference tracing context.
///
/// This is intentionally a no-op capable handle instead of an `Option` at each
/// transport callsite. Whether tracing is enabled is a session concern; retry,
/// fallback, and stream mapping code should always be able to say what happened
/// without first branching on trace availability.
#[derive(Clone, Debug)]
pub struct InferenceTraceContext {
state: InferenceTraceContextState,
}
#[derive(Clone, Debug)]
enum InferenceTraceContextState {
Disabled,
Enabled(EnabledInferenceTraceContext),
}
#[derive(Clone, Debug)]
struct EnabledInferenceTraceContext {
writer: Arc<TraceWriter>,
thread_id: AgentThreadId,
codex_turn_id: CodexTurnId,
model: String,
provider_name: String,
}
/// One concrete upstream request attempt.
///
/// A Codex turn can create multiple attempts when auth recovery retries the
/// HTTP request or WebSocket setup falls back to HTTP. Completion is often
/// observed after the client returns the response stream, so the attempt owns
/// the terminal guard that prevents duplicate lifecycle events.
#[derive(Debug)]
pub struct InferenceTraceAttempt {
state: InferenceTraceAttemptState,
}
#[derive(Debug)]
enum InferenceTraceAttemptState {
Disabled,
Enabled(EnabledInferenceTraceAttempt),
}
#[derive(Debug)]
struct EnabledInferenceTraceAttempt {
context: EnabledInferenceTraceContext,
inference_call_id: InferenceCallId,
terminal_recorded: AtomicBool,
}
/// Non-delta response payload saved for completed or interrupted inference streams.
///
/// We intentionally record completed output items instead of every stream delta
/// here. The raw stream can be added later as a separate payload class; this
/// response summary gives the reducer stable response identity when available
/// plus model-visible output without duplicating high-volume text deltas.
#[derive(Serialize)]
struct TracedResponseStreamOutput<'a> {
response_id: Option<&'a str>,
upstream_request_id: Option<&'a str>,
token_usage: Option<&'a TokenUsage>,
output_items: TraceResponseItems<'a>,
}
impl InferenceTraceContext {
/// Builds a context that accepts trace calls and records nothing.
pub fn disabled() -> Self {
Self {
state: InferenceTraceContextState::Disabled,
}
}
/// Builds an enabled context for all upstream attempts made by one Codex turn.
pub fn enabled(
writer: Arc<TraceWriter>,
thread_id: AgentThreadId,
codex_turn_id: CodexTurnId,
model: String,
provider_name: String,
) -> Self {
Self {
state: InferenceTraceContextState::Enabled(EnabledInferenceTraceContext {
writer,
thread_id,
codex_turn_id,
model,
provider_name,
}),
}
}
/// Starts a new attempt after the concrete provider request has been built.
pub fn start_attempt(&self) -> InferenceTraceAttempt {
let InferenceTraceContextState::Enabled(context) = &self.state else {
return InferenceTraceAttempt::disabled();
};
InferenceTraceAttempt {
state: InferenceTraceAttemptState::Enabled(EnabledInferenceTraceAttempt {
context: context.clone(),
inference_call_id: next_inference_call_id(),
terminal_recorded: AtomicBool::new(false),
}),
}
}
}
impl InferenceTraceAttempt {
/// Builds an attempt that records nothing.
pub fn disabled() -> Self {
Self {
state: InferenceTraceAttemptState::Disabled,
}
}
/// Whether terminal trace records need the completed output items.
pub fn needs_output_items(&self) -> bool {
matches!(&self.state, InferenceTraceAttemptState::Enabled(_))
}
fn inference_call_id(&self) -> Option<&str> {
match &self.state {
InferenceTraceAttemptState::Disabled => None,
InferenceTraceAttemptState::Enabled(attempt) => {
Some(attempt.inference_call_id.as_str())
}
}
}
/// Adds rollout-trace propagation headers for this attempt when tracing is enabled.
pub fn add_request_headers(&self, headers: &mut HeaderMap) {
let Some(inference_call_id) = self.inference_call_id() else {
return;
};
let Ok(inference_call_id) = HeaderValue::from_str(inference_call_id) else {
// These IDs are generated internally as UUID strings, so rejection
// should be impossible in practice. Tracing remains best-effort,
// though, and must never make provider requests fail.
return;
};
headers.insert(INFERENCE_CALL_ID_HEADER, inference_call_id);
}
/// Records the request payload replay should treat as the model-visible inference input.
///
/// This is usually the exact provider request. Callers may instead pass a
/// logical request when the transport omits already-sent input, such as
/// websocket reuse after an untraced warmup response.
pub fn record_started(&self, request: &impl Serialize) {
let InferenceTraceAttemptState::Enabled(attempt) = &self.state else {
return;
};
let Some(request_payload) = write_json_payload_best_effort(
&attempt.context.writer,
RawPayloadKind::InferenceRequest,
request,
) else {
return;
};
append_with_context_best_effort(
&attempt.context,
RawTraceEventPayload::InferenceStarted {
inference_call_id: attempt.inference_call_id.clone(),
thread_id: attempt.context.thread_id.clone(),
codex_turn_id: attempt.context.codex_turn_id.clone(),
model: attempt.context.model.clone(),
provider_name: attempt.context.provider_name.clone(),
request_payload,
},
);
}
/// Records successful provider completion and serializes the observed output items.
///
/// Callers pass protocol-native response items so this crate owns the
/// trace-specific serialization rules. That keeps akode-core focused on
/// transport behavior while preserving trace evidence that normal request
/// serialization intentionally omits.
pub fn record_completed(
&self,
response_id: &str,
upstream_request_id: Option<&str>,
token_usage: &Option<TokenUsage>,
output_items: &[ResponseItem],
) {
let Some(attempt) = self.take_terminal_attempt() else {
return;
};
let Some(response_payload) = write_response_payload_best_effort(
attempt,
Some(response_id),
upstream_request_id,
token_usage.as_ref(),
output_items,
) else {
return;
};
append_with_context_best_effort(
&attempt.context,
RawTraceEventPayload::InferenceCompleted {
inference_call_id: attempt.inference_call_id.clone(),
response_id: Some(response_id.to_string()),
upstream_request_id: upstream_request_id.map(str::to_string),
response_payload,
},
);
}
/// Records pre-response and mid-stream failures.
pub fn record_failed(
&self,
error: impl Display,
upstream_request_id: Option<&str>,
output_items: &[ResponseItem],
) {
let Some(attempt) = self.take_terminal_attempt() else {
return;
};
let partial_response_payload = if output_items.is_empty() {
None
} else {
write_response_payload_best_effort(
attempt,
/*response_id*/ None,
upstream_request_id,
/*token_usage*/ None,
output_items,
)
};
append_with_context_best_effort(
&attempt.context,
RawTraceEventPayload::InferenceFailed {
inference_call_id: attempt.inference_call_id.clone(),
upstream_request_id: upstream_request_id.map(str::to_string),
error: error.to_string(),
partial_response_payload,
},
);
}
/// Records a provider stream that Codex intentionally stopped consuming.
///
/// This happens when the turn is interrupted or when mailbox delivery
/// preempts the current sampling request. Complete output items observed
/// before that point are retained as partial response evidence.
pub fn record_cancelled(
&self,
reason: impl Display,
upstream_request_id: Option<&str>,
output_items: &[ResponseItem],
) {
let Some(attempt) = self.take_terminal_attempt() else {
return;
};
let partial_response_payload = if output_items.is_empty() {
None
} else {
write_response_payload_best_effort(
attempt,
/*response_id*/ None,
upstream_request_id,
/*token_usage*/ None,
output_items,
)
};
append_with_context_best_effort(
&attempt.context,
RawTraceEventPayload::InferenceCancelled {
inference_call_id: attempt.inference_call_id.clone(),
upstream_request_id: upstream_request_id.map(str::to_string),
reason: reason.to_string(),
partial_response_payload,
},
);
}
fn take_terminal_attempt(&self) -> Option<&EnabledInferenceTraceAttempt> {
let attempt = match &self.state {
InferenceTraceAttemptState::Disabled => return None,
InferenceTraceAttemptState::Enabled(attempt) => attempt,
};
if attempt.terminal_recorded.swap(true, Ordering::AcqRel) {
return None;
}
Some(attempt)
}
}
/// Serializes a response item for trace evidence rather than future request construction.
///
/// The protocol serializer intentionally omits some readable reasoning content
/// when shaping items for later model requests. Rollout traces need the item as
/// Codex received it, so this helper restores that content in the raw payload.
fn trace_response_item_json(item: &ResponseItem) -> serde_json::Result<JsonValue> {
let mut value = serde_json::to_value(item)?;
if let ResponseItem::Reasoning {
content: Some(content),
..
} = item
&& let JsonValue::Object(object) = &mut value
{
object.insert("content".to_string(), serde_json::to_value(content)?);
}
Ok(value)
}
/// Serializes response evidence one item at a time, propagating failures to the writer.
pub(crate) struct TraceResponseItems<'a>(pub &'a [ResponseItem]);
impl Serialize for TraceResponseItems<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut sequence = serializer.serialize_seq(Some(self.0.len()))?;
for item in self.0 {
let value = trace_response_item_json(item).map_err(S::Error::custom)?;
sequence.serialize_element(&value)?;
}
sequence.end()
}
}
fn next_inference_call_id() -> InferenceCallId {
Uuid::new_v4().to_string()
}
fn write_json_payload_best_effort(
writer: &TraceWriter,
kind: RawPayloadKind,
payload: &impl Serialize,
) -> Option<crate::RawPayloadRef> {
writer.write_json_payload(kind, payload).ok()
}
fn write_response_payload_best_effort(
attempt: &EnabledInferenceTraceAttempt,
response_id: Option<&str>,
upstream_request_id: Option<&str>,
token_usage: Option<&TokenUsage>,
output_items: &[ResponseItem],
) -> Option<crate::RawPayloadRef> {
let response_payload = TracedResponseStreamOutput {
response_id,
upstream_request_id,
token_usage,
output_items: TraceResponseItems(output_items),
};
write_json_payload_best_effort(
&attempt.context.writer,
RawPayloadKind::InferenceResponse,
&response_payload,
)
}
fn append_with_context_best_effort(
context: &EnabledInferenceTraceContext,
payload: RawTraceEventPayload,
) {
let event_context = RawTraceEventContext {
thread_id: Some(context.thread_id.clone()),
codex_turn_id: Some(context.codex_turn_id.clone()),
};
let _ = context.writer.append_with_context(event_context, payload);
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use akode_protocol::ResponseItemId;
use akode_protocol::models::ReasoningItemContent;
use akode_protocol::models::ReasoningItemReasoningSummary;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use super::*;
use crate::model::ExecutionStatus;
use crate::replay_bundle;
#[test]
fn disabled_attempt_adds_no_request_headers() {
let mut headers = HeaderMap::new();
InferenceTraceAttempt::disabled().add_request_headers(&mut headers);
assert!(headers.is_empty());
}
#[test]
fn enabled_attempt_adds_inference_request_header() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = Arc::new(TraceWriter::create(
temp.path(),
"trace-1".to_string(),
"rollout-1".to_string(),
"thread-root".to_string(),
)?);
let context = InferenceTraceContext::enabled(
writer,
"thread-root".to_string(),
"turn-1".to_string(),
"gpt-test".to_string(),
"test-provider".to_string(),
);
let attempt = context.start_attempt();
let mut headers = HeaderMap::new();
attempt.add_request_headers(&mut headers);
let header = headers
.get(INFERENCE_CALL_ID_HEADER)
.expect("inference header present");
assert_eq!(Some(header.to_str()?), attempt.inference_call_id());
assert!(Uuid::parse_str(header.to_str()?).is_ok());
Ok(())
}
#[test]
fn enabled_context_records_replayable_inference_attempt() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = Arc::new(TraceWriter::create(
temp.path(),
"trace-1".to_string(),
"rollout-1".to_string(),
"thread-root".to_string(),
)?);
writer.append(RawTraceEventPayload::ThreadStarted {
thread_id: "thread-root".to_string(),
agent_path: "/root".to_string(),
metadata_payload: None,
})?;
writer.append(RawTraceEventPayload::CodexTurnStarted {
codex_turn_id: "turn-1".to_string(),
thread_id: "thread-root".to_string(),
})?;
let context = InferenceTraceContext::enabled(
writer,
"thread-root".to_string(),
"turn-1".to_string(),
"gpt-test".to_string(),
"test-provider".to_string(),
);
let attempt = context.start_attempt();
attempt.record_started(&json!({
"model": "gpt-test",
"input": [{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "hello"}]
}],
}));
attempt.record_completed("resp-1", Some("req-1"), &None, &[]);
let rollout = replay_bundle(temp.path())?;
let inference = rollout
.inference_calls
.values()
.next()
.expect("recorded inference call");
assert_eq!(rollout.inference_calls.len(), 1);
assert_eq!(inference.thread_id, "thread-root");
assert_eq!(inference.codex_turn_id, "turn-1");
assert_eq!(inference.execution.status, ExecutionStatus::Completed);
assert_eq!(inference.upstream_request_id, Some("req-1".to_string()));
assert_eq!(rollout.raw_payloads.len(), 2);
Ok(())
}
#[test]
fn traced_response_item_preserves_reasoning_content_omitted_by_normal_serializer() {
let item = ResponseItem::Reasoning {
id: Some(ResponseItemId::with_suffix("rs", "1")),
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "summary".to_string(),
}],
content: Some(vec![ReasoningItemContent::Text {
text: "raw reasoning".to_string(),
}]),
encrypted_content: Some("encoded".to_string()),
internal_chat_message_metadata_passthrough: None,
};
let normal = serde_json::to_value(&item).expect("response item serializes");
let traced = trace_response_item_json(&item).expect("trace item serializes");
assert_eq!(normal.get("content"), None);
assert_eq!(
traced,
json!({
"type": "reasoning",
"id": "rs_1",
"summary": [{"type": "summary_text", "text": "summary"}],
"content": [{"type": "text", "text": "raw reasoning"}],
"encrypted_content": "encoded",
}),
);
}
}

View File

@@ -0,0 +1,78 @@
//! Trace bundle format, writer, and reducer for Codex rollouts.
//!
//! This crate owns the trace schema. Hot-path Codex code should depend on the
//! small writer API here; semantic replay and viewer projections stay outside
//! `akode-core`.
//!
//! See `README.md` for the system diagram and reducer model.
mod bundle;
mod code_cell;
mod compaction;
mod inference;
mod mcp;
mod model;
mod payload;
mod protocol_event;
mod raw_event;
mod reducer;
mod thread;
mod tool_dispatch;
mod writer;
/// Conventional reduced-state cache name written next to a raw trace bundle.
pub use bundle::REDUCED_STATE_FILE_NAME;
/// No-op-capable handle for recording one code-mode runtime cell.
pub use code_cell::CodeCellTraceContext;
/// Raw checkpoint payload for a remote compaction install event.
pub use compaction::CompactionCheckpointTracePayload;
/// No-op-capable handle for recording remote-compaction requests.
pub use compaction::CompactionTraceAttempt;
/// Shared recorder context for a compaction checkpoint.
pub use compaction::CompactionTraceContext;
/// No-op-capable handle for recording one upstream inference attempt.
pub use inference::InferenceTraceAttempt;
/// Shared recorder context for inference attempts within one Codex turn.
pub use inference::InferenceTraceContext;
/// Trace-owned MCP execution correlation propagated to bridge request metadata.
pub use mcp::McpCallTraceContext;
/// Public reduced trace model returned by replay.
pub use model::*;
/// Stable identifier for one raw payload inside a rollout bundle.
pub use payload::RawPayloadId;
/// Coarse role labels for raw payload files.
pub use payload::RawPayloadKind;
/// Reference to a raw request/response/log payload stored in the bundle.
pub use payload::RawPayloadRef;
/// Monotonic sequence number assigned by the raw trace writer.
pub use raw_event::RawEventSeq;
/// Runtime requester observed before semantic reduction.
pub use raw_event::RawToolCallRequester;
/// One append-only raw trace event from `trace.jsonl`.
pub use raw_event::RawTraceEvent;
/// Event-envelope context supplied by hot-path trace producers.
pub use raw_event::RawTraceEventContext;
/// Typed payload for one raw trace event.
pub use raw_event::RawTraceEventPayload;
/// Replay a raw trace bundle and write/read its reduced `RolloutTrace`.
pub use reducer::replay_bundle;
/// Raw payload captured when a child agent reports completion to its parent.
pub use thread::AgentResultTracePayload;
/// Environment variable that enables local trace-bundle recording.
pub use thread::AKODE_ROLLOUT_TRACE_ROOT_ENV;
/// Raw metadata captured when a thread starts.
pub use thread::ThreadStartedTraceMetadata;
/// No-op-capable handle for recording one thread in a rollout bundle.
pub use thread::ThreadTraceContext;
/// Request data for the canonical Codex tool boundary.
pub use tool_dispatch::ToolDispatchInvocation;
/// Tool input observed at the registry boundary.
pub use tool_dispatch::ToolDispatchPayload;
/// Runtime source that caused a dispatch-level tool call.
pub use tool_dispatch::ToolDispatchRequester;
/// Result data returned from a dispatch-level tool call.
pub use tool_dispatch::ToolDispatchResult;
/// No-op-capable handle for recording one resolved tool dispatch.
pub use tool_dispatch::ToolDispatchTraceContext;
/// Append-only writer used by hot-path Codex instrumentation.
pub use writer::TraceWriter;

View File

@@ -0,0 +1,99 @@
//! Hot-path helpers for correlating concrete MCP executions with rollout traces.
//!
//! Core decides when an MCP request is actually going to execute. The trace
//! crate owns the globally unique ID, the trace event that preserves it in the
//! reduced artifact, and the bridge-private MCP request metadata key.
use crate::McpCallId;
use serde_json::Value as JsonValue;
const MCP_CALL_ID_META_KEY: &str = "codex_bridge_mcp_call_id";
/// No-op capable handle for one concrete MCP backend call.
#[derive(Clone, Debug)]
pub struct McpCallTraceContext {
mcp_call_id: Option<McpCallId>,
}
impl McpCallTraceContext {
/// Builds a context that records nothing and leaves request metadata unchanged.
pub fn disabled() -> Self {
Self { mcp_call_id: None }
}
/// Builds the trace handle for one concrete MCP execution.
pub(crate) fn enabled(mcp_call_id: McpCallId) -> Self {
Self {
mcp_call_id: Some(mcp_call_id),
}
}
/// Returns the trace-owned MCP call ID when rollout tracing is enabled.
pub(crate) fn mcp_call_id(&self) -> Option<&str> {
self.mcp_call_id.as_deref()
}
/// Adds bridge-private MCP correlation metadata to one outgoing request.
pub fn add_request_meta(&self, meta: Option<JsonValue>) -> Option<JsonValue> {
let Some(mcp_call_id) = self.mcp_call_id() else {
return meta;
};
match meta {
Some(JsonValue::Object(mut map)) => {
map.insert(
MCP_CALL_ID_META_KEY.to_string(),
JsonValue::String(mcp_call_id.to_string()),
);
Some(JsonValue::Object(map))
}
None => {
let mut map = serde_json::Map::new();
map.insert(
MCP_CALL_ID_META_KEY.to_string(),
JsonValue::String(mcp_call_id.to_string()),
);
Some(JsonValue::Object(map))
}
// This should never happen but if it does then we'll fallback to
// a noop rather than any breaking behavior. The tracing is best
// effort after all.
Some(_) => meta,
}
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::MCP_CALL_ID_META_KEY;
use super::McpCallTraceContext;
#[test]
fn disabled_mcp_trace_leaves_request_meta_unchanged() {
let meta = Some(json!({"source": "test"}));
assert_eq!(
McpCallTraceContext::disabled().add_request_meta(meta.clone()),
meta
);
}
#[test]
fn enabled_mcp_trace_adds_bridge_correlation_meta() {
let trace = McpCallTraceContext::enabled("mcp-call-id".to_string());
let meta = trace
.add_request_meta(Some(json!({"source": "test"})))
.expect("enabled trace keeps request metadata");
let object = meta
.as_object()
.expect("MCP request metadata remains an object");
assert_eq!(object["source"], json!("test"));
assert_eq!(
object[MCP_CALL_ID_META_KEY],
json!(trace.mcp_call_id().expect("enabled trace has an ID"))
);
}
}

View File

@@ -0,0 +1,208 @@
use serde::Deserialize;
use serde::Serialize;
use crate::payload::RawPayloadId;
use crate::raw_event::RawEventSeq;
use super::AgentPath;
use super::AgentThreadId;
use super::CodeCellId;
use super::CodexTurnId;
use super::CompactionId;
use super::ConversationItemId;
use super::EdgeId;
use super::InferenceCallId;
use super::ModelVisibleCallId;
use super::ToolCallId;
use super::session::ExecutionWindow;
/// One logical transcript item or transcript boundary.
///
/// The reducer builds conversation items primarily from inference request and
/// response payloads. Runtime objects can be listed in `produced_by`, but they
/// must not rewrite what the item body says the model saw. Structural items,
/// such as compaction markers, live in the same ordered list so conversation
/// views can show where the live history changed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConversationItem {
pub item_id: ConversationItemId,
/// Original Responses item ID, scoped to this thread. Retained for joining
/// history acceptance and exact inference without matching rendered text.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub responses_item_id: Option<String>,
/// Wall-clock time of the first local HistoryItemAccepted event in trace order.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub accepted_at_unix_ms: Option<i64>,
/// Sequence of the same event for this Responses item in this thread.
/// Seeing the item in inherited or prepared context is not an acceptance.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub accepted_seq: Option<RawEventSeq>,
pub thread_id: AgentThreadId,
/// Runtime activation that first introduced this item locally, when known.
pub codex_turn_id: Option<CodexTurnId>,
pub first_seen_at_unix_ms: i64,
pub role: ConversationRole,
/// Codex channel for assistant/tool content, when the item is channel-specific.
pub channel: Option<ConversationChannel>,
pub kind: ConversationItemKind,
/// Routing metadata carried by a Responses `agent_message` item.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent_message: Option<AgentMessageMetadata>,
pub body: ConversationBody,
/// Protocol/model `call_id` for function/custom tool call and output items.
pub call_id: Option<ModelVisibleCallId>,
/// Runtime or control-plane objects that caused this conversation item to exist.
pub produced_by: Vec<ProducerRef>,
}
/// Sender and destination identities attached to a model-visible agent message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentMessageMetadata {
/// Agent path that authored the message.
pub author: AgentPath,
/// Agent path that received the message.
pub recipient: AgentPath,
}
/// Model-visible role assigned to a conversation item.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConversationRole {
System,
Developer,
User,
Assistant,
Tool,
}
/// Codex channel for model-visible content.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConversationChannel {
Analysis,
Commentary,
Final,
/// Remote compaction summaries are reintroduced as assistant summary-channel content.
Summary,
}
/// Responses item category after normalization into the reduced transcript.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConversationItemKind {
Message,
Reasoning,
FunctionCall,
FunctionCallOutput,
CustomToolCall,
CustomToolCallOutput,
/// Structural marker inserted where live history was replaced by compaction.
CompactionMarker,
}
/// Ordered content parts for a reduced conversation item.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConversationBody {
/// Renderable model-visible parts. Raw payload refs are used when the bytes
/// are too large or too structured for the normal conversation path.
pub parts: Vec<ConversationPart>,
}
/// One model-visible part inside a conversation item.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ConversationPart {
Text {
text: String,
},
/// A model-provided summary of content whose full form may also be present.
///
/// Reasoning summaries are not interchangeable with raw reasoning text:
/// both can be present in one payload, and replay/debug tooling needs to
/// preserve which representation the model actually returned.
Summary {
text: String,
},
/// Opaque model-visible content that is intentionally not decoded here.
///
/// Reasoning can be carried as `encrypted_content` with no readable text.
/// Keeping that blob inline makes it part of item identity, unlike a raw
/// payload reference whose ID changes every time the same item is replayed
/// in a later inference request.
Encoded {
label: String,
value: String,
},
/// Small JSON-ish body represented by a summary plus a raw ref.
Json {
summary: String,
raw_payload_id: RawPayloadId,
},
Code {
language: String,
source: String,
},
/// Large or uncommon payload that should be lazy-loaded from details UI.
PayloadRef {
label: String,
raw_payload_id: RawPayloadId,
/// Content identity across snapshots, independent of the containing payload file.
#[serde(default, skip_serializing_if = "Option::is_none")]
content_sha256: Option<String>,
},
}
/// Explanation for where a conversation item came from.
///
/// This is deliberately plural at the call site: a function output can be both
/// model-visible conversation and the product of a runtime tool call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ProducerRef {
UserInput,
Inference { inference_call_id: InferenceCallId },
Tool { tool_call_id: ToolCallId },
CodeCell { code_cell_id: CodeCellId },
InteractionEdge { edge_id: EdgeId },
Compaction { compaction_id: CompactionId },
Harness,
}
/// One outbound inference request and its response metadata.
///
/// Full upstream request/response bodies live behind raw payload refs. The
/// request/response item ID lists are the reduced, model-visible snapshot.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InferenceCall {
pub inference_call_id: InferenceCallId,
pub thread_id: AgentThreadId,
pub codex_turn_id: CodexTurnId,
pub execution: ExecutionWindow,
pub model: String,
pub provider_name: String,
/// Responses API response id, used by follow-up `previous_response_id` requests.
pub response_id: Option<String>,
/// Request id returned by HTTP/proxy/engine infrastructure.
pub upstream_request_id: Option<String>,
/// Complete ordered input snapshot sent with this request.
pub request_item_ids: Vec<ConversationItemId>,
/// Ordered output items produced by this response.
pub response_item_ids: Vec<ConversationItemId>,
/// Runtime tool calls whose model-visible call item came from this response.
pub tool_call_ids_started_by_response: Vec<ToolCallId>,
pub usage: Option<TokenUsage>,
pub raw_request_payload_id: RawPayloadId,
/// Full upstream response payload. `None` while running or after pre-stream failures.
pub raw_response_payload_id: Option<RawPayloadId>,
}
/// Token usage summary for one inference call.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenUsage {
pub input_tokens: u64,
pub cached_input_tokens: u64,
#[serde(default)]
pub cache_write_input_tokens: u64,
pub output_tokens: u64,
pub reasoning_output_tokens: u64,
}

View File

@@ -0,0 +1,127 @@
//! Reduced rollout trace model.
//!
//! These types describe the deterministic replay output. They intentionally
//! separate model-visible conversation from runtime/debug objects.
use std::collections::BTreeMap;
use serde::Deserialize;
use serde::Serialize;
use crate::payload::RawPayloadId;
use crate::payload::RawPayloadRef;
mod conversation;
mod runtime;
mod session;
pub use conversation::*;
pub use runtime::*;
pub use session::*;
/// Codex conversation/session UUID.
pub type AgentThreadId = String;
/// Stable multi-agent routing path such as `/root` or `/root/search_docs`.
pub type AgentPath = String;
/// Runtime submission/activation UUID. This is not a chat turn.
pub type CodexTurnId = String;
/// Reduced transcript item ID assigned by the trace reducer.
pub type ConversationItemId = String;
/// Local ID for one outbound upstream inference request.
pub type InferenceCallId = String;
/// Globally unique ID for one concrete MCP backend request.
pub type McpCallId = String;
/// Reducer-owned ID for one runtime tool-call object.
pub type ToolCallId = String;
/// Responses `call_id` / custom-tool call ID visible in inference payloads.
pub type ModelVisibleCallId = String;
/// Tool invocation ID assigned inside the code-mode JavaScript runtime.
pub type CodeModeRuntimeToolId = String;
/// Reducer-owned ID for one model-authored `exec` JavaScript cell.
pub type CodeCellId = String;
/// Process/session ID returned by Codex's terminal runtime.
pub type TerminalId = String;
/// Reducer-owned ID for one command/write/poll operation against a terminal.
pub type TerminalOperationId = String;
/// Reducer-owned ID for one installed conversation-history checkpoint.
pub type CompactionId = String;
/// Reducer-owned ID for one upstream request that computes a compaction.
pub type CompactionRequestId = String;
/// Reducer-owned ID for one information-flow edge.
pub type EdgeId = String;
/// Reducer-owned ID for request/log correlation metadata.
pub type CorrelationId = String;
/// Canonical reduced graph for one Codex rollout.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RolloutTrace {
pub schema_version: u32,
/// Unique identity for this trace capture.
///
/// `rollout_id` names the Codex rollout/session being observed. `trace_id`
/// names the diagnostic artifact produced for that rollout, which keeps
/// storage/replay identity separate from the product-level session identity.
pub trace_id: String,
/// CLI-visible rollout/run identity. Higher-level experiment/sample IDs wrap this object.
pub rollout_id: String,
pub started_at_unix_ms: i64,
/// Wall-clock timestamp for terminal rollout status. `None` means running or partial trace.
pub ended_at_unix_ms: Option<i64>,
pub status: RolloutStatus,
/// All recorder handles closed without a recorded write failure; not task success.
#[serde(default)]
pub recording_complete: bool,
pub root_thread_id: AgentThreadId,
pub threads: BTreeMap<AgentThreadId, AgentThread>,
pub codex_turns: BTreeMap<CodexTurnId, CodexTurn>,
pub conversation_items: BTreeMap<ConversationItemId, ConversationItem>,
pub inference_calls: BTreeMap<InferenceCallId, InferenceCall>,
/// Model-authored `exec` JavaScript cells keyed by reducer-owned cell ID.
pub code_cells: BTreeMap<CodeCellId, CodeCell>,
pub tool_calls: BTreeMap<ToolCallId, ToolCall>,
/// Terminal runtime sessions keyed by process/session ID returned by the runtime.
pub terminal_sessions: BTreeMap<TerminalId, TerminalSession>,
/// Commands/writes/polls against terminals keyed by reducer-owned operation ID.
pub terminal_operations: BTreeMap<TerminalOperationId, TerminalOperation>,
/// Installed compaction checkpoints keyed by checkpoint ID.
pub compactions: BTreeMap<CompactionId, Compaction>,
/// Upstream remote compaction calls keyed by local request ID.
pub compaction_requests: BTreeMap<CompactionRequestId, CompactionRequest>,
/// Information-flow edges between threads, cells, tools, and runtime resources.
pub interaction_edges: BTreeMap<EdgeId, InteractionEdge>,
/// Raw JSON payloads keyed by raw-payload ID. Most point at files outside this object.
pub raw_payloads: BTreeMap<RawPayloadId, RawPayloadRef>,
}
impl RolloutTrace {
/// Builds an empty reduced trace that a reducer can populate.
pub(crate) fn new(
schema_version: u32,
trace_id: String,
rollout_id: String,
root_thread_id: AgentThreadId,
started_at_unix_ms: i64,
) -> Self {
Self {
schema_version,
trace_id,
rollout_id,
started_at_unix_ms,
ended_at_unix_ms: None,
status: RolloutStatus::Running,
recording_complete: false,
root_thread_id,
threads: BTreeMap::new(),
codex_turns: BTreeMap::new(),
conversation_items: BTreeMap::new(),
inference_calls: BTreeMap::new(),
code_cells: BTreeMap::new(),
tool_calls: BTreeMap::new(),
terminal_sessions: BTreeMap::new(),
terminal_operations: BTreeMap::new(),
compactions: BTreeMap::new(),
compaction_requests: BTreeMap::new(),
interaction_edges: BTreeMap::new(),
raw_payloads: BTreeMap::new(),
}
}
}

View File

@@ -0,0 +1,342 @@
use serde::Deserialize;
use serde::Serialize;
use crate::payload::RawPayloadId;
use crate::raw_event::RawEventSeq;
use super::AgentPath;
use super::AgentThreadId;
use super::CodeCellId;
use super::CodeModeRuntimeToolId;
use super::CodexTurnId;
use super::CompactionId;
use super::CompactionRequestId;
use super::ConversationItemId;
use super::EdgeId;
use super::McpCallId;
use super::ModelVisibleCallId;
use super::TerminalId;
use super::TerminalOperationId;
use super::ToolCallId;
use super::session::ExecutionWindow;
/// Runtime/debug object for one model-authored `exec` cell.
///
/// The JavaScript source and custom-tool outputs are still conversation items;
/// this object tracks the code-mode runtime boundary and nested runtime work.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CodeCell {
/// Reducer-owned graph id derived from the model-visible `exec` call id.
/// Runtime cell ids are stored separately because they are only handles for
/// later waits and nested code-mode tools.
pub code_cell_id: CodeCellId,
pub model_visible_call_id: ModelVisibleCallId,
pub thread_id: AgentThreadId,
pub codex_turn_id: CodexTurnId,
/// Conversation item containing the model-authored JavaScript.
pub source_item_id: ConversationItemId,
pub output_item_ids: Vec<ConversationItemId>,
/// Raw code-mode runtime/session id, useful when matching runtime payloads.
pub runtime_cell_id: Option<String>,
/// Full JS-cell runtime window; yielded cells can outlive the initial custom call.
pub execution: ExecutionWindow,
pub runtime_status: CodeCellRuntimeStatus,
pub initial_response_at_unix_ms: Option<i64>,
pub initial_response_seq: Option<RawEventSeq>,
pub initial_response_status: Option<CodeCellRuntimeStatus>,
pub raw_initial_response_payload_id: Option<RawPayloadId>,
pub raw_result_payload_id: Option<RawPayloadId>,
pub yielded_at_unix_ms: Option<i64>,
pub yielded_seq: Option<RawEventSeq>,
pub source_js: String,
pub nested_tool_call_ids: Vec<ToolCallId>,
pub wait_tool_call_ids: Vec<ToolCallId>,
}
/// Code-mode runtime lifecycle.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CodeCellRuntimeStatus {
/// The `exec` request has been accepted but the runtime has not yet started user code.
Starting,
/// Runtime is executing JavaScript and has not yet yielded or terminated.
Running,
/// Initial `exec` returned while JavaScript kept running in the background.
Yielded,
/// Runtime reached a normal terminal result.
Completed,
/// Runtime reached an error terminal result.
Failed,
/// Runtime was explicitly terminated.
Terminated,
}
/// Installed conversation-history replacement boundary.
///
/// Duration-bearing upstream requests live in `CompactionRequest`. This object
/// is the checkpoint where replacement history became the live thread history.
/// The boundary marker and the model-visible summary are separate conversation
/// items: the marker says where history was replaced, while the summary is part
/// of `replacement_item_ids` when the compact endpoint returned one.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Compaction {
pub compaction_id: CompactionId,
pub thread_id: AgentThreadId,
pub codex_turn_id: CodexTurnId,
pub installed_at_unix_ms: i64,
/// Structural conversation item marking where pre-compaction history ended.
pub marker_item_id: ConversationItemId,
/// Upstream compaction request attempts that contributed to this checkpoint.
pub request_ids: Vec<CompactionRequestId>,
/// Logical conversation items present immediately before replacement.
pub input_item_ids: Vec<ConversationItemId>,
/// Replacement conversation items installed by the checkpoint.
pub replacement_item_ids: Vec<ConversationItemId>,
}
/// One upstream remote request made while computing a compaction checkpoint.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompactionRequest {
pub compaction_request_id: CompactionRequestId,
pub compaction_id: CompactionId,
pub thread_id: AgentThreadId,
pub codex_turn_id: CodexTurnId,
pub execution: ExecutionWindow,
pub model: String,
pub provider_name: String,
pub raw_request_payload_id: RawPayloadId,
/// Full compaction response payload. `None` while running or after pre-response failures.
pub raw_response_payload_id: Option<RawPayloadId>,
}
/// Runtime operation requested by the model, a JS code cell, or Codex itself.
///
/// A `ToolCall` is not a chat transcript row. Model-visible call/output items
/// link to it through `model_visible_*_item_ids`; runtime-only tools can have
/// empty model-visible lists.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCall {
pub tool_call_id: ToolCallId,
/// Globally unique MCP execution ID, when this tool reached an MCP backend.
pub mcp_call_id: Option<McpCallId>,
/// Model-visible protocol call ID, if the model directly requested this tool.
pub model_visible_call_id: Option<ModelVisibleCallId>,
/// Code-mode runtime's internal tool invocation ID, if this call came from JS.
pub code_mode_runtime_tool_id: Option<CodeModeRuntimeToolId>,
/// Cell started by this outer exec dispatch, if a matching cell was recorded.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub started_code_cell_id: Option<CodeCellId>,
pub thread_id: AgentThreadId,
/// Runtime activation that started the tool. Background work may outlive this turn.
pub started_by_codex_turn_id: Option<CodexTurnId>,
pub execution: ExecutionWindow,
pub requester: ToolCallRequester,
pub kind: ToolCallKind,
pub model_visible_call_item_ids: Vec<ConversationItemId>,
pub model_visible_output_item_ids: Vec<ConversationItemId>,
/// Terminal operation started by this tool, when the tool touched a terminal.
pub terminal_operation_id: Option<TerminalOperationId>,
pub summary: ToolCallSummary,
/// Original invocation at the Codex tool boundary.
///
/// Direct model tools store the model's function/custom call payload here.
/// Code-mode nested tools store the JSON call made by model-authored JS.
/// Runtime protocol events are deliberately kept separate below because
/// they describe how Codex executed the request, not what the caller sent.
pub raw_invocation_payload_id: Option<RawPayloadId>,
/// Result returned to the immediate requester.
///
/// For direct tools this is the tool output item returned to the model; for
/// code-mode nested tools this is the value returned to JavaScript.
pub raw_result_payload_id: Option<RawPayloadId>,
/// Runtime/protocol payloads observed while executing the tool.
///
/// Examples include exec begin/end, patch begin/end, and MCP begin/end
/// events. Reducers can use these to build richer runtime objects such as
/// terminal operations without overwriting the canonical invocation/result.
pub raw_runtime_payload_ids: Vec<RawPayloadId>,
}
/// Requester of a runtime tool.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ToolCallRequester {
Model,
/// Model-authored JavaScript requested the tool through code-mode.
CodeCell {
code_cell_id: CodeCellId,
},
}
/// Runtime tool category.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ToolCallKind {
ExecCommand,
WriteStdin,
ApplyPatch,
/// Resolved backend identity from an MCP runtime invocation. The callable
/// namespace/name may differ and remain in the summary and raw invocation.
Mcp {
server: String,
tool: String,
},
Web,
ImageGeneration,
SpawnAgent,
AssignAgentTask,
SendMessage,
/// Multi-agent wait operation. Code-mode wait is modeled separately.
WaitAgent,
CloseAgent,
Other {
name: String,
},
}
/// Bounded card/list summary for a tool call.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ToolCallSummary {
/// Tool is summarized by its terminal operation.
Terminal { operation_id: TerminalOperationId },
Agent {
target_agent_path: AgentPath,
/// Task name/path segment when the operation creates or targets a task.
task_name: Option<String>,
message_preview: String,
},
WaitAgent {
/// Wait target, when narrower than "any child".
target_agent_path: Option<AgentPath>,
timeout_ms: Option<u64>,
},
Generic {
label: String,
input_preview: Option<String>,
output_preview: Option<String>,
},
}
/// One terminal process lifetime, including its command and subsequent polls.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TerminalSession {
pub terminal_id: TerminalId,
pub thread_id: AgentThreadId,
pub created_by_operation_id: TerminalOperationId,
pub operation_ids: Vec<TerminalOperationId>,
/// Terminal lifetime. This can outlive the operation that created it.
pub execution: ExecutionWindow,
}
/// One command/write/poll operation against a terminal session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TerminalOperation {
pub operation_id: TerminalOperationId,
/// Reduced session identity, distinct from the recyclable runtime process ID.
pub terminal_id: Option<TerminalId>,
pub tool_call_id: ToolCallId,
pub kind: TerminalOperationKind,
/// Operation execution window. This is not necessarily the terminal session lifetime.
pub execution: ExecutionWindow,
pub request: TerminalRequest,
/// Runtime-observed terminal result. Model-visible output links through observations.
pub result: Option<TerminalResult>,
pub model_observations: Vec<TerminalModelObservation>,
pub raw_payload_ids: Vec<RawPayloadId>,
}
/// Terminal operation category.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TerminalOperationKind {
ExecCommand,
WriteStdin,
}
/// Terminal request summary.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum TerminalRequest {
ExecCommand {
command: Vec<String>,
display_command: String,
cwd: String,
yield_time_ms: Option<u64>,
max_output_tokens: Option<usize>,
},
/// Request to interact with an existing terminal.
WriteStdin {
/// Bytes/text sent to stdin. Empty string means poll/read without writing bytes.
stdin: String,
yield_time_ms: Option<u64>,
max_output_tokens: Option<usize>,
},
}
/// Terminal result observed by the runtime.
///
/// This is debugger/runtime output. It is not proof that the model saw the same
/// bytes; link model-visible call/output items through `TerminalModelObservation`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalResult {
/// Process exit code. `None` if the process is still running or no exit status was produced.
pub exit_code: Option<i32>,
pub stdout: String,
pub stderr: String,
/// Tool runtime's formatted caller-facing output, when present.
pub formatted_output: Option<String>,
/// Token count before truncation, when the tool runtime reported it.
pub original_token_count: Option<usize>,
/// Streaming chunk ID, when this result was assembled from chunked terminal output.
pub chunk_id: Option<String>,
}
/// Conversation items that observed a terminal operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalModelObservation {
pub call_item_ids: Vec<ConversationItemId>,
pub output_item_ids: Vec<ConversationItemId>,
pub source: TerminalObservationSource,
}
/// Source of model-visible terminal observation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TerminalObservationSource {
DirectToolCall,
CodeCellOutput,
}
/// Directed information-flow relationship between trace objects.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InteractionEdge {
pub edge_id: EdgeId,
pub kind: InteractionEdgeKind,
pub source: TraceAnchor,
pub target: TraceAnchor,
pub started_at_unix_ms: i64,
pub ended_at_unix_ms: Option<i64>,
pub carried_item_ids: Vec<ConversationItemId>,
pub carried_raw_payload_ids: Vec<RawPayloadId>,
}
/// Information-flow edge category.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InteractionEdgeKind {
SpawnAgent,
AssignAgentTask,
SendMessage,
AgentResult,
CloseAgent,
}
/// Typed pointer to one stable reduced-trace object.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum TraceAnchor {
ConversationItem { item_id: ConversationItemId },
ToolCall { tool_call_id: ToolCallId },
Thread { thread_id: AgentThreadId },
}

View File

@@ -0,0 +1,111 @@
use serde::Deserialize;
use serde::Serialize;
use crate::raw_event::RawEventSeq;
use super::AgentPath;
use super::AgentThreadId;
use super::CodexTurnId;
use super::ConversationItemId;
use super::EdgeId;
/// Coarse terminal status for the rollout.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RolloutStatus {
/// Writer has not seen a terminal rollout event.
Running,
/// Rollout ended normally.
Completed,
/// Rollout ended because an operation failed.
Failed,
/// Rollout was cancelled or otherwise stopped before normal completion.
Aborted,
}
/// One Codex thread/session participating in the rollout.
///
/// Threads are agents in the multi-agent sense, but the root interactive
/// session is represented by the same object. Runtime objects live in top-level
/// maps and point back to their owning thread; only transcript order is stored
/// here because compaction/reconciliation makes it semantic.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AgentThread {
pub thread_id: AgentThreadId,
/// Stable routing identity. Viewer/search should prefer this over nickname.
pub agent_path: AgentPath,
/// Presentation hint. It can collide and must not be used as identity.
pub nickname: Option<String>,
pub origin: AgentOrigin,
/// Session lifecycle for this thread.
///
/// Child threads can end independently from the root rollout, for example
/// after a parent calls `close_agent`. Keeping this on the thread prevents
/// those shutdowns from being mistaken for whole-rollout completion.
pub execution: ExecutionWindow,
/// Configured model presentation hint. Individual inference calls carry the actual upstream model.
pub default_model: Option<String>,
/// Accepted model-visible conversation in transcript order. Unaccepted
/// response items remain in the graph, reachable through their inference call.
pub conversation_item_ids: Vec<ConversationItemId>,
}
/// Provenance for a traced Codex thread.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum AgentOrigin {
Root,
Spawned {
parent_thread_id: AgentThreadId,
/// Interaction edge that carried the spawn task.
spawn_edge_id: EdgeId,
/// Stable path segment/task name selected by the parent/tool call.
task_name: String,
/// Selected agent role/type, for example `worker` or `explorer`.
agent_role: String,
},
}
/// Runtime interval for a typed trace object.
///
/// Wall-clock timestamps are for display and latency. Sequence numbers are the
/// causal ordering primitive and should be used to pair observations or break
/// same-millisecond ties.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutionWindow {
pub started_at_unix_ms: i64,
pub started_seq: RawEventSeq,
pub ended_at_unix_ms: Option<i64>,
pub ended_seq: Option<RawEventSeq>,
pub status: ExecutionStatus,
}
/// Coarse lifecycle status for a runtime object.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionStatus {
/// Object is still live or the trace ended before its terminal event.
Running,
/// Object completed successfully.
Completed,
/// Object reached an error state.
Failed,
/// Object was cancelled by user/policy/runtime before completion.
Cancelled,
/// Object was aborted when its owner/runtime stopped.
Aborted,
}
/// One activation of the Codex runtime for one thread.
///
/// A Codex turn groups protocol/runtime work for one thread activation.
/// It is not a user/assistant message pair; conversation belongs in
/// `ConversationItem`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CodexTurn {
pub codex_turn_id: CodexTurnId,
pub thread_id: AgentThreadId,
pub execution: ExecutionWindow,
/// Conversation items that directly triggered this activation, when known.
pub input_item_ids: Vec<ConversationItemId>,
}

View File

@@ -0,0 +1,49 @@
//! References to heavyweight trace payloads stored outside the reduced graph.
use serde::Deserialize;
use serde::Serialize;
/// Stable identifier for one raw payload inside a rollout bundle.
pub type RawPayloadId = String;
/// Reference to a raw request/response/log payload.
///
/// `RolloutTrace` stores these references so normal timeline and conversation
/// rendering does not require the browser or reducer output to inline every
/// upstream request, tool response, or terminal log.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RawPayloadRef {
pub raw_payload_id: RawPayloadId,
/// Payload role. This lets details UI choose syntax highlighting and labels
/// without opening the payload file first.
pub kind: RawPayloadKind,
/// Path relative to the trace bundle root.
///
/// The writer always materializes payloads as bundle-local files. Keeping
/// this as a plain path avoids exposing storage modes we do not produce.
pub path: String,
}
/// Coarse role of a raw payload.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum RawPayloadKind {
InferenceRequest,
/// Full upstream inference response or non-delta response stream summary.
InferenceResponse,
CompactionRequest,
/// Trace-only checkpoint captured when processed replacement history is installed.
CompactionCheckpoint,
CompactionResponse,
ToolInvocation,
ToolResult,
/// Raw runtime/protocol observation for an executing tool.
ToolRuntimeEvent,
/// Raw terminal runtime event or stream shard.
TerminalRuntimeEvent,
ProtocolEvent,
/// One-shot metadata captured when a Codex session/thread starts.
SessionMetadata,
/// Runtime notification payload carried when a child agent reports back to its parent.
AgentResult,
}

View File

@@ -0,0 +1,570 @@
//! Mapping from Codex protocol events into raw rollout-trace events.
//!
//! The session layer already emits protocol events for turn lifecycle, terminal
//! sessions, patch application, MCP calls, and collaboration tools. Rollout
//! tracing reuses those observations where they preserve the original payload.
//! MCP results are recorded before protocol-event truncation instead. This module
//! translates protocol events into the smaller trace vocabulary.
//!
//! The long explicit `EventMsg` matches are intentional. Most protocol events
//! are not trace runtime boundaries, but spelling them out makes new protocol
//! variants a compile-time prompt to decide whether the trace should capture
//! them.
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::ExecCommandBeginEvent;
use akode_protocol::protocol::ExecCommandEndEvent;
use akode_protocol::protocol::ExecCommandSource;
use akode_protocol::protocol::ExecCommandStatus;
use akode_protocol::protocol::McpToolCallBeginEvent;
use akode_protocol::protocol::PatchApplyBeginEvent;
use akode_protocol::protocol::PatchApplyEndEvent;
use akode_protocol::protocol::PatchApplyStatus;
use akode_protocol::protocol::SubAgentActivityEvent;
use akode_protocol::protocol::SubAgentActivityKind;
use akode_protocol::protocol::TurnAbortReason;
use serde::Serialize;
use std::time::Duration;
use crate::AgentThreadId;
use crate::CodexTurnId;
use crate::ExecutionStatus;
use crate::RawTraceEventPayload;
use crate::ToolCallKind;
pub(crate) struct CodexTurnTraceEvent {
pub context_turn_id: CodexTurnId,
pub payload: RawTraceEventPayload,
}
pub(crate) fn codex_turn_trace_event(
thread_id: AgentThreadId,
default_turn_id: &str,
event: &EventMsg,
) -> Option<CodexTurnTraceEvent> {
match event {
EventMsg::TurnStarted(event) => {
let codex_turn_id = event.turn_id.clone();
Some(CodexTurnTraceEvent {
context_turn_id: codex_turn_id.clone(),
payload: RawTraceEventPayload::CodexTurnStarted {
codex_turn_id,
thread_id,
},
})
}
EventMsg::TurnComplete(event) => {
let codex_turn_id = event.turn_id.clone();
Some(CodexTurnTraceEvent {
context_turn_id: codex_turn_id.clone(),
payload: RawTraceEventPayload::CodexTurnEnded {
codex_turn_id,
status: if event.error.is_some() {
ExecutionStatus::Failed
} else {
ExecutionStatus::Completed
},
},
})
}
EventMsg::TurnAborted(event) => {
let codex_turn_id = event
.turn_id
.clone()
.unwrap_or_else(|| default_turn_id.to_string());
Some(CodexTurnTraceEvent {
context_turn_id: codex_turn_id.clone(),
payload: RawTraceEventPayload::CodexTurnEnded {
codex_turn_id,
status: execution_status_for_abort_reason(&event.reason),
},
})
}
EventMsg::RawResponseItem(event) => Some(CodexTurnTraceEvent {
context_turn_id: default_turn_id.to_string(),
payload: RawTraceEventPayload::HistoryItemAccepted {
item_id: event.item.id()?.to_string(),
},
}),
_ => None,
}
}
pub(crate) enum ToolRuntimeTraceEvent<'a> {
Started {
tool_call_id: &'a str,
kind: ToolCallKind,
payload: ToolRuntimePayload<'a>,
},
Ended {
tool_call_id: &'a str,
status: ExecutionStatus,
payload: ToolRuntimePayload<'a>,
},
}
/// Borrowed protocol payload that should be persisted as tool runtime data.
///
/// The trace wants the exact protocol payload shape for E2E debugging, while
/// reducers consume the surrounding typed trace events. This enum lets the
/// recorder serialize the original event by reference, without first cloning it
/// or converting it through `serde_json::Value`.
pub(crate) enum ToolRuntimePayload<'a> {
ExecCommandBegin(&'a ExecCommandBeginEvent),
ExecCommandEnd(&'a ExecCommandEndEvent),
PatchApplyBegin(&'a PatchApplyBeginEvent),
PatchApplyEnd(&'a PatchApplyEndEvent),
McpToolCallBegin(&'a McpToolCallBeginEvent),
CollabAgentSpawnBegin(&'a akode_protocol::protocol::CollabAgentSpawnBeginEvent),
CollabAgentSpawnEnd(&'a akode_protocol::protocol::CollabAgentSpawnEndEvent),
CollabAgentInteractionBegin(&'a akode_protocol::protocol::CollabAgentInteractionBeginEvent),
CollabAgentInteractionEnd(&'a akode_protocol::protocol::CollabAgentInteractionEndEvent),
CollabWaitingBegin(&'a akode_protocol::protocol::CollabWaitingBeginEvent),
CollabWaitingEnd(&'a akode_protocol::protocol::CollabWaitingEndEvent),
CollabCloseBegin(&'a akode_protocol::protocol::CollabCloseBeginEvent),
CollabCloseEnd(&'a akode_protocol::protocol::CollabCloseEndEvent),
SubAgentActivity(&'a SubAgentActivityEvent),
}
impl Serialize for ToolRuntimePayload<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
ToolRuntimePayload::ExecCommandBegin(event) => {
ExecCommandBeginTracePayload::from(*event).serialize(serializer)
}
ToolRuntimePayload::ExecCommandEnd(event) => {
ExecCommandEndTracePayload::from(*event).serialize(serializer)
}
ToolRuntimePayload::PatchApplyBegin(event) => event.serialize(serializer),
ToolRuntimePayload::PatchApplyEnd(event) => event.serialize(serializer),
ToolRuntimePayload::McpToolCallBegin(event) => event.serialize(serializer),
ToolRuntimePayload::CollabAgentSpawnBegin(event) => event.serialize(serializer),
ToolRuntimePayload::CollabAgentSpawnEnd(event) => event.serialize(serializer),
ToolRuntimePayload::CollabAgentInteractionBegin(event) => event.serialize(serializer),
ToolRuntimePayload::CollabAgentInteractionEnd(event) => event.serialize(serializer),
ToolRuntimePayload::CollabWaitingBegin(event) => event.serialize(serializer),
ToolRuntimePayload::CollabWaitingEnd(event) => event.serialize(serializer),
ToolRuntimePayload::CollabCloseBegin(event) => event.serialize(serializer),
ToolRuntimePayload::CollabCloseEnd(event) => event.serialize(serializer),
ToolRuntimePayload::SubAgentActivity(event) => event.serialize(serializer),
}
}
}
/// Rollout-trace representation of an exec begin event.
///
/// Rollout traces share the rollout compatibility requirement that paths remain path-flavored
/// strings on disk, even though live events carry `PathUri` internally.
#[derive(Serialize)]
struct ExecCommandBeginTracePayload<'a> {
call_id: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
plugin_id: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
script_path: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
process_id: Option<&'a str>,
turn_id: &'a str,
started_at_ms: i64,
command: &'a [String],
cwd: String,
parsed_cmd: &'a [akode_protocol::parse_command::ParsedCommand],
source: ExecCommandSource,
#[serde(skip_serializing_if = "Option::is_none")]
interaction_input: Option<&'a str>,
}
impl<'a> From<&'a ExecCommandBeginEvent> for ExecCommandBeginTracePayload<'a> {
fn from(event: &'a ExecCommandBeginEvent) -> Self {
let ExecCommandBeginEvent {
call_id,
plugin_id,
script_path,
process_id,
turn_id,
started_at_ms,
command,
cwd,
parsed_cmd,
source,
interaction_input,
} = event;
Self {
call_id,
plugin_id: plugin_id.as_deref(),
script_path: script_path.as_deref(),
process_id: process_id.as_deref(),
turn_id,
started_at_ms: *started_at_ms,
command,
cwd: cwd.inferred_native_path_string(),
parsed_cmd,
source: *source,
interaction_input: interaction_input.as_deref(),
}
}
}
/// Rollout-trace representation of an exec end event.
///
/// Like [`ExecCommandBeginTracePayload`], this renders `cwd` as an inferred native path to preserve
/// the on-disk format rather than serializing the internal `PathUri`.
#[derive(Serialize)]
struct ExecCommandEndTracePayload<'a> {
call_id: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
plugin_id: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
script_path: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
process_id: Option<&'a str>,
turn_id: &'a str,
completed_at_ms: i64,
command: &'a [String],
cwd: String,
parsed_cmd: &'a [akode_protocol::parse_command::ParsedCommand],
source: ExecCommandSource,
#[serde(skip_serializing_if = "Option::is_none")]
interaction_input: Option<&'a str>,
aggregated_output: &'a str,
exit_code: i32,
duration: Duration,
status: &'a ExecCommandStatus,
}
impl<'a> From<&'a ExecCommandEndEvent> for ExecCommandEndTracePayload<'a> {
fn from(event: &'a ExecCommandEndEvent) -> Self {
let ExecCommandEndEvent {
call_id,
plugin_id,
script_path,
process_id,
turn_id,
completed_at_ms,
command,
cwd,
parsed_cmd,
source,
interaction_input,
aggregated_output,
exit_code,
duration,
status,
} = event;
Self {
call_id,
plugin_id: plugin_id.as_deref(),
script_path: script_path.as_deref(),
process_id: process_id.as_deref(),
turn_id,
completed_at_ms: *completed_at_ms,
command,
cwd: cwd.inferred_native_path_string(),
parsed_cmd,
source: *source,
interaction_input: interaction_input.as_deref(),
aggregated_output,
exit_code: *exit_code,
duration: *duration,
status,
}
}
}
pub(crate) fn tool_runtime_trace_event(event: &EventMsg) -> Option<ToolRuntimeTraceEvent<'_>> {
match event {
EventMsg::ExecCommandBegin(event) if event.source != ExecCommandSource::UserShell => {
Some(ToolRuntimeTraceEvent::Started {
tool_call_id: &event.call_id,
kind: match event.source {
ExecCommandSource::UnifiedExecInteraction => ToolCallKind::WriteStdin,
ExecCommandSource::Agent
| ExecCommandSource::UserShell
| ExecCommandSource::UnifiedExecStartup => ToolCallKind::ExecCommand,
},
payload: ToolRuntimePayload::ExecCommandBegin(event),
})
}
EventMsg::ExecCommandEnd(event) if event.source != ExecCommandSource::UserShell => {
Some(ToolRuntimeTraceEvent::Ended {
tool_call_id: &event.call_id,
status: event.status.trace_execution_status(),
payload: ToolRuntimePayload::ExecCommandEnd(event),
})
}
EventMsg::PatchApplyBegin(event) => Some(ToolRuntimeTraceEvent::Started {
tool_call_id: &event.call_id,
kind: ToolCallKind::ApplyPatch,
payload: ToolRuntimePayload::PatchApplyBegin(event),
}),
EventMsg::PatchApplyEnd(event) => Some(ToolRuntimeTraceEvent::Ended {
tool_call_id: &event.call_id,
status: event.status.trace_execution_status(),
payload: ToolRuntimePayload::PatchApplyEnd(event),
}),
EventMsg::McpToolCallBegin(event) => Some(ToolRuntimeTraceEvent::Started {
tool_call_id: &event.call_id,
kind: ToolCallKind::Mcp {
server: event.invocation.server.clone(),
tool: event.invocation.tool.clone(),
},
payload: ToolRuntimePayload::McpToolCallBegin(event),
}),
// The full backend result is recorded before this UI event can truncate it.
EventMsg::McpToolCallEnd(_) => None,
EventMsg::CollabAgentSpawnBegin(event) => Some(ToolRuntimeTraceEvent::Started {
tool_call_id: &event.call_id,
kind: ToolCallKind::SpawnAgent,
payload: ToolRuntimePayload::CollabAgentSpawnBegin(event),
}),
EventMsg::CollabAgentSpawnEnd(event) => Some(ToolRuntimeTraceEvent::Ended {
tool_call_id: &event.call_id,
// A spawn end without a child thread id means the runtime boundary
// finished without creating the requested child thread.
status: if event.new_thread_id.is_some() {
ExecutionStatus::Completed
} else {
ExecutionStatus::Failed
},
payload: ToolRuntimePayload::CollabAgentSpawnEnd(event),
}),
EventMsg::CollabAgentInteractionBegin(event) => Some(ToolRuntimeTraceEvent::Started {
tool_call_id: &event.call_id,
kind: ToolCallKind::SendMessage,
payload: ToolRuntimePayload::CollabAgentInteractionBegin(event),
}),
EventMsg::CollabAgentInteractionEnd(event) => Some(ToolRuntimeTraceEvent::Ended {
tool_call_id: &event.call_id,
status: ExecutionStatus::Completed,
payload: ToolRuntimePayload::CollabAgentInteractionEnd(event),
}),
EventMsg::CollabWaitingBegin(event) => Some(ToolRuntimeTraceEvent::Started {
tool_call_id: &event.call_id,
kind: ToolCallKind::WaitAgent,
payload: ToolRuntimePayload::CollabWaitingBegin(event),
}),
EventMsg::CollabWaitingEnd(event) => Some(ToolRuntimeTraceEvent::Ended {
tool_call_id: &event.call_id,
status: ExecutionStatus::Completed,
payload: ToolRuntimePayload::CollabWaitingEnd(event),
}),
EventMsg::CollabCloseBegin(event) => Some(ToolRuntimeTraceEvent::Started {
tool_call_id: &event.call_id,
kind: ToolCallKind::CloseAgent,
payload: ToolRuntimePayload::CollabCloseBegin(event),
}),
EventMsg::CollabCloseEnd(event) => Some(ToolRuntimeTraceEvent::Ended {
tool_call_id: &event.call_id,
status: ExecutionStatus::Completed,
payload: ToolRuntimePayload::CollabCloseEnd(event),
}),
EventMsg::SubAgentActivity(event) if event.kind != SubAgentActivityKind::Completed => {
Some(ToolRuntimeTraceEvent::Ended {
tool_call_id: &event.event_id,
status: ExecutionStatus::Completed,
payload: ToolRuntimePayload::SubAgentActivity(event),
})
}
EventMsg::SubAgentActivity(_) => None,
EventMsg::Error(_)
| EventMsg::Warning(_)
| EventMsg::AuthRecoveryStarted(_)
| EventMsg::AuthRecoveryCompleted(_)
| EventMsg::GuardianWarning(_)
| EventMsg::SafetyBuffering(_)
| EventMsg::RealtimeConversationStarted(_)
| EventMsg::RealtimeConversationRealtime(_)
| EventMsg::RealtimeConversationClosed(_)
| EventMsg::RealtimeConversationSdp(_)
| EventMsg::TurnModerationMetadata(_)
| EventMsg::ContextCompacted(_)
| EventMsg::ThreadRolledBack(_)
| EventMsg::ThreadGoalUpdated(_)
| EventMsg::ThreadQueueChanged(_)
| EventMsg::TurnStarted(_)
| EventMsg::ThreadSettingsApplied(_)
| EventMsg::TurnComplete(_)
| EventMsg::TokenCount(_)
| EventMsg::AgentMessage(_)
| EventMsg::UserMessage(_)
| EventMsg::AgentReasoning(_)
| EventMsg::AgentReasoningRawContent(_)
| EventMsg::AgentReasoningSectionBreak(_)
| EventMsg::SessionConfigured(_)
| EventMsg::EnvironmentConnected(_)
| EventMsg::EnvironmentDisconnected(_)
| EventMsg::McpStartupUpdate(_)
| EventMsg::McpStartupComplete(_)
| EventMsg::WebSearchBegin(_)
| EventMsg::WebSearchEnd(_)
| EventMsg::ImageGenerationBegin(_)
| EventMsg::ImageGenerationEnd(_)
| EventMsg::ViewImageToolCall(_)
| EventMsg::ExecCommandBegin(_)
| EventMsg::ExecCommandOutputDelta(_)
| EventMsg::TerminalInteraction(_)
| EventMsg::ExecCommandEnd(_)
| EventMsg::ExecApprovalRequest(_)
| EventMsg::RequestPermissions(_)
| EventMsg::RequestUserInput(_)
| EventMsg::DynamicToolCallRequest(_)
| EventMsg::DynamicToolCallResponse(_)
| EventMsg::ElicitationRequest(_)
| EventMsg::ElicitationAbandoned(_)
| EventMsg::NetworkApprovalResolved { .. }
| EventMsg::ApplyPatchApprovalRequest(_)
| EventMsg::GuardianAssessment(_)
| EventMsg::DeprecationNotice(_)
| EventMsg::StreamError(_)
| EventMsg::PatchApplyUpdated(_)
| EventMsg::TurnDiff(_)
| EventMsg::RealtimeConversationListVoicesResponse(_)
| EventMsg::PlanUpdate(_)
| EventMsg::TurnAborted(_)
| EventMsg::ShutdownComplete
| EventMsg::EnteredReviewMode(_)
| EventMsg::ExitedReviewMode(_)
| EventMsg::PrivateSessionEvent(_)
| EventMsg::RawResponseItem(_)
| EventMsg::RawResponseCompleted(_)
| EventMsg::ItemStarted(_)
| EventMsg::ItemCompleted(_)
| EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::PlanDelta(_)
| EventMsg::ReasoningContentDelta(_)
| EventMsg::ReasoningRawContentDelta(_)
| EventMsg::CollabResumeBegin(_)
| EventMsg::CollabResumeEnd(_) => None,
}
}
pub(crate) fn wrapped_protocol_event_type(event: &EventMsg) -> Option<&'static str> {
match event {
EventMsg::SessionConfigured(_) => Some("session_configured"),
EventMsg::TurnStarted(_) => Some("turn_started"),
EventMsg::TurnComplete(_) => Some("turn_complete"),
EventMsg::TurnAborted(_) => Some("turn_aborted"),
EventMsg::ThreadRolledBack(_) => Some("thread_rolled_back"),
EventMsg::Error(_) => Some("error"),
EventMsg::Warning(_) => Some("warning"),
EventMsg::ShutdownComplete => Some("shutdown_complete"),
EventMsg::AuthRecoveryStarted(_)
| EventMsg::AuthRecoveryCompleted(_)
| EventMsg::GuardianWarning(_)
| EventMsg::SafetyBuffering(_)
| EventMsg::RealtimeConversationStarted(_)
| EventMsg::RealtimeConversationRealtime(_)
| EventMsg::RealtimeConversationClosed(_)
| EventMsg::RealtimeConversationSdp(_)
| EventMsg::TurnModerationMetadata(_)
| EventMsg::ContextCompacted(_)
| EventMsg::ThreadSettingsApplied(_)
| EventMsg::EnvironmentConnected(_)
| EventMsg::EnvironmentDisconnected(_)
| EventMsg::TokenCount(_)
| EventMsg::AgentMessage(_)
| EventMsg::UserMessage(_)
| EventMsg::AgentReasoning(_)
| EventMsg::AgentReasoningRawContent(_)
| EventMsg::AgentReasoningSectionBreak(_)
| EventMsg::ThreadGoalUpdated(_)
| EventMsg::ThreadQueueChanged(_)
| EventMsg::McpStartupUpdate(_)
| EventMsg::McpStartupComplete(_)
| EventMsg::McpToolCallBegin(_)
| EventMsg::McpToolCallEnd(_)
| EventMsg::WebSearchBegin(_)
| EventMsg::WebSearchEnd(_)
| EventMsg::ImageGenerationBegin(_)
| EventMsg::ImageGenerationEnd(_)
| EventMsg::ViewImageToolCall(_)
| EventMsg::ExecCommandBegin(_)
| EventMsg::ExecCommandOutputDelta(_)
| EventMsg::TerminalInteraction(_)
| EventMsg::ExecCommandEnd(_)
| EventMsg::ExecApprovalRequest(_)
| EventMsg::RequestPermissions(_)
| EventMsg::RequestUserInput(_)
| EventMsg::DynamicToolCallRequest(_)
| EventMsg::DynamicToolCallResponse(_)
| EventMsg::ElicitationRequest(_)
| EventMsg::ElicitationAbandoned(_)
| EventMsg::NetworkApprovalResolved { .. }
| EventMsg::ApplyPatchApprovalRequest(_)
| EventMsg::GuardianAssessment(_)
| EventMsg::DeprecationNotice(_)
| EventMsg::StreamError(_)
| EventMsg::PatchApplyBegin(_)
| EventMsg::PatchApplyUpdated(_)
| EventMsg::PatchApplyEnd(_)
| EventMsg::TurnDiff(_)
| EventMsg::RealtimeConversationListVoicesResponse(_)
| EventMsg::PlanUpdate(_)
| EventMsg::EnteredReviewMode(_)
| EventMsg::ExitedReviewMode(_)
| EventMsg::PrivateSessionEvent(_)
| EventMsg::RawResponseItem(_)
| EventMsg::RawResponseCompleted(_)
| EventMsg::ItemStarted(_)
| EventMsg::ItemCompleted(_)
| EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::PlanDelta(_)
| EventMsg::ReasoningContentDelta(_)
| EventMsg::ReasoningRawContentDelta(_)
| EventMsg::CollabAgentSpawnBegin(_)
| EventMsg::CollabAgentSpawnEnd(_)
| EventMsg::CollabAgentInteractionBegin(_)
| EventMsg::CollabAgentInteractionEnd(_)
| EventMsg::CollabWaitingBegin(_)
| EventMsg::CollabWaitingEnd(_)
| EventMsg::CollabCloseBegin(_)
| EventMsg::CollabCloseEnd(_)
| EventMsg::CollabResumeBegin(_)
| EventMsg::CollabResumeEnd(_)
| EventMsg::SubAgentActivity(_) => None,
}
}
trait TraceExecutionStatus {
fn trace_execution_status(&self) -> ExecutionStatus;
}
impl TraceExecutionStatus for ExecCommandStatus {
fn trace_execution_status(&self) -> ExecutionStatus {
match self {
ExecCommandStatus::Completed => ExecutionStatus::Completed,
ExecCommandStatus::Failed => ExecutionStatus::Failed,
ExecCommandStatus::Declined => ExecutionStatus::Cancelled,
}
}
}
impl TraceExecutionStatus for PatchApplyStatus {
fn trace_execution_status(&self) -> ExecutionStatus {
match self {
PatchApplyStatus::Completed => ExecutionStatus::Completed,
PatchApplyStatus::Failed => ExecutionStatus::Failed,
PatchApplyStatus::Declined => ExecutionStatus::Cancelled,
}
}
}
fn execution_status_for_abort_reason(reason: &TurnAbortReason) -> ExecutionStatus {
match reason {
TurnAbortReason::Interrupted
| TurnAbortReason::Replaced
| TurnAbortReason::ReviewEnded
| TurnAbortReason::BudgetLimited => ExecutionStatus::Cancelled,
}
}
#[cfg(test)]
#[path = "protocol_event_tests.rs"]
mod tests;

View File

@@ -0,0 +1,151 @@
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::ExecCommandBeginEvent;
use akode_protocol::protocol::ExecCommandEndEvent;
use akode_protocol::protocol::ExecCommandSource;
use akode_protocol::protocol::ExecCommandStatus;
use akode_protocol::protocol::SubAgentActivityEvent;
use akode_protocol::protocol::SubAgentActivityKind;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::time::Duration;
use super::ToolRuntimeTraceEvent;
use super::tool_runtime_trace_event;
use crate::ExecutionStatus;
#[test]
fn sub_agent_activity_is_a_terminal_tool_runtime_event() -> anyhow::Result<()> {
let agent_thread_id = ThreadId::new();
let event = EventMsg::SubAgentActivity(SubAgentActivityEvent {
model: Some("gpt-5".into()),
reasoning_effort: Some(akode_protocol::openai_models::ReasoningEffort::High),
event_id: "call-spawn".to_string(),
occurred_at_ms: 1234,
agent_thread_id,
agent_path: AgentPath::try_from("/root/reviewer").map_err(anyhow::Error::msg)?,
kind: SubAgentActivityKind::Started,
});
let Some(ToolRuntimeTraceEvent::Ended {
tool_call_id,
status,
payload,
}) = tool_runtime_trace_event(&event)
else {
panic!("expected terminal tool runtime event");
};
assert_eq!(tool_call_id, "call-spawn");
assert_eq!(status, ExecutionStatus::Completed);
assert_eq!(
serde_json::to_value(payload)?,
json!({
"event_id": "call-spawn",
"occurred_at_ms": 1234,
"agent_thread_id": agent_thread_id,
"agent_path": "/root/reviewer",
"kind": "started",
"model": "gpt-5",
"reasoning_effort": "high"
})
);
Ok(())
}
#[test]
fn completed_sub_agent_activity_is_not_a_tool_runtime_event() -> anyhow::Result<()> {
let event = EventMsg::SubAgentActivity(SubAgentActivityEvent {
model: None,
reasoning_effort: None,
event_id: "child-turn-completed".to_string(),
occurred_at_ms: 1234,
agent_thread_id: ThreadId::new(),
agent_path: AgentPath::try_from("/root/reviewer").map_err(anyhow::Error::msg)?,
kind: SubAgentActivityKind::Completed,
});
assert!(tool_runtime_trace_event(&event).is_none());
Ok(())
}
#[test]
fn exec_command_trace_payloads_use_inferred_native_cwd() -> anyhow::Result<()> {
// Convention inference depends on the URI spelling, not the test host, so exercise both
// Windows and POSIX paths on every platform.
let begin = EventMsg::ExecCommandBegin(ExecCommandBeginEvent {
call_id: "call-begin".to_string(),
plugin_id: Some("sample@openai-curated".to_string()),
script_path: Some("scripts/run.py".to_string()),
process_id: Some("process-1".to_string()),
turn_id: "turn-1".to_string(),
started_at_ms: 1234,
command: vec!["pwd".to_string()],
cwd: "file:///C:/windows".parse()?,
parsed_cmd: Vec::new(),
source: ExecCommandSource::Agent,
interaction_input: None,
});
let end = EventMsg::ExecCommandEnd(ExecCommandEndEvent {
call_id: "call-end".to_string(),
plugin_id: Some("sample@openai-curated".to_string()),
script_path: Some("scripts/run.py".to_string()),
process_id: None,
turn_id: "turn-1".to_string(),
completed_at_ms: 2345,
command: vec!["pwd".to_string()],
cwd: "file:///workspace/project".parse()?,
parsed_cmd: Vec::new(),
source: ExecCommandSource::UnifiedExecInteraction,
interaction_input: Some("input".to_string()),
aggregated_output: "combined output".to_string(),
exit_code: 0,
duration: Duration::from_millis(250),
status: ExecCommandStatus::Completed,
});
let Some(ToolRuntimeTraceEvent::Started { payload, .. }) = tool_runtime_trace_event(&begin)
else {
panic!("expected started tool runtime event");
};
assert_eq!(
serde_json::to_value(payload)?,
json!({
"call_id": "call-begin",
"plugin_id": "sample@openai-curated",
"script_path": "scripts/run.py",
"process_id": "process-1",
"turn_id": "turn-1",
"started_at_ms": 1234,
"command": ["pwd"],
"cwd": r"C:\windows",
"parsed_cmd": [],
"source": "agent"
})
);
let Some(ToolRuntimeTraceEvent::Ended { payload, .. }) = tool_runtime_trace_event(&end) else {
panic!("expected ended tool runtime event");
};
assert_eq!(
serde_json::to_value(payload)?,
json!({
"call_id": "call-end",
"plugin_id": "sample@openai-curated",
"script_path": "scripts/run.py",
"turn_id": "turn-1",
"completed_at_ms": 2345,
"command": ["pwd"],
"cwd": "/workspace/project",
"parsed_cmd": [],
"source": "unified_exec_interaction",
"interaction_input": "input",
"aggregated_output": "combined output",
"exit_code": 0,
"duration": {"secs": 0, "nanos": 250000000},
"status": "completed"
})
);
Ok(())
}

View File

@@ -0,0 +1,334 @@
//! Append-only raw trace events.
use crate::model::AgentThreadId;
use crate::model::CodeCellRuntimeStatus;
use crate::model::CodexTurnId;
use crate::model::CompactionId;
use crate::model::CompactionRequestId;
use crate::model::EdgeId;
use crate::model::ExecutionStatus;
use crate::model::InferenceCallId;
use crate::model::McpCallId;
use crate::model::ModelVisibleCallId;
use crate::model::RolloutStatus;
use crate::model::ToolCallId;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::payload::RawPayloadRef;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
/// Monotonic sequence number assigned by the raw trace writer.
pub type RawEventSeq = u64;
/// Current raw event envelope schema version.
pub(crate) const RAW_TRACE_EVENT_SCHEMA_VERSION: u32 = 2;
/// One append-only raw trace event.
///
/// Every event uses the same envelope so partial replay and corruption checks
/// can run before the reducer understands the event-specific payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RawTraceEvent {
pub schema_version: u32,
/// Contiguous writer-assigned order inside one rollout event log.
pub seq: RawEventSeq,
/// Unix wall-clock timestamp in milliseconds. Use for display/latency.
pub wall_time_unix_ms: i64,
pub rollout_id: String,
pub thread_id: Option<AgentThreadId>,
pub codex_turn_id: Option<CodexTurnId>,
pub payload: RawTraceEventPayload,
}
/// Writer-supplied context that appears in the raw event envelope.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RawTraceEventContext {
pub thread_id: Option<AgentThreadId>,
pub codex_turn_id: Option<CodexTurnId>,
}
/// Runtime requester as observed at the raw tool boundary.
///
/// This intentionally uses runtime-local identifiers. The reducer is the only
/// place that maps these handles to graph identities such as `CodeCellId`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum RawToolCallRequester {
Model,
CodeCell {
/// Runtime-local code-mode cell handle.
runtime_cell_id: String,
},
}
/// Typed payload for a raw trace event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum RawTraceEventPayload {
/// Final record after all producers release a writer with no recorded errors.
RecordingCompleted,
RolloutStarted {
trace_id: String,
root_thread_id: AgentThreadId,
},
RolloutEnded {
status: RolloutStatus,
},
ThreadStarted {
thread_id: AgentThreadId,
/// Stable agent path.
agent_path: String,
metadata_payload: Option<RawPayloadRef>,
},
ThreadEnded {
thread_id: AgentThreadId,
status: RolloutStatus,
},
/// An evicted runtime was reloaded for a thread already recorded in this bundle.
ThreadResumed {
thread_id: AgentThreadId,
},
CodexTurnStarted {
codex_turn_id: CodexTurnId,
thread_id: AgentThreadId,
},
CodexTurnEnded {
codex_turn_id: CodexTurnId,
status: ExecutionStatus,
},
/// The harness appended this Responses item to its history. This is not
/// evidence of its rendered content, which may be truncated before sampling.
HistoryItemAccepted {
item_id: String,
},
InferenceStarted {
inference_call_id: InferenceCallId,
thread_id: AgentThreadId,
codex_turn_id: CodexTurnId,
model: String,
provider_name: String,
request_payload: RawPayloadRef,
},
InferenceCompleted {
inference_call_id: InferenceCallId,
/// Responses API `response.id`; used by `previous_response_id`.
response_id: Option<String>,
/// Provider transport request id, such as `x-request-id`.
upstream_request_id: Option<String>,
response_payload: RawPayloadRef,
},
InferenceFailed {
inference_call_id: InferenceCallId,
/// Provider transport request id, such as `x-request-id`, when the
/// provider returned one before the stream failed.
upstream_request_id: Option<String>,
error: String,
/// Partial response payload, when stream events arrived before failure.
partial_response_payload: Option<RawPayloadRef>,
},
InferenceCancelled {
inference_call_id: InferenceCallId,
/// Provider transport request id, such as `x-request-id`, when observed
/// before Codex stopped consuming the stream.
upstream_request_id: Option<String>,
/// Why Codex stopped consuming the provider stream before a terminal response event.
reason: String,
/// Completed output items observed before cancellation, if any.
partial_response_payload: Option<RawPayloadRef>,
},
ToolCallStarted {
tool_call_id: ToolCallId,
/// Protocol/model call ID when this runtime call came from model output.
model_visible_call_id: Option<String>,
/// Code-mode runtime bridge ID when model-authored code issued this call.
code_mode_runtime_tool_id: Option<String>,
/// Runtime requester that caused this tool lifecycle.
requester: RawToolCallRequester,
kind: ToolCallKind,
summary: ToolCallSummary,
invocation_payload: Option<RawPayloadRef>,
},
/// Bridge correlation UUID assigned only when a tool reaches an MCP backend.
McpToolCallCorrelationAssigned {
tool_call_id: ToolCallId,
mcp_call_id: McpCallId,
},
/// Exec selected by the runtime after resolving a recyclable process handle.
StdinTargetResolved {
tool_call_id: ToolCallId,
exec_tool_call_id: ToolCallId,
},
ToolCallRuntimeStarted {
tool_call_id: ToolCallId,
/// Executed handler, which may differ from the requested callable.
kind: ToolCallKind,
/// Runtime/protocol observation for how Codex began executing the tool.
runtime_payload: RawPayloadRef,
},
ToolCallRuntimeEnded {
tool_call_id: ToolCallId,
status: ExecutionStatus,
/// Runtime/protocol observation for how Codex finished executing the tool.
runtime_payload: RawPayloadRef,
},
ToolCallEnded {
tool_call_id: ToolCallId,
status: ExecutionStatus,
result_payload: Option<RawPayloadRef>,
},
CodeCellStarted {
/// Runtime-local handle allocated by code mode for waits and nested tools.
runtime_cell_id: String,
/// Custom tool call id on the model-visible `exec` item.
model_visible_call_id: ModelVisibleCallId,
/// JavaScript source after the public `exec` wrapper has been parsed.
source_js: String,
},
CodeCellInitialResponse {
/// Runtime-local handle, matching `CodeCellStarted`.
runtime_cell_id: String,
status: CodeCellRuntimeStatus,
response_payload: Option<RawPayloadRef>,
},
CodeCellEnded {
/// Runtime-local handle, matching `CodeCellStarted`.
runtime_cell_id: String,
status: CodeCellRuntimeStatus,
response_payload: Option<RawPayloadRef>,
},
CompactionRequestStarted {
compaction_id: CompactionId,
compaction_request_id: CompactionRequestId,
thread_id: AgentThreadId,
codex_turn_id: CodexTurnId,
model: String,
provider_name: String,
request_payload: RawPayloadRef,
},
CompactionRequestCompleted {
compaction_id: CompactionId,
compaction_request_id: CompactionRequestId,
response_payload: RawPayloadRef,
},
CompactionRequestFailed {
compaction_id: CompactionId,
compaction_request_id: CompactionRequestId,
error: String,
},
/// Checkpoint installation event for remote-compacted replacement history.
CompactionInstalled {
compaction_id: CompactionId,
/// Trace-only checkpoint payload. Do not route this through public UI protocol.
checkpoint_payload: RawPayloadRef,
},
/// Multi-agent v2 child-to-parent completion delivery.
AgentResultObserved {
edge_id: EdgeId,
child_thread_id: AgentThreadId,
child_codex_turn_id: CodexTurnId,
parent_thread_id: AgentThreadId,
message: String,
/// Raw notification payload. This is evidence for the runtime delivery,
/// not the parent-side model-visible item.
carried_payload: Option<RawPayloadRef>,
},
/// Existing UI/protocol event wrapped into trace format.
ProtocolEventObserved {
event_type: String,
event_payload: RawPayloadRef,
},
/// Structured payload for early instrumentation before a dedicated variant exists.
Other {
kind: String,
summary: String,
payloads: Vec<RawPayloadRef>,
/// Small structured metadata. Large data belongs in `payloads`.
metadata: Value,
},
}
impl RawTraceEventPayload {
/// Raw payload refs that must exist before this raw event is appended.
pub(crate) fn raw_payload_refs(&self) -> Vec<&RawPayloadRef> {
match self {
RawTraceEventPayload::RecordingCompleted
| RawTraceEventPayload::RolloutStarted { .. }
| RawTraceEventPayload::RolloutEnded { .. }
| RawTraceEventPayload::ThreadEnded { .. }
| RawTraceEventPayload::ThreadResumed { .. }
| RawTraceEventPayload::CodexTurnStarted { .. }
| RawTraceEventPayload::CodexTurnEnded { .. }
| RawTraceEventPayload::HistoryItemAccepted { .. }
| RawTraceEventPayload::CompactionRequestFailed { .. }
| RawTraceEventPayload::CodeCellStarted { .. }
| RawTraceEventPayload::McpToolCallCorrelationAssigned { .. }
| RawTraceEventPayload::StdinTargetResolved { .. }
| RawTraceEventPayload::AgentResultObserved {
carried_payload: None,
..
} => Vec::new(),
RawTraceEventPayload::ThreadStarted {
metadata_payload, ..
} => metadata_payload.iter().collect(),
RawTraceEventPayload::InferenceStarted {
request_payload, ..
}
| RawTraceEventPayload::InferenceCompleted {
response_payload: request_payload,
..
}
| RawTraceEventPayload::CompactionRequestStarted {
request_payload, ..
}
| RawTraceEventPayload::CompactionRequestCompleted {
response_payload: request_payload,
..
}
| RawTraceEventPayload::CompactionInstalled {
checkpoint_payload: request_payload,
..
}
| RawTraceEventPayload::ProtocolEventObserved {
event_payload: request_payload,
..
} => vec![request_payload],
RawTraceEventPayload::InferenceFailed {
partial_response_payload,
..
}
| RawTraceEventPayload::InferenceCancelled {
partial_response_payload,
..
}
| RawTraceEventPayload::ToolCallStarted {
invocation_payload: partial_response_payload,
..
}
| RawTraceEventPayload::ToolCallEnded {
result_payload: partial_response_payload,
..
}
| RawTraceEventPayload::CodeCellInitialResponse {
response_payload: partial_response_payload,
..
}
| RawTraceEventPayload::CodeCellEnded {
response_payload: partial_response_payload,
..
} => partial_response_payload.iter().collect(),
RawTraceEventPayload::AgentResultObserved {
carried_payload: Some(carried_payload),
..
} => vec![carried_payload],
RawTraceEventPayload::ToolCallRuntimeStarted {
runtime_payload, ..
}
| RawTraceEventPayload::ToolCallRuntimeEnded {
runtime_payload, ..
} => vec![runtime_payload],
RawTraceEventPayload::Other { payloads, .. } => payloads.iter().collect(),
}
}
}

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 akode_protocol::models::AgentMessageInputContent;
use akode_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 == akode_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 akode_protocol::protocol::CollabAgentInteractionBeginEvent;
use akode_protocol::protocol::CollabAgentInteractionEndEvent;
use akode_protocol::protocol::CollabAgentSpawnEndEvent;
use akode_protocol::protocol::CollabCloseBeginEvent;
use akode_protocol::protocol::CollabCloseEndEvent;
use akode_protocol::protocol::InterAgentCommunication;
use akode_protocol::protocol::SubAgentActivityEvent;
use akode_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(())
}

View File

@@ -0,0 +1,589 @@
//! Thread-scoped rollout trace helpers.
//!
//! A rollout bundle can contain a root thread plus spawned child threads. This
//! context owns the stable identity for one thread inside that bundle. Keeping
//! thread-local event methods here avoids repeatedly plumbing `thread_id`
//! through session code.
use akode_protocol::mcp::CallToolResult;
use akode_protocol::protocol::AgentStatus;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::SessionSource;
use serde::Serialize;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use tracing::debug;
use tracing::warn;
use uuid::Uuid;
use crate::AgentThreadId;
use crate::CodeCellTraceContext;
use crate::CodexTurnId;
use crate::CompactionId;
use crate::CompactionTraceContext;
use crate::ExecutionStatus;
use crate::InferenceTraceContext;
use crate::McpCallTraceContext;
use crate::RawPayloadKind;
use crate::RawPayloadRef;
use crate::RawTraceEventContext;
use crate::RawTraceEventPayload;
use crate::RolloutStatus;
use crate::ToolCallId;
use crate::ToolDispatchInvocation;
use crate::ToolDispatchTraceContext;
use crate::TraceWriter;
use crate::protocol_event::codex_turn_trace_event;
use crate::protocol_event::tool_runtime_trace_event;
use crate::protocol_event::wrapped_protocol_event_type;
/// Environment variable that enables local trace-bundle recording.
///
/// The value is a root directory. Each independent root session gets one child
/// bundle directory. Spawned child threads share their root session's bundle so
/// one reduced `state.json` describes the whole multi-agent rollout tree.
pub const AKODE_ROLLOUT_TRACE_ROOT_ENV: &str = "AKODE_ROLLOUT_TRACE_ROOT";
/// Metadata captured once at thread/session start.
///
/// This payload is intentionally operational rather than reduced: it is a raw
/// payload that later reducers can mine as the reduced thread model evolves.
#[derive(Serialize)]
pub struct ThreadStartedTraceMetadata {
pub thread_id: String,
pub agent_path: String,
pub task_name: Option<String>,
pub nickname: Option<String>,
pub agent_role: Option<String>,
pub session_source: SessionSource,
pub cwd: std::path::PathBuf,
pub rollout_path: Option<std::path::PathBuf>,
pub model: String,
pub provider_name: String,
pub approval_policy: String,
pub sandbox_policy: String,
}
/// Trace-only payload for a child completion notification delivered to its parent.
#[derive(Serialize)]
pub struct AgentResultTracePayload<'a> {
pub child_agent_path: &'a str,
pub message: &'a str,
pub status: &'a AgentStatus,
}
/// No-op capable trace handle for one thread in a rollout bundle.
#[derive(Clone, Debug)]
pub struct ThreadTraceContext {
state: ThreadTraceContextState,
}
#[derive(Clone, Debug)]
enum ThreadTraceContextState {
Disabled,
Enabled(EnabledThreadTraceContext),
}
#[derive(Clone, Debug)]
struct EnabledThreadTraceContext {
writer: Arc<TraceWriter>,
root_thread_id: AgentThreadId,
thread_id: AgentThreadId,
}
impl ThreadTraceContext {
/// Builds a context that accepts trace calls and records nothing.
pub fn disabled() -> Self {
Self {
state: ThreadTraceContextState::Disabled,
}
}
/// Starts tracing when configured; an enabled recorder must initialize successfully.
pub fn start_root(metadata: ThreadStartedTraceMetadata) -> anyhow::Result<Self> {
let Some(root) = std::env::var_os(AKODE_ROLLOUT_TRACE_ROOT_ENV) else {
return Ok(Self::disabled());
};
start_root_in_root(&PathBuf::from(root), metadata)
}
/// Starts a root trace in a known directory.
///
/// This is public for tests that need replayable trace bundles without
/// mutating process environment.
pub fn start_root_in_root_for_test(
root: &Path,
metadata: ThreadStartedTraceMetadata,
) -> anyhow::Result<Self> {
start_root_in_root(root, metadata)
}
/// Starts one thread lifecycle inside an existing rollout bundle.
pub(crate) fn start(
writer: Arc<TraceWriter>,
root_thread_id: AgentThreadId,
metadata: ThreadStartedTraceMetadata,
) -> anyhow::Result<Self> {
let context = EnabledThreadTraceContext {
writer,
root_thread_id,
thread_id: metadata.thread_id.clone(),
};
record_thread_started(&context, metadata);
context.writer.check()?;
Ok(Self {
state: ThreadTraceContextState::Enabled(context),
})
}
/// Returns whether this handle will write trace events.
///
/// Most methods have their own disabled fast path. Callers should branch on
/// this only when preparing trace payloads would otherwise clone data the
/// production path needs to move elsewhere.
pub fn is_enabled(&self) -> bool {
matches!(self.state, ThreadTraceContextState::Enabled(_))
}
/// Starts a new child thread in this context's rollout tree.
pub fn start_child_thread_trace(
&self,
metadata: ThreadStartedTraceMetadata,
) -> anyhow::Result<Self> {
match &self.state {
ThreadTraceContextState::Disabled => Ok(Self::disabled()),
ThreadTraceContextState::Enabled(context) => Self::start(
Arc::clone(&context.writer),
context.root_thread_id.clone(),
metadata,
),
}
}
/// Reattaches an evicted child to this rollout without starting a new thread.
pub fn resume_child_thread_trace(&self, thread_id: String) -> anyhow::Result<Self> {
let ThreadTraceContextState::Enabled(parent) = &self.state else {
return Ok(Self::disabled());
};
let context = EnabledThreadTraceContext {
writer: Arc::clone(&parent.writer),
root_thread_id: parent.root_thread_id.clone(),
thread_id: thread_id.clone(),
};
context
.writer
.append(RawTraceEventPayload::ThreadResumed { thread_id })?;
Ok(Self {
state: ThreadTraceContextState::Enabled(context),
})
}
/// Emits terminal trace events when the thread stops.
///
/// Spawned child sessions share their root bundle, so only the root
/// thread end closes the rollout. This is not recording finalization: child
/// threads and detached producers may still hold the shared writer.
/// Recording errors stay with the writer and prevent the closing event.
pub fn record_ended(&self, status: RolloutStatus) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
context.append_best_effort(RawTraceEventPayload::ThreadEnded {
thread_id: context.thread_id.clone(),
status: status.clone(),
});
if context.thread_id == context.root_thread_id {
context.append_best_effort(RawTraceEventPayload::RolloutEnded { status });
}
}
/// Wraps selected protocol events as raw trace breadcrumbs.
///
/// High-volume stream deltas stay out of this wrapper; typed inference,
/// tool, terminal, and code-mode hooks provide the canonical runtime data.
pub fn record_protocol_event(&self, event: &EventMsg) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
let Some(event_type) = wrapped_protocol_event_type(event) else {
return;
};
let Some(event_payload) =
context.write_json_payload_best_effort(RawPayloadKind::ProtocolEvent, event)
else {
return;
};
context.append_best_effort(RawTraceEventPayload::ProtocolEventObserved {
event_type: event_type.to_string(),
event_payload,
});
}
/// Records turn lifecycle and history acceptance from existing protocol events.
pub fn record_codex_turn_event(&self, default_turn_id: &str, event: &EventMsg) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
let Some(trace_event) =
codex_turn_trace_event(context.thread_id.clone(), default_turn_id, event)
else {
return;
};
context.append_with_context_best_effort(
trace_event.context_turn_id.clone(),
trace_event.payload,
);
}
/// Emits typed runtime tool events from existing protocol lifecycle events.
///
/// These events are runtime observations on an already-dispatched tool. The
/// dispatch trace records the caller-facing boundary; these payloads explain
/// what Codex did while executing that boundary.
pub fn record_tool_call_event(&self, codex_turn_id: impl Into<CodexTurnId>, event: &EventMsg) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
let Some(trace_event) = tool_runtime_trace_event(event) else {
return;
};
let Some(payload) = context.raw_tool_runtime_payload(trace_event) else {
return;
};
context.append_with_context_best_effort(codex_turn_id.into(), payload);
}
/// Records the full MCP backend result before callbacks, sanitization, or UI truncation.
/// The dispatch trace separately records the result returned to the caller.
pub fn record_mcp_tool_result(
&self,
codex_turn_id: &str,
tool_call_id: &str,
result: &Result<CallToolResult, String>,
) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
#[derive(Serialize)]
struct Payload<'a> {
result: &'a Result<CallToolResult, String>,
}
let Some(runtime_payload) = context
.write_json_payload_best_effort(RawPayloadKind::ToolRuntimeEvent, &Payload { result })
else {
return;
};
context.append_with_context_best_effort(
codex_turn_id.to_owned(),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: tool_call_id.to_owned(),
status: if result.is_ok() {
ExecutionStatus::Completed
} else {
ExecutionStatus::Failed
},
runtime_payload,
},
);
}
/// Records the exec actually selected by stdin, since its process handle can be reused.
pub fn record_stdin_target(
&self,
codex_turn_id: &str,
tool_call_id: &str,
exec_tool_call_id: &str,
) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
context.append_with_context_best_effort(
codex_turn_id.to_string(),
RawTraceEventPayload::StdinTargetResolved {
tool_call_id: tool_call_id.to_string(),
exec_tool_call_id: exec_tool_call_id.to_string(),
},
);
}
/// Emits the v2 child-to-parent completion message as an explicit graph edge.
///
/// The notification is runtime delivery from a completed child turn into
/// the parent's mailbox, not a tool call executed by the child. Recording it
/// directly preserves timing and source without making the reducer infer
/// the edge from a later parent prompt snapshot.
pub fn record_agent_result_interaction(
&self,
child_codex_turn_id: impl Into<CodexTurnId>,
parent_thread_id: impl Into<AgentThreadId>,
payload: &AgentResultTracePayload<'_>,
) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
let child_codex_turn_id = child_codex_turn_id.into();
let parent_thread_id = parent_thread_id.into();
let carried_payload =
context.write_json_payload_best_effort(RawPayloadKind::AgentResult, payload);
context.append_with_context_best_effort(
child_codex_turn_id.clone(),
RawTraceEventPayload::AgentResultObserved {
edge_id: format!(
"edge:agent_result:{}:{child_codex_turn_id}:{parent_thread_id}",
context.thread_id
),
child_thread_id: context.thread_id.clone(),
child_codex_turn_id,
parent_thread_id,
message: payload.message.to_string(),
carried_payload,
},
);
}
/// Emits a turn-start lifecycle event.
///
/// Most production turn lifecycle wiring lives outside this PR layer, but
/// trace-focused integration tests need a small explicit hook so reducer
/// inputs remain valid without exercising the full session loop.
pub fn record_codex_turn_started(&self, codex_turn_id: impl Into<CodexTurnId>) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
let codex_turn_id = codex_turn_id.into();
context.append_with_context_best_effort(
codex_turn_id.clone(),
RawTraceEventPayload::CodexTurnStarted {
codex_turn_id,
thread_id: context.thread_id.clone(),
},
);
}
/// Starts a first-class code-mode cell lifecycle and returns its trace handle.
pub fn start_code_cell_trace(
&self,
codex_turn_id: impl Into<CodexTurnId>,
runtime_cell_id: impl Into<String>,
model_visible_call_id: impl Into<String>,
source_js: impl Into<String>,
) -> CodeCellTraceContext {
let context = self.code_cell_trace_context(codex_turn_id, runtime_cell_id);
context.record_started(model_visible_call_id, source_js);
context
}
/// Builds a trace handle for an already-started code-mode runtime cell.
pub fn code_cell_trace_context(
&self,
codex_turn_id: impl Into<CodexTurnId>,
runtime_cell_id: impl Into<String>,
) -> CodeCellTraceContext {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return CodeCellTraceContext::disabled();
};
CodeCellTraceContext::enabled(
Arc::clone(&context.writer),
context.thread_id.clone(),
codex_turn_id,
runtime_cell_id,
)
}
/// Starts one dispatch-level tool lifecycle and returns its trace handle.
///
/// `invocation` is lazy because adapting core tool objects into trace-owned
/// payloads can clone large arguments. Disabled tracing should not pay that
/// cost on the hot tool-dispatch path.
pub fn start_tool_dispatch_trace(
&self,
invocation: impl FnOnce() -> Option<ToolDispatchInvocation>,
) -> ToolDispatchTraceContext {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return ToolDispatchTraceContext::disabled();
};
let Some(invocation) = invocation() else {
return ToolDispatchTraceContext::disabled();
};
ToolDispatchTraceContext::start(Arc::clone(&context.writer), invocation)
}
/// Builds reusable inference trace context for one Codex turn.
///
/// The returned context is intentionally not "an inference call" yet.
/// Transport code owns retry/fallback attempts and calls `start_attempt`
/// only after it has built the concrete request payload for that attempt.
pub fn inference_trace_context(
&self,
codex_turn_id: impl Into<CodexTurnId>,
model: impl Into<String>,
provider_name: impl Into<String>,
) -> InferenceTraceContext {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return InferenceTraceContext::disabled();
};
InferenceTraceContext::enabled(
Arc::clone(&context.writer),
context.thread_id.clone(),
codex_turn_id.into(),
model.into(),
provider_name.into(),
)
}
/// Builds remote-compaction trace context for one checkpoint.
///
/// Rollout tracing currently has a first-class checkpoint model only for remote compaction.
/// The compact endpoint is a model-facing request whose output replaces live history, so it
/// needs both request/response attempt events and a later checkpoint event when processed
/// replacement history is installed.
pub fn compaction_trace_context(
&self,
codex_turn_id: impl Into<CodexTurnId>,
compaction_id: impl Into<CompactionId>,
model: impl Into<String>,
provider_name: impl Into<String>,
) -> CompactionTraceContext {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return CompactionTraceContext::disabled();
};
CompactionTraceContext::enabled(
Arc::clone(&context.writer),
context.thread_id.clone(),
codex_turn_id.into(),
compaction_id.into(),
model.into(),
provider_name.into(),
)
}
/// Starts bridge correlation for one concrete MCP backend request.
///
/// Dispatch-level tool IDs remain compact and UI-friendly. This UUID is
/// deliberately separate: it is only for cross-process log joins where a
/// rollout-local counter would collide across samples.
pub fn start_mcp_call_trace(&self, tool_call_id: impl Into<ToolCallId>) -> McpCallTraceContext {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return McpCallTraceContext::disabled();
};
let mcp_call_id = Uuid::new_v4().to_string();
let trace = McpCallTraceContext::enabled(mcp_call_id.clone());
context.append_best_effort(RawTraceEventPayload::McpToolCallCorrelationAssigned {
tool_call_id: tool_call_id.into(),
mcp_call_id,
});
trace
}
}
fn start_root_in_root(
root: &Path,
metadata: ThreadStartedTraceMetadata,
) -> anyhow::Result<ThreadTraceContext> {
let trace_id = Uuid::new_v4().to_string();
let thread_id = metadata.thread_id.clone();
let bundle_dir = root.join(format!("trace-{trace_id}-{thread_id}"));
let writer = TraceWriter::create(
&bundle_dir,
trace_id.clone(),
thread_id.clone(),
thread_id.clone(),
)?;
let writer = Arc::new(writer);
writer.append(RawTraceEventPayload::RolloutStarted {
trace_id,
root_thread_id: thread_id.clone(),
})?;
debug!("recording rollout trace at {}", bundle_dir.display());
ThreadTraceContext::start(writer, thread_id, metadata)
}
fn record_thread_started(
context: &EnabledThreadTraceContext,
metadata: ThreadStartedTraceMetadata,
) {
let metadata_payload =
context.write_json_payload_best_effort(RawPayloadKind::SessionMetadata, &metadata);
context.append_best_effort(RawTraceEventPayload::ThreadStarted {
thread_id: metadata.thread_id,
agent_path: metadata.agent_path,
metadata_payload,
});
}
impl EnabledThreadTraceContext {
fn write_json_payload_best_effort(
&self,
kind: RawPayloadKind,
payload: &impl Serialize,
) -> Option<RawPayloadRef> {
match self.writer.write_json_payload(kind, payload) {
Ok(payload_ref) => Some(payload_ref),
Err(err) => {
warn!("failed to write rollout trace payload: {err:#}");
None
}
}
}
fn raw_tool_runtime_payload(
&self,
trace_event: crate::protocol_event::ToolRuntimeTraceEvent<'_>,
) -> Option<RawTraceEventPayload> {
match trace_event {
crate::protocol_event::ToolRuntimeTraceEvent::Started {
tool_call_id,
kind,
payload,
} => {
let runtime_payload = self
.write_json_payload_best_effort(RawPayloadKind::ToolRuntimeEvent, &payload)?;
Some(RawTraceEventPayload::ToolCallRuntimeStarted {
tool_call_id: tool_call_id.to_string(),
kind,
runtime_payload,
})
}
crate::protocol_event::ToolRuntimeTraceEvent::Ended {
tool_call_id,
status,
payload,
} => {
let runtime_payload = self
.write_json_payload_best_effort(RawPayloadKind::ToolRuntimeEvent, &payload)?;
Some(RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: tool_call_id.to_string(),
status,
runtime_payload,
})
}
}
}
fn append_best_effort(&self, payload: RawTraceEventPayload) {
if let Err(err) = self.writer.append(payload) {
warn!("failed to append rollout trace event: {err:#}");
}
}
fn append_with_context_best_effort(
&self,
codex_turn_id: CodexTurnId,
payload: RawTraceEventPayload,
) {
let event_context = RawTraceEventContext {
thread_id: Some(self.thread_id.clone()),
codex_turn_id: Some(codex_turn_id),
};
if let Err(err) = self.writer.append_with_context(event_context, payload) {
warn!("failed to append rollout trace event: {err:#}");
}
}
}
#[cfg(test)]
#[path = "thread_tests.rs"]
mod tests;

View File

@@ -0,0 +1,412 @@
use std::cell::Cell;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::models::FunctionCallOutputPayload;
use akode_protocol::models::ResponseInputItem;
use akode_protocol::protocol::AgentStatus;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::FileChange;
use akode_protocol::protocol::PatchApplyBeginEvent;
use akode_protocol::protocol::PatchApplyEndEvent;
use akode_protocol::protocol::PatchApplyStatus;
use akode_protocol::protocol::SandboxPolicy;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentSource;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::*;
use crate::AgentResultTracePayload;
use crate::CompactionCheckpointTracePayload;
use crate::ExecutionStatus;
use crate::RawTraceEventPayload;
use crate::RolloutStatus;
use crate::ToolCallKind;
use crate::ToolDispatchPayload;
use crate::ToolDispatchRequester;
use crate::ToolDispatchResult;
use crate::replay_bundle;
#[test]
fn create_in_root_writes_replayable_lifecycle_events() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let thread_id = ThreadId::new();
let thread_trace = ThreadTraceContext::start_root_in_root_for_test(
temp.path(),
ThreadStartedTraceMetadata {
thread_id: thread_id.to_string(),
agent_path: "/root".to_string(),
task_name: None,
nickname: None,
agent_role: None,
session_source: SessionSource::Exec,
cwd: PathBuf::from("/workspace"),
rollout_path: Some(PathBuf::from("/tmp/rollout.jsonl")),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
approval_policy: "never".to_string(),
sandbox_policy: format!("{:?}", SandboxPolicy::DangerFullAccess),
},
)?;
thread_trace.record_ended(RolloutStatus::Completed);
let bundle_dir = single_bundle_dir(temp.path())?;
let replayed = replay_bundle(&bundle_dir)?;
assert_eq!(replayed.status, RolloutStatus::Completed);
assert_eq!(replayed.root_thread_id, thread_id.to_string());
assert_eq!(replayed.threads[&thread_id.to_string()].agent_path, "/root");
assert_eq!(replayed.raw_payloads.len(), 1);
assert!(!replayed.recording_complete);
thread_trace.record_protocol_event(&EventMsg::ShutdownComplete);
drop(thread_trace);
let complete = replay_bundle(&bundle_dir)?;
assert_eq!(complete.status, RolloutStatus::Completed);
assert!(complete.recording_complete);
// A syntactically valid prefix is still an incomplete export.
let path = bundle_dir.join("trace.jsonl");
let events = fs::read_to_string(&path)?;
fs::write(&path, events.strip_suffix('\n').unwrap())?;
assert!(!replay_bundle(&bundle_dir)?.recording_complete);
let (prefix, _) = events.trim_end().rsplit_once('\n').unwrap();
fs::write(&path, prefix)?;
assert!(!replay_bundle(&bundle_dir)?.recording_complete);
fs::write(&path, &events)?;
// Completion closes the log; even a correctly numbered later event is invalid.
let mut trailing: serde_json::Value = serde_json::from_str(events.lines().last().unwrap())?;
trailing["seq"] = (trailing["seq"].as_u64().unwrap() + 1).into();
fs::write(&path, format!("{events}{trailing}\n"))?;
assert!(replay_bundle(&bundle_dir).is_err());
fs::write(&path, &events)?;
// Protocol breadcrumbs are opaque to replay, but their payloads are still required.
let opaque = complete
.raw_payloads
.values()
.find(|payload| payload.kind == RawPayloadKind::ProtocolEvent)
.unwrap();
fs::write(bundle_dir.join(&opaque.path), "{\"truncated\":")?;
assert!(replay_bundle(&bundle_dir).is_err());
fs::write(bundle_dir.join(&opaque.path), b"{\"value\":\"\xff\"}")?;
assert!(replay_bundle(&bundle_dir).is_err());
fs::remove_file(bundle_dir.join(&opaque.path))?;
assert!(replay_bundle(&bundle_dir).is_err());
Ok(())
}
#[test]
fn spawned_thread_start_appends_to_root_bundle() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let root_thread_id = ThreadId::new();
let child_thread_id = ThreadId::new();
let root_trace = ThreadTraceContext::start_root_in_root_for_test(
temp.path(),
minimal_metadata(root_thread_id),
)?;
let child_trace = root_trace.start_child_thread_trace(ThreadStartedTraceMetadata {
thread_id: child_thread_id.to_string(),
agent_path: "/root/repo_file_counter".to_string(),
task_name: Some("repo_file_counter".to_string()),
nickname: Some("Kepler".to_string()),
agent_role: Some("worker".to_string()),
session_source: SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: root_thread_id,
depth: 1,
agent_path: Some(
AgentPath::try_from("/root/repo_file_counter").map_err(anyhow::Error::msg)?,
),
agent_nickname: Some("Kepler".to_string()),
agent_role: Some("worker".to_string()),
}),
cwd: PathBuf::from("/workspace"),
rollout_path: Some(PathBuf::from("/tmp/child-rollout.jsonl")),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
approval_policy: "never".to_string(),
sandbox_policy: format!("{:?}", SandboxPolicy::DangerFullAccess),
})?;
child_trace.record_ended(RolloutStatus::Completed);
let bundle_dir = single_bundle_dir(temp.path())?;
let replayed = replay_bundle(&bundle_dir)?;
assert_eq!(fs::read_dir(temp.path())?.count(), 1);
assert_eq!(replayed.threads.len(), 2);
assert_eq!(
replayed.threads[&child_thread_id.to_string()].agent_path,
"/root/repo_file_counter"
);
assert_eq!(replayed.status, RolloutStatus::Running);
assert_eq!(
replayed.threads[&child_thread_id.to_string()]
.execution
.status,
ExecutionStatus::Completed
);
assert_eq!(replayed.raw_payloads.len(), 2);
root_trace.record_ended(RolloutStatus::Completed);
drop(root_trace);
// Root shutdown does not close the recording while a child still owns it.
assert!(!replay_bundle(&bundle_dir)?.recording_complete);
drop(child_trace);
assert!(replay_bundle(&bundle_dir)?.recording_complete);
Ok(())
}
#[test]
fn resumed_child_rejects_a_failed_shared_writer() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let root = ThreadTraceContext::start_root_in_root_for_test(
temp.path(),
minimal_metadata(ThreadId::new()),
)?;
let child_id = ThreadId::new();
let child = root.start_child_thread_trace(minimal_metadata(child_id))?;
child.record_ended(RolloutStatus::Completed);
drop(child);
// A parent payload write fails while the child is evicted.
let bundle = single_bundle_dir(temp.path())?;
let payloads = bundle.join("payloads");
let backup = temp.path().join("saved-payloads");
fs::rename(&payloads, &backup)?;
root.record_protocol_event(&EventMsg::ShutdownComplete);
fs::rename(backup, payloads)?;
assert!(
root.resume_child_thread_trace(child_id.to_string())
.is_err()
);
drop(root);
assert!(!replay_bundle(&bundle)?.recording_complete);
Ok(())
}
#[test]
fn disabled_thread_context_accepts_trace_calls_without_writing() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let thread_trace = ThreadTraceContext::disabled();
thread_trace.record_ended(RolloutStatus::Completed);
thread_trace.record_protocol_event(&EventMsg::ShutdownComplete);
thread_trace.record_codex_turn_event("turn-1", &EventMsg::ShutdownComplete);
thread_trace.record_tool_call_event("turn-1", &EventMsg::ShutdownComplete);
thread_trace.record_agent_result_interaction(
"turn-1",
ThreadId::new(),
&AgentResultTracePayload {
child_agent_path: "/root/child",
message: "done",
status: &AgentStatus::Completed(Some("done".to_string())),
},
);
let inference_trace =
thread_trace.inference_trace_context("turn-1", "gpt-test", "test-provider");
let inference_attempt = inference_trace.start_attempt();
inference_attempt.record_started(&serde_json::json!({ "kind": "inference" }));
let token_usage: Option<akode_protocol::protocol::TokenUsage> = None;
inference_attempt.record_completed("response-1", Some("req-1"), &token_usage, &[]);
inference_attempt.record_failed("inference failed", /*upstream_request_id*/ None, &[]);
let compaction_trace = thread_trace.compaction_trace_context(
"turn-1",
"compaction-1",
"gpt-test",
"test-provider",
);
assert!(!compaction_trace.is_enabled());
let compaction_attempt =
compaction_trace.start_attempt(&serde_json::json!({ "kind": "compaction" }));
compaction_attempt.record_completed(&[]);
compaction_attempt.record_failed("compaction failed");
compaction_trace.record_installed(&CompactionCheckpointTracePayload {
input_history: &[],
replacement_history: &[],
});
let built_dispatch_invocation = Cell::new(false);
let dispatch_trace = thread_trace.start_tool_dispatch_trace(|| {
built_dispatch_invocation.set(true);
None
});
assert!(!built_dispatch_invocation.get());
assert!(!dispatch_trace.is_enabled());
assert_eq!(fs::read_dir(temp.path())?.count(), 0);
Ok(())
}
#[test]
fn compaction_contexts_share_identity_across_models() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let thread_id = ThreadId::new();
let thread_trace =
ThreadTraceContext::start_root_in_root_for_test(temp.path(), minimal_metadata(thread_id))?;
thread_trace.record_codex_turn_started("turn-1");
for model in ["gpt-previous", "gpt-selected"] {
let compaction_trace =
thread_trace.compaction_trace_context("turn-1", "compaction-1", model, "test-provider");
assert!(compaction_trace.is_enabled());
compaction_trace
.start_attempt(&serde_json::json!({ "model": model }))
.record_failed("test failure");
}
let replayed = replay_bundle(&single_bundle_dir(temp.path())?)?;
let mut attempts = replayed
.compaction_requests
.values()
.map(|attempt| (attempt.model.clone(), attempt.compaction_id.clone()))
.collect::<Vec<_>>();
attempts.sort();
assert_eq!(
attempts,
vec![
("gpt-previous".to_string(), "compaction-1".to_string()),
("gpt-selected".to_string(), "compaction-1".to_string()),
]
);
Ok(())
}
#[test]
fn protocol_wrapper_records_selected_events_as_raw_payloads() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let thread_id = ThreadId::new();
let thread_trace =
ThreadTraceContext::start_root_in_root_for_test(temp.path(), minimal_metadata(thread_id))?;
thread_trace.record_protocol_event(&EventMsg::ShutdownComplete);
let event_log = fs::read_to_string(single_bundle_dir(temp.path())?.join("trace.jsonl"))?;
let protocol_event_seen = event_log.lines().any(|line| {
let event: crate::RawTraceEvent = serde_json::from_str(line).expect("raw trace event");
matches!(
event.payload,
RawTraceEventPayload::ProtocolEventObserved {
event_type,
..
} if event_type == "shutdown_complete"
)
});
assert!(protocol_event_seen);
Ok(())
}
#[test]
fn intercepted_exec_records_patch_without_a_terminal() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let thread_id = ThreadId::new();
let trace =
ThreadTraceContext::start_root_in_root_for_test(temp.path(), minimal_metadata(thread_id))?;
trace.record_codex_turn_started("turn-1");
let dispatch = trace.start_tool_dispatch_trace(|| Some(ToolDispatchInvocation {
thread_id: thread_id.to_string(),
codex_turn_id: "turn-1".to_string(),
tool_call_id: "patch-call".to_string(),
tool_name: "exec_command".to_string(),
tool_namespace: None,
requester: ToolDispatchRequester::Model {
model_visible_call_id: "patch-call".to_string(),
},
payload: ToolDispatchPayload::Function {
arguments: serde_json::json!({"cmd": "apply_patch <<'EOF'\n*** Begin Patch\n*** Add File: hello.txt\n+hello\n*** End Patch\nEOF"}).to_string(),
},
}));
let bundle = single_bundle_dir(temp.path())?;
let before = replay_bundle(&bundle)?.tool_calls["patch-call"].clone();
let changes = HashMap::from([(
PathBuf::from("hello.txt"),
FileChange::Add {
content: "hello\n".to_string(),
},
)]);
trace.record_tool_call_event(
"turn-1",
&EventMsg::PatchApplyBegin(PatchApplyBeginEvent {
call_id: "patch-call".to_string(),
turn_id: "turn-1".to_string(),
auto_approved: true,
changes: changes.clone(),
}),
);
trace.record_tool_call_event(
"turn-1",
&EventMsg::PatchApplyEnd(PatchApplyEndEvent {
call_id: "patch-call".to_string(),
turn_id: "turn-1".to_string(),
stdout: "Success".to_string(),
stderr: String::new(),
success: true,
changes,
status: PatchApplyStatus::Completed,
}),
);
dispatch.record_completed(
ExecutionStatus::Completed,
ToolDispatchResult::DirectResponse {
response_item: ResponseInputItem::FunctionCallOutput {
call_id: "patch-call".to_string(),
output: FunctionCallOutputPayload::from_text("Success".to_string()),
},
},
);
let rollout = replay_bundle(&bundle)?;
let call = &rollout.tool_calls["patch-call"];
assert_eq!(call.kind, ToolCallKind::ApplyPatch);
assert_eq!(call.execution.status, ExecutionStatus::Completed);
assert_eq!(call.summary, before.summary);
assert_eq!(
call.raw_invocation_payload_id,
before.raw_invocation_payload_id
);
assert_eq!(call.raw_runtime_payload_ids.len(), 2);
assert!(call.raw_result_payload_id.is_some());
assert!(rollout.terminal_operations.is_empty());
assert!(rollout.terminal_sessions.is_empty());
Ok(())
}
fn minimal_metadata(thread_id: ThreadId) -> ThreadStartedTraceMetadata {
ThreadStartedTraceMetadata {
thread_id: thread_id.to_string(),
agent_path: "/root".to_string(),
task_name: None,
nickname: None,
agent_role: None,
session_source: SessionSource::Exec,
cwd: PathBuf::from("/workspace"),
rollout_path: None,
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
approval_policy: "never".to_string(),
sandbox_policy: "danger-full-access".to_string(),
}
}
fn single_bundle_dir(root: &Path) -> anyhow::Result<PathBuf> {
let mut entries = fs::read_dir(root)?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<Result<Vec<_>, _>>()?;
entries.sort();
assert_eq!(entries.len(), 1);
Ok(entries.remove(0))
}

View File

@@ -0,0 +1,411 @@
//! Hot-path helpers for recording canonical tool dispatch boundaries.
//!
//! Core owns tool routing and result conversion. The trace crate owns the raw
//! event schema, payload shape, and no-op behavior, so core only adapts its
//! domain objects into the small request/result structs defined here.
use std::fmt::Display;
use std::sync::Arc;
use akode_protocol::models::AdditionalPermissionProfile;
use akode_protocol::models::ResponseInputItem;
use akode_protocol::models::SandboxPermissions;
use akode_protocol::models::SearchToolCallParams;
use serde::Serialize;
use serde_json::Value as JsonValue;
use serde_json::json;
use tracing::warn;
use crate::model::AgentThreadId;
use crate::model::CodeModeRuntimeToolId;
use crate::model::CodexTurnId;
use crate::model::ExecutionStatus;
use crate::model::ModelVisibleCallId;
use crate::model::ToolCallId;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::payload::RawPayloadKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawToolCallRequester;
use crate::raw_event::RawTraceEventContext;
use crate::raw_event::RawTraceEventPayload;
use crate::writer::TraceWriter;
/// No-op capable trace handle for one resolved tool dispatch.
#[derive(Clone, Debug)]
pub struct ToolDispatchTraceContext {
state: ToolDispatchTraceContextState,
}
#[derive(Clone, Debug)]
enum ToolDispatchTraceContextState {
Disabled,
Enabled(EnabledToolDispatchTraceContext),
}
#[derive(Clone, Debug)]
struct EnabledToolDispatchTraceContext {
writer: Arc<TraceWriter>,
thread_id: AgentThreadId,
codex_turn_id: CodexTurnId,
tool_call_id: ToolCallId,
}
/// Core-facing request data for the canonical Codex tool boundary.
pub struct ToolDispatchInvocation {
pub thread_id: AgentThreadId,
pub codex_turn_id: CodexTurnId,
pub tool_call_id: ToolCallId,
pub tool_name: String,
pub tool_namespace: Option<String>,
pub requester: ToolDispatchRequester,
pub payload: ToolDispatchPayload,
}
/// Runtime source that caused a dispatch-level tool call.
pub enum ToolDispatchRequester {
Model {
model_visible_call_id: ModelVisibleCallId,
},
CodeCell {
runtime_cell_id: String,
runtime_tool_call_id: CodeModeRuntimeToolId,
},
}
/// Tool input observed at the registry boundary.
pub enum ToolDispatchPayload {
Function {
arguments: String,
},
ToolSearch {
arguments: SearchToolCallParams,
},
Custom {
input: String,
},
LocalShell {
command: Vec<String>,
workdir: Option<String>,
timeout_ms: Option<u64>,
sandbox_permissions: Option<SandboxPermissions>,
prefix_rule: Option<Vec<String>>,
additional_permissions: Option<AdditionalPermissionProfile>,
justification: Option<String>,
},
}
/// Result data returned from a dispatch-level tool call.
#[derive(Serialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ToolDispatchResult {
DirectResponse { response_item: ResponseInputItem },
CodeModeResponse { value: JsonValue },
}
/// Raw invocation payload for the canonical Codex tool boundary.
#[derive(Serialize)]
struct DispatchedToolTraceRequest<'a> {
tool_name: &'a str,
tool_namespace: Option<&'a str>,
payload: &'a JsonValue,
}
/// Raw response payload for dispatch-level tool trace events.
#[derive(Serialize)]
#[serde(rename_all = "snake_case", tag = "type")]
enum DispatchedToolTraceResponse<'a> {
DirectResponse {
response_item: &'a ResponseInputItem,
},
CodeModeResponse {
value: &'a JsonValue,
},
Error {
error: String,
},
}
impl ToolDispatchTraceContext {
/// Builds a context that accepts trace calls and records nothing.
pub(crate) fn disabled() -> Self {
Self {
state: ToolDispatchTraceContextState::Disabled,
}
}
/// Returns whether caller-side result conversion would be recorded.
///
/// Core uses this to avoid formatting or cloning tool outputs when the
/// dispatch lifecycle is disabled.
pub fn is_enabled(&self) -> bool {
matches!(self.state, ToolDispatchTraceContextState::Enabled(_))
}
/// Starts one dispatch-level lifecycle and returns the handle for its result.
pub(crate) fn start(writer: Arc<TraceWriter>, invocation: ToolDispatchInvocation) -> Self {
// An exec request can fail before a CodeCellStarted event. Record the
// dispatch independently so its caller-facing error survives in that case.
let context = EnabledToolDispatchTraceContext {
writer,
thread_id: invocation.thread_id.clone(),
codex_turn_id: invocation.codex_turn_id.clone(),
tool_call_id: invocation.tool_call_id.clone(),
};
record_started(&context, invocation);
Self {
state: ToolDispatchTraceContextState::Enabled(context),
}
}
/// Records the caller-facing successful or failed tool result.
pub fn record_completed(&self, status: ExecutionStatus, result: ToolDispatchResult) {
let ToolDispatchTraceContextState::Enabled(context) = &self.state else {
return;
};
let response = match &result {
ToolDispatchResult::DirectResponse { response_item } => {
DispatchedToolTraceResponse::DirectResponse { response_item }
}
ToolDispatchResult::CodeModeResponse { value } => {
DispatchedToolTraceResponse::CodeModeResponse { value }
}
};
append_tool_call_ended(context, status, &response);
}
/// Records a dispatch failure before the tool produced a normal result payload.
pub fn record_failed(&self, error: impl Display) {
let ToolDispatchTraceContextState::Enabled(context) = &self.state else {
return;
};
append_tool_call_ended(
context,
ExecutionStatus::Failed,
&DispatchedToolTraceResponse::Error {
error: error.to_string(),
},
);
}
}
fn record_started(context: &EnabledToolDispatchTraceContext, invocation: ToolDispatchInvocation) {
let tool_name = invocation.tool_name;
let tool_namespace = invocation.tool_namespace;
let kind = dispatched_tool_kind(&tool_name, &invocation.payload);
let label = dispatched_tool_label(&tool_name, tool_namespace.as_deref(), &invocation.payload);
let input_preview = Some(invocation.payload.log_payload_preview());
let payload = invocation.payload.into_json_payload();
let request = DispatchedToolTraceRequest {
tool_name: tool_name.as_str(),
tool_namespace: tool_namespace.as_deref(),
payload: &payload,
};
let request_payload =
write_json_payload_best_effort(&context.writer, RawPayloadKind::ToolInvocation, &request);
let (model_visible_call_id, code_mode_runtime_tool_id, requester) =
requester_fields(invocation.requester);
append_with_context_best_effort(
context,
RawTraceEventPayload::ToolCallStarted {
tool_call_id: context.tool_call_id.clone(),
model_visible_call_id,
code_mode_runtime_tool_id,
requester,
kind,
summary: ToolCallSummary::Generic {
label,
input_preview,
output_preview: None,
},
invocation_payload: request_payload,
},
);
}
fn requester_fields(
requester: ToolDispatchRequester,
) -> (
Option<ModelVisibleCallId>,
Option<CodeModeRuntimeToolId>,
RawToolCallRequester,
) {
match requester {
ToolDispatchRequester::Model {
model_visible_call_id,
} => (
Some(model_visible_call_id),
None,
RawToolCallRequester::Model,
),
ToolDispatchRequester::CodeCell {
runtime_cell_id,
runtime_tool_call_id,
} => (
None,
Some(runtime_tool_call_id),
RawToolCallRequester::CodeCell { runtime_cell_id },
),
}
}
fn dispatched_tool_kind(tool_name: &str, _payload: &ToolDispatchPayload) -> ToolCallKind {
match tool_name {
"exec_command" | "local_shell" | "shell" | "shell_command" => ToolCallKind::ExecCommand,
"write_stdin" => ToolCallKind::WriteStdin,
"apply_patch" => ToolCallKind::ApplyPatch,
"web_search" | "web_search_preview" => ToolCallKind::Web,
"image_generation" | "image_query" | "imagegen" => ToolCallKind::ImageGeneration,
"spawn_agent" => ToolCallKind::SpawnAgent,
"send_message" => ToolCallKind::SendMessage,
"followup_task" | "assign_task" => ToolCallKind::AssignAgentTask,
"wait_agent" => ToolCallKind::WaitAgent,
"close_agent" | "interrupt_agent" => ToolCallKind::CloseAgent,
other => ToolCallKind::Other {
name: other.to_string(),
},
}
}
fn dispatched_tool_label(
tool_name: &str,
tool_namespace: Option<&str>,
_payload: &ToolDispatchPayload,
) -> String {
match tool_namespace {
Some(namespace) => format!("{namespace}.{tool_name}"),
None => tool_name.to_string(),
}
}
impl ToolDispatchPayload {
fn log_payload_preview(&self) -> String {
match self {
ToolDispatchPayload::Function { arguments } => truncate_preview(arguments),
ToolDispatchPayload::ToolSearch { arguments } => truncate_preview(&arguments.query),
ToolDispatchPayload::Custom { input } => truncate_preview(input),
ToolDispatchPayload::LocalShell { command, .. } => truncate_preview(&command.join(" ")),
}
}
fn into_json_payload(self) -> JsonValue {
match self {
ToolDispatchPayload::Function { arguments } => json!({
"type": "function",
"arguments": arguments,
}),
ToolDispatchPayload::ToolSearch { arguments } => json!({
"type": "tool_search",
"arguments": arguments,
}),
ToolDispatchPayload::Custom { input } => json!({
"type": "custom",
"input": input,
}),
ToolDispatchPayload::LocalShell {
command,
workdir,
timeout_ms,
sandbox_permissions,
prefix_rule,
additional_permissions,
justification,
} => json!({
"type": "local_shell",
"command": command,
"workdir": workdir,
"timeout_ms": timeout_ms,
"sandbox_permissions": sandbox_permissions,
"prefix_rule": prefix_rule,
"additional_permissions": additional_permissions,
"justification": justification,
}),
}
}
}
fn truncate_preview(value: &str) -> String {
const MAX_PREVIEW_CHARS: usize = 160;
let mut chars = value.chars();
let mut preview = chars.by_ref().take(MAX_PREVIEW_CHARS).collect::<String>();
if chars.next().is_some() {
preview.push_str("...");
}
preview
}
fn append_tool_call_ended(
context: &EnabledToolDispatchTraceContext,
status: ExecutionStatus,
response: &DispatchedToolTraceResponse<'_>,
) {
let response_payload =
write_json_payload_best_effort(&context.writer, RawPayloadKind::ToolResult, response);
append_with_context_best_effort(
context,
RawTraceEventPayload::ToolCallEnded {
tool_call_id: context.tool_call_id.clone(),
status,
result_payload: response_payload,
},
);
}
fn write_json_payload_best_effort(
writer: &TraceWriter,
kind: RawPayloadKind,
payload: &impl Serialize,
) -> Option<RawPayloadRef> {
match writer.write_json_payload(kind, payload) {
Ok(payload_ref) => Some(payload_ref),
Err(err) => {
warn!("failed to write rollout trace payload: {err:#}");
None
}
}
}
fn append_with_context_best_effort(
context: &EnabledToolDispatchTraceContext,
payload: RawTraceEventPayload,
) {
let event_context = RawTraceEventContext {
thread_id: Some(context.thread_id.clone()),
codex_turn_id: Some(context.codex_turn_id.clone()),
};
if let Err(err) = context.writer.append_with_context(event_context, payload) {
warn!("failed to append rollout trace event: {err:#}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_interrupt_agent_as_close_agent() {
assert_eq!(
dispatched_tool_kind(
"interrupt_agent",
&ToolDispatchPayload::Function {
arguments: r#"{"target":"/root/child"}"#.to_string(),
},
),
ToolCallKind::CloseAgent
);
}
#[test]
fn classifies_imagegen_as_image_generation() {
assert_eq!(
dispatched_tool_kind(
"imagegen",
&ToolDispatchPayload::Function {
arguments: String::new(),
},
),
ToolCallKind::ImageGeneration
);
}
}

View File

@@ -0,0 +1,365 @@
//! Hot-path trace bundle writer.
//!
//! All producers share one writer. Write failures prevent further recording and
//! suppress the final closing event.
use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufWriter;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::PoisonError;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde::Serialize;
use crate::bundle::MANIFEST_FILE_NAME;
use crate::bundle::PAYLOADS_DIR_NAME;
use crate::bundle::RAW_EVENT_LOG_FILE_NAME;
use crate::bundle::TraceBundleManifest;
use crate::model::AgentThreadId;
use crate::payload::RawPayloadKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RAW_TRACE_EVENT_SCHEMA_VERSION;
use crate::raw_event::RawTraceEvent;
use crate::raw_event::RawTraceEventContext;
use crate::raw_event::RawTraceEventPayload;
/// Local trace bundle writer.
///
/// The writer appends raw events and writes payload files. It does not keep a
/// reduced `RolloutTrace` in memory; replay is owned by the reducer.
#[derive(Debug)]
pub struct TraceWriter {
inner: Mutex<TraceWriterInner>,
}
#[derive(Debug)]
struct TraceWriterInner {
manifest: TraceBundleManifest,
payloads_dir: PathBuf,
event_log: BufWriter<File>,
next_seq: u64,
next_payload_ordinal: u64,
// Preserve the first failure even when a producer cannot return it to its caller.
error: Option<String>,
}
impl TraceWriter {
/// Creates a trace bundle directory and writes its manifest.
pub fn create(
bundle_dir: impl AsRef<Path>,
trace_id: String,
rollout_id: String,
root_thread_id: AgentThreadId,
) -> Result<Self> {
let bundle_dir = bundle_dir.as_ref().to_path_buf();
let payloads_dir = bundle_dir.join(PAYLOADS_DIR_NAME);
std::fs::create_dir_all(&payloads_dir)
.with_context(|| format!("create trace payload dir {}", payloads_dir.display()))?;
let started_at_unix_ms = unix_time_ms();
let manifest =
TraceBundleManifest::new(trace_id, rollout_id, root_thread_id, started_at_unix_ms);
let event_log_path = bundle_dir.join(RAW_EVENT_LOG_FILE_NAME);
let event_log = OpenOptions::new()
.create_new(true)
.write(true)
.open(&event_log_path)
.with_context(|| format!("open trace event log {}", event_log_path.display()))?;
write_json_file(&bundle_dir.join(MANIFEST_FILE_NAME), &manifest)?;
Ok(Self {
inner: Mutex::new(TraceWriterInner {
manifest,
payloads_dir,
event_log: BufWriter::new(event_log),
next_seq: 1,
next_payload_ordinal: 1,
error: None,
}),
})
}
/// Writes a JSON payload file and returns its reduced-state reference.
pub fn write_json_payload(
&self,
kind: RawPayloadKind,
value: &impl Serialize,
) -> Result<RawPayloadRef> {
let mut inner = self.lock_inner();
inner.check()?;
let ordinal = inner.next_payload_ordinal;
inner.next_payload_ordinal += 1;
let raw_payload_id = format!("raw_payload:{ordinal}");
let relative_path = format!("{PAYLOADS_DIR_NAME}/{ordinal}.json");
let absolute_path = inner.payloads_dir.join(format!("{ordinal}.json"));
// Payload files are created before the event that references them. A
// replay interrupted after an event is appended should never point at a
// payload file that the writer planned but had not written yet.
let result = write_json_file(&absolute_path, value);
inner.record_result(result)?;
Ok(RawPayloadRef {
raw_payload_id,
kind,
path: relative_path,
})
}
/// Appends one raw event with no extra envelope context.
pub fn append(&self, payload: RawTraceEventPayload) -> Result<RawTraceEvent> {
self.append_with_context(RawTraceEventContext::default(), payload)
}
/// Appends one raw event with explicit thread/turn context.
pub fn append_with_context(
&self,
context: RawTraceEventContext,
payload: RawTraceEventPayload,
) -> Result<RawTraceEvent> {
let mut inner = self.lock_inner();
inner.check()?;
let event = RawTraceEvent {
schema_version: RAW_TRACE_EVENT_SCHEMA_VERSION,
seq: inner.next_seq,
wall_time_unix_ms: unix_time_ms(),
rollout_id: inner.manifest.rollout_id.clone(),
thread_id: context.thread_id,
codex_turn_id: context.codex_turn_id,
payload,
};
let result = (|| {
serde_json::to_writer(&mut inner.event_log, &event)?;
inner.event_log.write_all(b"\n")?;
inner.event_log.flush()?;
Ok(())
})();
inner.record_result(result)?;
inner.next_seq += 1;
Ok(event)
}
/// Reports any earlier recording failure, including failures in detached producers.
pub(crate) fn check(&self) -> Result<()> {
self.lock_inner().check()
}
fn lock_inner(&self) -> MutexGuard<'_, TraceWriterInner> {
// Preserve the event log after a panic in tracing code. Dropping the
// writer would lose subsequent diagnostic events in exactly the session
// we are trying to debug.
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl TraceWriterInner {
fn check(&self) -> Result<()> {
if let Some(error) = &self.error {
bail!("rollout recording failed: {error}");
}
Ok(())
}
fn record_result<T>(&mut self, result: Result<T>) -> Result<T> {
if let Err(error) = &result {
let error = format!("{error:#}");
tracing::error!("rollout recording failed: {error}");
self.error = Some(error);
}
result
}
}
impl Drop for TraceWriter {
fn drop(&mut self) {
// The last producer releases the writer, even for interrupted turns.
// This marks recorder closure, not successful task completion.
if !self.inner.is_poisoned() && !std::thread::panicking() {
let _ = self.append(RawTraceEventPayload::RecordingCompleted);
}
}
}
fn write_json_file(path: &Path, value: &impl Serialize) -> Result<()> {
let file = File::create(path).with_context(|| format!("create {}", path.display()))?;
let mut writer = BufWriter::new(file);
serde_json::to_writer_pretty(&mut writer, value)
.with_context(|| format!("write JSON {}", path.display()))?;
writer
.flush()
.with_context(|| format!("flush JSON {}", path.display()))
}
pub(crate) fn unix_time_ms() -> i64 {
let duration = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::model::ExecutionStatus;
use crate::model::RolloutStatus;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventPayload;
use crate::replay_bundle;
use crate::writer::TraceWriter;
#[test]
fn writer_records_payload_refs_and_replays_rollout_status() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = TraceWriter::create(
temp.path(),
"trace-1".to_string(),
"rollout-1".to_string(),
"thread-root".to_string(),
)?;
writer.append(RawTraceEventPayload::RolloutStarted {
trace_id: "trace-1".to_string(),
root_thread_id: "thread-root".to_string(),
})?;
let metadata_payload = writer.write_json_payload(
RawPayloadKind::ProtocolEvent,
&json!({
"source": "test",
"model": "gpt-test",
}),
)?;
writer.append(RawTraceEventPayload::ThreadStarted {
thread_id: "thread-root".to_string(),
agent_path: "/root".to_string(),
metadata_payload: Some(metadata_payload.clone()),
})?;
writer.append(RawTraceEventPayload::CodexTurnStarted {
codex_turn_id: "turn-1".to_string(),
thread_id: "thread-root".to_string(),
})?;
let inference_request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"model": "gpt-test",
"input": [{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "hello"}]
}],
}),
)?;
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: inference_request.clone(),
})?;
let inference_response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": "resp-1",
"output_items": [],
}),
)?;
writer.append(RawTraceEventPayload::InferenceCompleted {
inference_call_id: "inference-1".to_string(),
response_id: Some("resp-1".to_string()),
upstream_request_id: Some("req-1".to_string()),
response_payload: inference_response.clone(),
})?;
writer.append(RawTraceEventPayload::CodexTurnEnded {
codex_turn_id: "turn-1".to_string(),
status: ExecutionStatus::Completed,
})?;
writer.append(RawTraceEventPayload::RolloutEnded {
status: RolloutStatus::Completed,
})?;
let rollout = replay_bundle(temp.path())?;
assert_eq!(rollout.status, RolloutStatus::Completed);
assert_eq!(rollout.root_thread_id, "thread-root");
assert_eq!(rollout.threads["thread-root"].agent_path, "/root");
assert_eq!(rollout.codex_turns["turn-1"].thread_id, "thread-root");
assert_eq!(
rollout.codex_turns["turn-1"].execution.status,
ExecutionStatus::Completed,
);
assert_eq!(
rollout.inference_calls["inference-1"].raw_request_payload_id,
inference_request.raw_payload_id,
);
assert_eq!(
rollout.inference_calls["inference-1"].raw_response_payload_id,
Some(inference_response.raw_payload_id),
);
assert_eq!(
rollout.raw_payloads[&metadata_payload.raw_payload_id].path,
"payloads/1.json"
);
Ok(())
}
#[test]
fn payload_failure_prevents_finalization_even_after_storage_recovers() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer =
TraceWriter::create(temp.path(), "trace".into(), "rollout".into(), "root".into())?;
std::fs::remove_dir(temp.path().join("payloads"))?;
assert!(
writer
.write_json_payload(RawPayloadKind::ProtocolEvent, &json!({}))
.is_err()
);
std::fs::create_dir(temp.path().join("payloads"))?;
assert!(writer.check().is_err());
assert!(
writer
.write_json_payload(RawPayloadKind::ProtocolEvent, &json!({}))
.is_err()
);
drop(writer);
assert_eq!(
std::fs::read_to_string(temp.path().join("trace.jsonl"))?,
""
);
Ok(())
}
#[test]
fn event_write_failure_prevents_finalization() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer =
TraceWriter::create(temp.path(), "trace".into(), "rollout".into(), "root".into())?;
// A read-only file makes the real buffered write fail on every platform.
writer.lock_inner().event_log =
std::io::BufWriter::new(std::fs::File::open(temp.path().join("trace.jsonl"))?);
assert!(
writer
.append(RawTraceEventPayload::RolloutEnded {
status: RolloutStatus::Completed
})
.is_err()
);
assert!(writer.check().is_err());
drop(writer);
assert_eq!(
std::fs::read_to_string(temp.path().join("trace.jsonl"))?,
""
);
Ok(())
}
}