Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Add bounded diagnostics for agent spawn failures (#51355)

jifc0c230e6730b
diff --git a/codex-rs/core/src/agent/control/execution.rs b/codex-rs/core/src/agent/control/execution.rs
index 084f7c0054..adae03b8ec 100644
--- a/codex-rs/core/src/agent/control/execution.rs
+++ b/codex-rs/core/src/agent/control/execution.rs
@@ -3,6 +3,7 @@
use super::LocalAgentControl;
use crate::agent::types::AgentExecutionGuard;
+use codex_protocol::error::AgentErrorContext;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::Result as CodexResult;
@@ -42,9 +43,10 @@ impl LocalAgentControl {
if self.runtime.agent_execution_limiter.has_capacity() {
Ok(())
} else {
- Err(CodexErr::new(CodexErrorDetails::AgentLimitReached {
- max_threads,
- }))
+ Err(
+ CodexErr::new(CodexErrorDetails::AgentLimitReached { max_threads })
+ .with_agent_context(AgentErrorContext::ExecutionCapacity),
+ )
}
}
diff --git a/codex-rs/core/src/agent/control/residency.rs b/codex-rs/core/src/agent/control/residency.rs
index b53f48b2ca..7f2ad89af8 100644
--- a/codex-rs/core/src/agent/control/residency.rs
+++ b/codex-rs/core/src/agent/control/residency.rs
@@ -6,6 +6,7 @@ use crate::codex_thread::CodexThread;
use crate::config::Config;
use crate::thread_manager::ThreadManagerState;
use codex_protocol::ThreadId;
+use codex_protocol::error::AgentErrorContext;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::Result as CodexResult;
@@ -119,7 +120,8 @@ impl V2Residency {
{
return Err(CodexErr::new(CodexErrorDetails::AgentLimitReached {
max_threads: capacity,
- }));
+ })
+ .with_agent_context(AgentErrorContext::ResidencyCapacity));
}
}
}
diff --git a/codex-rs/core/src/agent/control/runtime.rs b/codex-rs/core/src/agent/control/runtime.rs
index 5fdf62560f..2ebc34a5f2 100644
--- a/codex-rs/core/src/agent/control/runtime.rs
+++ b/codex-rs/core/src/agent/control/runtime.rs
@@ -14,6 +14,7 @@ use arc_swap::ArcSwapOption;
use codex_extension_api::ThreadInstructionsProvider;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
+use codex_protocol::error::AgentErrorContext;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use std::sync::Arc;
@@ -185,9 +186,10 @@ impl AgentControlInit {
impl LocalAgentRuntime {
pub(crate) fn admit_start(&self) -> CodexResult<AgentTreeMembership> {
if self.shutdown_state.members.is_closed() {
- return Err(CodexErr::InvalidRequest(
- "agent runtime is shutting down".to_owned(),
- ));
+ return Err(
+ CodexErr::InvalidRequest("agent runtime is shutting down".to_owned())
+ .with_agent_context(AgentErrorContext::RuntimeShutdown),
+ );
}
let membership = AgentTreeMembership {
state: Arc::clone(&self.shutdown_state),
@@ -196,9 +198,10 @@ impl LocalAgentRuntime {
// Closing a TaskTracker does not reject new tokens. Recheck so a start racing with
// shutdown is either admitted before the fence or rejected after it.
if self.shutdown_state.members.is_closed() {
- return Err(CodexErr::InvalidRequest(
- "agent runtime is shutting down".to_owned(),
- ));
+ return Err(
+ CodexErr::InvalidRequest("agent runtime is shutting down".to_owned())
+ .with_agent_context(AgentErrorContext::RuntimeShutdown),
+ );
}
Ok(membership)
}
diff --git a/codex-rs/core/src/agent/control/runtime_context.rs b/codex-rs/core/src/agent/control/runtime_context.rs
index 2034d03fbd..d4f8f9b86e 100644
--- a/codex-rs/core/src/agent/control/runtime_context.rs
+++ b/codex-rs/core/src/agent/control/runtime_context.rs
@@ -6,6 +6,7 @@ use crate::agent::types::AgentMetadata;
use crate::session_prefix::format_subagent_context_line;
use crate::thread_manager::ThreadManagerState;
use codex_protocol::ThreadId;
+use codex_protocol::error::AgentErrorContext;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use std::collections::HashMap;
@@ -130,8 +131,9 @@ impl LocalAgentRuntime {
}
pub(super) fn upgrade(&self) -> CodexResult<Arc<ThreadManagerState>> {
- self.manager
- .upgrade()
- .ok_or_else(|| CodexErr::UnsupportedOperation("thread manager dropped".to_string()))
+ self.manager.upgrade().ok_or_else(|| {
+ CodexErr::UnsupportedOperation("thread manager dropped".to_string())
+ .with_agent_context(AgentErrorContext::ManagerUnavailable)
+ })
}
}
diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs
index deef223bfc..901a8f153e 100644
--- a/codex-rs/core/src/agent/control/spawn.rs
+++ b/codex-rs/core/src/agent/control/spawn.rs
@@ -27,6 +27,7 @@ use codex_extension_api::ExtensionDataInit;
use codex_features::Feature;
use codex_history::ResponseItemEnvelope;
use codex_prompts::ResolvedModelMessages;
+use codex_protocol::error::AgentErrorContext;
use codex_protocol::intersect_effective_permission_profiles;
use codex_protocol::protocol::EnvironmentConfigState;
use codex_thread_store::PersistContext;
@@ -764,17 +765,16 @@ impl LocalAgentControl {
fork_context,
child_create,
} = match (session_source, options.fork_mode.as_ref(), inheritance) {
- (Some(session_source), Some(_), inheritance) => {
- Box::pin(self.spawn_forked_thread(
- &state,
- config,
- session_source,
- &options,
- inheritance,
- multi_agent_version,
- ))
- .await?
- }
+ (Some(session_source), Some(_), inheritance) => Box::pin(self.spawn_forked_thread(
+ &state,
+ config,
+ session_source,
+ &options,
+ inheritance,
+ multi_agent_version,
+ ))
+ .await
+ .map_err(|err| err.with_agent_context(AgentErrorContext::ForkHistory))?,
(Some(session_source), None, inheritance) => {
let (history_mode, dynamic_tools) = if let Some(parent_thread_id) =
options.parent_thread_id
@@ -815,7 +815,8 @@ impl LocalAgentControl {
inheritance.exec_policy,
environments,
))
- .await?;
+ .await
+ .map_err(|err| err.with_agent_context(AgentErrorContext::ChildStartup))?;
SpawnedThreadResult {
new_thread,
fork_context: None,
@@ -824,8 +825,9 @@ impl LocalAgentControl {
}
(None, _, _) => {
let child_create_started_at = Instant::now();
- let new_thread =
- Box::pin(state.spawn_new_thread(config.clone(), self.clone())).await?;
+ let new_thread = Box::pin(state.spawn_new_thread(config.clone(), self.clone()))
+ .await
+ .map_err(|err| err.with_agent_context(AgentErrorContext::ChildStartup))?;
SpawnedThreadResult {
new_thread,
fork_context: None,
@@ -909,7 +911,8 @@ impl LocalAgentControl {
match initial_input {
SpawnInitialInput::UserInput(input) => {
self.send_input(new_thread.thread_id, input, start_options)
- .await?;
+ .await
+ .map_err(|err| err.with_agent_context(AgentErrorContext::InputAdmission))?;
}
SpawnInitialInput::InterAgentCommunication(communication, context) => {
self.send_inter_agent_communication_after_capacity_check(
@@ -919,7 +922,8 @@ impl LocalAgentControl {
context,
start_options,
)
- .await?;
+ .await
+ .map_err(|err| err.with_agent_context(AgentErrorContext::InputAdmission))?;
}
}
let input_admission = input_admission_started_at.elapsed();
@@ -1295,7 +1299,8 @@ impl LocalAgentControl {
/*environments*/ None,
thread_extension_init,
)
- .await?;
+ .await
+ .map_err(|err| err.with_agent_context(AgentErrorContext::ChildStartup))?;
let child_create = child_create_started_at.elapsed();
Ok(SpawnedThreadResult {
new_thread,
diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs
index a0a1df5458..7bb29d8e00 100644
--- a/codex-rs/core/src/agent/control_tests.rs
+++ b/codex-rs/core/src/agent/control_tests.rs
@@ -50,6 +50,8 @@ use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::Settings;
+use codex_protocol::error::AgentErrorContext;
+use codex_protocol::error::CodexErrKind;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::items::TurnItem;
use codex_protocol::items::UserMessageItem;
@@ -94,7 +96,10 @@ use codex_thread_store::ThreadStore;
use codex_utils_path_uri::PathUri;
use core_test_support::responses::strip_response_item_ids;
use pretty_assertions::assert_eq;
+use std::future::Future;
use std::sync::RwLock;
+use std::task::Context;
+use std::task::Waker;
use tempfile::TempDir;
use tokio::time::Duration;
use tokio::time::sleep;
@@ -629,6 +634,165 @@ async fn on_event_updates_status_from_shutdown_complete() {
assert_eq!(status, Some(AgentStatus::Shutdown));
}
+#[tokio::test]
+async fn spawn_failure_context_distinguishes_execution_and_residency_capacity() {
+ let mut harness = AgentControlHarness::new().await;
+ harness
+ .config
+ .multi_agent_v2
+ .max_concurrent_threads_per_session = 2;
+ harness
+ .control
+ .runtime
+ .agent_execution_limiter
+ .initialize(/*max_threads*/ 1);
+ let source = SessionSource::SubAgent(SubAgentSource::Other("worker".to_string()));
+ let running = harness
+ .control
+ .execution_guard(MultiAgentVersion::V2, &source);
+ let execution_error = harness
+ .control
+ .ensure_execution_capacity(MultiAgentVersion::V2, &source)
+ .expect_err("running turn fills execution capacity");
+ drop(running);
+ harness
+ .control
+ .ensure_execution_capacity(MultiAgentVersion::V2, &source)
+ .expect("execution capacity released");
+
+ let state = harness.control.runtime.upgrade().unwrap();
+ let membership = harness.control.runtime.admit_start().unwrap();
+ let _resident = harness
+ .control
+ .reserve_v2_residency_slot(
+ &state,
+ &harness.config,
+ &membership,
+ /*protected_thread_id*/ None,
+ )
+ .await
+ .expect("first pending resident fits");
+ let residency_error = match harness
+ .control
+ .reserve_v2_residency_slot(
+ &state,
+ &harness.config,
+ &membership,
+ /*protected_thread_id*/ None,
+ )
+ .await
+ {
+ Ok(_) => panic!("pending resident fills residency capacity"),
+ Err(err) => err,
+ };
+ assert_eq!(
+ [execution_error, residency_error].map(|err| (
+ err.agent_context(),
+ CodexErrKind::from(&err),
+ err.to_string(),
+ )),
+ [
+ (
+ Some(AgentErrorContext::ExecutionCapacity),
+ CodexErrKind::AgentLimitReached,
+ "agent thread limit reached".to_string()
+ ),
+ (
+ Some(AgentErrorContext::ResidencyCapacity),
+ CodexErrKind::AgentLimitReached,
+ "agent thread limit reached".to_string()
+ ),
+ ],
+ );
+}
+
+#[tokio::test]
+async fn spawn_failure_context_survives_manager_and_fork_errors() {
+ let harness = AgentControlHarness::new().await;
+ let manager_error = LocalAgentControl::default()
+ .spawn_agent(
+ harness.config.clone(),
+ text_input("hello"),
+ /*session_source*/ None,
+ )
+ .await
+ .expect_err("missing manager");
+ let fork_error = harness
+ .control
+ .spawn_agent_internal(
+ harness.config.clone(),
+ spawn::SpawnInitialInput::UserInput(text_input("hello")),
+ Some(SessionSource::SubAgent(SubAgentSource::Other(
+ "worker".to_string(),
+ ))),
+ SpawnAgentOptions {
+ fork_mode: Some(SpawnAgentForkMode::FullHistory),
+ ..Default::default()
+ },
+ )
+ .await
+ .expect_err("fork requires a parent spawn call id");
+ assert_eq!(
+ [manager_error, fork_error].map(|err| (err.agent_context(), CodexErrKind::from(&err))),
+ [
+ (
+ Some(AgentErrorContext::ManagerUnavailable),
+ CodexErrKind::UnsupportedOperation
+ ),
+ (Some(AgentErrorContext::ForkHistory), CodexErrKind::Fatal),
+ ],
+ );
+}
+
+#[tokio::test]
+async fn spawn_failure_context_preserves_shutdown_during_child_startup() {
+ let harness = AgentControlHarness::new().await;
+ let state = harness.control.runtime.upgrade().expect("live manager");
+ let spawn = harness.control.spawn_agent(
+ harness.config.clone(),
+ text_input("hello"),
+ Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
+ parent_thread_id: ThreadId::new(),
+ depth: 1,
+ agent_path: None,
+ agent_nickname: None,
+ agent_role: None,
+ })),
+ );
+ tokio::pin!(spawn);
+ let shutdown = {
+ // Block parent lookup after outer admission. Poll synchronously so the guard
+ // never crosses an await, including the one hidden inside futures::poll!.
+ let _threads = state.threads.write().await;
+ assert!(
+ spawn
+ .as_mut()
+ .poll(&mut Context::from_waker(Waker::noop()))
+ .is_pending()
+ );
+ harness.control.runtime.request_shutdown()
+ };
+ let error = spawn
+ .await
+ .expect_err("child admission must reject shutdown");
+ assert_eq!(
+ (
+ error.agent_context(),
+ CodexErrKind::from(&error),
+ error.to_string(),
+ ),
+ (
+ Some(AgentErrorContext::RuntimeShutdown),
+ CodexErrKind::InvalidRequest,
+ "agent runtime is shutting down".to_string(),
+ ),
+ );
+ shutdown
+ .wait()
+ .await
+ .expect("spawn releases its membership");
+}
+
#[tokio::test]
async fn spawn_agent_errors_when_manager_dropped() {
let control = LocalAgentControl::default();
diff --git a/codex-rs/core/src/agent/registry.rs b/codex-rs/core/src/agent/registry.rs
index d7fae371d5..7c21422c26 100644
--- a/codex-rs/core/src/agent/registry.rs
+++ b/codex-rs/core/src/agent/registry.rs
@@ -1,6 +1,7 @@
use crate::agent::types::AgentMetadata;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
+use codex_protocol::error::AgentErrorContext;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::Result;
@@ -92,9 +93,10 @@ impl AgentRegistry {
) -> Result<SpawnReservation> {
if let Some(max_threads) = max_threads {
if !self.try_increment_spawned(max_threads) {
- return Err(CodexErr::new(CodexErrorDetails::AgentLimitReached {
- max_threads,
- }));
+ return Err(
+ CodexErr::new(CodexErrorDetails::AgentLimitReached { max_threads })
+ .with_agent_context(AgentErrorContext::RegistryCapacity),
+ );
}
} else {
self.total_count.fetch_add(1, Ordering::AcqRel);
@@ -302,7 +304,8 @@ impl AgentRegistry {
match active_agents.agent_tree.entry(agent_path.to_string()) {
Entry::Occupied(_) => Err(CodexErr::UnsupportedOperation(format!(
"agent path `{agent_path}` already exists"
- ))),
+ ))
+ .with_agent_context(AgentErrorContext::DuplicatePath)),
Entry::Vacant(entry) => {
entry.insert(AgentMetadata {
agent_path: Some(agent_path.clone()),
@@ -364,6 +367,7 @@ impl SpawnReservation {
.reserve_agent_nickname(names, preferred)
.ok_or_else(|| {
CodexErr::UnsupportedOperation("no available agent nicknames".to_string())
+ .with_agent_context(AgentErrorContext::NicknameUnavailable)
})?;
self.reserved_agent_nickname = Some(agent_nickname.clone());
Ok(agent_nickname)
diff --git a/codex-rs/core/src/agent/registry_tests.rs b/codex-rs/core/src/agent/registry_tests.rs
index 24d204ee56..523c35951d 100644
--- a/codex-rs/core/src/agent/registry_tests.rs
+++ b/codex-rs/core/src/agent/registry_tests.rs
@@ -1,5 +1,6 @@
use super::*;
use codex_protocol::AgentPath;
+use codex_protocol::error::AgentErrorContext;
use codex_protocol::error::CodexErrorDetails;
use pretty_assertions::assert_eq;
use std::collections::HashSet;
@@ -571,3 +572,29 @@ fn thread_identity_can_move_between_agent_paths() {
.expect("releasing the migrated agent should free its spawn slot");
drop(reservation);
}
+
+#[test]
+fn spawn_failure_context_distinguishes_registry_rejections() {
+ let registry = Arc::new(AgentRegistry::default());
+ let mut reservation = registry.reserve_spawn_slot(Some(1)).expect("first slot");
+ let capacity_error = match registry.reserve_spawn_slot(Some(1)) {
+ Ok(_) => panic!("registry limit should be enforced"),
+ Err(err) => err,
+ };
+ let path = agent_path("/root/worker");
+ reservation.reserve_agent_path(&path).expect("first path");
+ let duplicate_error = reservation
+ .reserve_agent_path(&path)
+ .expect_err("duplicate path");
+ let nickname_error = reservation
+ .reserve_agent_nickname_with_preference(&[], /*preferred*/ None)
+ .expect_err("empty nickname pool");
+ assert_eq!(
+ [capacity_error, duplicate_error, nickname_error].map(|err| err.agent_context()),
+ [
+ Some(AgentErrorContext::RegistryCapacity),
+ Some(AgentErrorContext::DuplicatePath),
+ Some(AgentErrorContext::NicknameUnavailable),
+ ],
+ );
+}
diff --git a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs
index 5a7bd67b87..94079e0eba 100644
--- a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs
+++ b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs
@@ -142,6 +142,8 @@ async fn handle_spawn_agent(
&turn.session_telemetry,
turn.config.apps_mcp_product_sku.as_deref(),
&err,
+ &call_id,
+ &turn.sub_id,
fork_mode.as_ref(),
MultiAgentVersion::V1,
);
diff --git a/codex-rs/core/src/tools/handlers/multi_agents_common.rs b/codex-rs/core/src/tools/handlers/multi_agents_common.rs
index 2146fdf84c..7521750ba4 100644
--- a/codex-rs/core/src/tools/handlers/multi_agents_common.rs
+++ b/codex-rs/core/src/tools/handlers/multi_agents_common.rs
@@ -79,6 +79,8 @@ pub(crate) fn record_collab_spawn_failure(
telemetry: &SessionTelemetry,
product_sku: Option<&str>,
err: &CodexErr,
+ call_id: &str,
+ turn_id: &str,
fork_mode: Option<&SpawnAgentForkMode>,
multi_agent_version: MultiAgentVersion,
) {
@@ -101,7 +103,14 @@ pub(crate) fn record_collab_spawn_failure(
telemetry
.clone()
.with_product_sku(product_sku)
- .record_multi_agent_spawn_failure(reason, fork_mode, multi_agent_version);
+ .record_multi_agent_spawn_failure(
+ reason,
+ err,
+ call_id,
+ turn_id,
+ fork_mode,
+ multi_agent_version,
+ );
}
pub(crate) fn collab_agent_error(agent_id: ThreadId, err: CodexErr) -> FunctionCallError {
diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs
index 31cd68a9f2..bd75eafc9f 100644
--- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs
+++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs
@@ -361,6 +361,8 @@ async fn spawn_agent_limit_failure_emits_bounded_metric() {
))
.collect::<BTreeMap<_, _>>(),
BTreeMap::from([
+ ("detail".to_string(), "registry_capacity".to_string()),
+ ("error_kind".to_string(), "agent_limit_reached".to_string()),
("fork_mode".to_string(), "none".to_string()),
("multi_agent_version".to_string(), "v1".to_string()),
("product_sku".to_string(), "codex".to_string()),
diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs
index 3267d42aef..218fbdc254 100644
--- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs
+++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs
@@ -211,6 +211,8 @@ async fn handle_spawn_agent(
&turn.session_telemetry,
turn.config.apps_mcp_product_sku.as_deref(),
&err,
+ &call_id,
+ &turn.sub_id,
fork_mode.as_ref(),
MultiAgentVersion::V2,
);
diff --git a/codex-rs/otel/src/events/session_telemetry.rs b/codex-rs/otel/src/events/session_telemetry.rs
index c5fb87bf5f..53dbe31737 100644
--- a/codex-rs/otel/src/events/session_telemetry.rs
+++ b/codex-rs/otel/src/events/session_telemetry.rs
@@ -45,6 +45,8 @@ use codex_protocol::ThreadId;
use codex_protocol::ToolName;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::ToolResultLogConfig;
+use codex_protocol::error::CodexErr;
+use codex_protocol::error::CodexErrKind;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AskForApproval;
@@ -291,14 +293,34 @@ impl SessionTelemetry {
pub fn record_multi_agent_spawn_failure(
&self,
reason: &'static str,
+ err: &CodexErr,
+ call_id: &str,
+ turn_id: &str,
fork_mode: &'static str,
multi_agent_version: &'static str,
) {
+ let detail = err.agent_context().map_or("unknown", <&str>::from);
+ let error_kind: &'static str = CodexErrKind::from(err).into();
+ // Only bounded classifications and correlation IDs belong in trace-safe diagnostics.
+ trace_event!(
+ self,
+ event.name = MULTI_AGENT_SPAWN_FAILURE_METRIC,
+ reason,
+ detail,
+ error_kind,
+ call_id,
+ turn_id,
+ fork_mode,
+ multi_agent_version,
+ product_sku = self.metadata.product_sku,
+ );
let Some(metrics) = &self.metrics else {
return;
};
let mut tags = self.multi_agent_spawn_tags(fork_mode, multi_agent_version);
tags.push(("reason", reason));
+ tags.push(("detail", detail));
+ tags.push(("error_kind", error_kind));
let _ = metrics.counter(MULTI_AGENT_SPAWN_FAILURE_METRIC, /*inc*/ 1, &tags);
}
diff --git a/codex-rs/otel/tests/suite/manager_metrics.rs b/codex-rs/otel/tests/suite/manager_metrics.rs
index e60d0c726b..653ed5be36 100644
--- a/codex-rs/otel/tests/suite/manager_metrics.rs
+++ b/codex-rs/otel/tests/suite/manager_metrics.rs
@@ -3,6 +3,7 @@ use crate::harness::build_metrics_with_defaults;
use crate::harness::find_metric;
use crate::harness::histogram_data;
use crate::harness::latest_metrics;
+use codex_otel::MULTI_AGENT_SPAWN_FAILURE_METRIC;
use codex_otel::PLUGIN_INSTALL_ELICITATION_SENT_METRIC;
use codex_otel::PLUGIN_INSTALL_SUGGESTION_METRIC;
use codex_otel::Result;
@@ -12,6 +13,8 @@ use codex_otel::TOOL_CALL_DURATION_METRIC;
use codex_otel::TelemetryAuthMode;
use codex_protocol::ThreadId;
use codex_protocol::ToolName;
+use codex_protocol::error::AgentErrorContext;
+use codex_protocol::error::CodexErr;
use codex_protocol::protocol::SessionSource;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
@@ -362,3 +365,63 @@ fn manager_records_plugin_install_elicitation_sent_metric() -> Result<()> {
Ok(())
}
+
+#[test]
+fn spawn_failure_metrics_preserve_reason_and_bound_diagnostic_labels() -> Result<()> {
+ let (metrics, exporter) = build_metrics_with_defaults(&[])?;
+ let telemetry = SessionTelemetry::new(
+ ThreadId::new(),
+ "gpt-5.1",
+ "gpt-5.1",
+ /*account_id*/ None,
+ /*account_email*/ None,
+ /*auth_mode*/ None,
+ "test_originator".to_string(),
+ /*log_user_prompts*/ false,
+ "tty".to_string(),
+ SessionSource::Cli,
+ )
+ .with_metrics_without_metadata_tags(metrics)
+ .with_product_sku(Some("codex"));
+ let mut expected = BTreeMap::new();
+ for (context, detail) in [
+ (Some(AgentErrorContext::ChildStartup), "child_startup"),
+ (None, "unknown"),
+ ] {
+ // Distinct messages and correlation IDs must aggregate into the same bounded series.
+ for id in ["private-first", "private-second"] {
+ let mut err = CodexErr::from(std::io::Error::other(id));
+ if let Some(context) = context {
+ err = err
+ .with_agent_context(context)
+ .with_agent_context(AgentErrorContext::ForkHistory);
+ }
+ telemetry.record_multi_agent_spawn_failure("internal", &err, id, id, "all", "v2");
+ }
+ expected.insert(
+ BTreeMap::from([
+ ("reason".to_string(), "internal".to_string()),
+ ("detail".to_string(), detail.to_string()),
+ ("error_kind".to_string(), "io".to_string()),
+ ("fork_mode".to_string(), "all".to_string()),
+ ("multi_agent_version".to_string(), "v2".to_string()),
+ ("product_sku".to_string(), "codex".to_string()),
+ ]),
+ 2,
+ );
+ }
+ telemetry.shutdown_metrics()?;
+ let resource_metrics = latest_metrics(&exporter);
+ let counter = find_metric(&resource_metrics, MULTI_AGENT_SPAWN_FAILURE_METRIC)
+ .expect("spawn failure counter");
+ let AggregatedMetrics::U64(MetricData::Sum(sum)) = counter.data() else {
+ panic!("expected spawn failure counter");
+ };
+ assert_eq!(
+ sum.data_points()
+ .map(|point| (attributes_to_map(point.attributes()), point.value()))
+ .collect::<BTreeMap<_, _>>(),
+ expected,
+ );
+ Ok(())
+}
diff --git a/codex-rs/protocol/src/agent_error.rs b/codex-rs/protocol/src/agent_error.rs
new file mode 100644
index 0000000000..1339ab8d15
--- /dev/null
+++ b/codex-rs/protocol/src/agent_error.rs
@@ -0,0 +1,32 @@
+//! Bounded agent failure diagnostics, separate from error behavior and user-visible messages.
+//! The first annotation wins so outer spawn stages preserve more precise failure origins.
+
+use super::CodexErr;
+
+/// A failure origin, or the spawn stage when no more precise origin is available.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum_macros::IntoStaticStr)]
+#[strum(serialize_all = "snake_case")]
+pub enum AgentErrorContext {
+ ExecutionCapacity,
+ ResidencyCapacity,
+ RegistryCapacity,
+ DuplicatePath,
+ NicknameUnavailable,
+ ManagerUnavailable,
+ RuntimeShutdown,
+ ForkHistory,
+ ChildStartup,
+ InputAdmission,
+}
+
+impl CodexErr {
+ /// Attach bounded diagnostics without replacing a more precise inner annotation.
+ pub fn with_agent_context(mut self, context: AgentErrorContext) -> Self {
+ self.agent_context.get_or_insert(context);
+ self
+ }
+
+ pub fn agent_context(&self) -> Option<AgentErrorContext> {
+ self.agent_context
+ }
+}
diff --git a/codex-rs/protocol/src/error.rs b/codex-rs/protocol/src/error.rs
index 4a89f709db..9e44430d6f 100644
--- a/codex-rs/protocol/src/error.rs
+++ b/codex-rs/protocol/src/error.rs
@@ -30,6 +30,10 @@ use strum_macros::EnumDiscriminants;
use thiserror::Error;
use tokio::task::JoinError;
+#[path = "agent_error.rs"]
+mod agent;
+pub use agent::AgentErrorContext;
+
pub type Result<T> = std::result::Result<T, CodexErr>;
/// Limit UI error messages to a reasonable size while keeping useful context.
@@ -73,12 +77,14 @@ pub enum SandboxErr {
pub struct CodexErr {
details: CodexErrorDetails,
retry_after: Option<RetryAfter>,
+ agent_context: Option<AgentErrorContext>,
}
/// The semantic category and diagnostic payload for a [`CodexErr`].
#[derive(Error, Debug, EnumDiscriminants)]
#[strum_discriminants(name(CodexErrKind))]
-#[strum_discriminants(derive(serde::Serialize))]
+#[strum_discriminants(derive(serde::Serialize, strum_macros::IntoStaticStr))]
+#[strum_discriminants(strum(serialize_all = "snake_case"))]
#[strum_discriminants(serde(rename_all = "snake_case"))]
#[strum_discriminants(doc = "The payload-free semantic category used for analytics.")]
pub enum CodexErrorDetails {
@@ -239,6 +245,7 @@ impl From<CodexErrorDetails> for CodexErr {
Self {
details,
retry_after: None,
+ agent_context: None,
}
}
}
@@ -303,6 +310,7 @@ macro_rules! codex_err_unit_constructors {
pub const $variant: Self = Self {
details: CodexErrorDetails::$variant,
retry_after: None,
+ agent_context: None,
};
)*
};