Add opt-in overhead timing to code-mode responses (#46288)

## Why

Code-mode responses show host duration without exposing time spent outside the host, including app-server waiting.

## What changed

- Add `features.code_mode.experimental_show_cell_overhead`, disabled by default, to show handler duration, host duration, and their difference in `exec` and `wait` response headers.
- Reuse the completed handler measurement from tool-call logging, excluding dispatch waiting, and capture it even when logging is disabled.
- Preserve the existing timing format when the option is disabled or host timing is unavailable, and preserve boolean feature toggles when merging nested code-mode configuration.

## Testing

Add coverage for timing headers, zero and missing host measurements, negative rounding differences, content preservation, and configuration merging. Extend app-server tests across gRPC and stdio to verify timing includes post-host elicitation waiting, and add a response snapshot for successful execution and a failed wait.

GitOrigin-RevId: 929b84784d9c6077cf2b5927a90bd2d5f3870078
This commit is contained in:
cassirer-openai authored and copyberry committed 2026-09-17 19:34:45 +00:00
1 parent 0a5b999169
commit 0fd1cd8d99
19 files changed
+619 -116

No files matched your search

+2
View File
@@ -635,6 +635,7 @@ async fn load_config_resolves_code_mode_config() -> std::io::Result<()> {
[features.code_mode]
enabled = true
default_exec_yield_time_ms = 10000
experimental_show_cell_overhead = true
excluded_tool_namespaces = ["mcp__codex_apps", "multi_agent_v1"]
direct_only_tool_namespaces = ["mcp__history", "mcp__notes"]
@@ -652,6 +653,7 @@ disable_in_process_fallback = true
.await?;
assert_eq!(config.code_mode.default_exec_yield_time_ms, 10_000);
assert!(config.code_mode.experimental_show_cell_overhead);
assert_eq!(
config.code_mode.excluded_tool_namespaces,
vec!["mcp__codex_apps".to_string(), "multi_agent_v1".to_string()]
+8
View File
@@ -1127,6 +1127,10 @@ const DEFAULT_CODE_MODE_EXEC_YIELD_TIME_MS: u64 = 30_000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CodeModeConfig {
pub default_exec_yield_time_ms: u64,
/// Show handler duration, code-mode host duration, and harness overhead
/// in each code-mode cell response.
/// Experimental: this option and the response format may change or be removed.
pub experimental_show_cell_overhead: bool,
pub excluded_tool_namespaces: Vec<String>,
pub direct_only_tool_namespaces: Vec<String>,
/// Keep code mode fail-closed when the standalone host is unavailable.
@@ -1137,6 +1141,7 @@ impl Default for CodeModeConfig {
fn default() -> Self {
Self {
default_exec_yield_time_ms: DEFAULT_CODE_MODE_EXEC_YIELD_TIME_MS,
experimental_show_cell_overhead: false,
excluded_tool_namespaces: Vec::new(),
direct_only_tool_namespaces: Vec::new(),
disable_in_process_fallback: false,
@@ -2679,6 +2684,9 @@ fn resolve_code_mode_config(config_toml: &ConfigToml) -> CodeModeConfig {
default_exec_yield_time_ms: base
.and_then(|config| config.default_exec_yield_time_ms)
.unwrap_or(DEFAULT_CODE_MODE_EXEC_YIELD_TIME_MS),
experimental_show_cell_overhead: base
.and_then(|config| config.experimental_show_cell_overhead)
.unwrap_or_default(),
excluded_tool_namespaces: base
.and_then(|config| config.excluded_tool_namespaces.as_ref())
.cloned()
@@ -1,5 +1,4 @@
use crate::function_tool::FunctionCallError;
use crate::tools::context::FunctionToolOutput;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
use crate::tools::context::boxed_tool_output;
@@ -13,6 +12,7 @@ use super::ExecContext;
use super::PUBLIC_TOOL_NAME;
use super::handle_runtime_response;
use super::is_exec_tool_name;
use super::output::CodeModeToolOutput;
use super::telemetry::CodeModeToolCallGuard;
use super::telemetry::trace_id;
@@ -39,7 +39,7 @@ impl CodeModeExecuteHandler {
originating_call: Option<crate::tools::context::ToolCallOrigin>,
code: String,
telemetry: &mut CodeModeToolCallGuard,
) -> Result<FunctionToolOutput, FunctionCallError> {
) -> Result<CodeModeToolOutput, FunctionCallError> {
let args =
codex_code_mode::parse_exec_source(&code).map_err(FunctionCallError::RespondToModel)?;
let exec = ExecContext {
@@ -146,14 +146,13 @@ impl CodeModeExecuteHandler {
let wall_time = response
.code_mode_host_duration()
.unwrap_or_else(|| started_at.elapsed());
handle_runtime_response(
Ok(handle_runtime_response(
&step_context.settings.model_info,
response,
args.max_output_tokens,
wall_time,
)
.await
.map_err(FunctionCallError::RespondToModel)
exec.turn.config.code_mode.experimental_show_cell_overhead,
))
}
}
+27 -43
View File
@@ -1,6 +1,7 @@
mod delegate;
mod execute_handler;
pub(crate) mod execute_spec;
mod output;
mod response_adapter;
mod telemetry;
mod wait_handler;
@@ -51,6 +52,7 @@ use delegate::CodeModeCellDelegate;
use delegate::CodeModeDispatchBroker;
use delegate::CodeModeDispatchWorker;
pub(crate) use execute_handler::CodeModeExecuteHandler;
use output::CodeModeToolOutput;
use response_adapter::into_function_call_output_content_items;
pub(crate) use wait_handler::CodeModeWaitHandler;
@@ -251,51 +253,43 @@ impl CodeModeService {
}
}
pub(super) async fn handle_runtime_response(
fn handle_runtime_response(
model_info: &codex_protocol::openai_models::ModelInfo,
response: RuntimeResponse,
max_output_tokens: Option<usize>,
wall_time: Duration,
) -> Result<FunctionToolOutput, String> {
experimental_show_cell_overhead: bool,
) -> CodeModeToolOutput {
let script_status = format_script_status(&response);
let supports_original = can_request_original_image_detail(model_info);
let host_duration = response
.code_mode_host_duration()
.filter(|_| experimental_show_cell_overhead);
match response {
RuntimeResponse::Yielded { content_items, .. } => {
let mut content_items = into_function_call_output_content_items(content_items);
sanitize_image_detail_items(supports_original, &mut content_items);
content_items = truncate_code_mode_result(content_items, max_output_tokens);
prepend_script_status(&mut content_items, &script_status, wall_time);
Ok(FunctionToolOutput::from_content(content_items, Some(true)))
}
RuntimeResponse::Terminated { content_items, .. } => {
let mut content_items = into_function_call_output_content_items(content_items);
sanitize_image_detail_items(supports_original, &mut content_items);
content_items = truncate_code_mode_result(content_items, max_output_tokens);
prepend_script_status(&mut content_items, &script_status, wall_time);
Ok(FunctionToolOutput::from_content(content_items, Some(true)))
}
let (content_items, error_text) = match response {
RuntimeResponse::Yielded { content_items, .. }
| RuntimeResponse::Terminated { content_items, .. } => (content_items, None),
RuntimeResponse::Result {
content_items,
error_text,
..
} => {
let mut content_items = into_function_call_output_content_items(content_items);
sanitize_image_detail_items(supports_original, &mut content_items);
let success = error_text.is_none();
if let Some(error_text) = error_text {
content_items.push(FunctionCallOutputContentItem::InputText {
text: format!("Script error:\n{error_text}"),
});
}
content_items = truncate_code_mode_result(content_items, max_output_tokens);
prepend_script_status(&mut content_items, &script_status, wall_time);
Ok(FunctionToolOutput::from_content(
content_items,
Some(success),
))
}
} => (content_items, error_text),
};
let mut content_items = into_function_call_output_content_items(content_items);
sanitize_image_detail_items(supports_original, &mut content_items);
let success = error_text.is_none();
if let Some(error_text) = error_text {
content_items.push(FunctionCallOutputContentItem::InputText {
text: format!("Script error:\n{error_text}"),
});
}
content_items = truncate_code_mode_result(content_items, max_output_tokens);
CodeModeToolOutput::new(
FunctionToolOutput::from_content(content_items, Some(success)),
script_status,
wall_time,
host_duration,
)
}
fn format_script_status(response: &RuntimeResponse) -> String {
@@ -314,16 +308,6 @@ fn format_script_status(response: &RuntimeResponse) -> String {
}
}
fn prepend_script_status(
content_items: &mut Vec<FunctionCallOutputContentItem>,
status: &str,
wall_time: Duration,
) {
let wall_time_seconds = ((wall_time.as_secs_f32()) * 10.0).round() / 10.0;
let header = format!("{status}\nWall time {wall_time_seconds:.1} seconds\nOutput:\n");
content_items.insert(0, FunctionCallOutputContentItem::InputText { text: header });
}
fn truncate_code_mode_result(
items: Vec<FunctionCallOutputContentItem>,
max_output_tokens: Option<usize>,
@@ -0,0 +1,76 @@
//! Code-mode response headers use the host measurement and completed handler timing.
//! Content is already truncated; only the bounded header changes at completion.
use std::time::Duration;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::ResponseInputItem;
use crate::tools::context::FunctionToolOutput;
use crate::tools::context::ToolOutput;
use crate::tools::context::ToolPayload;
pub(super) struct CodeModeToolOutput {
output: FunctionToolOutput,
status: String,
host_duration: Option<Duration>,
}
impl CodeModeToolOutput {
pub(super) fn new(
mut output: FunctionToolOutput,
status: String,
wall_time: Duration,
host_duration: Option<Duration>,
) -> Self {
// Use the host-only header when overhead is hidden or host timing is unavailable.
let wall_time_seconds = (wall_time.as_secs_f32() * 10.0).round() / 10.0;
output.body.insert(
/*index*/ 0,
FunctionCallOutputContentItem::InputText {
text: format!("{status}\nWall time {wall_time_seconds:.1} seconds\nOutput:\n"),
},
);
Self {
output,
status,
host_duration,
}
}
}
impl ToolOutput for CodeModeToolOutput {
fn log_output(&self) -> String {
self.output.log_output()
}
fn success_for_logging(&self) -> bool {
self.output.success_for_logging()
}
fn set_handler_duration_ms(&mut self, handler_duration_ms: u64) {
let Some(host_duration) = self.host_duration else {
return;
};
let total_seconds = handler_duration_ms as f64 / 1_000.0;
let host_seconds = host_duration.as_secs_f64();
// Match the logged measurements before rounding. Millisecond quantization of the
// outer measurement can legitimately produce a small negative difference.
let overhead_seconds = total_seconds - host_seconds;
let status = &self.status;
// The constructor owns this slot; script text and media stay untouched.
self.output.body[0] = FunctionCallOutputContentItem::InputText {
text: format!(
"{status}\nWall time {total_seconds:.3} seconds (code-mode {host_seconds:.3} seconds; overhead {overhead_seconds:.3} seconds)\nOutput:\n"
),
};
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
self.output.to_response_item(call_id, payload)
}
}
#[cfg(test)]
#[path = "output_tests.rs"]
mod tests;
@@ -0,0 +1,65 @@
//! Checks code-mode timing headers, including absent and zero host measurements.
use super::*;
use codex_protocol::models::ImageReference;
use pretty_assertions::assert_eq;
#[test]
fn completed_timing_preserves_content_and_distinguishes_zero_from_unavailable() {
let content = vec![
FunctionCallOutputContentItem::InputText {
text: "result".to_string(),
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/png;base64,image".to_string(),
},
detail: None,
},
FunctionCallOutputContentItem::InputAudio {
audio_url: "data:audio/wav;base64,audio".to_string(),
},
];
for (host_duration, expected_timing) in [
(
Some(Duration::from_millis(/*millis*/ 750)),
"Wall time 1.250 seconds (code-mode 0.750 seconds; overhead 0.500 seconds)",
),
(
Some(Duration::ZERO),
"Wall time 1.250 seconds (code-mode 0.000 seconds; overhead 1.250 seconds)",
),
(
Some(Duration::from_micros(/*micros*/ 1_251_400)),
"Wall time 1.250 seconds (code-mode 1.251 seconds; overhead -0.001 seconds)",
),
(None, "Wall time 0.8 seconds"),
] {
let mut output = CodeModeToolOutput::new(
FunctionToolOutput::from_content(content.clone(), Some(false)),
"Script failed".to_string(),
Duration::from_millis(/*millis*/ 750),
host_duration,
);
output.set_handler_duration_ms(/*handler_duration_ms*/ 1_250);
let mut expected_content = vec![FunctionCallOutputContentItem::InputText {
text: format!("Script failed\n{expected_timing}\nOutput:\n"),
}];
expected_content.extend(content.clone());
let expected = FunctionToolOutput::from_content(expected_content, Some(false));
for payload in [
ToolPayload::Custom {
input: "text('result')".to_string(),
},
ToolPayload::Function {
arguments: r#"{"cell_id":"1"}"#.to_string(),
},
] {
let response = output.to_response_item("call", &payload);
assert_eq!(response, expected.to_response_item("call", &payload));
// Serialization must reuse the completed value, including on retries.
assert_eq!(output.to_response_item("call", &payload), response);
}
assert_eq!(output.success_for_logging(), false);
}
}
@@ -178,15 +178,13 @@ impl CodeModeWaitHandler {
let wall_time = wait_response
.code_mode_host_duration()
.unwrap_or_else(|| started_at.elapsed());
handle_runtime_response(
Ok(boxed_tool_output(handle_runtime_response(
&step_context.settings.model_info,
wait_response.into(),
args.max_tokens,
wall_time,
)
.await
.map_err(FunctionCallError::RespondToModel)
.map(boxed_tool_output)
exec.turn.config.code_mode.experimental_show_cell_overhead,
)))
}
_ => Err(FunctionCallError::RespondToModel(format!(
"{WAIT_TOOL_NAME} expects JSON arguments"
+92 -34
View File
@@ -32,7 +32,7 @@ use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ToolResultMetadata;
struct ToolCallTimingGuard {
started_at: Instant,
started_at: Option<Instant>,
execution_started_at: Arc<OnceLock<Instant>>,
conversation_id: String,
turn_id: String,
@@ -130,8 +130,14 @@ impl ToolCallRuntime {
let lock = Arc::clone(&self.parallel_execution);
let invocation_cancellation_token = cancellation_token.clone();
let started = Instant::now();
let tool_call_timing_guard =
ToolCallTimingGuard::capture(started, &session.thread_id, &turn.sub_id, &call, &source);
let tool_call_timing_guard = ToolCallTimingGuard::capture(
started,
&session.thread_id,
&turn.sub_id,
&call,
&source,
turn.config.code_mode.experimental_show_cell_overhead,
);
let execution_started_at = tool_call_timing_guard
.as_ref()
.map(|timing| Arc::clone(&timing.execution_started_at));
@@ -213,8 +219,8 @@ impl ToolCallRuntime {
));
async move {
let _tool_call_timing_guard = tool_call_timing_guard;
tokio::select! {
let mut tool_call_timing_guard = tool_call_timing_guard;
let mut result = tokio::select! {
res = &mut dispatch_handle => res.map_err(Self::tool_task_join_error)?,
_ = cancellation_token.cancelled() => {
if terminal_outcome_reached.load(Ordering::Acquire) || dispatch_handle.is_finished() {
@@ -224,30 +230,40 @@ impl ToolCallRuntime {
abort_dispatch_span.record("aborted", true);
dispatch_handle.abort();
match dispatch_handle.await {
Ok(result) => return result,
Err(err) if err.is_cancelled() => {}
Err(err) => return Err(Self::tool_task_join_error(err)),
Ok(result) => result,
Err(err) if err.is_cancelled() => {
let response = Self::aborted_response(&call, secs);
call_trace::result_ready(
thread_id,
&abort_turn.sub_id,
&call.tool_name,
&call.call_id,
trace_source,
);
notify_tool_aborted(
abort_session.as_ref(),
abort_turn.as_ref(),
call.call_id.as_str(),
&call.tool_name,
abort_source,
)
.await;
Ok(response)
}
Err(err) => Err(Self::tool_task_join_error(err)),
}
let response = Self::aborted_response(&call, secs);
call_trace::result_ready(
thread_id,
&abort_turn.sub_id,
&call.tool_name,
&call.call_id,
trace_source,
);
notify_tool_aborted(
abort_session.as_ref(),
abort_turn.as_ref(),
call.call_id.as_str(),
&call.tool_name,
abort_source,
)
.await;
Ok(response)
}
},
};
// Use one completion measurement for logging and response formatting.
// Measuring inside a handler would omit routing and output processing.
if let Some(timing) = tool_call_timing_guard.as_mut()
&& let Some(handler_duration_ms) = timing.finish()
&& let Ok(result) = &mut result
{
result.result.set_handler_duration_ms(handler_duration_ms);
}
result
}
.in_current_span()
}
@@ -312,6 +328,7 @@ impl ToolCallTimingGuard {
turn_id: &str,
call: &ToolCall,
source: &ToolCallSource,
experimental_show_cell_overhead: bool,
) -> Option<Self> {
// Code-mode calls are nested within a direct code-mode tool call whose
// timing already includes them. Suppress nested guards so consumers do
@@ -319,13 +336,13 @@ impl ToolCallTimingGuard {
if !matches!(
source,
ToolCallSource::Direct | ToolCallSource::DirectPlaintextMessage
) || !tracing::enabled!(tracing::Level::INFO)
) || (!experimental_show_cell_overhead && !tracing::enabled!(tracing::Level::INFO))
{
return None;
}
Some(Self {
started_at,
started_at: Some(started_at),
execution_started_at: Arc::new(OnceLock::new()),
conversation_id: conversation_id.to_string(),
turn_id: turn_id.to_string(),
@@ -333,10 +350,11 @@ impl ToolCallTimingGuard {
tool_name: call.tool_name.clone(),
})
}
}
impl Drop for ToolCallTimingGuard {
fn drop(&mut self) {
/// Log call timing once and return the handler duration in milliseconds.
fn finish(&mut self) -> Option<u64> {
// Taking the start instant keeps normal completion and Drop from logging twice.
let started_at = self.started_at.take()?;
let completed_at = Instant::now();
// Snapshot once so a concurrently-starting dispatch cannot make one
// event internally inconsistent.
@@ -346,12 +364,10 @@ impl Drop for ToolCallTimingGuard {
.copied()
.filter(|execution_started_at| *execution_started_at <= completed_at);
let duration_ms = |duration: std::time::Duration| u64::try_from(duration.as_millis()).ok();
let total_duration_ms = duration_ms(completed_at.duration_since(self.started_at));
let total_duration_ms = duration_ms(completed_at.duration_since(started_at));
let dispatch_duration_ms = execution_started_at.map_or_else(
|| total_duration_ms,
|execution_started_at| {
duration_ms(execution_started_at.duration_since(self.started_at))
},
|execution_started_at| duration_ms(execution_started_at.duration_since(started_at)),
);
let handler_duration_ms = execution_started_at.map_or(Some(0), |execution_started_at| {
duration_ms(completed_at.duration_since(execution_started_at))
@@ -388,6 +404,14 @@ impl Drop for ToolCallTimingGuard {
);
}
}
handler_duration_ms
}
}
impl Drop for ToolCallTimingGuard {
fn drop(&mut self) {
// Cancellation can drop the outer future before its normal completion path runs.
let _ = self.finish();
}
}
@@ -434,6 +458,7 @@ mod tests {
"turn-id",
&call,
&ToolCallSource::Direct,
/*experimental_show_cell_overhead*/ false,
);
assert!(
direct_guard.is_some(),
@@ -450,6 +475,7 @@ mod tests {
cell_id: "cell-1".to_string(),
runtime_tool_call_id: "runtime-call-1".to_string(),
},
/*experimental_show_cell_overhead*/ false,
);
assert!(
code_mode_guard.is_none(),
@@ -458,6 +484,38 @@ mod tests {
});
}
#[test]
fn output_timing_works_without_logs_and_excludes_dispatch_waiting() {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("exec"),
call_id: "call-1".to_string(),
payload: ToolPayload::Custom {
input: "text('ready')".to_string(),
},
encrypted_function_args: None,
};
let started_at = Instant::now() - Duration::from_secs(/*secs*/ 5);
let mut timing = ToolCallTimingGuard::capture(
started_at,
&"conversation-id",
"turn-id",
&call,
&ToolCallSource::Direct,
/*experimental_show_cell_overhead*/ true,
)
.expect("model-visible timing must not depend on INFO logging");
timing
.execution_started_at
.set(started_at + Duration::from_secs(/*secs*/ 4))
.expect("execution start is unset");
let handler_ms = timing.finish().expect("completed handler duration");
assert!(u128::from(handler_ms) <= started_at.elapsed().as_millis() - 4_000);
assert!(handler_ms >= 1_000);
assert_eq!(timing.finish(), None, "completion is consumed exactly once");
});
}
#[tokio::test]
async fn cancellation_before_dispatch_admission_logs_dispatch_only_timing() -> anyhow::Result<()>
{
+4
View File
@@ -232,6 +232,10 @@ impl ToolOutput for PostToolUseFeedbackOutput {
self.original.success_for_logging()
}
fn set_handler_duration_ms(&mut self, handler_duration_ms: u64) {
self.original.set_handler_duration_ms(handler_duration_ms);
}
fn fallback_token_limit_override(&self) -> Option<usize> {
self.original.fallback_token_limit_override()
}