use crate::metrics::MetricsError; use crate::metrics::Result; use crate::metrics::config::MetricsConfig; use crate::metrics::names::TURN_CRITICAL_PATH_COMPONENT_METRIC; use crate::metrics::names::TURN_CRITICAL_PATH_DURATION_METRIC; use crate::metrics::timer::Timer; use crate::metrics::validation::validate_metric_name; use crate::metrics::validation::validate_tag_key; use crate::metrics::validation::validate_tag_value; use crate::metrics::validation::validate_tags; use codex_utils_string::sanitize_metric_tag_value; use opentelemetry::KeyValue; use opentelemetry::metrics::Counter; use opentelemetry::metrics::Gauge; use opentelemetry::metrics::Histogram; use opentelemetry::metrics::Meter; use opentelemetry::metrics::MeterProvider as _; use opentelemetry_sdk::Resource; use opentelemetry_sdk::metrics::InstrumentKind; use opentelemetry_sdk::metrics::ManualReader; use opentelemetry_sdk::metrics::PeriodicReader; use opentelemetry_sdk::metrics::Pipeline; use opentelemetry_sdk::metrics::SdkMeterProvider; use opentelemetry_sdk::metrics::Temporality; use opentelemetry_sdk::metrics::data::ResourceMetrics; use opentelemetry_sdk::metrics::reader::MetricReader; use opentelemetry_semantic_conventions as semconv; use std::collections::BTreeMap; use std::collections::HashMap; use std::sync::Arc; use std::sync::LazyLock; use std::sync::Mutex; use std::sync::RwLock; use std::sync::Weak; use std::time::Duration; use tracing::debug; const ENV_ATTRIBUTE: &str = "env"; const METER_NAME: &str = "codex"; const MILLISECOND_DURATION_UNIT: &str = "ms"; const MILLISECOND_DURATION_DESCRIPTION: &str = "Duration in milliseconds."; const MILLISECOND_DURATION_BOUNDARIES: &[f64] = &[ 0.0, 5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 250.0, 500.0, 750.0, 1_000.0, 1_250.0, 1_500.0, 1_750.0, 2_000.0, 2_250.0, 2_500.0, 3_000.0, 3_500.0, 4_000.0, 4_500.0, 5_000.0, 6_000.0, 7_000.0, 7_500.0, 8_000.0, 9_000.0, 10_000.0, 12_000.0, 15_000.0, 20_000.0, 30_000.0, 60_000.0, 120_000.0, ]; // Whole-turn profiles can accumulate minutes of inference, tool execution, or user wait. static TURN_CRITICAL_PATH_DURATION_BOUNDARIES: LazyLock> = LazyLock::new(|| { let mut bounds = MILLISECOND_DURATION_BOUNDARIES.to_vec(); bounds.extend([ 180_000.0, 300_000.0, 600_000.0, 900_000.0, 1_800_000.0, 3_600_000.0, 7_200_000.0, ]); bounds }); const SECOND_DURATION_UNIT: &str = "s"; const SECOND_DURATION_BOUNDARIES: &[f64] = &[ 0.0, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, 12.0, 15.0, 20.0, 30.0, 60.0, 120.0, ]; #[derive(Debug, Eq, Hash, PartialEq)] struct InstrumentKey { name: String, unit: Option<&'static str>, description: Option, } #[derive(Clone, Debug)] struct SharedManualReader { inner: Arc, } impl SharedManualReader { fn new(inner: Arc) -> Self { Self { inner } } } impl MetricReader for SharedManualReader { fn register_pipeline(&self, pipeline: Weak) { self.inner.register_pipeline(pipeline); } fn collect(&self, rm: &mut ResourceMetrics) -> opentelemetry_sdk::error::OTelSdkResult { self.inner.collect(rm) } fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult { self.inner.force_flush() } fn shutdown_with_timeout(&self, timeout: Duration) -> opentelemetry_sdk::error::OTelSdkResult { self.inner.shutdown_with_timeout(timeout) } fn temporality(&self, kind: InstrumentKind) -> Temporality { self.inner.temporality(kind) } } #[derive(Debug)] pub(super) struct MetricsClientInner { meter_provider: SdkMeterProvider, meter: Meter, counters: Mutex>>, gauges: Mutex>>, histograms: Mutex>>, duration_histograms: Mutex>>, runtime_reader: Option>, default_tags: BTreeMap, } impl MetricsClientInner { fn counter( &self, name: &str, description: Option<&str>, inc: i64, tags: &[(&str, &str)], ) -> Result<()> { validate_metric_name(name)?; if inc < 0 { return Err(MetricsError::NegativeCounterIncrement { name: name.to_string(), inc, }); } let attributes = self.attributes(tags)?; let mut counters = self .counters .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let key = InstrumentKey { name: name.to_string(), unit: None, description: description.map(str::to_string), }; let counter = counters.entry(key).or_insert_with(|| { let builder = self.meter.u64_counter(name.to_string()); match description { Some(description) => builder.with_description(description.to_string()).build(), None => builder.build(), } }); counter.add(inc as u64, &attributes); Ok(()) } fn histogram( &self, name: &str, value: i64, boundaries: Option<&[f64]>, tags: &[(&str, &str)], ) -> Result<()> { validate_metric_name(name)?; let attributes = self.attributes(tags)?; let mut histograms = self .histograms .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let histogram = histograms.entry(name.to_string()).or_insert_with(|| { let builder = self.meter.f64_histogram(name.to_string()); match boundaries { Some(boundaries) => builder.with_boundaries(boundaries.to_vec()).build(), None => builder.build(), } }); histogram.record(value as f64, &attributes); Ok(()) } fn gauge( &self, name: &str, description: Option<&str>, value: i64, tags: &[(&str, &str)], ) -> Result<()> { validate_metric_name(name)?; let attributes = self.attributes(tags)?; let mut gauges = self .gauges .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let key = InstrumentKey { name: name.to_string(), unit: None, description: description.map(str::to_string), }; let gauge = gauges.entry(key).or_insert_with(|| { let builder = self.meter.i64_gauge(name.to_string()); match description { Some(description) => builder.with_description(description.to_string()).build(), None => builder.build(), } }); gauge.record(value, &attributes); Ok(()) } fn register_observable_gauge( &self, name: &str, description: &str, observe: impl Fn() -> i64 + Send + Sync + 'static, tags: &[(&str, &str)], ) -> Result<()> { validate_metric_name(name)?; let attributes = self.attributes(tags)?; let _gauge = self .meter .i64_observable_gauge(name.to_string()) .with_description(description.to_string()) .with_callback(move |observer| observer.observe(observe(), &attributes)) .build(); Ok(()) } fn duration_histogram( &self, name: &str, value: f64, unit: &'static str, description: &str, boundaries: &'static [f64], tags: &[(&str, &str)], ) -> Result<()> { validate_metric_name(name)?; let attributes = self.attributes(tags)?; let mut histograms = self .duration_histograms .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let key = InstrumentKey { name: name.to_string(), unit: Some(unit), description: Some(description.to_string()), }; let histogram = histograms.entry(key).or_insert_with(|| { self.meter .f64_histogram(name.to_string()) .with_unit(unit) .with_description(description.to_string()) .with_boundaries(boundaries.to_vec()) .build() }); histogram.record(value, &attributes); Ok(()) } fn attributes(&self, tags: &[(&str, &str)]) -> Result> { if tags.is_empty() { return Ok(self .default_tags .iter() .map(|(key, value)| KeyValue::new(key.clone(), value.clone())) .collect()); } let mut merged = self.default_tags.clone(); for (key, value) in tags { validate_tag_key(key)?; validate_tag_value(value)?; merged.insert((*key).to_string(), (*value).to_string()); } Ok(merged .into_iter() .map(|(key, value)| KeyValue::new(key, value)) .collect()) } fn shutdown(&self) -> Result<()> { debug!("flushing OTEL metrics"); self.meter_provider .force_flush() .map_err(|source| MetricsError::ProviderShutdown { source })?; self.meter_provider .shutdown() .map_err(|source| MetricsError::ProviderShutdown { source })?; Ok(()) } } /// Local, in-process OpenTelemetry metrics client. It never exports over the network. #[derive(Clone, Debug)] pub struct MetricsClient { // Keep the original provider so its owner only shuts down its own reader. pub(super) inner: Arc, // Installed clients share this slot, so existing clones follow account changes. pub(super) active: Option>>>, } impl MetricsClient { /// Build a metrics client from configuration and validate defaults. pub fn new(config: MetricsConfig) -> Result { let MetricsConfig { environment, service_name, service_version, exporter, export_interval, runtime_reader, default_tags, } = config; validate_tags(&default_tags)?; let mut resource_attributes = Vec::with_capacity(4); resource_attributes.push(KeyValue::new( semconv::attribute::SERVICE_VERSION, service_version, )); resource_attributes.push(KeyValue::new(ENV_ATTRIBUTE, environment)); resource_attributes.extend(os_resource_attributes()); let resource = Resource::builder() .with_service_name(service_name) .with_attributes(resource_attributes) .build(); let runtime_reader = runtime_reader.then(|| { Arc::new( ManualReader::builder() .with_temporality(Temporality::Delta) .build(), ) }); let (meter_provider, meter) = build_provider(resource, exporter, export_interval, runtime_reader.clone()); Ok(Self { inner: Arc::new(MetricsClientInner { meter_provider, meter, counters: Mutex::new(HashMap::new()), gauges: Mutex::new(HashMap::new()), histograms: Mutex::new(HashMap::new()), duration_histograms: Mutex::new(HashMap::new()), runtime_reader, default_tags, }), active: None, }) } pub(super) fn active_inner(&self) -> Arc { match &self.active { Some(active) => active .read() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone(), None => Arc::clone(&self.inner), } } /// Send a single counter increment. pub fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) -> Result<()> { self.active_inner() .counter(name, /*description*/ None, inc, tags) } /// Send a single counter increment with an instrument description. pub fn counter_with_description( &self, name: &str, description: &str, inc: i64, tags: &[(&str, &str)], ) -> Result<()> { self.active_inner() .counter(name, Some(description), inc, tags) } /// Send a single histogram sample. pub fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) -> Result<()> { self.active_inner() .histogram(name, value, /*boundaries*/ None, tags) } /// Send a single histogram sample using explicit bucket boundaries. pub fn histogram_with_boundaries( &self, name: &str, value: i64, boundaries: &[f64], tags: &[(&str, &str)], ) -> Result<()> { self.active_inner() .histogram(name, value, Some(boundaries), tags) } /// Send a single gauge measurement. pub fn gauge(&self, name: &str, value: i64, tags: &[(&str, &str)]) -> Result<()> { self.active_inner() .gauge(name, /*description*/ None, value, tags) } /// Send a single gauge measurement with an instrument description. pub fn gauge_with_description( &self, name: &str, description: &str, value: i64, tags: &[(&str, &str)], ) -> Result<()> { self.active_inner() .gauge(name, Some(description), value, tags) } /// Register a gauge callback that reports the current value on every collection. pub fn register_observable_gauge_with_description( &self, name: &str, description: &str, observe: impl Fn() -> i64 + Send + Sync + 'static, tags: &[(&str, &str)], ) -> Result<()> { self.active_inner() .register_observable_gauge(name, description, observe, tags) } /// Record a duration in milliseconds using a histogram. pub fn record_duration( &self, name: &str, duration: Duration, tags: &[(&str, &str)], ) -> Result<()> { self.active_inner().duration_histogram( name, duration.as_millis().min(i64::MAX as u128) as f64, MILLISECOND_DURATION_UNIT, MILLISECOND_DURATION_DESCRIPTION, match name { TURN_CRITICAL_PATH_DURATION_METRIC | TURN_CRITICAL_PATH_COMPONENT_METRIC => { &TURN_CRITICAL_PATH_DURATION_BOUNDARIES } _ => MILLISECOND_DURATION_BOUNDARIES, }, tags, ) } /// Record a duration supplied as fractional milliseconds using a histogram. pub(crate) fn record_duration_ms_f64( &self, name: &str, duration_ms: f64, tags: &[(&str, &str)], ) -> Result<()> { self.active_inner().duration_histogram( name, duration_ms, MILLISECOND_DURATION_UNIT, MILLISECOND_DURATION_DESCRIPTION, MILLISECOND_DURATION_BOUNDARIES, tags, ) } /// Record a duration in seconds using a histogram with an instrument description. pub fn record_duration_seconds_with_description( &self, name: &str, description: &str, duration: Duration, tags: &[(&str, &str)], ) -> Result<()> { self.active_inner().duration_histogram( name, duration.as_secs_f64(), SECOND_DURATION_UNIT, description, SECOND_DURATION_BOUNDARIES, tags, ) } pub fn start_timer( &self, name: &str, tags: &[(&str, &str)], ) -> std::result::Result { Ok(Timer::new(name, tags, self)) } /// Collect a runtime metrics snapshot without shutting down the provider. pub fn snapshot(&self) -> Result { let inner = self.active_inner(); let Some(reader) = &inner.runtime_reader else { return Err(MetricsError::RuntimeSnapshotUnavailable); }; let mut snapshot = ResourceMetrics::default(); reader .collect(&mut snapshot) .map_err(|source| MetricsError::RuntimeSnapshotCollect { source })?; Ok(snapshot) } /// Flush metrics and stop the underlying OTEL meter provider. pub fn shutdown(&self) -> Result<()> { super::buffered::GLOBAL.suspend(self); self.inner.shutdown() } } fn os_resource_attributes() -> Vec { // Provider creation must not repeat OS discovery subprocesses. static OS_INFO: LazyLock = LazyLock::new(os_info::get); let os_info = &*OS_INFO; let os_type_raw = os_info.os_type().to_string(); let os_type = sanitize_metric_tag_value(os_type_raw.as_str()); let os_version_raw = os_info.version().to_string(); let os_version = sanitize_metric_tag_value(os_version_raw.as_str()); let mut attributes = Vec::new(); if os_type != "unspecified" { attributes.push(KeyValue::new("os", os_type)); } if os_version != "unspecified" { attributes.push(KeyValue::new("os_version", os_version)); } attributes } fn build_provider( resource: Resource, exporter: E, interval: Option, runtime_reader: Option>, ) -> (SdkMeterProvider, Meter) where E: opentelemetry_sdk::metrics::exporter::PushMetricExporter + 'static, { let mut reader_builder = PeriodicReader::builder(exporter); if let Some(interval) = interval { reader_builder = reader_builder.with_interval(interval); } let reader = reader_builder.build(); let mut provider_builder = SdkMeterProvider::builder().with_resource(resource); if let Some(reader) = runtime_reader { provider_builder = provider_builder.with_reader(SharedManualReader::new(reader)); } let provider = provider_builder.with_reader(reader).build(); let meter = provider.meter(METER_NAME); (provider, meter) }