Add OpenTelemetry for subagent lifecycles (#62567)

## Why

Correlating a subagent's creation, turn attempts, and stop requests
helps explain what happened when those actions span workers.

## What changed

- Emit structured events and counters for successful spawns and accepted
  `close_agent` and `interrupt_agent` calls. Count accepted stops even
  when the target is already idle or unloaded.
- Track initial, follow-up, and resumed turn attempts for spawned
  subagents. Record each start and at most one outcome per attempt:
  completed, failed, interrupted, or suspended.
- Use thread, turn, and call IDs to correlate structured events while
  keeping those IDs out of metric labels.

## Testing

Add coverage for lifecycle counts, duplicate outcomes, stop handling,
and event correlation across workers. Improve the Windows elevated
sandbox test for an approved `git pull` by provisioning the sandbox
before the turn and reporting setup or launch failures with diagnostics.

GitOrigin-RevId: bc1190302e1dffbdd79c7ac984b6debe1dac4a65
This commit is contained in:
Bryan Ashley
2026-11-19 18:39:32 +00:00
committed by copyberry
parent 617ad20df0
commit 65454c7b99
18 changed files with 779 additions and 35 deletions
@@ -1,5 +1,6 @@
use super::*;
use crate::tools::handlers::multi_agents_spec::create_close_agent_tool_v1;
use codex_otel::SubagentStopAction;
use codex_tools::ToolSpec;
pub(crate) struct Handler;
@@ -68,10 +69,24 @@ async fn handle_close_agent(
let previous_status = local_agent_control.get_status(agent_id).await;
let result = local_agent_control.close_agent(agent_id).await;
let (status, receiver_agent) = match &result {
Ok(snapshot) => (
snapshot.status().cloned().unwrap_or(AgentStatus::NotFound),
snapshot.metadata().clone(),
),
Ok(snapshot) => {
// Legacy close can also address unrelated loaded threads.
if snapshot.metadata().agent_id.is_some()
&& agent_id != ThreadId::from(session.session_id())
{
turn.session_telemetry.record_multi_agent_stop_accepted(
session.session_id(),
agent_id,
&call_id,
SubagentStopAction::Close,
snapshot.status(),
);
}
(
snapshot.status().cloned().unwrap_or(AgentStatus::NotFound),
snapshot.metadata().clone(),
)
}
Err(_) => (previous_status, receiver_agent),
};
session
@@ -161,7 +161,14 @@ async fn handle_spawn_agent(
collab_spawn_error(err)
});
let (new_thread_id, status) = match &result {
Ok((spawned_agent, _)) => (Some(spawned_agent.thread_id), spawned_agent.status.clone()),
Ok((spawned_agent, _)) => {
turn.session_telemetry.record_multi_agent_spawned(
session.session_id(),
&turn.sub_id,
spawned_agent.thread_id,
);
(Some(spawned_agent.thread_id), spawned_agent.status.clone())
}
Err(_) => (None, AgentStatus::NotFound),
};
let agent_snapshot = result.as_ref().ok().map(|(_, config)| config);
@@ -3841,23 +3841,29 @@ async fn multi_agent_v2_wait_agent_does_not_return_completed_content() {
#[tokio::test]
async fn multi_agent_v2_interrupt_agent_accepts_task_name_target() {
let (mut session, mut turn) = make_session_and_context().await;
let (_, turn) = make_session_and_context().await;
let mut config = (*turn.config).clone();
config.features.enable(Feature::MultiAgentV2).unwrap();
config.apps_mcp_product_sku = Some("codex".into());
let manager = thread_manager();
let root = manager
.start_thread(StartThreadOptions::new((*turn.config).clone()))
.start_thread(StartThreadOptions::new(config))
.await
.expect("root thread should start");
set_agent_control(&mut session, manager.agent_control());
session.thread_id = root.thread_id;
let mut config = (*turn.config).clone();
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
set_turn_config(&mut turn, config);
let session = Arc::new(session);
let turn = Arc::new(turn);
let session = root.thread.session.clone();
let metrics = MetricsClient::new(
MetricsConfig::in_memory("test", "core", "1", Default::default()).with_runtime_reader(),
)
.unwrap();
let attach_metrics = |mut turn: Arc<TurnContext>| {
let context = Arc::get_mut(&mut turn).unwrap();
context.session_telemetry = context
.session_telemetry
.clone()
.with_metrics(metrics.clone());
turn
};
let turn = attach_metrics(session.new_default_turn().await);
SpawnAgentHandlerV2::default()
.handle(invocation(
session.clone(),
@@ -3882,10 +3888,11 @@ async fn multi_agent_v2_interrupt_agent_accepts_task_name_target() {
.await
.expect("worker thread should be resident");
let worker_session = worker_thread.session.clone();
let worker_turn = attach_metrics(worker_session.new_default_turn().await);
SpawnAgentHandlerV2::default()
.handle(invocation(
worker_session.clone(),
worker_session.new_default_turn().await,
worker_turn.clone(),
"spawn_agent",
function_payload(json!({
"message": "inspect a child task",
@@ -3944,6 +3951,82 @@ async fn multi_agent_v2_interrupt_agent_accepts_task_name_target() {
!ops.iter()
.any(|(thread_id, op)| *thread_id == child_id && matches!(op, Op::InterruptAgent))
);
InterruptAgentHandler
.handle(invocation(
worker_session,
worker_turn,
"interrupt_agent",
function_payload(json!({"target": child_id.to_string()})),
))
.await
.unwrap();
assert!(
InterruptAgentHandler
.handle(invocation(
session.clone(),
turn.clone(),
"interrupt_agent",
function_payload(json!({"target": "/root"}))
))
.await
.is_err()
);
CloseAgentHandler
.handle(invocation(
session,
turn,
"close_agent",
function_payload(json!({"target": child_id.to_string()})),
))
.await
.unwrap();
let snapshot = metrics.snapshot().unwrap();
let observations = snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics);
let mut counts = BTreeMap::new();
for metric in observations.filter(|m| {
matches!(
m.name(),
codex_otel::MULTI_AGENT_SPAWNED_METRIC | codex_otel::MULTI_AGENT_STOP_ACCEPTED_METRIC
)
}) {
let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else {
panic!("subagent lifecycle metric should be a counter");
};
for point in sum.data_points() {
let label = |key| {
point
.attributes()
.find(|a| a.key.as_str() == key)
.map(|a| a.value.as_str().into_owned())
.unwrap_or_default()
};
assert_eq!(label("product_sku"), "codex");
*counts
.entry((metric.name().to_string(), label("caller"), label("action")))
.or_insert(0) += point.value();
}
}
let stop = codex_otel::MULTI_AGENT_STOP_ACCEPTED_METRIC;
assert_eq!(
counts,
BTreeMap::from([
(
(
codex_otel::MULTI_AGENT_SPAWNED_METRIC.into(),
String::new(),
String::new()
),
2
),
((stop.into(), "root".into(), "interrupt".into()), 1),
((stop.into(), "root".into(), "close".into()), 1),
((stop.into(), "subagent".into(), "interrupt".into()), 1),
])
);
}
#[tokio::test]
@@ -2,6 +2,7 @@ use super::analytics::ToolCallAnalytics;
use super::*;
use crate::agent::api::AgentTarget;
use crate::tools::handlers::multi_agents_spec::create_interrupt_agent_tool_v2;
use codex_otel::SubagentStopAction;
use codex_protocol::protocol::MultiAgentVersion;
use codex_tools::ToolSpec;
@@ -58,6 +59,13 @@ async fn handle_interrupt_agent(
let agent_path = snapshot.metadata().agent_path.clone().ok_or_else(|| {
FunctionCallError::RespondToModel("target agent is missing an agent_path".to_string())
})?;
turn.session_telemetry.record_multi_agent_stop_accepted(
session.session_id(),
agent_id,
&call_id,
SubagentStopAction::Interrupt,
snapshot.status(),
);
let previous_status = snapshot.status().cloned().unwrap_or(AgentStatus::NotFound);
emit_sub_agent_activity(
&session,