mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Add multi-agent spawn latency and failure metrics (#47984)
## What changed - Record successful spawn phase durations in `codex.multi_agent.spawn.phase.duration_ms`, covering residency reservation and fork context when applicable, child creation, durability waits, input admission, and total latency. - Count spawn failures from the V1 and V2 tool handlers in `codex.multi_agent.spawn.failure`, grouped by bounded error categories. - Use bounded labels for fork mode, multi-agent version, product SKU, and successful-spawn history mode. Emit phase timings only after a successful spawn. ## Testing Add in-memory metrics tests for phase durations and labels, plus a tool-handler test verifying that a thread-limit failure emits one counter increment with the expected labels. GitOrigin-RevId: 04cba9042b9b34acdf57376ace5288c3f741f3b2
This commit is contained in:
@@ -12,6 +12,7 @@ use crate::agent::types::SpawnAgentForkMode;
|
||||
use crate::agent::types::SpawnAgentOptions;
|
||||
use crate::tools::handlers::multi_agents_spec::SpawnAgentToolOptions;
|
||||
use crate::tools::handlers::multi_agents_spec::create_spawn_agent_tool_v1;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_tools::ToolSpec;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -108,6 +109,7 @@ async fn handle_spawn_agent(
|
||||
.await
|
||||
.map_err(FunctionCallError::RespondToModel)?;
|
||||
let config = prepared.config;
|
||||
let fork_mode = args.fork_context.then_some(SpawnAgentForkMode::FullHistory);
|
||||
let result = session
|
||||
.services
|
||||
.agent_control
|
||||
@@ -123,8 +125,8 @@ async fn handle_spawn_agent(
|
||||
/*task_name*/ None,
|
||||
)?,
|
||||
options: SpawnAgentOptions {
|
||||
fork_parent_spawn_call_id: args.fork_context.then(|| call_id.clone()),
|
||||
fork_mode: args.fork_context.then_some(SpawnAgentForkMode::FullHistory),
|
||||
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
|
||||
fork_mode: fork_mode.clone(),
|
||||
parent_thread_id: Some(session.thread_id),
|
||||
parent_turn_id: Some(turn.sub_id.clone()),
|
||||
root_turn_id: turn.turn_metadata_state.root_turn_id(),
|
||||
@@ -135,7 +137,16 @@ async fn handle_spawn_agent(
|
||||
},
|
||||
})
|
||||
.await
|
||||
.map_err(collab_spawn_error);
|
||||
.map_err(|err| {
|
||||
record_collab_spawn_failure(
|
||||
&turn.session_telemetry,
|
||||
turn.config.apps_mcp_product_sku.as_deref(),
|
||||
&err,
|
||||
fork_mode.as_ref(),
|
||||
MultiAgentVersion::V1,
|
||||
);
|
||||
collab_spawn_error(err)
|
||||
});
|
||||
let (new_thread_id, status) = match &result {
|
||||
Ok((spawned_agent, _)) => (Some(spawned_agent.thread_id), spawned_agent.status.clone()),
|
||||
Err(_) => (None, AgentStatus::NotFound),
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
use crate::agent::types::SpawnAgentForkMode;
|
||||
use crate::config::DEFAULT_MULTI_AGENT_V2_MIN_WAIT_TIMEOUT_MS;
|
||||
use crate::config::HARD_MAX_MULTI_AGENT_V2_TIMEOUT_MS;
|
||||
use crate::function_tool::FunctionCallError;
|
||||
use crate::tools::context::FunctionToolOutput;
|
||||
use crate::tools::context::ToolOutput;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
@@ -72,6 +75,36 @@ pub(crate) fn collab_spawn_error(err: CodexErr) -> FunctionCallError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_collab_spawn_failure(
|
||||
telemetry: &SessionTelemetry,
|
||||
product_sku: Option<&str>,
|
||||
err: &CodexErr,
|
||||
fork_mode: Option<&SpawnAgentForkMode>,
|
||||
multi_agent_version: MultiAgentVersion,
|
||||
) {
|
||||
let reason = match err.details() {
|
||||
CodexErrorDetails::AgentLimitReached { .. } => "limit_reached",
|
||||
CodexErrorDetails::InvalidRequest(_) => "invalid_request",
|
||||
CodexErrorDetails::ThreadNotFound(_) => "thread_not_found",
|
||||
CodexErrorDetails::UnsupportedOperation(_) => "unsupported_operation",
|
||||
_ => "internal",
|
||||
};
|
||||
let fork_mode = match fork_mode {
|
||||
None => "none",
|
||||
Some(SpawnAgentForkMode::FullHistory) => "all",
|
||||
Some(SpawnAgentForkMode::LastNTurns(_)) => "last_n",
|
||||
};
|
||||
let multi_agent_version = match multi_agent_version {
|
||||
MultiAgentVersion::Disabled => "disabled",
|
||||
MultiAgentVersion::V1 => "v1",
|
||||
MultiAgentVersion::V2 => "v2",
|
||||
};
|
||||
telemetry
|
||||
.clone()
|
||||
.with_product_sku(product_sku)
|
||||
.record_multi_agent_spawn_failure(reason, fork_mode, multi_agent_version);
|
||||
}
|
||||
|
||||
pub(crate) fn collab_agent_error(agent_id: ThreadId, err: CodexErr) -> FunctionCallError {
|
||||
match err.details() {
|
||||
CodexErrorDetails::ThreadNotFound(id) => {
|
||||
|
||||
@@ -36,6 +36,9 @@ use codex_login::CodexAuth;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
use codex_models_manager::manager::StaticModelsManager;
|
||||
use codex_otel::MULTI_AGENT_SPAWN_FAILURE_METRIC;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
@@ -73,9 +76,13 @@ use codex_protocol::protocol::TurnCompleteEvent;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use codex_state::DirectionalThreadSpawnEdgeStatus;
|
||||
use core_test_support::TempDirExt;
|
||||
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -294,6 +301,74 @@ async fn spawn_agent_rejects_when_message_and_items_are_both_set() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_agent_limit_failure_emits_bounded_metric() {
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory(
|
||||
"test",
|
||||
"codex-core",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
InMemoryMetricExporter::default(),
|
||||
)
|
||||
.with_runtime_reader(),
|
||||
)
|
||||
.expect("create in-memory metrics client");
|
||||
let (mut session, mut turn) = make_session_and_context().await;
|
||||
turn.session_telemetry = turn.session_telemetry.clone().with_metrics(metrics.clone());
|
||||
let mut config = (*turn.config).clone();
|
||||
config.agent_max_threads = Some(0);
|
||||
config.apps_mcp_product_sku = Some("codex".to_string());
|
||||
turn.config = Arc::new(config);
|
||||
let manager = thread_manager();
|
||||
set_agent_control(&mut session, manager.agent_control());
|
||||
|
||||
let Err(err) = SpawnAgentHandler::default()
|
||||
.handle(invocation(
|
||||
Arc::new(session),
|
||||
Arc::new(turn),
|
||||
"spawn_agent",
|
||||
function_payload(json!({"message": "inspect this repo"})),
|
||||
))
|
||||
.await
|
||||
else {
|
||||
panic!("spawn_agent should respect the thread limit");
|
||||
};
|
||||
assert_eq!(
|
||||
err,
|
||||
FunctionCallError::RespondToModel(
|
||||
"collab spawn failed: agent thread limit reached".to_string()
|
||||
)
|
||||
);
|
||||
|
||||
let snapshot = metrics.snapshot().expect("snapshot spawn metrics");
|
||||
let failure_metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
.find(|metric| metric.name() == MULTI_AGENT_SPAWN_FAILURE_METRIC)
|
||||
.expect("spawn failure metric");
|
||||
let AggregatedMetrics::U64(MetricData::Sum(sum)) = failure_metric.data() else {
|
||||
panic!("expected spawn failure counter");
|
||||
};
|
||||
let points = sum.data_points().collect::<Vec<_>>();
|
||||
assert_eq!(points.len(), 1);
|
||||
assert_eq!(points[0].value(), 1);
|
||||
assert_eq!(
|
||||
points[0]
|
||||
.attributes()
|
||||
.map(|attribute| (
|
||||
attribute.key.as_str().to_string(),
|
||||
attribute.value.as_str().to_string(),
|
||||
))
|
||||
.collect::<BTreeMap<_, _>>(),
|
||||
BTreeMap::from([
|
||||
("fork_mode".to_string(), "none".to_string()),
|
||||
("multi_agent_version".to_string(), "v1".to_string()),
|
||||
("product_sku".to_string(), "codex".to_string()),
|
||||
("reason".to_string(), "limit_reached".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_agent_uses_explorer_role_and_preserves_approval_policy() {
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
||||
@@ -194,7 +194,7 @@ async fn handle_spawn_agent(
|
||||
source: spawn_source,
|
||||
options: SpawnAgentOptions {
|
||||
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
|
||||
fork_mode,
|
||||
fork_mode: fork_mode.clone(),
|
||||
parent_thread_id: Some(session.thread_id),
|
||||
parent_turn_id: Some(turn.sub_id.clone()),
|
||||
root_turn_id: turn.turn_metadata_state.root_turn_id(),
|
||||
@@ -205,7 +205,16 @@ async fn handle_spawn_agent(
|
||||
},
|
||||
})
|
||||
.await
|
||||
.map_err(collab_spawn_error)?;
|
||||
.map_err(|err| {
|
||||
record_collab_spawn_failure(
|
||||
&turn.session_telemetry,
|
||||
turn.config.apps_mcp_product_sku.as_deref(),
|
||||
&err,
|
||||
fork_mode.as_ref(),
|
||||
MultiAgentVersion::V2,
|
||||
);
|
||||
collab_spawn_error(err)
|
||||
})?;
|
||||
let new_thread_id = spawned_agent.thread_id;
|
||||
let agent_status = spawned_agent.status;
|
||||
let nickname = agent_snapshot
|
||||
|
||||
Reference in New Issue
Block a user