From 74ac27f497edec0a38ae4e52ba8ae957c474346e Mon Sep 17 00:00:00 2001 From: yanqinhua Date: Thu, 4 Jun 2026 11:49:29 -0400 Subject: [PATCH] Add Codex OTEL resource attributes --- codex-rs/config/src/types.rs | 5 +++ codex-rs/core/config.schema.json | 7 ++++ codex-rs/core/src/config/config_tests.rs | 30 ++++++++++++++ codex-rs/core/src/config/otel.rs | 24 +++++++++++ codex-rs/core/src/otel_init.rs | 1 + codex-rs/otel/README.md | 9 +++- codex-rs/otel/src/config.rs | 19 +++++++-- codex-rs/otel/src/lib.rs | 1 + codex-rs/otel/src/provider.rs | 41 +++++++++++++++++-- .../otel/tests/suite/otlp_http_loopback.rs | 4 ++ codex-rs/windows-sandbox-rs/src/wfp_setup.rs | 1 + 11 files changed, 134 insertions(+), 8 deletions(-) diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index 7b634a5188..8d907bd9fe 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -526,6 +526,9 @@ pub struct OtelConfigToml { /// Optional metrics exporter pub metrics_exporter: Option, + /// Attributes to add to exported OTEL resources. + pub resource_attributes: Option>, + /// Attributes to add to every exported trace span. pub span_attributes: Option>, @@ -541,6 +544,7 @@ pub struct OtelConfig { pub exporter: OtelExporterKind, pub trace_exporter: OtelExporterKind, pub metrics_exporter: OtelExporterKind, + pub resource_attributes: BTreeMap, pub span_attributes: BTreeMap, pub tracestate: BTreeMap>, } @@ -553,6 +557,7 @@ impl Default for OtelConfig { exporter: OtelExporterKind::None, trace_exporter: OtelExporterKind::None, metrics_exporter: OtelExporterKind::Statsig, + resource_attributes: BTreeMap::new(), span_attributes: BTreeMap::new(), tracestate: BTreeMap::new(), } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index b281b44bb7..c8d4fc93b3 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2001,6 +2001,13 @@ ], "description": "Optional metrics exporter" }, + "resource_attributes": { + "additionalProperties": { + "type": "string" + }, + "description": "Attributes to add to exported OTEL resources.", + "type": "object" + }, "span_attributes": { "additionalProperties": { "type": "string" diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index dac8286749..9300695f73 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -8037,6 +8037,10 @@ async fn load_config_applies_otel_trace_metadata() -> std::io::Result<()> { let mut fixture = create_test_fixture()?; fixture.cfg = toml::from_str( r#" +[otel.resource_attributes] +"openai_cluster_kind" = "applied-devbox" +"openai_cluster_name" = "devbox-1" + [otel.span_attributes] "example.trace_attr" = "enabled" @@ -8057,6 +8061,16 @@ beta = "two" ) .await?; + assert_eq!( + config.otel.resource_attributes, + BTreeMap::from([ + ( + "openai_cluster_kind".to_string(), + "applied-devbox".to_string(), + ), + ("openai_cluster_name".to_string(), "devbox-1".to_string()), + ]) + ); assert_eq!( config.otel.span_attributes, BTreeMap::from([("example.trace_attr".to_string(), "enabled".to_string())]) @@ -8086,6 +8100,10 @@ environment = "test" "" = "missing-key" "example.trace_attr" = "enabled" +[otel.resource_attributes] +"" = "missing-key" +"openai_cluster_name" = "devbox-1" + [otel.tracestate.example] alpha = "one" beta = "two\ntoo" @@ -8107,6 +8125,10 @@ alpha = "one\ntwo" .await?; assert_eq!(config.otel.environment, "test"); + assert_eq!( + config.otel.resource_attributes, + BTreeMap::from([("openai_cluster_name".to_string(), "devbox-1".to_string())]) + ); assert_eq!( config.otel.span_attributes, BTreeMap::from([("example.trace_attr".to_string(), "enabled".to_string())]) @@ -8118,6 +8140,14 @@ alpha = "one\ntwo" BTreeMap::from([("alpha".to_string(), "one".to_string())]), )]) ); + assert!( + config.startup_warnings.iter().any(|warning| { + warning.contains("Ignoring invalid `otel.resource_attributes` config") + && warning.contains("configured resource attribute key must not be empty") + }), + "{:?}", + config.startup_warnings + ); assert!( config.startup_warnings.iter().any(|warning| { warning.contains("Ignoring invalid `otel.span_attributes` config") diff --git a/codex-rs/core/src/config/otel.rs b/codex-rs/core/src/config/otel.rs index cb65d304d1..7637b3e763 100644 --- a/codex-rs/core/src/config/otel.rs +++ b/codex-rs/core/src/config/otel.rs @@ -22,6 +22,8 @@ pub(crate) fn resolve_config( // Provider initialization installs process-global OTEL state. Sanitize // user-editable trace metadata here so malformed config is reported as a // startup warning instead of making startup fail. + let resource_attributes = + resolve_resource_attributes(config.resource_attributes, startup_warnings); let span_attributes = resolve_span_attributes(config.span_attributes, startup_warnings); let tracestate = resolve_tracestate(config.tracestate, startup_warnings); @@ -31,11 +33,33 @@ pub(crate) fn resolve_config( exporter, trace_exporter, metrics_exporter, + resource_attributes, span_attributes, tracestate, } } +fn resolve_resource_attributes( + resource_attributes: Option>, + startup_warnings: &mut Vec, +) -> BTreeMap { + let Some(resource_attributes) = resource_attributes else { + return BTreeMap::new(); + }; + + let mut valid_attributes = BTreeMap::new(); + for (key, value) in resource_attributes { + let attribute = BTreeMap::from([(key.clone(), value.clone())]); + if let Err(err) = codex_otel::validate_resource_attributes(&attribute) { + push_invalid_config_warning("otel.resource_attributes", err, startup_warnings); + continue; + } + valid_attributes.insert(key, value); + } + + valid_attributes +} + fn resolve_span_attributes( span_attributes: Option>, startup_warnings: &mut Vec, diff --git a/codex-rs/core/src/otel_init.rs b/codex-rs/core/src/otel_init.rs index 8b5aac5f78..97f0f26aba 100644 --- a/codex-rs/core/src/otel_init.rs +++ b/codex-rs/core/src/otel_init.rs @@ -89,6 +89,7 @@ pub fn build_provider( trace_exporter, metrics_exporter, runtime_metrics, + resource_attributes: config.otel.resource_attributes.clone(), span_attributes: config.otel.span_attributes.clone(), tracestate: config.otel.tracestate.clone(), }) diff --git a/codex-rs/otel/README.md b/codex-rs/otel/README.md index afae1b2f03..fad145e1c5 100644 --- a/codex-rs/otel/README.md +++ b/codex-rs/otel/README.md @@ -39,6 +39,7 @@ let settings = OtelSettings { tls: None, }, metrics_exporter: OtelExporter::None, + resource_attributes: std::collections::BTreeMap::new(), span_attributes: std::collections::BTreeMap::new(), tracestate: std::collections::BTreeMap::new(), }; @@ -51,10 +52,14 @@ if let Some(provider) = OtelProvider::from(&settings)? { } ``` -Configured span attributes and W3C tracestate member fields are applied to -exported trace spans and propagated trace context: +Configured resource attributes are applied to exported OTEL resources. Configured +span attributes and W3C tracestate member fields are applied to exported trace +spans and propagated trace context: ```toml +[otel.resource_attributes] +"example.resource_attr" = "enabled" + [otel.span_attributes] "example.trace_attr" = "enabled" diff --git a/codex-rs/otel/src/config.rs b/codex-rs/otel/src/config.rs index ab60ea601e..ac404bd46d 100644 --- a/codex-rs/otel/src/config.rs +++ b/codex-rs/otel/src/config.rs @@ -35,18 +35,30 @@ pub(crate) fn resolve_exporter(exporter: &OtelExporter) -> OtelExporter { } } -/// Validates configured span attributes before they are attached to exported spans. -pub fn validate_span_attributes(attributes: &BTreeMap) -> std::io::Result<()> { +fn validate_attribute_keys( + attributes: &BTreeMap, + kind: &str, +) -> std::io::Result<()> { if attributes.keys().any(String::is_empty) { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, - "configured span attribute key must not be empty", + format!("configured {kind} attribute key must not be empty"), )); } Ok(()) } +/// Validates configured resource attributes before they are attached to exported resources. +pub fn validate_resource_attributes(attributes: &BTreeMap) -> std::io::Result<()> { + validate_attribute_keys(attributes, "resource") +} + +/// Validates configured span attributes before they are attached to exported spans. +pub fn validate_span_attributes(attributes: &BTreeMap) -> std::io::Result<()> { + validate_attribute_keys(attributes, "span") +} + #[derive(Clone, Debug)] pub struct OtelSettings { pub environment: String, @@ -57,6 +69,7 @@ pub struct OtelSettings { pub trace_exporter: OtelExporter, pub metrics_exporter: OtelExporter, pub runtime_metrics: bool, + pub resource_attributes: BTreeMap, pub span_attributes: BTreeMap, pub tracestate: BTreeMap>, } diff --git a/codex-rs/otel/src/lib.rs b/codex-rs/otel/src/lib.rs index 1a689d3684..ce057ad58e 100644 --- a/codex-rs/otel/src/lib.rs +++ b/codex-rs/otel/src/lib.rs @@ -16,6 +16,7 @@ pub use crate::config::OtelHttpProtocol; pub use crate::config::OtelSettings; pub use crate::config::OtelTlsConfig; pub use crate::config::StatsigMetricsSettings; +pub use crate::config::validate_resource_attributes; pub use crate::config::validate_span_attributes; pub use crate::events::session_telemetry::AuthEnvTelemetryMetadata; pub use crate::events::session_telemetry::SessionTelemetry; diff --git a/codex-rs/otel/src/provider.rs b/codex-rs/otel/src/provider.rs index 26f732da71..a47f946d0b 100644 --- a/codex-rs/otel/src/provider.rs +++ b/codex-rs/otel/src/provider.rs @@ -89,9 +89,9 @@ impl OtelProvider { } // Provider setup installs process-global OTEL state that cannot be - // rolled back. Validate trace metadata before any setup path can - // mutate those globals, and keep span attribute checks aligned with - // config loading when traces are exported. + // rolled back. Validate configured metadata before any setup path can + // mutate those globals, and keep checks aligned with config loading. + crate::config::validate_resource_attributes(&settings.resource_attributes)?; if trace_enabled { crate::config::validate_span_attributes(&settings.span_attributes)?; } @@ -232,6 +232,12 @@ fn resource_attributes( ), KeyValue::new(ENV_ATTRIBUTE, settings.environment.clone()), ]; + attributes.extend( + settings + .resource_attributes + .iter() + .map(|(key, value)| KeyValue::new(key.clone(), value.clone())), + ); if kind == ResourceKind::Logs && let Some(host_name) = host_name.and_then(normalize_host_name) { @@ -509,6 +515,34 @@ mod tests { ); } + #[test] + fn resource_attributes_include_configured_attributes_for_logs_and_traces() { + let mut settings = test_otel_settings(); + settings.resource_attributes = BTreeMap::from([ + ( + "openai_cluster_kind".to_string(), + "applied-devbox".to_string(), + ), + ("openai_cluster_name".to_string(), "devbox-1".to_string()), + ]); + + for kind in [ResourceKind::Logs, ResourceKind::Traces] { + let attrs = resource_attributes(&settings, Some("opentelemetry-test"), kind) + .into_iter() + .map(|kv| (kv.key.as_str().to_string(), kv.value.as_str().to_string())) + .collect::>(); + + assert_eq!( + attrs.get("openai_cluster_kind").map(String::as_str), + Some("applied-devbox") + ); + assert_eq!( + attrs.get("openai_cluster_name").map(String::as_str), + Some("devbox-1") + ); + } + } + #[test] fn log_export_target_excludes_trace_safe_events() { assert!(is_log_export_target("codex_otel.log_only")); @@ -535,6 +569,7 @@ mod tests { trace_exporter: OtelExporter::None, metrics_exporter: OtelExporter::None, runtime_metrics: false, + resource_attributes: BTreeMap::new(), span_attributes: BTreeMap::new(), tracestate: BTreeMap::new(), } diff --git a/codex-rs/otel/tests/suite/otlp_http_loopback.rs b/codex-rs/otel/tests/suite/otlp_http_loopback.rs index 4c2dd36f76..5e60c748d8 100644 --- a/codex-rs/otel/tests/suite/otlp_http_loopback.rs +++ b/codex-rs/otel/tests/suite/otlp_http_loopback.rs @@ -240,6 +240,7 @@ fn otel_provider_rejects_header_unsafe_configured_tracestate() { }, metrics_exporter: OtelExporter::None, runtime_metrics: false, + resource_attributes: BTreeMap::new(), span_attributes: BTreeMap::new(), tracestate: BTreeMap::from([( "example".to_string(), @@ -305,6 +306,7 @@ fn otlp_http_exporter_sends_traces_to_collector() }, metrics_exporter: OtelExporter::None, runtime_metrics: false, + resource_attributes: BTreeMap::new(), span_attributes: BTreeMap::from([( "test.configured_attribute".to_string(), "configured-value".to_string(), @@ -449,6 +451,7 @@ async fn otlp_http_exporter_sends_traces_to_collector_in_tokio_runtime() }, metrics_exporter: OtelExporter::None, runtime_metrics: false, + resource_attributes: BTreeMap::new(), span_attributes: BTreeMap::new(), tracestate: BTreeMap::new(), })? @@ -570,6 +573,7 @@ fn otlp_http_exporter_sends_traces_to_collector_in_current_thread_tokio_runtime( }, metrics_exporter: OtelExporter::None, runtime_metrics: false, + resource_attributes: BTreeMap::new(), span_attributes: BTreeMap::new(), tracestate: BTreeMap::new(), }) diff --git a/codex-rs/windows-sandbox-rs/src/wfp_setup.rs b/codex-rs/windows-sandbox-rs/src/wfp_setup.rs index 351d2edd2f..f2c573de27 100644 --- a/codex-rs/windows-sandbox-rs/src/wfp_setup.rs +++ b/codex-rs/windows-sandbox-rs/src/wfp_setup.rs @@ -55,6 +55,7 @@ fn build_wfp_metrics_provider( trace_exporter: OtelExporter::None, metrics_exporter: OtelExporter::Statsig, runtime_metrics: false, + resource_attributes: BTreeMap::new(), span_attributes: BTreeMap::new(), tracestate: BTreeMap::new(), })