Files
richardopenai 2dec46e30a [codex] Record exec-server lifecycle metrics (#27467)
## Summary

- Record bounded connection, request, and process lifecycle metrics.
- Report active gauges from callbacks on every collection, including
delta exports.
- Serialize active-count updates so concurrent starts and finishes
cannot publish stale values.
- Serialize process exit, explicit termination, and shutdown through the
process registry so exactly one completion result wins.
- Keep the implementation small with single-owner RAII guards and one
real OTLP/HTTP integration test using the existing `wiremock`
dependency.

## Root cause

Process exit and session shutdown previously used cloned completion
state. That avoided duplicate emission, but it duplicated lifecycle
ownership and made the ordering harder to reason about. The process
registry mutex already defines the lifecycle ordering, so the final
implementation stores the metric guard and termination flag directly on
the process entry. Whichever path claims the entry first owns the
completion result.

Production metric export uses delta temporality. Event-only synchronous
gauge recordings disappear after the next collection when no count
changes, so active counts now use observable callbacks that report
current state on every collection.

The cleanup also removes the constant `result="accepted"` connection
tag, redundant route and response assertions, a custom HTTP collector,
and fallback initialization machinery that did not add behavior.

## Stack

Review and land this stack in order:

1. #27466 — trace exec-server JSON-RPC requests
2. #27467 — record bounded connection, request, and process lifecycle
metrics **(this PR)**
3. #27470 — observe remote registration and Noise rendezvous lifecycle

## Validation

- `just test -p codex-exec-server --lib` (158 passed)
- `just test -p codex-cli --test exec_server` (3 passed)
- `just test -p codex-otel
observable_gauge_is_collected_on_every_delta_snapshot` (1 passed)
- `CARGO_BUILD_JOBS=1 just fix -p codex-otel -p codex-exec-server`
- `just fmt`
- `git diff --check`
2026-06-25 11:02:11 -07:00

158 lines
5.2 KiB
Rust

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(())
}