mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Measure initial output collection time for exec_command (#63695)
## Why End-to-end tool duration does not show how much time `exec_command` spends collecting its initial output. Tracking the duration and call count separately lets readers of the metrics compute the mean collection time for each configured shell snapshot mode. ## What changed Record the initial output collection time in whole milliseconds and count each successful process manager response, including collections shorter than a millisecond. The timing starts after the early-exit wait and can include draining output after the process exits. Tag both counters with the configured `shell_snapshot_mode` (`disabled`, `v1`, or `v2`), including when execution falls back. Intercepted patches, process manager errors, and `write_stdin` calls are excluded. ## Testing Extend a unified exec integration test to check that the recorded time matches the initial response within one millisecond, both counters carry the `v2` tag, and a subsequent `write_stdin` leaves the count at one. GitOrigin-RevId: 289336cf2544a78abb3417484b48d2d22109a56c
This commit is contained in:
@@ -2,6 +2,7 @@ use std::sync::Arc;
|
||||
|
||||
use crate::function_tool::FunctionCallError;
|
||||
use crate::maybe_emit_implicit_skill_invocation;
|
||||
use crate::session::session::Session;
|
||||
use crate::tools::context::ExecCommandToolOutput;
|
||||
use crate::tools::context::ToolEnvironments;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
@@ -27,6 +28,8 @@ use crate::unified_exec::UnifiedExecProcessManager;
|
||||
use crate::unified_exec::generate_chunk_id;
|
||||
use crate::unified_exec::output::CapturedStream;
|
||||
use codex_features::Feature;
|
||||
use codex_otel::EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_COUNT_METRIC;
|
||||
use codex_otel::EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_TOTAL_METRIC;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_otel::TOOL_CALL_UNIFIED_EXEC_METRIC;
|
||||
use codex_tools::JsonSchema;
|
||||
@@ -232,7 +235,20 @@ impl ExecCommandHandler {
|
||||
None => manager.exec_command(request, &context).await,
|
||||
};
|
||||
match result {
|
||||
Ok(response) => Ok(boxed_tool_output(response)),
|
||||
Ok(response) => {
|
||||
let tags = [shell_snapshot_mode_tag(&session)];
|
||||
step_context.session_telemetry.counter(
|
||||
EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_TOTAL_METRIC,
|
||||
response.wall_time.as_millis().min(i64::MAX as u128) as i64,
|
||||
&tags,
|
||||
);
|
||||
step_context.session_telemetry.counter(
|
||||
EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_COUNT_METRIC,
|
||||
/*inc*/ 1,
|
||||
&tags,
|
||||
);
|
||||
Ok(boxed_tool_output(response))
|
||||
}
|
||||
Err(UnifiedExecError::SandboxDenied {
|
||||
output,
|
||||
original_token_count,
|
||||
@@ -305,16 +321,8 @@ fn one_shot_exec_command_spec(spec: ToolSpec) -> ToolSpec {
|
||||
|
||||
impl CoreToolRuntime for ExecCommandHandler {
|
||||
fn telemetry_tags(&self, invocation: &ToolInvocation) -> ToolTelemetryTags {
|
||||
// Record the configured mode so fallback calls remain in their rollout cohort.
|
||||
// This does not indicate whether the command actually used a snapshot.
|
||||
let mode = if invocation.session.enabled(Feature::ShellSnapshotV2) {
|
||||
"v2"
|
||||
} else if invocation.session.enabled(Feature::ShellSnapshot) {
|
||||
"v1"
|
||||
} else {
|
||||
"disabled"
|
||||
};
|
||||
vec![("shell_snapshot_mode", mode.to_string())]
|
||||
let (key, mode) = shell_snapshot_mode_tag(&invocation.session);
|
||||
vec![(key, mode.to_string())]
|
||||
}
|
||||
|
||||
fn environments_for_input(
|
||||
@@ -389,6 +397,19 @@ impl CoreToolRuntime for ExecCommandHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn shell_snapshot_mode_tag(session: &Session) -> (&'static str, &'static str) {
|
||||
// Record the configured mode so fallback calls remain in their rollout cohort.
|
||||
// This does not indicate whether the command actually used a snapshot.
|
||||
let mode = if session.enabled(Feature::ShellSnapshotV2) {
|
||||
"v2"
|
||||
} else if session.enabled(Feature::ShellSnapshot) {
|
||||
"v1"
|
||||
} else {
|
||||
"disabled"
|
||||
};
|
||||
("shell_snapshot_mode", mode)
|
||||
}
|
||||
|
||||
fn emit_unified_exec_tty_metric(session_telemetry: &SessionTelemetry, tty: bool) {
|
||||
session_telemetry.counter(
|
||||
TOOL_CALL_UNIFIED_EXEC_METRIC,
|
||||
|
||||
@@ -15,6 +15,10 @@ use std::sync::OnceLock;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_otel::EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_COUNT_METRIC;
|
||||
use codex_otel::EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_TOTAL_METRIC;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::EnvironmentVariablePattern;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
@@ -61,6 +65,9 @@ use core_test_support::test_codex::turn_permission_fields;
|
||||
use core_test_support::wait_for_event;
|
||||
use core_test_support::wait_for_event_match;
|
||||
use core_test_support::wait_for_event_with_timeout;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ScopeMetrics;
|
||||
use pretty_assertions::assert_eq;
|
||||
use regex_lite::Regex;
|
||||
use serde_json::Value;
|
||||
@@ -2096,8 +2103,21 @@ async fn write_stdin_clamps_model_requested_max_output_tokens_to_policy() -> Res
|
||||
|
||||
let mut builder = test_codex().with_model("gpt-5.5").with_config(|config| {
|
||||
config.tool_output_token_limit = Some(50);
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ShellSnapshotV2)
|
||||
.expect("test config should allow ShellSnapshotV2");
|
||||
});
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
let mut test = builder.build_with_auto_env(&server).await?;
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
|
||||
)?;
|
||||
let mut options = test.start_thread_options().await;
|
||||
options.thread_extension_init.insert(metrics.clone());
|
||||
let thread = test.thread_manager.start_thread(options).await?;
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
test.codex = thread.thread;
|
||||
test.session_configured = thread.session_configured;
|
||||
|
||||
let start_call_id = "uexec-stdin-clamp-start";
|
||||
let start_args = serde_json::json!({
|
||||
@@ -2168,6 +2188,44 @@ async fn write_stdin_clamps_model_requested_max_output_tokens_to_policy() -> Res
|
||||
})
|
||||
.await;
|
||||
|
||||
// The initial call waits for the first yield. The later write_stdin must not count again.
|
||||
let snapshot = metrics.snapshot()?;
|
||||
let counter = |name: &str| {
|
||||
let metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.find(|metric| metric.name() == name)
|
||||
.unwrap_or_else(|| panic!("missing {name}"));
|
||||
let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else {
|
||||
panic!("expected counter {name}");
|
||||
};
|
||||
let mut points = sum.data_points();
|
||||
let point = points.next().expect("one counter series");
|
||||
assert!(
|
||||
points.next().is_none(),
|
||||
"unexpected extra series for {name}"
|
||||
);
|
||||
let tags = point
|
||||
.attributes()
|
||||
.map(|tag| (tag.key.as_str(), tag.value.to_string()))
|
||||
.collect::<HashMap<_, _>>();
|
||||
(tags, point.value())
|
||||
};
|
||||
let (tags, total_ms) = counter(EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_TOTAL_METRIC);
|
||||
assert_eq!(tags["shell_snapshot_mode"], "v2");
|
||||
assert_eq!(
|
||||
counter(EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_COUNT_METRIC),
|
||||
(tags, 1)
|
||||
);
|
||||
assert!(total_ms > 0);
|
||||
// The counter truncates to whole milliseconds and the response rounds to 0.1 ms.
|
||||
let recorded = Duration::from_millis(total_ms);
|
||||
let reported = Duration::from_secs_f64(start_output.wall_time_seconds);
|
||||
assert!(
|
||||
recorded.abs_diff(reported) <= Duration::from_millis(1),
|
||||
"recorded {recorded:?}, reported {reported:?}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,14 @@ pub const TOOL_CALL_DURATION_METRIC: &str = "codex.tool.call.duration_ms";
|
||||
/// calls to compute a mean without averaging histogram export batches.
|
||||
pub const EXEC_COMMAND_DURATION_TOTAL_METRIC: &str = "codex.exec_command.duration_total_ms";
|
||||
pub const EXEC_COMMAND_COUNT_METRIC: &str = "codex.exec_command.calls";
|
||||
/// Initial output collection time reported by `exec_command`. The timer starts
|
||||
/// after the early-exit wait and can include draining output after exit.
|
||||
pub const EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_TOTAL_METRIC: &str =
|
||||
"codex.exec_command.initial_output_collection_total_ms";
|
||||
/// Counts the same collections, even when they take less than a millisecond.
|
||||
/// Excludes intercepted patches, process manager errors and `write_stdin`.
|
||||
pub const EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_COUNT_METRIC: &str =
|
||||
"codex.exec_command.initial_output_collection_calls";
|
||||
pub const TOOL_CALL_UNIFIED_EXEC_METRIC: &str = "codex.tool.unified_exec";
|
||||
pub const MULTI_AGENT_SPAWN_FAILURE_METRIC: &str = "codex.multi_agent.spawn.failure";
|
||||
pub const MULTI_AGENT_SPAWN_PHASE_DURATION_METRIC: &str =
|
||||
|
||||
Reference in New Issue
Block a user