Lightweight coding agent that runs in your terminal
Rust
Honor custom OTLP metrics exporters when analytics is disabled (#52278)
jackz2c3156adf4c9
diff --git a/codex-rs/app-server/tests/suite/v2/analytics.rs b/codex-rs/app-server/tests/suite/v2/analytics.rsindex d8e8813c97..29b2b4be8b 100644--- a/codex-rs/app-server/tests/suite/v2/analytics.rs+++ b/codex-rs/app-server/tests/suite/v2/analytics.rs@@ -518,61 +518,58 @@ async fn multi_agent_v2_tools_emit_collaborator_analytics() -> Result<()> {Ok(())}-fn set_metrics_exporter(config: &mut codex_core::config::Config) {- config.otel.metrics_exporter = OtelExporterKind::OtlpHttp {- endpoint: "http://localhost:4318".to_string(),- headers: HashMap::new(),- protocol: OtelHttpProtocol::Json,- tls: None,- };-}-#[tokio::test]-async fn app_server_default_analytics_disabled_without_flag() -> Result<()> {+async fn metrics_exporters_respect_analytics_preferences() -> Result<()> {let codex_home = TempDir::new()?;let mut config = ConfigBuilder::default().codex_home(codex_home.path().to_path_buf()).build().await?;- set_metrics_exporter(&mut config);- config.analytics_enabled = None;-- let provider = codex_core::otel_init::build_provider(- &config,- SERVICE_VERSION,- Some("codex-app-server"),- /*default_analytics_enabled*/ false,- )- .map_err(|err| anyhow::anyhow!(err.to_string()))?;-- // With analytics unset in the config and the default flag is false, metrics are disabled.- // A provider may still exist for non-metrics telemetry, so check metrics specifically.- let has_metrics = provider.as_ref().and_then(|otel| otel.metrics()).is_some();- assert_eq!(has_metrics, false);- Ok(())-}--#[tokio::test]-async fn app_server_default_analytics_enabled_with_flag() -> Result<()> {- let codex_home = TempDir::new()?;- let mut config = ConfigBuilder::default()- .codex_home(codex_home.path().to_path_buf())- .build()- .await?;- set_metrics_exporter(&mut config);- config.analytics_enabled = None;-- let provider = codex_core::otel_init::build_provider(- &config,- SERVICE_VERSION,- Some("codex-app-server"),- /*default_analytics_enabled*/ true,- )- .map_err(|err| anyhow::anyhow!(err.to_string()))?;+ for exporter in [+ OtelExporterKind::None,+ OtelExporterKind::Statsig,+ OtelExporterKind::OtlpHttp {+ endpoint: "http://localhost:4318".to_string(),+ headers: HashMap::new(),+ protocol: OtelHttpProtocol::Json,+ tls: None,+ },+ OtelExporterKind::OtlpGrpc {+ endpoint: "http://localhost:4317".to_string(),+ headers: HashMap::new(),+ tls: None,+ },+ ] {+ config.otel.metrics_exporter = exporter;+ for analytics_enabled in [None, Some(false), Some(true)] {+ config.analytics_enabled = analytics_enabled;+ for default_analytics_enabled in [false, true] {+ let expected_metrics = match config.otel.metrics_exporter {+ OtelExporterKind::None => false,+ // The built-in exporter is disabled in debug builds even with consent.+ OtelExporterKind::Statsig => {+ !cfg!(debug_assertions)+ && analytics_enabled.unwrap_or(default_analytics_enabled)+ }+ OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } => true,+ };+ let provider = codex_core::otel_init::build_provider(+ &config,+ SERVICE_VERSION,+ Some("codex-app-server"),+ default_analytics_enabled,+ )+ .map_err(|err| anyhow::anyhow!(err.to_string()))?;+ assert_eq!(+ provider.as_ref().and_then(|otel| otel.metrics()).is_some(),+ expected_metrics,+ "exporter={:?}, analytics={analytics_enabled:?}, default={default_analytics_enabled}",+ config.otel.metrics_exporter,+ );+ }+ }+ }- // With analytics unset in the config and the default flag is true, metrics are enabled.- let has_metrics = provider.as_ref().and_then(|otel| otel.metrics()).is_some();- assert_eq!(has_metrics, true);Ok(())}diff --git a/codex-rs/app-server/tests/suite/v2/otel.rs b/codex-rs/app-server/tests/suite/v2/otel.rsindex e6ba7144b4..144b1d4e33 100644--- a/codex-rs/app-server/tests/suite/v2/otel.rs+++ b/codex-rs/app-server/tests/suite/v2/otel.rs@@ -185,7 +185,7 @@ base_url = "http://127.0.0.1:1/v1"wire_api = "responses"[analytics]-enabled = true+enabled = false[otel]environment = "test"diff --git a/codex-rs/cli/tests/daemon_telemetry.rs b/codex-rs/cli/tests/daemon_telemetry.rsindex 5e265992f3..1d34cefe14 100644--- a/codex-rs/cli/tests/daemon_telemetry.rs+++ b/codex-rs/cli/tests/daemon_telemetry.rs@@ -1,4 +1,4 @@-//! Foreground updates honor app-server consent and never claim unconfirmed installation.+//! Foreground updates honor explicit metrics exporters and never claim unconfirmed installation.use anyhow::Context as _;use pretty_assertions::assert_eq;@@ -8,12 +8,13 @@ use wiremock::MockServer;use wiremock::ResponseTemplate;#[tokio::test]-async fn foreground_update_respects_consent_and_reports_unconfirmed() -> anyhow::Result<()> {- for (analytics_config, analytics_default_enabled, expected_requests) in [- ("", false, 0),- ("", true, 1),- ("analytics.enabled = true\n", false, 1),- ("analytics.enabled = false\n", true, 0),+async fn foreground_update_honors_metrics_exporter_and_reports_unconfirmed() -> anyhow::Result<()> {+ for (analytics_config, analytics_default_enabled, metrics_enabled) in [+ ("", false, true),+ ("", true, true),+ ("analytics.enabled = true\n", false, true),+ ("analytics.enabled = false\n", true, true),+ ("analytics.enabled = true\n", true, false),] {let codex = codex_utils_cargo_bin::cargo_bin("codex")?;let server = MockServer::start().await;@@ -39,6 +40,9 @@ async fn foreground_update_respects_consent_and_reports_unconfirmed() -> anyhow:if analytics_default_enabled {command.arg("--analytics-default-enabled");}+ if !metrics_enabled {+ command.args(["-c", "otel.metrics_exporter=\"none\""]);+ }let output = command.args(["daemon", "update", "--from-cli", "--yes"]).output()@@ -48,8 +52,8 @@ async fn foreground_update_respects_consent_and_reports_unconfirmed() -> anyhow:.received_requests().await.context("metric requests")?;- assert_eq!(requests.len(), expected_requests);- if expected_requests == 0 {+ assert_eq!(requests.len(), usize::from(metrics_enabled));+ if !metrics_enabled {continue;}let body: Value = serde_json::from_slice(&requests[0].body)?;diff --git a/codex-rs/cli/tests/worktree.rs b/codex-rs/cli/tests/worktree.rsindex 928a57e649..664b2e1d65 100644--- a/codex-rs/cli/tests/worktree.rs+++ b/codex-rs/cli/tests/worktree.rs@@ -198,7 +198,7 @@ sandbox_mode = "workspace-write"windows.sandbox = "unelevated"tui.disable_paste_burst = true[otel]-metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" }} }}+metrics_exporter = "none"[model_providers.local]name = "local test"base_url = "{}/v1"@@ -211,7 +211,6 @@ trust_level = "trusted"server.uri(),backend == "daemon",server.uri(),- server.uri(),serde_json::to_string(&source)?,serde_json::to_string(&launcher)?),@@ -408,7 +407,15 @@ trust_level = "trusted"args.extend(["--cd".into(), source.join(".codex").display().to_string()]);}if analytics {- args.extend(["-c".into(), "analytics.enabled=true".into()]);+ args.extend([+ "-c".into(),+ "analytics.enabled=true".into(),+ "-c".into(),+ format!(+ "otel.metrics_exporter={{otlp-http={{endpoint=\"{}/metrics\",protocol=\"json\"}}}}",+ server.uri()+ ),+ ]);}args.push(prompt.into());if previous.is_empty() {@@ -674,7 +681,7 @@ trust_level = "trusted"}assert_eq!(tags, expected_tags);} else {- assert!(metrics.is_empty(), "analytics disabled");+ assert!(metrics.is_empty(), "metrics exporter disabled");}let (body, checkout, metadata) = observed.with_context(|| {diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rsindex 1ff5cf929a..8c8c66ea1d 100644--- a/codex-rs/config/src/config_toml.rs+++ b/codex-rs/config/src/config_toml.rs@@ -531,8 +531,9 @@ pub struct ConfigToml {/// Legacy fallback for `tui.disable_paste_burst`. Prefer the setting under `[tui]`.pub disable_paste_burst: Option<bool>,- /// When `false`, disables analytics across Codex product surfaces in this machine.- /// Defaults to `true`.+ /// When `enabled` is `false`, disables OpenAI analytics across Codex product surfaces on this machine.+ /// Custom OTLP metrics exporters are controlled by `otel.metrics_exporter`.+ /// When unset, the default depends on the client.pub analytics: Option<AnalyticsConfigToml>,/// When `false`, disables feedback collection across Codex product surfaces.diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rsindex 2a2ad0b07d..e78a7a751c 100644--- a/codex-rs/config/src/types.rs+++ b/codex-rs/config/src/types.rs@@ -246,7 +246,8 @@ pub enum HistoryPersistence {#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]#[schemars(deny_unknown_fields)]pub struct AnalyticsConfigToml {- /// When `false`, disables analytics across Codex product surfaces in this profile.+ /// When `false`, disables OpenAI analytics across Codex product surfaces in this profile.+ /// Custom OTLP metrics exporters remain enabled; set `otel.metrics_exporter = "none"` to disable them.pub enabled: Option<bool>,}@@ -641,7 +642,8 @@ pub struct OtelConfigToml {/// Optional trace exporterpub trace_exporter: Option<OtelExporterKind>,- /// Optional metrics exporter+ /// Metrics exporter. Defaults to `statsig`, which follows `analytics.enabled`.+ /// Custom OTLP exporters are independent of `analytics.enabled`; `none` disables metrics export.pub metrics_exporter: Option<OtelExporterKind>,/// Attributes to add to every exported trace span.diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.jsonindex aba6689bd3..432b31c63a 100644--- a/codex-rs/core/config.schema.json+++ b/codex-rs/core/config.schema.json@@ -117,7 +117,7 @@"description": "Analytics settings loaded from config.toml. Fields are optional so we can apply defaults.","properties": {"enabled": {- "description": "When `false`, disables analytics across Codex product surfaces in this profile.",+ "description": "When `false`, disables OpenAI analytics across Codex product surfaces in this profile. Custom OTLP metrics exporters remain enabled; set `otel.metrics_exporter = \"none\"` to disable them.","type": "boolean"}},@@ -3430,7 +3430,7 @@"$ref": "#/definitions/OtelExporterKind"}],- "description": "Optional metrics exporter"+ "description": "Metrics exporter. Defaults to `statsig`, which follows `analytics.enabled`. Custom OTLP exporters are independent of `analytics.enabled`; `none` disables metrics export."},"span_attributes": {"additionalProperties": {@@ -6839,7 +6839,7 @@"$ref": "#/definitions/AnalyticsConfigToml"}],- "description": "When `false`, disables analytics across Codex product surfaces in this machine. Defaults to `true`."+ "description": "When `enabled` is `false`, disables OpenAI analytics across Codex product surfaces on this machine. Custom OTLP metrics exporters are controlled by `otel.metrics_exporter`. When unset, the default depends on the client."},"approval_policy": {"allOf": [diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rsindex 99c0176fc0..696872522d 100644--- a/codex-rs/core/src/config/mod.rs+++ b/codex-rs/core/src/config/mod.rs@@ -1155,7 +1155,8 @@ pub struct Config {/// or placeholder replacement will occur for fast keypress bursts.pub disable_paste_burst: bool,- /// When `false`, disables analytics across Codex product surfaces in this machine.+ /// When `false`, disables OpenAI analytics across Codex product surfaces on this machine.+ /// Custom OTLP metrics exporters are controlled by `otel.metrics_exporter`./// Voluntarily left as Optional because the default value might depend on the client.pub analytics_enabled: Option<bool>,diff --git a/codex-rs/core/src/otel_init.rs b/codex-rs/core/src/otel_init.rsindex bd9df090ff..a6b6a70ec0 100644--- a/codex-rs/core/src/otel_init.rs+++ b/codex-rs/core/src/otel_init.rs@@ -67,13 +67,15 @@ pub fn build_provider(let exporter = to_otel_exporter(&config.otel.exporter);let trace_exporter = to_otel_exporter(&config.otel.trace_exporter);- let metrics_exporter = if config- .analytics_enabled- .unwrap_or(default_analytics_enabled)+ // Analytics consent controls the built-in exporter, not explicit OTLP collectors.+ let metrics_exporter = if matches!(config.otel.metrics_exporter, Kind::Statsig)+ && !config+ .analytics_enabled+ .unwrap_or(default_analytics_enabled){- to_otel_exporter(&config.otel.metrics_exporter)- } else {OtelExporter::None+ } else {+ to_otel_exporter(&config.otel.metrics_exporter)};let originator = originator();