mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Add failure stages and OS error kinds to daemon startup metrics (#65049)
## Why The TUI's daemon auto-start metric reports a failure reason, but broad reasons such as `other` leave it unclear which startup step failed. ## What changed Add `failure_stage` and `os_error_kind` to failed `codex.daemon.start` attempts. For example, a missing executable reports `spawn` at `process_spawn` with `not_found`. The metric uses a fixed set of error categories and keeps raw OS codes and diagnostic text local. Report Windows detached-launch restrictions as `windows_detach_restricted`, matching the reason recorded when the TUI falls back to an embedded app server. ## Testing Cover missing executables, Windows launch restrictions, and preservation of the underlying I/O error. An in-memory metrics test checks that a failed attempt increments the counter once and maps an unknown OS code to `other`. GitOrigin-RevId: c5976517e1178fb8d65257362a893ad6254a2ddd
This commit is contained in:
@@ -262,7 +262,8 @@ impl PidBackend {
|
||||
})
|
||||
}
|
||||
.await;
|
||||
let record = match crate::diagnostics::result("process_identity", started, record) {
|
||||
let stage = "process_identity";
|
||||
let record = match crate::diagnostics::result(stage, started, record) {
|
||||
Ok(record) => record,
|
||||
Err(err) => {
|
||||
let exited = managed_app_server && matches!(child.try_wait(), Ok(Some(_)));
|
||||
@@ -276,17 +277,18 @@ impl PidBackend {
|
||||
let _ = fs::remove_file(&self.pid_file).await;
|
||||
}
|
||||
return if exited {
|
||||
Err(err).context(StartFailure::EarlyChildExit(context))
|
||||
Err(err).context(StartFailure::EarlyChildExit(stage, context))
|
||||
} else {
|
||||
Err(err).context(context)
|
||||
Err(err).context(StartFailure::Backend(stage, context))
|
||||
};
|
||||
}
|
||||
};
|
||||
let contents = serde_json::to_vec(&record).context("failed to serialize pid record")?;
|
||||
let temp_pid_file = self.pid_file.with_extension("pid.tmp");
|
||||
let started = std::time::Instant::now();
|
||||
let stage = "pid_write";
|
||||
if let Err(err) = crate::diagnostics::result(
|
||||
"pid_write",
|
||||
stage,
|
||||
started,
|
||||
fs::write(&temp_pid_file, &contents)
|
||||
.await
|
||||
@@ -297,12 +299,16 @@ impl PidBackend {
|
||||
let _ = fs::remove_file(&self.pid_file).await;
|
||||
}
|
||||
return Err(err).with_context(|| {
|
||||
format!("failed to write pid temp file {}", temp_pid_file.display())
|
||||
StartFailure::Backend(
|
||||
stage,
|
||||
format!("failed to write pid temp file {}", temp_pid_file.display()),
|
||||
)
|
||||
});
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let stage = "pid_publish";
|
||||
if let Err(err) = crate::diagnostics::result(
|
||||
"pid_publish",
|
||||
stage,
|
||||
started,
|
||||
fs::rename(&temp_pid_file, &self.pid_file)
|
||||
.await
|
||||
@@ -314,7 +320,10 @@ impl PidBackend {
|
||||
let _ = fs::remove_file(&self.pid_file).await;
|
||||
}
|
||||
return Err(err).with_context(|| {
|
||||
format!("failed to publish pid file {}", self.pid_file.display())
|
||||
StartFailure::Backend(
|
||||
stage,
|
||||
format!("failed to publish pid file {}", self.pid_file.display()),
|
||||
)
|
||||
});
|
||||
}
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -274,8 +274,12 @@ async fn start_retries_stale_empty_pid_file_under_its_own_lock() {
|
||||
.starts_with("failed to spawn detached app-server process using ")
|
||||
);
|
||||
assert_eq!(
|
||||
crate::telemetry::StartError::from(err).failure_reason(),
|
||||
"spawn"
|
||||
crate::telemetry::StartError::from(err).failure_tags(),
|
||||
[
|
||||
("failure_reason", "spawn"),
|
||||
("failure_stage", "process_spawn"),
|
||||
("os_error_kind", "not_found"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -153,12 +153,24 @@ fn detached_launch_preflight_rejects_restrictive_job() {
|
||||
err.is::<super::DetachedLaunchRestricted>(),
|
||||
"expected a classified job restriction: {err:#}"
|
||||
);
|
||||
assert_eq!(
|
||||
crate::telemetry::StartError::at("install")(err).failure_tags(),
|
||||
[
|
||||
("failure_reason", "windows_detach_restricted"),
|
||||
("failure_stage", "process_spawn"),
|
||||
("os_error_kind", "permission_denied"),
|
||||
]
|
||||
);
|
||||
// File access failures must still fail normally, even in a restricted
|
||||
// job: a CLI must not hide corrupt or inaccessible installations.
|
||||
let temp = tempfile::tempdir().expect("test directory");
|
||||
let err =
|
||||
super::ensure_detached_launch(temp.path()).expect_err("directory is not an executable");
|
||||
assert!(!err.is::<super::DetachedLaunchRestricted>(), "{err:#}");
|
||||
assert_eq!(
|
||||
crate::telemetry::StartError::at("install")(err).failure_reason(),
|
||||
"spawn"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let output = std::process::Command::new(executable)
|
||||
|
||||
@@ -15,6 +15,20 @@ fn failure_omits_error_messages_and_context() {
|
||||
os_code: None
|
||||
},
|
||||
);
|
||||
let error = error.context(crate::telemetry::StartFailure::Backend(
|
||||
"process_identity",
|
||||
"private pid".into(),
|
||||
));
|
||||
let failure = crate::telemetry::StartError::at("backend_start")(error);
|
||||
assert!(failure.error.is::<std::io::Error>());
|
||||
assert_eq!(
|
||||
failure.failure_tags(),
|
||||
[
|
||||
("failure_reason", "other"),
|
||||
("failure_stage", "process_identity"),
|
||||
("os_error_kind", "permission_denied"),
|
||||
]
|
||||
);
|
||||
let error = anyhow::anyhow!("secret child output");
|
||||
assert_eq!(
|
||||
Failure::from(&error),
|
||||
|
||||
@@ -23,14 +23,23 @@ pub async fn start_with_features(features: &BTreeMap<String, bool>) -> Result<Li
|
||||
pub async fn start_with_features_classified(
|
||||
features: &BTreeMap<String, bool>,
|
||||
) -> Result<LifecycleOutput, StartError> {
|
||||
ensure_supported_platform()?;
|
||||
ensure_supported_platform().map_err(StartError::at("preflight"))?;
|
||||
#[cfg(windows)]
|
||||
crate::backend::windows::ensure_not_elevated()?;
|
||||
let mut daemon = Daemon::from_environment()?;
|
||||
crate::backend::windows::ensure_not_elevated().map_err(StartError::at("preflight"))?;
|
||||
let mut daemon = Daemon::from_environment().map_err(StartError::at("environment"))?;
|
||||
daemon.log_diagnostics = true;
|
||||
let _operation_lock = daemon.acquire_operation_lock().await?;
|
||||
let selected = daemon.current_installation()?;
|
||||
let mut overrides = selected.load_settings().await?.feature_overrides;
|
||||
let _operation_lock = daemon
|
||||
.acquire_operation_lock()
|
||||
.await
|
||||
.map_err(StartError::at("operation_lock"))?;
|
||||
let selected = daemon
|
||||
.current_installation()
|
||||
.map_err(StartError::at("select_installation"))?;
|
||||
let mut overrides = selected
|
||||
.load_settings()
|
||||
.await
|
||||
.map_err(StartError::at("load_settings"))?
|
||||
.feature_overrides;
|
||||
overrides.extend(features.clone());
|
||||
Box::pin(selected.start(&overrides)).await
|
||||
}
|
||||
|
||||
@@ -456,16 +456,26 @@ impl Daemon {
|
||||
feature_overrides: &BTreeMap<String, bool>,
|
||||
) -> Result<LifecycleOutput, StartError> {
|
||||
let mut managed = self.clone();
|
||||
let mut settings = self.load_settings().await?;
|
||||
let mut settings = self
|
||||
.load_settings()
|
||||
.await
|
||||
.map_err(StartError::at("load_settings"))?;
|
||||
let (status, backend, pid, info) = if let Ok(info) = client::probe(&self.socket_path).await
|
||||
{
|
||||
(
|
||||
LifecycleStatus::AlreadyRunning,
|
||||
self.running_backend(&settings).await?,
|
||||
self.running_backend(&settings)
|
||||
.await
|
||||
.map_err(StartError::at("check_running"))?,
|
||||
None,
|
||||
info,
|
||||
)
|
||||
} else if self.running_backend_instance(&settings).await?.is_some() {
|
||||
} else if self
|
||||
.running_backend_instance(&settings)
|
||||
.await
|
||||
.map_err(StartError::at("check_running"))?
|
||||
.is_some()
|
||||
{
|
||||
(
|
||||
LifecycleStatus::AlreadyRunning,
|
||||
Some(BackendKind::Pid),
|
||||
@@ -481,20 +491,26 @@ impl Daemon {
|
||||
}
|
||||
prepare_install::prepare(self, &settings)
|
||||
.await
|
||||
.map_err(StartError::install)?;
|
||||
.map_err(StartError::at("install"))?;
|
||||
managed.managed_codex_bin = self
|
||||
.current_managed_codex_bin()
|
||||
.map_err(StartError::install)?;
|
||||
.map_err(StartError::at("install"))?;
|
||||
managed
|
||||
.ensure_managed_codex_bin()
|
||||
.map_err(StartError::install)?;
|
||||
.map_err(StartError::at("install"))?;
|
||||
// Only a fresh launch may replace these settings. Keep them for restarts
|
||||
// and updates, without changing the user's config or a running daemon.
|
||||
if settings.feature_overrides != *feature_overrides {
|
||||
settings.feature_overrides = feature_overrides.clone();
|
||||
settings.save(&self.settings_file).await?;
|
||||
settings
|
||||
.save(&self.settings_file)
|
||||
.await
|
||||
.map_err(StartError::at("save_settings"))?;
|
||||
}
|
||||
let pid = managed.start_managed_backend(&settings).await?;
|
||||
let pid = managed
|
||||
.start_managed_backend(&settings)
|
||||
.await
|
||||
.map_err(StartError::at("backend_start"))?;
|
||||
(
|
||||
LifecycleStatus::Started,
|
||||
Some(BackendKind::Pid),
|
||||
@@ -744,7 +760,7 @@ impl Daemon {
|
||||
};
|
||||
let context = self.app_server_not_ready_context().await;
|
||||
Err(err).context(if exited_before_ready {
|
||||
StartFailure::EarlyChildExit(context)
|
||||
StartFailure::EarlyChildExit("readiness", context)
|
||||
} else {
|
||||
StartFailure::ReadinessTimeout(context)
|
||||
})
|
||||
|
||||
@@ -1,35 +1,71 @@
|
||||
//! Bounded observations for foreground callers. This module never exports telemetry;
|
||||
//! in particular, the detached updater must not create a telemetry provider.
|
||||
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
|
||||
/// Shared reason for the failed daemon attempt and a confirmed embedded launch.
|
||||
pub const WINDOWS_DETACH_RESTRICTED: &str = "windows_detach_restricted";
|
||||
|
||||
/// Failure of a foreground auto-start, with the original diagnostic kept separate from the metric.
|
||||
#[derive(Debug)]
|
||||
pub struct StartError {
|
||||
pub error: anyhow::Error,
|
||||
during_install: bool,
|
||||
stage: &'static str,
|
||||
}
|
||||
|
||||
impl StartError {
|
||||
pub fn failure_reason(&self) -> &'static str {
|
||||
self.classification().0
|
||||
}
|
||||
|
||||
pub fn failure_tags(&self) -> [(&'static str, &'static str); 3] {
|
||||
let (reason, stage) = self.classification();
|
||||
// Only export known categories. OS codes and diagnostic text stay local.
|
||||
let kind = self.error.chain().find_map(|cause| {
|
||||
cause
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.map(std::io::Error::kind)
|
||||
});
|
||||
let os_error = match kind {
|
||||
Some(ErrorKind::PermissionDenied) => "permission_denied",
|
||||
Some(ErrorKind::NotFound) => "not_found",
|
||||
Some(ErrorKind::AlreadyExists) => "already_exists",
|
||||
Some(ErrorKind::WouldBlock) => "would_block",
|
||||
Some(ErrorKind::TimedOut) => "timed_out",
|
||||
Some(ErrorKind::ConnectionRefused) => "connection_refused",
|
||||
Some(ErrorKind::InvalidInput) => "invalid_input",
|
||||
Some(ErrorKind::InvalidData) => "invalid_data",
|
||||
Some(ErrorKind::StorageFull) => "storage_full",
|
||||
Some(ErrorKind::ReadOnlyFilesystem) => "read_only_filesystem",
|
||||
Some(ErrorKind::ResourceBusy) => "resource_busy",
|
||||
Some(_) => "other",
|
||||
None => "none",
|
||||
};
|
||||
[
|
||||
("failure_reason", reason),
|
||||
("failure_stage", stage),
|
||||
("os_error_kind", os_error),
|
||||
]
|
||||
}
|
||||
|
||||
fn classification(&self) -> (&'static str, &'static str) {
|
||||
#[cfg(windows)]
|
||||
if self.error.is::<crate::DetachedLaunchRestricted>() {
|
||||
return "spawn";
|
||||
return (WINDOWS_DETACH_RESTRICTED, "process_spawn");
|
||||
}
|
||||
match self.error.downcast_ref::<StartFailure>() {
|
||||
Some(StartFailure::Spawn(_)) => "spawn",
|
||||
Some(StartFailure::EarlyChildExit(_)) => "early_child_exit",
|
||||
Some(StartFailure::ReadinessTimeout(_)) => "readiness_timeout",
|
||||
None if self.during_install => "install",
|
||||
None => "other",
|
||||
Some(StartFailure::Spawn(_)) => ("spawn", "process_spawn"),
|
||||
Some(StartFailure::EarlyChildExit(stage, _)) => ("early_child_exit", stage),
|
||||
Some(StartFailure::ReadinessTimeout(_)) => ("readiness_timeout", "readiness"),
|
||||
Some(StartFailure::Backend(stage, _)) => ("other", stage),
|
||||
None if self.stage == "install" => ("install", self.stage),
|
||||
None => ("other", self.stage),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn install(error: anyhow::Error) -> Self {
|
||||
Self {
|
||||
error,
|
||||
during_install: true,
|
||||
}
|
||||
pub(crate) fn at(stage: &'static str) -> impl FnOnce(anyhow::Error) -> Self {
|
||||
move |error| Self { error, stage }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +73,7 @@ impl From<anyhow::Error> for StartError {
|
||||
fn from(error: anyhow::Error) -> Self {
|
||||
Self {
|
||||
error,
|
||||
during_install: false,
|
||||
stage: "unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,7 +82,8 @@ impl From<anyhow::Error> for StartError {
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum StartFailure {
|
||||
Spawn(String),
|
||||
EarlyChildExit(String),
|
||||
EarlyChildExit(&'static str, String),
|
||||
Backend(&'static str, String),
|
||||
ReadinessTimeout(String),
|
||||
}
|
||||
|
||||
@@ -54,7 +91,8 @@ impl std::fmt::Display for StartFailure {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Spawn(message)
|
||||
| Self::EarlyChildExit(message)
|
||||
| Self::EarlyChildExit(_, message)
|
||||
| Self::Backend(_, message)
|
||||
| Self::ReadinessTimeout(message) => f.write_str(message),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,43 @@ fn feature_overrides_allow_daemon_without_allowing_arbitrary_config() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_launch_telemetry_counts_one_failure_without_exposing_unknown_os_codes() {
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ScopeMetrics;
|
||||
|
||||
let metrics = codex_otel::MetricsClient::new(
|
||||
codex_otel::MetricsConfig::in_memory("test", "test", "1", Default::default())
|
||||
.with_runtime_reader(),
|
||||
)
|
||||
.unwrap();
|
||||
let error = anyhow::Error::from(std::io::Error::from_raw_os_error(i32::MAX));
|
||||
let home = TempDir::new().unwrap();
|
||||
daemon_telemetry::record_attempt(&metrics, home.path(), &Err(error.into())).await;
|
||||
|
||||
let snapshot = metrics.snapshot().unwrap();
|
||||
let mut counters = snapshot.scope_metrics().flat_map(ScopeMetrics::metrics);
|
||||
let counter = counters.next().unwrap();
|
||||
assert_eq!(counter.name(), "codex.daemon.start");
|
||||
assert!(counters.next().is_none());
|
||||
let AggregatedMetrics::U64(MetricData::Sum(sum)) = counter.data() else {
|
||||
panic!("expected daemon attempt counter");
|
||||
};
|
||||
let mut points = sum.data_points();
|
||||
let point = points.next().unwrap();
|
||||
assert!(points.next().is_none());
|
||||
assert_eq!(point.value(), 1);
|
||||
let tags: std::collections::BTreeMap<_, _> = point
|
||||
.attributes()
|
||||
.map(|a| (a.key.as_str(), a.value.to_string()))
|
||||
.collect();
|
||||
assert_eq!(tags["outcome"], "failed");
|
||||
assert_eq!(tags["failure_reason"], "other");
|
||||
assert_eq!(tags["failure_stage"], "unknown");
|
||||
assert_eq!(tags["os_error_kind"], "other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daemon_launch_telemetry_records_once_on_connection_update_or_early_return() {
|
||||
for mode in [Some("in_process"), Some("update_requested"), None] {
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
use super::*;
|
||||
use crate::terminal_size_telemetry::LaunchTags;
|
||||
use codex_app_server_daemon::LifecycleOutput;
|
||||
use codex_app_server_daemon::LifecycleStatus;
|
||||
use codex_app_server_daemon::telemetry::StartError;
|
||||
|
||||
/// Record the connection mode or update handoff once. Other early exits are unconfirmed.
|
||||
pub(super) struct Launch<F: FnOnce(&'static str) -> LaunchTags>(pub(super) Option<F>);
|
||||
@@ -23,14 +26,11 @@ impl<F: FnOnce(&'static str) -> LaunchTags> Drop for Launch<F> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn record_start(
|
||||
config: &Config,
|
||||
result: &Result<
|
||||
codex_app_server_daemon::LifecycleOutput,
|
||||
codex_app_server_daemon::telemetry::StartError,
|
||||
>,
|
||||
pub(super) async fn record_attempt(
|
||||
metrics: &codex_otel::MetricsClient,
|
||||
codex_home: &std::path::Path,
|
||||
result: &Result<LifecycleOutput, StartError>,
|
||||
) {
|
||||
use codex_app_server_daemon::LifecycleStatus;
|
||||
let outcome = match result {
|
||||
Ok(output) => match output.status {
|
||||
LifecycleStatus::Started => "started",
|
||||
@@ -42,6 +42,20 @@ pub(super) async fn record_start(
|
||||
},
|
||||
Err(_) => "failed",
|
||||
};
|
||||
let mut tags = codex_app_server_daemon::telemetry::settings_tags(codex_home)
|
||||
.await
|
||||
.to_vec();
|
||||
tags.extend([
|
||||
("initiation_source", "tui_auto_start"),
|
||||
("outcome", outcome),
|
||||
]);
|
||||
if let Err(error) = result {
|
||||
tags.extend(error.failure_tags());
|
||||
}
|
||||
let _ = metrics.counter("codex.daemon.start", /*inc*/ 1, &tags);
|
||||
}
|
||||
|
||||
pub(super) async fn record_start(config: &Config, result: &Result<LifecycleOutput, StartError>) {
|
||||
// Failure can happen before normal TUI telemetry is initialized. This short-lived
|
||||
// provider uses exactly the same consent and identity construction as TUI startup.
|
||||
let Ok(Ok(Some(otel))) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
@@ -55,17 +69,7 @@ pub(super) async fn record_start(
|
||||
return;
|
||||
};
|
||||
if let Some(metrics) = otel.metrics() {
|
||||
let mut tags = codex_app_server_daemon::telemetry::settings_tags(&config.codex_home)
|
||||
.await
|
||||
.to_vec();
|
||||
tags.extend([
|
||||
("initiation_source", "tui_auto_start"),
|
||||
("outcome", outcome),
|
||||
]);
|
||||
if let Err(error) = result {
|
||||
tags.push(("failure_reason", error.failure_reason()));
|
||||
}
|
||||
let _ = metrics.counter("codex.daemon.start", /*inc*/ 1, &tags);
|
||||
record_attempt(metrics, &config.codex_home, result).await;
|
||||
}
|
||||
let _ = otel
|
||||
.shutdown_with_timeout(INTERACTIVE_OTEL_SHUTDOWN_TIMEOUT)
|
||||
|
||||
@@ -808,7 +808,9 @@ pub(super) async fn run_main_inner(
|
||||
Some("GCP sign-in") => "gcp_sign_in",
|
||||
Some(daemon_startup::GATEWAY_SIGN_IN_EXCLUSION) => "gateway_sign_in",
|
||||
Some(daemon_startup::WSL_DRVFS_EXCLUSION) => "wsl_drvfs",
|
||||
Some("this Windows launcher") => "windows_detach_restricted",
|
||||
Some("this Windows launcher") => {
|
||||
codex_app_server_daemon::telemetry::WINDOWS_DETACH_RESTRICTED
|
||||
}
|
||||
Some("daemon feature settings") => "daemon_compatibility",
|
||||
None if selection_reason == "auto_start_disabled" => {
|
||||
"auto_start_disabled_no_daemon"
|
||||
|
||||
Reference in New Issue
Block a user