Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
use codex_otel::MetricsClient;
use codex_otel::MetricsConfig;
use codex_otel::Result;
use opentelemetry::KeyValue;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::Metric;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::metrics::data::ResourceMetrics;
use std::collections::BTreeMap;
pub(crate) fn build_metrics_with_defaults(
default_tags: &[(&str, &str)],
) -> Result<(MetricsClient, InMemoryMetricExporter)> {
let exporter = InMemoryMetricExporter::default();
let mut config = MetricsConfig::in_memory(
"test",
"codex-cli",
env!("CARGO_PKG_VERSION"),
exporter.clone(),
);
for (key, value) in default_tags {
config = config.with_tag(*key, *value)?;
}
let metrics = MetricsClient::new(config)?;
Ok((metrics, exporter))
}
pub(crate) fn latest_metrics(exporter: &InMemoryMetricExporter) -> ResourceMetrics {
exporter
.get_finished_metrics()
.expect("finished metrics should be available")
.into_iter()
.last()
.expect("metrics export should exist")
}
pub(crate) fn find_metric<'a>(
resource_metrics: &'a ResourceMetrics,
name: &str,
) -> Option<&'a Metric> {
for scope_metrics in resource_metrics.scope_metrics() {
for metric in scope_metrics.metrics() {
if metric.name() == name {
return Some(metric);
}
}
}
None
}
pub(crate) fn attributes_to_map<'a>(
attributes: impl Iterator<Item = &'a KeyValue>,
) -> BTreeMap<String, String> {
attributes
.map(|kv| (kv.key.as_str().to_string(), kv.value.as_str().to_string()))
.collect()
}
pub(crate) fn histogram_data(
resource_metrics: &ResourceMetrics,
name: &str,
) -> (Vec<f64>, Vec<u64>, f64, u64) {
let metric = find_metric(resource_metrics, name).expect("metric should exist");
match metric.data() {
AggregatedMetrics::F64(data) => match data {
MetricData::Histogram(histogram) => {
let points: Vec<_> = histogram.data_points().collect();
assert_eq!(points.len(), 1);
let point = points[0];
let bounds = point.bounds().collect();
let bucket_counts = point.bucket_counts().collect();
(bounds, bucket_counts, point.sum(), point.count())
}
_ => panic!("unexpected histogram aggregation"),
},
_ => panic!("unexpected metric data type"),
}
}

View File

@@ -0,0 +1,126 @@
//! Exercises global operation buffering across shutdown and rejected configuration changes.
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_otel::MetricsClient;
use codex_otel::MetricsConfig;
use codex_otel::OtelExporter;
use codex_otel::OtelHttpProtocol;
use codex_otel::OtelProvider;
use codex_otel::OtelSettings;
use codex_otel::install_global_metrics;
use codex_otel::record_global_operation;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::time::Duration;
fn install() -> MetricsClient {
install_global_metrics(
MetricsClient::new(
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
)
.expect("build in-memory metrics"),
)
}
fn observe() {
record_global_operation(
"test.operations",
"test.duration",
Duration::from_millis(/*millis*/ 7),
&[],
)
.expect("record an operation");
}
fn totals(metrics: &MetricsClient) -> (u64, u64, f64) {
let snapshot = metrics.snapshot().expect("collect runtime metrics");
let mut totals = (0, 0, 0.0);
for metric in snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
{
match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => {
totals.0 += sum
.data_points()
.map(opentelemetry_sdk::metrics::data::SumDataPoint::value)
.sum::<u64>();
}
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => {
for point in histogram.data_points() {
totals.1 += point.count();
totals.2 += point.sum();
}
}
_ => panic!("unexpected metric"),
}
}
totals
}
#[test]
fn shutdown_buffers_until_replacement_and_preserves_newer_installations() {
let first = install();
first.shutdown().unwrap();
observe();
let second = install();
assert_eq!(totals(&second), (1, 1, 7.0));
let third = install();
second.shutdown().unwrap();
observe();
assert_eq!(totals(&third), (1, 1, 7.0));
third.shutdown().unwrap();
}
#[test]
fn rejected_opt_out_preserves_recording_and_accepted_opt_out_survives_shutdown() {
let metrics = install();
let mut settings = OtelSettings {
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
environment: "test".to_string(),
service_name: "test".to_string(),
service_version: "1".to_string(),
codex_home: ".".into(),
exporter: OtelExporter::None,
trace_exporter: OtelExporter::OtlpHttp {
endpoint: "http://127.0.0.1:1/v1/traces".to_string(),
headers: Default::default(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
metrics_exporter: OtelExporter::None,
runtime_metrics: false,
span_attributes: HashMap::from([(String::new(), "invalid".to_string())]),
tracestate: BTreeMap::new(),
};
assert_eq!(
OtelProvider::try_new(&settings).err().unwrap().to_string(),
"configured span attribute key must not be empty"
);
observe();
assert_eq!(totals(&metrics), (1, 1, 7.0));
metrics.shutdown().unwrap();
observe();
assert!(OtelProvider::try_new(&settings).is_err());
let replacement = install();
assert_eq!(totals(&replacement), (1, 1, 7.0));
replacement.shutdown().unwrap();
settings.span_attributes.clear();
for trace_exporter in [settings.trace_exporter.clone(), OtelExporter::None] {
let metrics = install();
settings.trace_exporter = trace_exporter;
let _provider = OtelProvider::try_new(&settings).unwrap();
metrics.shutdown().unwrap();
observe();
let replacement = install();
assert_eq!(totals(&replacement), (0, 0, 0.0));
replacement.shutdown().unwrap();
}
}

View File

@@ -0,0 +1,427 @@
use crate::harness::attributes_to_map;
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;
use codex_otel::SessionTelemetry;
use codex_otel::TOOL_CALL_COUNT_METRIC;
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;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::time::Duration;
#[test]
fn tool_metrics_keep_product_skus_separate_on_a_shared_client() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
let manager = 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);
let mut expected_counts = BTreeMap::new();
let mut expected_durations = BTreeMap::new();
for (sku, expected_sku, success, duration_ms) in [
(Some("codex"), Some("codex"), true, 11),
(Some("customer-specific-value"), Some("other"), false, 37),
(Some("another-unrecognized-value"), Some("other"), false, 41),
(Some(""), None, true, 43),
(None, None, true, 47),
] {
let telemetry = manager.clone().with_product_sku(sku);
telemetry.tool_result_with_tags(
&ToolName::plain("spawn_agent"),
"call-1",
"{}",
Duration::from_millis(duration_ms),
success,
"result",
&[("sandbox", "workspace")],
&[],
);
let mut labels = BTreeMap::from([
("tool".to_string(), "spawn_agent".to_string()),
("success".to_string(), success.to_string()),
("sandbox".to_string(), "workspace".to_string()),
]);
if let Some(sku) = expected_sku {
labels.insert("product_sku".to_string(), sku.to_string());
}
*expected_counts.entry(labels.clone()).or_insert(0) += 1;
let (count, sum) = expected_durations.entry(labels).or_insert((0, 0.0));
*count += 1;
*sum += duration_ms as f64;
}
manager.shutdown_metrics()?;
let resource_metrics = latest_metrics(&exporter);
let counter = find_metric(&resource_metrics, TOOL_CALL_COUNT_METRIC).expect("tool counter");
let AggregatedMetrics::U64(MetricData::Sum(sum)) = counter.data() else {
panic!("expected tool counter");
};
assert_eq!(
sum.data_points()
.map(|point| (attributes_to_map(point.attributes()), point.value()))
.collect::<BTreeMap<_, _>>(),
expected_counts,
);
let duration =
find_metric(&resource_metrics, TOOL_CALL_DURATION_METRIC).expect("tool duration");
let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = duration.data() else {
panic!("expected tool duration histogram");
};
assert_eq!(
histogram
.data_points()
.map(|point| (
attributes_to_map(point.attributes()),
(point.count(), point.sum()),
))
.collect::<BTreeMap<_, _>>(),
expected_durations,
);
Ok(())
}
// Ensures SessionTelemetry attaches metadata tags when forwarding metrics.
#[test]
fn manager_attaches_metadata_tags_to_metrics() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[("service", "codex-cli")])?;
let manager = SessionTelemetry::new(
ThreadId::new(),
"gpt-5.1",
"gpt-5.1",
Some("account-id".to_string()),
/*account_email*/ None,
Some(TelemetryAuthMode::ApiKey),
"test_originator".to_string(),
/*log_user_prompts*/ true,
"tty".to_string(),
SessionSource::Cli,
)
.with_metrics(metrics);
manager.counter(
"codex.session_started",
/*inc*/ 1,
&[("source", "tui")],
);
for tokens in [32_000, 256_000] {
manager.histogram_with_boundaries(
"codex.request_tokens",
tokens,
&[16_000.0, 128_000.0, 512_000.0],
&[("source", "tui")],
);
}
manager.shutdown_metrics()?;
let resource_metrics = latest_metrics(&exporter);
assert_eq!(
histogram_data(&resource_metrics, "codex.request_tokens"),
(
vec![16_000.0, 128_000.0, 512_000.0],
vec![0, 1, 1, 0],
288_000.0,
2,
)
);
let metric =
find_metric(&resource_metrics, "codex.session_started").expect("counter metric missing");
let attrs = match metric.data() {
AggregatedMetrics::U64(data) => match data {
MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
attributes_to_map(points[0].attributes())
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
let expected = BTreeMap::from([
(
"app.version".to_string(),
env!("CARGO_PKG_VERSION").to_string(),
),
(
"auth_mode".to_string(),
TelemetryAuthMode::ApiKey.to_string(),
),
("model".to_string(), "gpt-5.1".to_string()),
("originator".to_string(), "test_originator".to_string()),
("service".to_string(), "codex-cli".to_string()),
("session_source".to_string(), "cli".to_string()),
("source".to_string(), "tui".to_string()),
]);
assert_eq!(attrs, expected);
Ok(())
}
// Ensures metadata tagging can be disabled when recording via SessionTelemetry.
#[test]
fn manager_allows_disabling_metadata_tags() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
let manager = SessionTelemetry::new(
ThreadId::new(),
"gpt-4o",
"gpt-4o",
Some("account-id".to_string()),
/*account_email*/ None,
Some(TelemetryAuthMode::ApiKey),
"test_originator".to_string(),
/*log_user_prompts*/ true,
"tty".to_string(),
SessionSource::Cli,
)
.with_metrics_without_metadata_tags(metrics);
manager.counter(
"codex.session_started",
/*inc*/ 1,
&[("source", "tui")],
);
manager.shutdown_metrics()?;
let resource_metrics = latest_metrics(&exporter);
let metric =
find_metric(&resource_metrics, "codex.session_started").expect("counter metric missing");
let attrs = match metric.data() {
AggregatedMetrics::U64(data) => match data {
MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
attributes_to_map(points[0].attributes())
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
let expected = BTreeMap::from([("source".to_string(), "tui".to_string())]);
assert_eq!(attrs, expected);
Ok(())
}
#[test]
fn manager_attaches_optional_service_name_tag() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
let manager = 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_service_name("my_app_server_client")
.with_metrics(metrics);
manager.counter("codex.session_started", /*inc*/ 1, &[]);
manager.shutdown_metrics()?;
let resource_metrics = latest_metrics(&exporter);
let metric =
find_metric(&resource_metrics, "codex.session_started").expect("counter metric missing");
let attrs = match metric.data() {
AggregatedMetrics::U64(data) => match data {
MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
attributes_to_map(points[0].attributes())
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
assert_eq!(
attrs.get("service_name"),
Some(&"my_app_server_client".to_string())
);
Ok(())
}
#[test]
fn manager_records_plugin_install_suggestion_metric() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
let manager = SessionTelemetry::new(
ThreadId::new(),
"gpt-5.1",
"gpt-5.1",
Some("account-id".to_string()),
/*account_email*/ None,
Some(TelemetryAuthMode::ApiKey),
"test_originator".to_string(),
/*log_user_prompts*/ false,
"tty".to_string(),
SessionSource::Cli,
)
.with_metrics_without_metadata_tags(metrics);
manager.record_plugin_install_suggestion(
"connector",
"connector_calendar",
"Google Calendar",
"accept",
/*user_confirmed*/ true,
/*completed*/ false,
);
manager.shutdown_metrics()?;
let resource_metrics = latest_metrics(&exporter);
let metric = find_metric(&resource_metrics, PLUGIN_INSTALL_SUGGESTION_METRIC)
.expect("plugin install suggestion metric missing");
let attrs = match metric.data() {
AggregatedMetrics::U64(data) => match data {
MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
attributes_to_map(points[0].attributes())
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
assert_eq!(
attrs,
BTreeMap::from([
("completed".to_string(), "false".to_string()),
("response_action".to_string(), "accept".to_string()),
("tool_type".to_string(), "connector".to_string()),
])
);
Ok(())
}
#[test]
fn manager_records_plugin_install_elicitation_sent_metric() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
let manager = SessionTelemetry::new(
ThreadId::new(),
"gpt-5.1",
"gpt-5.1",
Some("account-id".to_string()),
/*account_email*/ None,
Some(TelemetryAuthMode::ApiKey),
"test_originator".to_string(),
/*log_user_prompts*/ false,
"tty".to_string(),
SessionSource::Cli,
)
.with_metrics_without_metadata_tags(metrics);
manager.record_plugin_install_elicitation_sent("plugin", "slack@openai-curated", "Slack");
manager.shutdown_metrics()?;
let resource_metrics = latest_metrics(&exporter);
let metric = find_metric(&resource_metrics, PLUGIN_INSTALL_ELICITATION_SENT_METRIC)
.expect("plugin install elicitation sent metric missing");
let attrs = match metric.data() {
AggregatedMetrics::U64(data) => match data {
MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
attributes_to_map(points[0].attributes())
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
assert_eq!(
attrs,
BTreeMap::from([("tool_type".to_string(), "plugin".to_string())])
);
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(())
}

View File

@@ -0,0 +1,10 @@
#[path = "buffered_operations_tests.rs"]
mod buffered_operations;
mod manager_metrics;
mod otel_export_routing_policy;
mod otlp_http_loopback;
mod runtime_summary;
mod send;
mod snapshot;
mod timing;
mod validation;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,947 @@
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_otel::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC;
use codex_otel::MetricsClient;
use codex_otel::MetricsConfig;
use codex_otel::OtelExporter;
use codex_otel::OtelHttpProtocol;
use codex_otel::OtelProvider;
use codex_otel::OtelSettings;
use codex_otel::Result;
use codex_otel::current_span_w3c_trace_context;
use codex_otel::set_parent_from_w3c_trace_context;
use codex_protocol::protocol::W3cTraceContext;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::io::Read as _;
use std::io::Write as _;
use std::net::TcpListener;
use std::net::TcpStream;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use tracing_subscriber::layer::SubscriberExt;
static TRACE_CONTEXT_CONFIG_LOCK: Mutex<()> = Mutex::new(());
struct CapturedRequest {
path: String,
content_type: Option<String>,
body: Vec<u8>,
}
fn read_http_request(
stream: &mut TcpStream,
) -> std::io::Result<(String, HashMap<String, String>, Vec<u8>)> {
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
let deadline = Instant::now() + Duration::from_secs(2);
let mut read_next = |buf: &mut [u8]| -> std::io::Result<usize> {
loop {
match stream.read(buf) {
Ok(n) => return Ok(n),
Err(err)
if err.kind() == std::io::ErrorKind::WouldBlock
|| err.kind() == std::io::ErrorKind::Interrupted =>
{
if Instant::now() >= deadline {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"timed out waiting for request data",
));
}
thread::sleep(Duration::from_millis(5));
}
Err(err) => return Err(err),
}
}
};
let mut buf = Vec::new();
let mut scratch = [0u8; 8192];
let header_end = loop {
let n = read_next(&mut scratch)?;
if n == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"EOF before headers",
));
}
buf.extend_from_slice(&scratch[..n]);
if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
break end;
}
if buf.len() > 1024 * 1024 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"headers too large",
));
}
};
let headers_bytes = &buf[..header_end];
let mut body_bytes = buf[header_end + 4..].to_vec();
let headers_str = std::str::from_utf8(headers_bytes).map_err(|err| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("headers not utf-8: {err}"),
)
})?;
let mut lines = headers_str.split("\r\n");
let start = lines.next().ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::InvalidData, "missing request line")
})?;
let mut parts = start.split_whitespace();
let _method = parts.next().unwrap_or_default();
let path = parts
.next()
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "missing path"))?
.to_string();
let mut headers = HashMap::new();
for line in lines {
let Some((k, v)) = line.split_once(':') else {
continue;
};
headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_string());
}
if let Some(len) = headers
.get("content-length")
.and_then(|v| v.parse::<usize>().ok())
{
while body_bytes.len() < len {
let n = read_next(&mut scratch)?;
if n == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"EOF before body complete",
));
}
body_bytes.extend_from_slice(&scratch[..n]);
if body_bytes.len() > len + 1024 * 1024 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"body too large",
));
}
}
body_bytes.truncate(len);
}
Ok((path, headers, body_bytes))
}
fn write_http_response(stream: &mut TcpStream, status: &str) -> std::io::Result<()> {
let response = format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
stream.write_all(response.as_bytes())?;
stream.flush()
}
#[test]
fn otlp_http_exporter_honors_cumulative_temporality_env() -> Result<()> {
// Isolate the environment setting from other tests, including under Bazel/libtest.
const CHILD_ENV: &str = "CODEX_OTEL_TEMPORALITY_TEST_CHILD";
if std::env::var_os(CHILD_ENV).is_none() {
let current_thread = thread::current();
let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
.args([
"--exact",
current_thread.name().expect("test name"),
"--nocapture",
])
.env(CHILD_ENV, "1")
.env(
"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",
"cumulative",
)
.env("OTEL_METRIC_EXPORT_INTERVAL", "60000")
.output()
.expect("run test with cumulative temporality configured");
assert!(
output.status.success(),
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
return Ok(());
}
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr = listener.local_addr().expect("local_addr");
listener.set_nonblocking(true).expect("set_nonblocking");
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
let server = thread::spawn(move || {
let mut captured = Vec::new();
let deadline = Instant::now() + Duration::from_secs(3);
while Instant::now() < deadline {
match listener.accept() {
Ok((mut stream, _)) => {
let result = read_http_request(&mut stream);
let _ = write_http_response(&mut stream, "202 Accepted");
if let Ok((path, headers, body)) = result {
captured.push(CapturedRequest {
path,
content_type: headers.get("content-type").cloned(),
body,
});
}
}
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(10));
}
Err(_) => break,
}
}
let _ = tx.send(captured);
});
let metrics = MetricsClient::new(MetricsConfig::otlp(
"test",
"codex-cli",
env!("CARGO_PKG_VERSION"),
OtelExporter::OtlpHttp {
endpoint: format!("http://{addr}/v1/metrics"),
headers: HashMap::new(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
))?;
metrics.counter("codex.turns", /*inc*/ 1, &[("source", "test")])?;
metrics.counter("codex.api_request", /*inc*/ 1, &[("status", "200")])?;
metrics.counter_with_description(
EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC,
"Client-side exec-server RPC attempts.",
/*inc*/ 1,
&[("method", "fs/readFile")],
)?;
metrics.record_duration(
"codex.api_request.duration_ms",
Duration::from_millis(100),
&[("status", "200")],
)?;
metrics.counter("codex.conversation.turn.count", /*inc*/ 1, &[])?;
metrics.record_duration(
"codex.responses_api_engine_iapi_ttft.duration_ms",
Duration::from_millis(100),
&[],
)?;
metrics.record_duration(
"codex.responses_api_engine_service_tbt.duration_ms",
Duration::from_millis(100),
&[],
)?;
metrics.record_duration(
"codex.responses_api_engine_service_ttft.duration_ms",
Duration::from_millis(100),
&[],
)?;
metrics.counter("codex.tool.call", /*inc*/ 1, &[("tool", "test")])?;
metrics.record_duration(
"codex.tool.call.duration_ms",
Duration::from_millis(42),
&[("tool", "test")],
)?;
metrics.histogram(
"codex.turn.token_usage",
/*value*/ 100,
&[("token_type", "total")],
)?;
metrics.gauge_with_description(
"codex.active",
"Number of active Codex operations.",
/*value*/ 1,
&[("component", "test")],
)?;
metrics.shutdown()?;
server.join().expect("server join");
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
let request = captured
.iter()
.find(|req| req.path == "/v1/metrics")
.expect("/v1/metrics request should be captured");
let content_type = request
.content_type
.as_deref()
.unwrap_or("<missing content-type>");
assert!(
content_type.starts_with("application/json"),
"unexpected content-type: {content_type}"
);
let payload: serde_json::Value = serde_json::from_slice(&request.body).expect("OTLP JSON");
let counter = payload["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]
.as_array()
.expect("exported metrics")
.iter()
.find(|metric| metric["name"] == "codex.turns")
.expect("exported counter");
assert_eq!(
counter["sum"]["aggregationTemporality"],
serde_json::json!(2)
);
let body = String::from_utf8_lossy(&request.body);
assert!(
body.contains("codex.turns"),
"expected metric name not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("codex.active"),
"expected gauge not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("\"codex.api_request\""),
"expected API-request counter not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains(EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC),
"custom OTLP must retain the exec-server client counter excluded from built-in Statsig"
);
assert!(
body.contains("\"codex.api_request.duration_ms\""),
"expected API-request duration not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("\"codex.conversation.turn.count\""),
"expected conversation turn count not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("\"codex.responses_api_engine_iapi_ttft.duration_ms\""),
"expected engine IAPI TTFT duration not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("\"codex.responses_api_engine_service_tbt.duration_ms\""),
"expected engine service TBT duration not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("\"codex.responses_api_engine_service_ttft.duration_ms\""),
"expected engine service TTFT duration not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("\"codex.tool.call\""),
"expected tool-call counter not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("\"codex.turn.token_usage\""),
"expected turn-token histogram not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("\"codex.tool.call.duration_ms\""),
"expected tool-call duration not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("component") && body.contains("test"),
"expected gauge tag not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
Ok(())
}
#[test]
fn otlp_http_exporter_sends_logs_to_collector()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr = listener.local_addr().expect("local_addr");
listener.set_nonblocking(true).expect("set_nonblocking");
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
let server = thread::spawn(move || {
let mut captured = Vec::new();
let deadline = Instant::now() + Duration::from_secs(3);
while Instant::now() < deadline {
match listener.accept() {
Ok((mut stream, _)) => {
let result = read_http_request(&mut stream);
let _ = write_http_response(&mut stream, "202 Accepted");
if let Ok((path, headers, body)) = result {
captured.push(CapturedRequest {
path,
content_type: headers.get("content-type").cloned(),
body,
});
}
}
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(10));
}
Err(_) => break,
}
}
let _ = tx.send(captured);
});
let otel = OtelProvider::try_new(&OtelSettings {
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
environment: "test".to_string(),
service_name: "codex-cli".to_string(),
service_version: env!("CARGO_PKG_VERSION").to_string(),
codex_home: PathBuf::from("."),
exporter: OtelExporter::OtlpHttp {
endpoint: format!("http://{addr}/v1/logs"),
headers: HashMap::new(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
trace_exporter: OtelExporter::None,
metrics_exporter: OtelExporter::None,
runtime_metrics: false,
span_attributes: HashMap::new(),
tracestate: BTreeMap::new(),
})?
.expect("otel provider");
let logger_layer = otel.logger_layer().expect("logger layer");
let subscriber = tracing_subscriber::registry().with(logger_layer);
tracing::subscriber::with_default(subscriber, || {
tracing::callsite::rebuild_interest_cache();
tracing::event!(
target: "codex_otel.log_only",
tracing::Level::INFO,
event.name = "codex.test.log_exported",
"test OTEL log export"
);
});
otel.shutdown();
server.join().expect("server join");
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
let request = captured
.iter()
.find(|req| req.path == "/v1/logs")
.expect("/v1/logs request should be captured");
let content_type = request
.content_type
.as_deref()
.unwrap_or("<missing content-type>");
assert!(
content_type.starts_with("application/json"),
"unexpected content-type: {content_type}"
);
let body = String::from_utf8_lossy(&request.body);
assert!(
body.contains("codex.test.log_exported"),
"expected exported log event not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
Ok(())
}
#[test]
fn otel_provider_rejects_header_unsafe_configured_tracestate() {
let result = OtelProvider::try_new(&OtelSettings {
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
environment: "test".to_string(),
service_name: "codex-cli".to_string(),
service_version: env!("CARGO_PKG_VERSION").to_string(),
codex_home: PathBuf::from("."),
exporter: OtelExporter::None,
trace_exporter: OtelExporter::OtlpHttp {
endpoint: "http://127.0.0.1:1/v1/traces".to_string(),
headers: HashMap::new(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
metrics_exporter: OtelExporter::None,
runtime_metrics: false,
span_attributes: HashMap::new(),
tracestate: BTreeMap::from([(
"example".to_string(),
BTreeMap::from([("alpha".to_string(), "one\ntwo".to_string())]),
)]),
});
let err = result
.err()
.expect("header-unsafe configured tracestate should be rejected");
assert!(err.to_string().contains("configured tracestate value"));
}
#[test]
fn otlp_http_exporter_sends_traces_to_collector()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr = listener.local_addr().expect("local_addr");
listener.set_nonblocking(true).expect("set_nonblocking");
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
let server = thread::spawn(move || {
let mut captured = Vec::new();
let deadline = Instant::now() + Duration::from_secs(3);
while Instant::now() < deadline {
match listener.accept() {
Ok((mut stream, _)) => {
let result = read_http_request(&mut stream);
let _ = write_http_response(&mut stream, "202 Accepted");
if let Ok((path, headers, body)) = result {
captured.push(CapturedRequest {
path,
content_type: headers.get("content-type").cloned(),
body,
});
}
}
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(10));
}
Err(_) => break,
}
}
let _ = tx.send(captured);
});
let otel = OtelProvider::try_new(&OtelSettings {
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
environment: "test".to_string(),
service_name: "codex-cli".to_string(),
service_version: env!("CARGO_PKG_VERSION").to_string(),
codex_home: PathBuf::from("."),
exporter: OtelExporter::None,
trace_exporter: OtelExporter::OtlpHttp {
endpoint: format!("http://{addr}/v1/traces"),
headers: HashMap::new(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
metrics_exporter: OtelExporter::None,
runtime_metrics: false,
span_attributes: HashMap::from([(
"test.configured_attribute".to_string(),
"configured-value".to_string(),
)]),
tracestate: BTreeMap::from([(
"example".to_string(),
BTreeMap::from([
("alpha".to_string(), "one".to_string()),
("beta".to_string(), "two".to_string()),
]),
)]),
})?
.expect("otel provider");
let tracing_layer = otel.tracing_layer().expect("tracing layer");
let subscriber = tracing_subscriber::registry().with(tracing_layer);
let propagated_trace = tracing::subscriber::with_default(subscriber, || {
let span = tracing::info_span!(
"trace-loopback",
otel.name = "trace-loopback",
otel.kind = "server",
rpc.system = "jsonrpc",
rpc.method = "trace-loopback",
);
assert!(set_parent_from_w3c_trace_context(
&span,
&W3cTraceContext {
traceparent: Some(
"00-00000000000000000000000000000001-0000000000000002-01".to_string(),
),
tracestate: Some("example=alpha:zero;keep:yes,other=value".to_string()),
},
));
let _guard = span.enter();
let propagated_trace =
current_span_w3c_trace_context().expect("current span should have trace context");
tracing::event!(
target: "codex_otel.trace_safe",
tracing::Level::INFO,
event.name = "codex.test.trace_event",
"test OTEL trace event"
);
tracing::info!("trace loopback event");
propagated_trace
});
otel.shutdown();
assert_eq!(
propagated_trace.tracestate.as_deref(),
Some("example=alpha:one;keep:yes;beta:two,other=value")
);
server.join().expect("server join");
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
let request = captured
.iter()
.find(|req| req.path == "/v1/traces")
.expect("/v1/traces request should be captured");
let content_type = request
.content_type
.as_deref()
.unwrap_or("<missing content-type>");
assert!(
content_type.starts_with("application/json"),
"unexpected content-type: {content_type}"
);
let body = String::from_utf8_lossy(&request.body);
assert!(
body.contains("trace-loopback"),
"expected span name not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("codex-cli"),
"expected service name not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("test.configured_attribute") && body.contains("configured-value"),
"expected configured span attribute not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("codex.test.trace_event"),
"expected trace event not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn otlp_http_exporter_sends_traces_to_collector_with_bounded_shutdown_in_tokio_runtime()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr = listener.local_addr().expect("local_addr");
listener.set_nonblocking(true).expect("set_nonblocking");
let otel = OtelProvider::try_new(&OtelSettings {
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
environment: "test".to_string(),
service_name: "codex-cli".to_string(),
service_version: env!("CARGO_PKG_VERSION").to_string(),
codex_home: PathBuf::from("."),
exporter: OtelExporter::None,
trace_exporter: OtelExporter::OtlpHttp {
endpoint: format!("http://{addr}/v1/traces"),
headers: HashMap::new(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
metrics_exporter: OtelExporter::None,
runtime_metrics: false,
span_attributes: HashMap::new(),
tracestate: BTreeMap::new(),
})?
.expect("otel provider");
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
let (stop_tx, stop_rx) = mpsc::channel();
let server = thread::spawn(move || {
let mut captured = Vec::new();
let deadline = Instant::now() + Duration::from_secs(3);
while Instant::now() < deadline {
match stop_rx.try_recv() {
Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
Err(mpsc::TryRecvError::Empty) => {}
}
match listener.accept() {
Ok((mut stream, _)) => {
let result = read_http_request(&mut stream);
let _ = write_http_response(&mut stream, "202 Accepted");
if let Ok((path, headers, body)) = result {
captured.push(CapturedRequest {
path,
content_type: headers.get("content-type").cloned(),
body,
});
}
}
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(10));
}
Err(_) => break,
}
}
let _ = tx.send(captured);
});
let tracing_layer = otel.tracing_layer().expect("tracing layer");
let subscriber = tracing_subscriber::registry().with(tracing_layer);
tracing::subscriber::with_default(subscriber, || {
let span = tracing::info_span!(
"trace-loopback-tokio",
otel.name = "trace-loopback-tokio",
otel.kind = "server",
rpc.system = "jsonrpc",
rpc.method = "trace-loopback-tokio",
);
let _guard = span.enter();
tracing::info!("trace loopback event from tokio runtime");
});
let shutdown_result = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(otel.shutdown_with_timeout(Duration::from_secs(/*secs*/ 2)))
});
let _ = stop_tx.send(());
server.join().expect("server join");
shutdown_result?;
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
let request = captured
.iter()
.find(|req| req.path == "/v1/traces")
.expect("/v1/traces request should be captured");
let content_type = request
.content_type
.as_deref()
.unwrap_or("<missing content-type>");
assert!(
content_type.starts_with("application/json"),
"unexpected content-type: {content_type}"
);
let body = String::from_utf8_lossy(&request.body);
assert!(
body.contains("trace-loopback-tokio"),
"expected span name not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("codex-cli"),
"expected service name not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
Ok(())
}
#[test]
fn otlp_http_exporter_times_out_when_collector_stalls_during_bounded_shutdown() {
let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr = listener.local_addr().expect("local_addr");
let (request_started_tx, request_started_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept trace request");
let (path, _, _) = read_http_request(&mut stream).expect("read trace request");
request_started_tx.send(path).expect("request started");
release_rx
.recv_timeout(Duration::from_secs(/*secs*/ 2))
.expect("collector released");
write_http_response(&mut stream, "202 Accepted").expect("write trace response");
});
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("build tokio runtime");
let (result, elapsed) = runtime.block_on(async move {
let otel = OtelProvider::try_new(&OtelSettings {
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
environment: "test".to_string(),
service_name: "codex-cli".to_string(),
service_version: env!("CARGO_PKG_VERSION").to_string(),
codex_home: PathBuf::from("."),
exporter: OtelExporter::None,
trace_exporter: OtelExporter::OtlpHttp {
endpoint: format!("http://{addr}/v1/traces"),
headers: HashMap::new(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
metrics_exporter: OtelExporter::None,
runtime_metrics: false,
span_attributes: HashMap::new(),
tracestate: BTreeMap::new(),
})
.expect("build otel provider")
.expect("otel provider");
let tracing_layer = otel.tracing_layer().expect("tracing layer");
let subscriber = tracing_subscriber::registry().with(tracing_layer);
tracing::subscriber::with_default(subscriber, || {
let span = tracing::info_span!("trace-loopback-stalled");
let _guard = span.enter();
tracing::info!("trace loopback event for stalled collector");
});
let started = Instant::now();
let result = otel
.shutdown_with_timeout(Duration::from_millis(/*millis*/ 50))
.await;
(result, started.elapsed())
});
let path = request_started_rx
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("trace request reached collector");
release_tx.send(()).expect("release collector");
server.join().expect("server join");
runtime.shutdown_timeout(Duration::from_secs(/*secs*/ 1));
assert_eq!(path, "/v1/traces");
assert_eq!(
result.as_ref().map_err(std::io::Error::kind),
Err(std::io::ErrorKind::TimedOut)
);
assert!(
elapsed < Duration::from_secs(/*secs*/ 1),
"bounded shutdown blocked for {elapsed:?}"
);
}
#[test]
fn otlp_http_exporter_sends_traces_to_collector_in_current_thread_tokio_runtime()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let addr = listener.local_addr().expect("local_addr");
listener.set_nonblocking(true).expect("set_nonblocking");
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
let server = thread::spawn(move || {
let mut captured = Vec::new();
let deadline = Instant::now() + Duration::from_secs(3);
while Instant::now() < deadline {
match listener.accept() {
Ok((mut stream, _)) => {
let result = read_http_request(&mut stream);
let _ = write_http_response(&mut stream, "202 Accepted");
if let Ok((path, headers, body)) = result {
captured.push(CapturedRequest {
path,
content_type: headers.get("content-type").cloned(),
body,
});
}
}
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(10));
}
Err(_) => break,
}
}
let _ = tx.send(captured);
});
let (runtime_result_tx, runtime_result_rx) = mpsc::channel::<std::result::Result<(), String>>();
let runtime_thread = thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("current-thread runtime");
let result = runtime.block_on(async move {
let otel = OtelProvider::try_new(&OtelSettings {
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
environment: "test".to_string(),
service_name: "codex-cli".to_string(),
service_version: env!("CARGO_PKG_VERSION").to_string(),
codex_home: PathBuf::from("."),
exporter: OtelExporter::None,
trace_exporter: OtelExporter::OtlpHttp {
endpoint: format!("http://{addr}/v1/traces"),
headers: HashMap::new(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
metrics_exporter: OtelExporter::None,
runtime_metrics: false,
span_attributes: HashMap::new(),
tracestate: BTreeMap::new(),
})
.map_err(|err| err.to_string())?
.expect("otel provider");
let tracing_layer = otel.tracing_layer().expect("tracing layer");
let subscriber = tracing_subscriber::registry().with(tracing_layer);
tracing::subscriber::with_default(subscriber, || {
let span = tracing::info_span!(
"trace-loopback-current-thread",
otel.name = "trace-loopback-current-thread",
otel.kind = "server",
rpc.system = "jsonrpc",
rpc.method = "trace-loopback-current-thread",
);
let _guard = span.enter();
tracing::info!("trace loopback event from current-thread tokio runtime");
});
otel.shutdown();
Ok::<(), String>(())
});
let _ = runtime_result_tx.send(result);
});
runtime_result_rx
.recv_timeout(Duration::from_secs(5))
.expect("current-thread runtime should complete")
.map_err(std::io::Error::other)?;
runtime_thread.join().expect("runtime thread");
server.join().expect("server join");
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
let request = captured
.iter()
.find(|req| req.path == "/v1/traces")
.expect("/v1/traces request should be captured");
let content_type = request
.content_type
.as_deref()
.unwrap_or("<missing content-type>");
assert!(
content_type.starts_with("application/json"),
"unexpected content-type: {content_type}"
);
let body = String::from_utf8_lossy(&request.body);
assert!(
body.contains("trace-loopback-current-thread"),
"expected span name not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
assert!(
body.contains("codex-cli"),
"expected service name not found; body prefix: {}",
&body.chars().take(2000).collect::<String>()
);
Ok(())
}

View File

@@ -0,0 +1,140 @@
use codex_otel::MetricsClient;
use codex_otel::MetricsConfig;
use codex_otel::Result;
use codex_otel::RuntimeMetricTotals;
use codex_otel::RuntimeMetricsSummary;
use codex_otel::SessionTelemetry;
use codex_otel::TelemetryAuthMode;
use codex_protocol::ThreadId;
use codex_protocol::ToolName;
use codex_protocol::protocol::SessionSource;
use eventsource_stream::Event as StreamEvent;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use pretty_assertions::assert_eq;
use std::time::Duration;
#[test]
fn runtime_metrics_summary_collects_tool_api_and_streaming_metrics() -> Result<()> {
let exporter = InMemoryMetricExporter::default();
let metrics = MetricsClient::new(
MetricsConfig::in_memory("test", "codex-cli", env!("CARGO_PKG_VERSION"), exporter)
.with_runtime_reader(),
)?;
let manager = SessionTelemetry::new(
ThreadId::new(),
"gpt-5.1",
"gpt-5.1",
Some("account-id".to_string()),
/*account_email*/ None,
Some(TelemetryAuthMode::ApiKey),
"test_originator".to_string(),
/*log_user_prompts*/ true,
"tty".to_string(),
SessionSource::Cli,
)
.with_metrics(metrics);
manager.reset_runtime_metrics();
manager.tool_result_with_tags(
&ToolName::plain("shell"),
"call-1",
"{\"cmd\":\"echo\"}",
Duration::from_millis(250),
/*success*/ true,
"ok",
&[],
/*extra_trace_fields*/ &[],
);
manager.record_api_request(
/*attempt*/ 1,
Some(200),
/*error*/ None,
Duration::from_millis(300),
/*auth_header_attached*/ false,
/*auth_header_name*/ None,
/*retry_after_unauthorized*/ false,
/*recovery_mode*/ None,
/*recovery_phase*/ None,
"/responses",
/*request_id*/ None,
/*cf_ray*/ None,
/*auth_error*/ None,
/*auth_error_code*/ None,
/*agent_identity_telemetry*/ None,
);
manager.record_websocket_request(
Duration::from_millis(400),
/*error*/ None,
/*connection_reused*/ false,
/*agent_identity_telemetry*/ None,
);
let sse_response: std::result::Result<
Option<std::result::Result<StreamEvent, eventsource_stream::EventStreamError<&str>>>,
tokio::time::error::Elapsed,
> = Ok(Some(Ok(StreamEvent {
event: "response.created".to_string(),
data: "{}".to_string(),
id: String::new(),
retry: None,
})));
manager.log_sse_event(&sse_response, Duration::from_millis(120));
manager.record_websocket_text_event(
r#"{"type":"response.created"}"#,
Some("response.created"),
Duration::from_millis(80),
);
manager.record_websocket_text_event(
r#"{"type":"responsesapi.websocket_timing","timing_metrics":{"responses_duration_excl_engine_and_client_tool_time_ms":124.25,"engine_service_total_ms":457,"engine_iapi_ttft_total_ms":211,"engine_service_ttft_total_ms":233,"engine_iapi_tbt_across_engine_calls_ms":2.450638,"engine_service_tbt_across_engine_calls_ms":5.267279}}"#,
Some("responsesapi.websocket_timing"),
Duration::from_millis(20),
);
manager.record_websocket_receive_failure(Duration::from_millis(10));
manager.record_duration(
"codex.turn.ttft.duration_ms",
Duration::from_millis(95),
&[],
);
manager.record_duration(
"codex.turn.ttfm.duration_ms",
Duration::from_millis(180),
&[],
);
let summary = manager
.runtime_metrics_summary()
.expect("runtime metrics summary should be available");
let expected = RuntimeMetricsSummary {
tool_calls: RuntimeMetricTotals {
count: 1,
duration_ms: 250,
},
api_calls: RuntimeMetricTotals {
count: 1,
duration_ms: 300,
},
streaming_events: RuntimeMetricTotals {
count: 1,
duration_ms: 120,
},
websocket_calls: RuntimeMetricTotals {
count: 1,
duration_ms: 400,
},
websocket_events: RuntimeMetricTotals {
count: 3,
duration_ms: 110,
},
responses_api_overhead_ms: 124,
responses_api_inference_time_ms: 457,
responses_api_engine_iapi_ttft_ms: 211,
responses_api_engine_service_ttft_ms: 233,
responses_api_engine_iapi_tbt_ms: 2.450638,
responses_api_engine_service_tbt_ms: 5.267279,
turn_ttft_ms: 95,
turn_ttfm_ms: 180,
};
assert_eq!(summary, expected);
Ok(())
}

View File

@@ -0,0 +1,360 @@
use crate::harness::attributes_to_map;
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::ADDITIONAL_CONTEXT_VALUE_BYTES_BUCKETS;
use codex_otel::ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC;
use codex_otel::Result;
use codex_otel::THREAD_SKILLS_COUNT_METRIC_BUCKETS;
use codex_otel::THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_BUCKETS;
use codex_otel::THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC;
use codex_otel::THREAD_SKILLS_ENABLED_TOTAL_METRIC;
use codex_otel::THREAD_SKILLS_TRUNCATED_BUCKETS;
use codex_otel::THREAD_SKILLS_TRUNCATED_METRIC;
use codex_otel::THREAD_TOOLS_FRAGMENT_BYTES_METRIC;
use codex_otel::THREAD_TOOLS_METRIC_BUCKETS;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
// Ensures counters/histograms render with default + per-call tags.
#[test]
fn send_builds_payload_with_tags_and_histograms() -> Result<()> {
let (metrics, exporter) =
build_metrics_with_defaults(&[("service", "codex-cli"), ("env", "prod")])?;
metrics.counter_with_description(
"codex.turns",
"Total number of Codex turns.",
/*inc*/ 1,
&[("model", "gpt-5.1"), ("env", "dev")],
)?;
metrics.histogram(
"codex.tool_latency",
/*value*/ 25,
&[("tool", "shell")],
)?;
metrics.gauge_with_description(
"codex.active",
"Number of active Codex operations.",
/*value*/ 2,
&[("component", "test")],
)?;
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
let counter = find_metric(&resource_metrics, "codex.turns").expect("counter metric missing");
assert_eq!(counter.description(), "Total number of Codex turns.");
let counter_attributes = match counter.data() {
opentelemetry_sdk::metrics::data::AggregatedMetrics::U64(data) => match data {
opentelemetry_sdk::metrics::data::MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
assert_eq!(points[0].value(), 1);
attributes_to_map(points[0].attributes())
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
let expected_counter_attributes = BTreeMap::from([
("service".to_string(), "codex-cli".to_string()),
("env".to_string(), "dev".to_string()),
("model".to_string(), "gpt-5.1".to_string()),
]);
assert_eq!(counter_attributes, expected_counter_attributes);
let (bounds, bucket_counts, sum, count) =
histogram_data(&resource_metrics, "codex.tool_latency");
assert!(!bounds.is_empty());
assert_eq!(bucket_counts.iter().sum::<u64>(), 1);
assert_eq!(sum, 25.0);
assert_eq!(count, 1);
let histogram_attrs = attributes_to_map(
find_metric(&resource_metrics, "codex.tool_latency")
.and_then(|metric| match metric.data() {
opentelemetry_sdk::metrics::data::AggregatedMetrics::F64(
opentelemetry_sdk::metrics::data::MetricData::Histogram(histogram),
) => histogram
.data_points()
.next()
.map(opentelemetry_sdk::metrics::data::HistogramDataPoint::attributes),
_ => None,
})
.expect("codex.tool_latency histogram attributes should exist"),
);
let expected_histogram_attributes = BTreeMap::from([
("service".to_string(), "codex-cli".to_string()),
("env".to_string(), "prod".to_string()),
("tool".to_string(), "shell".to_string()),
]);
assert_eq!(histogram_attrs, expected_histogram_attributes);
let gauge = find_metric(&resource_metrics, "codex.active").expect("gauge metric missing");
assert_eq!(gauge.description(), "Number of active Codex operations.");
let gauge_point = match gauge.data() {
opentelemetry_sdk::metrics::data::AggregatedMetrics::I64(data) => match data {
opentelemetry_sdk::metrics::data::MetricData::Gauge(gauge) => {
gauge.data_points().next().expect("gauge point")
}
_ => panic!("unexpected gauge aggregation"),
},
_ => panic!("unexpected gauge metric data type"),
};
assert_eq!(gauge_point.value(), 2);
assert_eq!(
attributes_to_map(gauge_point.attributes()),
BTreeMap::from([
("component".to_string(), "test".to_string()),
("env".to_string(), "prod".to_string()),
("service".to_string(), "codex-cli".to_string()),
])
);
Ok(())
}
#[test]
fn histogram_uses_explicit_bucket_boundaries() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
metrics.histogram_with_boundaries(
"codex.payload_bytes",
/*value*/ 1024,
&[256.0, 1024.0, 4096.0],
&[],
)?;
metrics.shutdown()?;
assert_eq!(
histogram_data(&latest_metrics(&exporter), "codex.payload_bytes"),
(vec![256.0, 1024.0, 4096.0], vec![0, 1, 0, 0], 1024.0, 1)
);
Ok(())
}
#[test]
fn additional_context_histogram_bounds_truncated_observations() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
let samples = [4_024, 4_027, 4_043];
for value in samples {
metrics.histogram_with_boundaries(
ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC,
value,
ADDITIONAL_CONTEXT_VALUE_BYTES_BUCKETS.as_slice(),
&[("stage", "after"), ("truncated", "true")],
)?;
}
metrics.shutdown()?;
let (bounds, counts, sum, count) = histogram_data(
&latest_metrics(&exporter),
ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC,
);
assert_eq!((sum, count), (12_094.0, 3));
assert_eq!(counts.iter().sum::<u64>(), count);
assert_eq!(counts.last(), Some(&0));
for (upper_bound, bucket_count) in bounds.iter().zip(&counts) {
assert!(
*bucket_count == 0 || *upper_bound <= 4_096.0,
"post-truncation observations landed in a bucket ending at {upper_bound} bytes"
);
}
Ok(())
}
#[test]
fn context_histograms_preserve_zero_and_family_ranges() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
let cases = [
(
THREAD_TOOLS_FRAGMENT_BYTES_METRIC,
THREAD_TOOLS_METRIC_BUCKETS.as_slice(),
32_768_i64,
512,
),
(
THREAD_SKILLS_ENABLED_TOTAL_METRIC,
THREAD_SKILLS_COUNT_METRIC_BUCKETS.as_slice(),
512,
514,
),
(
THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC,
THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_BUCKETS.as_slice(),
131_072,
512,
),
(
THREAD_SKILLS_TRUNCATED_METRIC,
THREAD_SKILLS_TRUNCATED_BUCKETS,
1,
3,
),
];
for (name, boundaries, maximum, _) in cases {
for value in [0, 1, maximum, maximum + 1] {
metrics.histogram_with_boundaries(name, value, boundaries, &[])?;
}
}
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
for (name, expected_bounds, maximum, bucket_count) in cases {
let (bounds, counts, sum, count) = histogram_data(&resource_metrics, name);
assert_eq!(bounds.as_slice(), expected_bounds);
assert_eq!(bounds.len(), bucket_count - 1);
assert_eq!(bounds[0], 0.0);
assert_eq!(bounds[1], 1.0);
assert_eq!(bounds[bucket_count - 2], maximum as f64);
assert!(bounds.windows(/*size*/ 2).all(|pair| pair[0] < pair[1]));
let mut expected_counts = vec![0; bucket_count];
for index in [0, 1, bucket_count - 2, bucket_count - 1] {
expected_counts[index] += 1;
}
assert_eq!(counts, expected_counts);
assert_eq!((sum, count), ((2 * maximum + 2) as f64, 4));
}
Ok(())
}
// Ensures defaults merge per line and overrides take precedence.
#[test]
fn send_merges_default_tags_per_line() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[
("service", "codex-cli"),
("env", "prod"),
("region", "us"),
])?;
metrics.counter(
"codex.alpha",
/*inc*/ 1,
&[("env", "dev"), ("component", "alpha")],
)?;
metrics.counter(
"codex.beta",
/*inc*/ 2,
&[("service", "worker"), ("component", "beta")],
)?;
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
let alpha_metric =
find_metric(&resource_metrics, "codex.alpha").expect("codex.alpha metric missing");
let alpha_point = match alpha_metric.data() {
opentelemetry_sdk::metrics::data::AggregatedMetrics::U64(data) => match data {
opentelemetry_sdk::metrics::data::MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
points[0]
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
assert_eq!(alpha_point.value(), 1);
let alpha_attrs = attributes_to_map(alpha_point.attributes());
let expected_alpha_attrs = BTreeMap::from([
("component".to_string(), "alpha".to_string()),
("env".to_string(), "dev".to_string()),
("region".to_string(), "us".to_string()),
("service".to_string(), "codex-cli".to_string()),
]);
assert_eq!(alpha_attrs, expected_alpha_attrs);
let beta_metric =
find_metric(&resource_metrics, "codex.beta").expect("codex.beta metric missing");
let beta_point = match beta_metric.data() {
opentelemetry_sdk::metrics::data::AggregatedMetrics::U64(data) => match data {
opentelemetry_sdk::metrics::data::MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
points[0]
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
assert_eq!(beta_point.value(), 2);
let beta_attrs = attributes_to_map(beta_point.attributes());
let expected_beta_attrs = BTreeMap::from([
("component".to_string(), "beta".to_string()),
("env".to_string(), "prod".to_string()),
("region".to_string(), "us".to_string()),
("service".to_string(), "worker".to_string()),
]);
assert_eq!(beta_attrs, expected_beta_attrs);
Ok(())
}
// Verifies enqueued metrics are delivered by the background worker.
#[test]
fn client_sends_enqueued_metric() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
metrics.counter("codex.turns", /*inc*/ 1, &[("model", "gpt-5.1")])?;
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
let counter = find_metric(&resource_metrics, "codex.turns").expect("counter metric missing");
let points = match counter.data() {
opentelemetry_sdk::metrics::data::AggregatedMetrics::U64(data) => match data {
opentelemetry_sdk::metrics::data::MetricData::Sum(sum) => {
sum.data_points().collect::<Vec<_>>()
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
assert_eq!(points.len(), 1);
let point = points[0];
assert_eq!(point.value(), 1);
let attrs = attributes_to_map(point.attributes());
assert_eq!(attrs.get("model").map(String::as_str), Some("gpt-5.1"));
Ok(())
}
// Ensures shutdown flushes successfully with in-memory exporters.
#[test]
fn shutdown_flushes_in_memory_exporter() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
metrics.counter("codex.turns", /*inc*/ 1, &[])?;
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
let counter = find_metric(&resource_metrics, "codex.turns").expect("counter metric missing");
let points = match counter.data() {
opentelemetry_sdk::metrics::data::AggregatedMetrics::U64(data) => match data {
opentelemetry_sdk::metrics::data::MetricData::Sum(sum) => {
sum.data_points().collect::<Vec<_>>()
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
assert_eq!(points.len(), 1);
Ok(())
}
// Ensures shutting down without recording metrics does not export anything.
#[test]
fn shutdown_without_metrics_exports_nothing() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
metrics.shutdown()?;
let finished = exporter.get_finished_metrics().unwrap();
assert!(finished.is_empty(), "expected no metrics exported");
Ok(())
}

View File

@@ -0,0 +1,222 @@
use crate::harness::attributes_to_map;
use crate::harness::find_metric;
use codex_otel::MetricsClient;
use codex_otel::MetricsConfig;
use codex_otel::Result;
use codex_otel::SessionTelemetry;
use codex_otel::TelemetryAuthMode;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionSource;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
#[test]
fn snapshot_collects_metrics_without_shutdown() -> Result<()> {
let exporter = InMemoryMetricExporter::default();
let config = MetricsConfig::in_memory(
"test",
"codex-cli",
env!("CARGO_PKG_VERSION"),
exporter.clone(),
)
.with_tag("service", "codex-cli")?
.with_runtime_reader();
let metrics = MetricsClient::new(config)?;
metrics.counter(
"codex.tool.call",
/*inc*/ 1,
&[("tool", "shell"), ("success", "true")],
)?;
let snapshot = metrics.snapshot()?;
let metric = find_metric(&snapshot, "codex.tool.call").expect("counter metric missing");
let attrs = match metric.data() {
AggregatedMetrics::U64(data) => match data {
MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
attributes_to_map(points[0].attributes())
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
let expected = BTreeMap::from([
("service".to_string(), "codex-cli".to_string()),
("success".to_string(), "true".to_string()),
("tool".to_string(), "shell".to_string()),
]);
assert_eq!(attrs, expected);
let finished = exporter
.get_finished_metrics()
.expect("finished metrics should be readable");
assert!(finished.is_empty(), "expected no periodic exports yet");
Ok(())
}
#[test]
fn observable_gauge_is_collected_on_every_delta_snapshot() -> Result<()> {
let exporter = InMemoryMetricExporter::default();
let config = MetricsConfig::in_memory("test", "codex-cli", env!("CARGO_PKG_VERSION"), exporter)
.with_runtime_reader();
let metrics = MetricsClient::new(config)?;
metrics.register_observable_gauge_with_description(
"codex.active",
"Number of active operations.",
|| 1,
&[("component", "test")],
)?;
for snapshot in [metrics.snapshot()?, metrics.snapshot()?] {
let gauge = find_metric(&snapshot, "codex.active").expect("gauge metric missing");
let point = match gauge.data() {
AggregatedMetrics::I64(MetricData::Gauge(gauge)) => {
gauge.data_points().next().expect("gauge point")
}
_ => panic!("unexpected gauge metric data type"),
};
assert_eq!(point.value(), 1);
assert_eq!(
attributes_to_map(point.attributes()),
BTreeMap::from([("component".to_string(), "test".to_string())])
);
}
metrics.shutdown()?;
Ok(())
}
#[test]
fn manager_snapshot_metrics_collects_without_shutdown() -> Result<()> {
let exporter = InMemoryMetricExporter::default();
let config = MetricsConfig::in_memory("test", "codex-cli", env!("CARGO_PKG_VERSION"), exporter)
.with_tag("service", "codex-cli")?
.with_runtime_reader();
let metrics = MetricsClient::new(config)?;
let manager = SessionTelemetry::new(
ThreadId::new(),
"gpt-5.1",
"gpt-5.1",
Some("account-id".to_string()),
/*account_email*/ None,
Some(TelemetryAuthMode::ApiKey),
"test_originator".to_string(),
/*log_user_prompts*/ true,
"tty".to_string(),
SessionSource::Cli,
)
.with_metrics(metrics);
manager.counter(
"codex.tool.call",
/*inc*/ 1,
&[("tool", "shell"), ("success", "true")],
);
let snapshot = manager.snapshot_metrics()?;
let metric = find_metric(&snapshot, "codex.tool.call").expect("counter metric missing");
let attrs = match metric.data() {
AggregatedMetrics::U64(data) => match data {
MetricData::Sum(sum) => {
let points: Vec<_> = sum.data_points().collect();
assert_eq!(points.len(), 1);
attributes_to_map(points[0].attributes())
}
_ => panic!("unexpected counter aggregation"),
},
_ => panic!("unexpected counter data type"),
};
let expected = BTreeMap::from([
(
"app.version".to_string(),
env!("CARGO_PKG_VERSION").to_string(),
),
(
"auth_mode".to_string(),
TelemetryAuthMode::ApiKey.to_string(),
),
("model".to_string(), "gpt-5.1".to_string()),
("originator".to_string(), "test_originator".to_string()),
("service".to_string(), "codex-cli".to_string()),
("session_source".to_string(), "cli".to_string()),
("success".to_string(), "true".to_string()),
("tool".to_string(), "shell".to_string()),
]);
assert_eq!(attrs, expected);
Ok(())
}
#[test]
fn manager_turn_cost_records_microusd_metric() -> Result<()> {
let exporter = InMemoryMetricExporter::default();
let config = MetricsConfig::in_memory("test", "codex-cli", env!("CARGO_PKG_VERSION"), exporter)
.with_runtime_reader();
let metrics = MetricsClient::new(config)?;
let thread_id = ThreadId::new();
let conversation_id = thread_id.to_string();
let manager = SessionTelemetry::new(
thread_id,
"gpt-5.6",
"gpt-5.6",
/*account_id*/ None,
/*account_email*/ None,
Some(TelemetryAuthMode::ApiKey),
"test_originator".to_string(),
/*log_user_prompts*/ false,
"tty".to_string(),
SessionSource::Cli,
)
.with_metrics(metrics);
manager.record_turn_cost(
"turn-123",
"0.0001245",
/*interrupted*/ false,
Some("fast"),
Some("high"),
);
let snapshot = manager.snapshot_metrics()?;
let metric = find_metric(&snapshot, "codex.turn.cost_microusd")
.expect("turn-cost microdollar metric missing");
let point = match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => {
sum.data_points().next().expect("turn-cost data point")
}
_ => panic!("unexpected turn-cost metric data type"),
};
assert_eq!(point.value(), 125);
assert_eq!(
attributes_to_map(point.attributes()),
BTreeMap::from([
(
"app.version".to_string(),
env!("CARGO_PKG_VERSION").to_string(),
),
(
"auth_mode".to_string(),
TelemetryAuthMode::ApiKey.to_string(),
),
("conversation.id".to_string(), conversation_id),
("model".to_string(), "gpt-5.6".to_string()),
("originator".to_string(), "test_originator".to_string()),
("reasoning_effort".to_string(), "high".to_string()),
("session_source".to_string(), "cli".to_string()),
("speed".to_string(), "fast".to_string()),
("turn.id".to_string(), "turn-123".to_string()),
("turn.interrupted".to_string(), "false".to_string()),
])
);
Ok(())
}

View File

@@ -0,0 +1,144 @@
use crate::harness::attributes_to_map;
use crate::harness::build_metrics_with_defaults;
use crate::harness::histogram_data;
use crate::harness::latest_metrics;
use codex_otel::Result;
use pretty_assertions::assert_eq;
use std::time::Duration;
// Ensures duration recording maps to histogram output.
#[test]
fn record_duration_records_histogram() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
metrics.record_duration(
"codex.request_latency",
Duration::from_millis(15),
&[("route", "chat")],
)?;
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
let (bounds, bucket_counts, sum, count) =
histogram_data(&resource_metrics, "codex.request_latency");
assert!(!bounds.is_empty());
assert_eq!(bucket_counts.iter().sum::<u64>(), 1);
assert_eq!(sum, 15.0);
assert_eq!(count, 1);
let metric = crate::harness::find_metric(&resource_metrics, "codex.request_latency")
.expect("codex.request_latency metric should exist");
assert_eq!(metric.unit(), "ms");
assert_eq!(metric.description(), "Duration in milliseconds.");
Ok(())
}
#[test]
fn record_duration_keeps_whole_millisecond_behavior() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
metrics.record_duration("codex.request_latency", Duration::from_micros(15_999), &[])?;
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
let (_, _, sum, count) = histogram_data(&resource_metrics, "codex.request_latency");
assert_eq!(sum, 15.0);
assert_eq!(count, 1);
Ok(())
}
/// Keeps long-running requests observable instead of collapsing their latency into the overflow bucket.
#[test]
fn record_duration_seconds_uses_fractional_seconds_and_scaled_buckets() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
for duration in [
Duration::from_millis(200),
Duration::from_secs(1),
Duration::from_millis(4900),
Duration::from_secs(12),
Duration::from_secs(15),
Duration::from_secs(20),
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(120),
Duration::from_secs(121),
] {
metrics.record_duration_seconds_with_description(
"codex.request_duration_seconds",
"Duration of Codex requests in seconds.",
duration,
&[("method", "initialize")],
)?;
}
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
let (bounds, bucket_counts, sum, count) =
histogram_data(&resource_metrics, "codex.request_duration_seconds");
assert_eq!(
bounds,
vec![
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,
]
);
assert_eq!(
bucket_counts,
vec![
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1
]
);
assert!((sum - 384.1).abs() < f64::EPSILON * 512.0);
assert_eq!(count, 10);
let metric = crate::harness::find_metric(&resource_metrics, "codex.request_duration_seconds")
.expect("codex.request_duration_seconds metric should exist");
assert_eq!(metric.unit(), "s");
assert_eq!(
metric.description(),
"Duration of Codex requests in seconds."
);
Ok(())
}
// Ensures time_result returns the closure output and records timing.
#[test]
fn timer_result_records_success() -> Result<()> {
let (metrics, exporter) = build_metrics_with_defaults(&[])?;
{
let timer = metrics.start_timer("codex.request_latency", &[("route", "chat")]);
assert!(timer.is_ok());
}
metrics.shutdown()?;
let resource_metrics = latest_metrics(&exporter);
let (bounds, bucket_counts, _sum, count) =
histogram_data(&resource_metrics, "codex.request_latency");
assert!(!bounds.is_empty());
assert_eq!(count, 1);
assert_eq!(bucket_counts.iter().sum::<u64>(), 1);
let metric = crate::harness::find_metric(&resource_metrics, "codex.request_latency")
.expect("codex.request_latency metric should exist");
assert_eq!(metric.unit(), "ms");
assert_eq!(metric.description(), "Duration in milliseconds.");
let attrs = attributes_to_map(
crate::harness::find_metric(&resource_metrics, "codex.request_latency")
.and_then(|metric| match metric.data() {
opentelemetry_sdk::metrics::data::AggregatedMetrics::F64(
opentelemetry_sdk::metrics::data::MetricData::Histogram(histogram),
) => histogram
.data_points()
.next()
.map(opentelemetry_sdk::metrics::data::HistogramDataPoint::attributes),
_ => None,
})
.expect("codex.request_latency attributes should exist"),
);
assert_eq!(attrs.get("route").map(String::as_str), Some("chat"));
Ok(())
}

View File

@@ -0,0 +1,91 @@
use codex_otel::MetricsClient;
use codex_otel::MetricsConfig;
use codex_otel::MetricsError;
use codex_otel::Result;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
fn build_in_memory_client() -> Result<MetricsClient> {
let exporter = InMemoryMetricExporter::default();
let config = MetricsConfig::in_memory("test", "codex-cli", env!("CARGO_PKG_VERSION"), exporter);
MetricsClient::new(config)
}
// Ensures invalid tag components are rejected during config build.
#[test]
fn invalid_tag_component_is_rejected() -> Result<()> {
let err = MetricsConfig::in_memory(
"test",
"codex-cli",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_tag("bad key", "value")
.unwrap_err();
assert!(matches!(
err,
MetricsError::InvalidTagComponent { label, value }
if label == "tag key" && value == "bad key"
));
Ok(())
}
// Ensures per-metric tag keys are validated.
#[test]
fn counter_rejects_invalid_tag_key() -> Result<()> {
let metrics = build_in_memory_client()?;
let err = metrics
.counter("codex.turns", /*inc*/ 1, &[("bad key", "value")])
.unwrap_err();
assert!(matches!(
err,
MetricsError::InvalidTagComponent { label, value }
if label == "tag key" && value == "bad key"
));
metrics.shutdown()?;
Ok(())
}
// Ensures per-metric tag values are validated.
#[test]
fn histogram_rejects_invalid_tag_value() -> Result<()> {
let metrics = build_in_memory_client()?;
let err = metrics
.histogram(
"codex.request_latency",
/*value*/ 3,
&[("route", "bad value")],
)
.unwrap_err();
assert!(matches!(
err,
MetricsError::InvalidTagComponent { label, value }
if label == "tag value" && value == "bad value"
));
metrics.shutdown()?;
Ok(())
}
// Ensures invalid metric names are rejected.
#[test]
fn counter_rejects_invalid_metric_name() -> Result<()> {
let metrics = build_in_memory_client()?;
let err = metrics.counter("bad name", /*inc*/ 1, &[]).unwrap_err();
assert!(matches!(
err,
MetricsError::InvalidMetricName { name } if name == "bad name"
));
metrics.shutdown()?;
Ok(())
}
#[test]
fn counter_rejects_negative_increment() -> Result<()> {
let metrics = build_in_memory_client()?;
let err = metrics.counter("codex.turns", /*inc*/ -1, &[]).unwrap_err();
assert!(matches!(
err,
MetricsError::NegativeCounterIncrement { name, inc } if name == "codex.turns" && inc == -1
));
metrics.shutdown()?;
Ok(())
}

View File

@@ -0,0 +1,4 @@
#![allow(clippy::expect_used)]
mod harness;
mod suite;