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,111 @@
//! Exports opted-in live final responses, with turn-local deduplication and bounded text.
//! Hosts supply completed raw messages and attribution; stored history is never changed.
use crate::SessionTelemetry;
use crate::events::shared::log_event;
use codex_protocol::AgentPath;
use codex_protocol::ResponseItemId;
use codex_protocol::models::ContentItem;
use codex_protocol::models::MessagePhase;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_utils_stream_parser::strip_citations;
use codex_utils_string::take_bytes_at_char_boundary;
use std::collections::HashSet;
use std::sync::Mutex;
const MAX_RESPONSE_BYTES: usize = 65_536;
/// Host-owned attribution for one live completed response item.
pub struct AgentResponseContext<'a> {
pub turn_id: &'a str,
pub session_source: &'a SessionSource,
pub parent_turn_id: Option<String>,
pub root_turn_id: Option<String>,
pub initiating_agent_path: Option<&'a AgentPath>,
}
/// One turn's response-log state. Create a fresh instance for each turn; never replay history.
/// Only construct when response logging is opted in and an OTLP log exporter is configured.
#[derive(Default)]
pub struct AgentResponseLogger {
logged: Mutex<HashSet<ResponseItemId>>,
}
impl AgentResponseLogger {
/// Record a live final message once, using the telemetry of its actual sampling step.
pub fn record(
&self,
telemetry: &SessionTelemetry,
item: &ResponseItem,
context: AgentResponseContext<'_>,
) {
let ResponseItem::Message {
id: Some(item_id),
role,
phase: Some(MessagePhase::FinalAnswer),
content,
..
} = item
else {
return;
};
if role != "assistant" {
return;
}
let (agent_type, parent_conversation_id) = match context.session_source {
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id, ..
}) => ("subagent", Some(parent_thread_id.to_string())),
SessionSource::Cli
| SessionSource::VSCode
| SessionSource::Exec
| SessionSource::Mcp
| SessionSource::Custom(_)
| SessionSource::Unknown => ("main", None),
SessionSource::Internal(_)
| SessionSource::SubAgent(
SubAgentSource::Review
| SubAgentSource::Compact
| SubAgentSource::MemoryConsolidation
| SubAgentSource::Other(_),
) => return,
};
let text = content
.iter()
.filter_map(|content| match content {
ContentItem::OutputText { text, .. } => Some(text.as_str()),
ContentItem::InputText { .. }
| ContentItem::InputImage { .. }
| ContentItem::InputAudio { .. } => None,
})
.collect::<String>();
// Keep plan content, stripping memory citations only from the exported copy.
let (text, _) = strip_citations(&text);
if text.trim().is_empty()
|| !self
.logged
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(item_id.clone())
{
return;
}
let response = take_bytes_at_char_boundary(&text, MAX_RESPONSE_BYTES);
log_event!(
telemetry,
event.name = "codex.agent_response",
agent.type = agent_type,
turn.id = context.turn_id,
item.id = item_id.as_str(),
parent.conversation.id = parent_conversation_id.as_deref(),
parent.turn.id = context.parent_turn_id.as_deref(),
root.turn.id = context.root_turn_id.as_deref(),
initiating.agent.path = context.initiating_agent_path.map(AgentPath::as_str),
response = response,
response_length = text.len() as u64,
response_truncated = response.len() < text.len(),
);
}
}

View File

@@ -0,0 +1,257 @@
//! Credential-storage metrics contain only bounded classifications, never credentials or paths.
//! Shared metrics infrastructure supplies OS/version metadata and startup buffering.
mod originator;
pub use originator::AuthStorageOriginator;
use std::error::Error;
use std::time::Duration;
use std::time::Instant;
use strum_macros::AsRefStr;
#[derive(Clone, Copy, Debug, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum CredentialKind {
Codex,
Mcp,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum StoreMode {
File,
Auto,
Keyring,
Ephemeral,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum Store {
File,
DirectKeyring,
Secrets,
Ephemeral,
/// A deletion spanning the selected backend, plaintext fallback, and legacy entries.
Multiple,
}
#[derive(Clone, Copy, Debug, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum Operation {
Load,
Save,
Delete,
Cleanup,
RefreshPersist,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, AsRefStr)]
#[strum(serialize_all = "snake_case")]
enum Outcome {
NotAttempted,
Success,
NotFound,
Error,
}
#[derive(Clone, Copy, Debug)]
struct Observation {
credential_kind: CredentialKind,
mode: StoreMode,
selected_store: Store,
actual_store: Store,
operation: Operation,
secure_outcome: Outcome,
outcome: Outcome,
duration: Duration,
phase: StoragePhase,
secure_error: &'static str,
originator: AuthStorageOriginator,
}
impl Observation {
fn record(self) {
let fallback = match (
self.mode,
self.phase,
self.actual_store,
self.secure_outcome,
) {
(StoreMode::Auto, StoragePhase::Policy, Store::File, Outcome::Error) => "secure_error",
(StoreMode::Auto, StoragePhase::Policy, Store::File, Outcome::NotFound) => {
"secure_entry_missing"
}
_ => "none",
};
let tags = &[
("credential_kind", self.credential_kind.as_ref()),
("store_mode", self.mode.as_ref()),
("selected_store", self.selected_store.as_ref()),
("actual_store", self.actual_store.as_ref()),
("operation", self.operation.as_ref()),
("secure_outcome", self.secure_outcome.as_ref()),
("outcome", self.outcome.as_ref()),
("fallback_reason", fallback),
("secure_error", self.secure_error),
("storage_phase", self.phase.as_ref()),
(crate::ORIGINATOR_TAG, self.originator.as_str()),
];
if fallback != "none" {
tracing::warn!(
credential_kind = self.credential_kind.as_ref(),
store_mode = self.mode.as_ref(),
selected_store = self.selected_store.as_ref(),
actual_store = self.actual_store.as_ref(),
operation = self.operation.as_ref(),
secure_outcome = self.secure_outcome.as_ref(),
outcome = self.outcome.as_ref(),
fallback_reason = fallback,
secure_error = self.secure_error,
storage_phase = self.phase.as_ref(),
originator = self.originator.as_str(),
"credential storage file fallback completed"
);
}
let (count, duration) = match self.operation {
Operation::RefreshPersist => (
"codex.auth_storage.refresh_persist",
"codex.auth_storage.refresh_persist.duration",
),
Operation::Load | Operation::Save | Operation::Delete | Operation::Cleanup => (
"codex.auth_storage.operation",
"codex.auth_storage.duration",
),
};
let _ = crate::record_global_operation(count, duration, self.duration, tags);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum StoragePhase {
Policy,
Pinned,
}
/// Records one logical storage operation, including the secure attempt and any file fallback.
/// Callers execute each attempt and pass its result by reference; error messages and payloads
/// are not read. The combined outcome and elapsed time are recorded when this guard is dropped.
/// Client attribution is supplied at construction and retained until emission.
#[derive(Debug)]
pub struct StorageTelemetry {
observation: Observation,
started: Instant,
}
impl StorageTelemetry {
pub fn new(
credential_kind: CredentialKind,
mode: StoreMode,
selected_store: Store,
operation: Operation,
originator: AuthStorageOriginator,
) -> Self {
Self {
observation: Observation {
credential_kind,
mode,
selected_store,
actual_store: selected_store,
operation,
secure_outcome: Outcome::NotAttempted,
outcome: Outcome::NotAttempted,
duration: Duration::ZERO,
phase: StoragePhase::Policy,
secure_error: "none",
originator,
},
started: Instant::now(),
}
}
/// Pinned operations retain their configured mode but never re-evaluate fallback policy.
pub fn with_phase(mut self, phase: StoragePhase) -> Self {
self.observation.phase = phase;
self
}
/// Classifies typed causes only; never formats errors or parses their messages.
/// May be called before or after recording the corresponding failed secure attempt.
pub fn record_secure_error(&mut self, error: &(dyn Error + 'static)) {
let mut cause = Some(error);
while let Some(error) = cause {
if let Some(error) = error.downcast_ref::<std::io::Error>() {
let category = match error.kind() {
std::io::ErrorKind::PermissionDenied => "access_denied",
std::io::ErrorKind::NotConnected => "unavailable",
std::io::ErrorKind::WouldBlock => "locked",
std::io::ErrorKind::Unsupported => "unsupported",
std::io::ErrorKind::TimedOut => "timeout",
_ => "other",
};
if category != "other" {
self.observation.secure_error = category;
return;
}
cause = error.get_ref().map(|error| error as &dyn Error);
} else {
cause = error.source();
}
}
self.observation.secure_error = "other";
}
pub fn record_load_attempt<T, E>(&mut self, store: Store, result: &Result<Option<T>, E>) {
let outcome = match result {
Ok(Some(_)) => Outcome::Success,
Ok(None) => Outcome::NotFound,
Err(_) => Outcome::Error,
};
self.record_attempt(store, outcome);
}
pub fn record_save_attempt<E>(&mut self, store: Store, result: &Result<(), E>) {
let outcome = match result {
Ok(()) => Outcome::Success,
Err(_) => Outcome::Error,
};
self.record_attempt(store, outcome);
}
pub fn record_delete_attempt<E>(&mut self, store: Store, result: &Result<bool, E>) {
let outcome = match result {
Ok(true) => Outcome::Success,
Ok(false) => Outcome::NotFound,
Err(_) => Outcome::Error,
};
self.record_attempt(store, outcome);
}
fn record_attempt(&mut self, store: Store, outcome: Outcome) {
self.observation.actual_store = store;
self.observation.outcome = outcome;
if matches!(store, Store::DirectKeyring | Store::Secrets) {
self.observation.secure_outcome = outcome;
if outcome != Outcome::Error {
self.observation.secure_error = "none";
} else if self.observation.secure_error == "none" {
self.observation.secure_error = "other";
}
}
}
}
impl Drop for StorageTelemetry {
fn drop(&mut self) {
if self.observation.outcome == Outcome::NotAttempted {
return;
}
self.observation.duration = self.started.elapsed();
self.observation.record();
}
}
#[cfg(test)]
#[path = "auth_storage_tests.rs"]
mod tests;

View File

@@ -0,0 +1,45 @@
//! Bounded attribution for auth-storage observations, scoped to one task.
//! Spawned tasks must explicitly carry this context across the task boundary.
use std::future::Future;
tokio::task_local! {
static CURRENT: AuthStorageOriginator;
}
/// A bounded client identity used only by credential-storage telemetry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AuthStorageOriginator(&'static str);
impl AuthStorageOriginator {
pub fn from_client_name(name: &str) -> Self {
let name = match name {
"Codex Desktop" => "codex_desktop",
_ => name,
};
Self(crate::bounded_originator_tag_value(name))
}
/// Unattributed work must not borrow another connection's identity.
pub fn current() -> Self {
CURRENT
.try_with(|originator| *originator)
.unwrap_or(Self("none"))
}
pub fn as_str(self) -> &'static str {
self.0
}
pub async fn scope<F: Future>(self, future: F) -> F::Output {
CURRENT.scope(self, future).await
}
pub fn sync_scope<R>(self, operation: impl FnOnce() -> R) -> R {
CURRENT.sync_scope(self, operation)
}
}
#[cfg(test)]
#[path = "originator_tests.rs"]
mod tests;

View File

@@ -0,0 +1,49 @@
//! Verifies attribution isolation and explicit propagation across task boundaries.
use super::AuthStorageOriginator;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use tokio::sync::Barrier;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn concurrent_clients_keep_their_originator_across_awaits_and_blocking_work() {
let barrier = Arc::new(Barrier::new(/*n*/ 3));
let mut tasks = Vec::new();
for name in ["Codex Desktop", "codex_vscode", "private-client-name"] {
let barrier = Arc::clone(&barrier);
let originator = AuthStorageOriginator::from_client_name(name);
tasks.push(tokio::spawn(originator.scope(async move {
barrier.wait().await;
tokio::task::yield_now().await;
let before = AuthStorageOriginator::current();
let nested = AuthStorageOriginator::from_client_name("codex_cli_rs")
.scope(async {
tokio::task::yield_now().await;
AuthStorageOriginator::current().as_str()
})
.await;
let blocking = tokio::task::spawn_blocking(move || {
before.sync_scope(AuthStorageOriginator::current)
})
.await
.unwrap();
(
before.as_str(),
nested,
blocking.as_str(),
AuthStorageOriginator::current().as_str(),
)
})));
}
let mut actual = Vec::new();
for task in tasks {
actual.push(task.await.unwrap());
}
assert_eq!(
actual,
["codex_desktop", "codex_vscode", "other"]
.map(|originator| (originator, "codex_cli_rs", originator, originator))
.to_vec()
);
assert_eq!(AuthStorageOriginator::current().as_str(), "none");
}

View File

@@ -0,0 +1,248 @@
//! Exercises buffered storage observations and bounded diagnostics.
use super::*;
use crate::MetricsClient;
use crate::MetricsConfig;
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;
// Provider installation is process-global. Isolate these cases even under Bazel/libtest,
// which otherwise runs all unit tests in a shared process.
fn run_in_subprocess() -> bool {
if std::env::var_os("CODEX_AUTH_STORAGE_TEST_CHILD").is_some() {
return false;
}
let thread = std::thread::current();
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", thread.name().unwrap(), "--nocapture"])
.env("CODEX_AUTH_STORAGE_TEST_CHILD", "1")
.output()
.unwrap();
assert!(
output.status.success(),
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
true
}
#[test]
fn startup_fallback_exports_one_logical_operation_without_error_contents() -> crate::Result<()> {
if run_in_subprocess() {
return Ok(());
}
let mut telemetry = AuthStorageOriginator::from_client_name("Codex Desktop").sync_scope(|| {
StorageTelemetry::new(
CredentialKind::Codex,
StoreMode::Auto,
Store::Secrets,
Operation::Save,
AuthStorageOriginator::current(),
)
});
let logs = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let writer = LogWriter(logs.clone());
let subscriber = tracing_subscriber::fmt()
.without_time()
.with_ansi(false)
.with_target(false)
.with_writer(move || writer.clone())
.finish();
let failure: Result<(), &str> = Err("sensitive error contents");
telemetry.record_save_attempt(Store::Secrets, &failure);
let success: Result<(), &str> = Ok(());
telemetry.record_save_attempt(Store::File, &success);
telemetry.record_secure_error(&std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"private account",
));
tracing::subscriber::with_default(subscriber, || drop(telemetry));
let logs = String::from_utf8(logs.lock().unwrap().clone()).unwrap();
assert_eq!(logs.lines().count(), 1);
assert!(logs.contains("secure_error=\"access_denied\""), "{logs}");
assert!(logs.contains("originator=\"codex_desktop\""), "{logs}");
assert!(logs.contains("outcome=\"success\""), "{logs}");
assert!(!logs.contains("private account") && !logs.contains("sensitive error contents"));
let metrics = crate::install_global_metrics(MetricsClient::new(
MetricsConfig::in_memory("test", "test", "1", InMemoryMetricExporter::default())
.with_runtime_reader(),
)?);
let snapshot = metrics.snapshot()?;
let mut counts = Vec::new();
let mut durations = Vec::new();
for metric in snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
{
match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => {
assert_eq!(metric.name(), "codex.auth_storage.operation");
for point in sum.data_points() {
counts.push((
point.value(),
point
.attributes()
.map(|attribute| {
(attribute.key.to_string(), attribute.value.to_string())
})
.collect::<BTreeMap<_, _>>(),
));
}
}
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => {
assert_eq!(metric.name(), "codex.auth_storage.duration");
durations.extend(
histogram
.data_points()
.map(opentelemetry_sdk::metrics::data::HistogramDataPoint::count),
);
}
_ => panic!("unexpected metric"),
}
}
assert_eq!(
counts,
vec![(
1,
BTreeMap::from([
("credential_kind".into(), "codex".into()),
("store_mode".into(), "auto".into()),
("selected_store".into(), "secrets".into()),
("actual_store".into(), "file".into()),
("operation".into(), "save".into()),
("secure_outcome".into(), "error".into()),
("outcome".into(), "success".into()),
("fallback_reason".into(), "secure_error".into()),
("secure_error".into(), "access_denied".into()),
("storage_phase".into(), "policy".into()),
("originator".into(), "codex_desktop".into()),
])
)]
);
assert_eq!(durations, vec![1]);
drop(StorageTelemetry::new(
CredentialKind::Codex,
StoreMode::Auto,
Store::Secrets,
Operation::Save,
AuthStorageOriginator::current(),
));
assert!(
metrics
.snapshot()?
.scope_metrics()
.all(|scope| scope.metrics().next().is_none())
);
StorageTelemetry::new(
CredentialKind::Mcp,
StoreMode::Auto,
Store::Secrets,
Operation::RefreshPersist,
AuthStorageOriginator::current(),
)
.record_save_attempt(Store::Secrets, &Ok::<(), ()>(()));
let snapshot = metrics.snapshot()?;
let mut names: Vec<_> = snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.map(opentelemetry_sdk::metrics::data::Metric::name)
.collect();
names.sort();
assert_eq!(
names,
vec![
"codex.auth_storage.refresh_persist",
"codex.auth_storage.refresh_persist.duration"
]
);
metrics.shutdown()
}
#[test]
fn missing_credentials_and_failed_fallback_keep_distinct_outcomes() {
if run_in_subprocess() {
return;
}
let mut telemetry = StorageTelemetry::new(
CredentialKind::Mcp,
StoreMode::Auto,
Store::DirectKeyring,
Operation::Load,
AuthStorageOriginator::current(),
);
let missing: Result<Option<String>, &str> = Ok(None);
telemetry.record_load_attempt(Store::DirectKeyring, &missing);
let failure: Result<Option<String>, &str> = Err("file unavailable");
telemetry.record_load_attempt(Store::File, &failure);
assert_eq!(
(
telemetry.observation.secure_outcome,
telemetry.observation.outcome,
telemetry.observation.actual_store
),
(Outcome::NotFound, Outcome::Error, Store::File)
);
}
#[test]
fn secure_error_classification_is_independent_of_attempt_recording_order() {
if run_in_subprocess() {
return;
}
for store in [Store::DirectKeyring, Store::Secrets] {
for classify_first in [true, false] {
let mut telemetry = StorageTelemetry::new(
CredentialKind::Codex,
StoreMode::Auto,
store,
Operation::Save,
AuthStorageOriginator::current(),
);
let failure = Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"private account",
));
if classify_first {
telemetry.record_secure_error(failure.as_ref().unwrap_err());
}
telemetry.record_save_attempt(store, &failure);
if !classify_first {
telemetry.record_secure_error(failure.as_ref().unwrap_err());
}
telemetry.record_save_attempt(Store::File, &Ok::<(), ()>(()));
assert_eq!(
(
telemetry.observation.secure_outcome,
telemetry.observation.outcome,
telemetry.observation.secure_error,
),
(Outcome::Error, Outcome::Success, "access_denied")
);
telemetry.record_save_attempt(store, &Ok::<(), ()>(()));
assert_eq!(
(
telemetry.observation.secure_outcome,
telemetry.observation.secure_error,
),
(Outcome::Success, "none")
);
}
}
}
#[derive(Clone)]
struct LogWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for LogWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

120
codex-rs/otel/src/config.rs Normal file
View File

@@ -0,0 +1,120 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::PathBuf;
use codex_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
pub(crate) const STATSIG_OTLP_HTTP_ENDPOINT: &str = "https://ab.chatgpt.com/otlp/v1/metrics";
pub(crate) const STATSIG_API_KEY_HEADER: &str = "statsig-api-key";
pub(crate) const STATSIG_API_KEY: &str = "client-MkRuleRQBd6qakfnDYqJVR9JuXcY57Ljly3vi5JVUIO";
pub(crate) fn resolve_exporter(exporter: &OtelExporter) -> OtelExporter {
match exporter {
OtelExporter::Statsig => {
// Keep the built-in Statsig default off in debug builds so
// incremental local development and test runs do not emit
// best-effort OTEL traffic unless a test or binary opts into an
// explicit exporter configuration.
if cfg!(debug_assertions) {
return OtelExporter::None;
}
OtelExporter::OtlpHttp {
endpoint: STATSIG_OTLP_HTTP_ENDPOINT.to_string(),
headers: HashMap::from([(
STATSIG_API_KEY_HEADER.to_string(),
STATSIG_API_KEY.to_string(),
)]),
protocol: OtelHttpProtocol::Json,
tls: None,
}
}
_ => exporter.clone(),
}
}
/// Validates configured span attributes before they are attached to exported spans.
pub fn validate_span_attributes(attributes: &HashMap<String, String>) -> std::io::Result<()> {
if attributes.keys().any(String::is_empty) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"configured span attribute key must not be empty",
));
}
Ok(())
}
#[derive(Clone, Debug)]
pub struct OtelSettings {
pub http_client_factory: codex_http_client::HttpClientFactory,
pub environment: String,
pub service_name: String,
pub service_version: String,
pub codex_home: PathBuf,
pub exporter: OtelExporter,
pub trace_exporter: OtelExporter,
pub metrics_exporter: OtelExporter,
pub runtime_metrics: bool,
pub span_attributes: HashMap<String, String>,
pub tracestate: BTreeMap<String, BTreeMap<String, String>>,
}
/// Resolved Statsig metrics settings that another process can use to recreate
/// the built-in metrics exporter configuration without receiving generic
/// exporter credentials in-process.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatsigMetricsSettings {
pub environment: String,
}
#[derive(Clone, Debug)]
pub enum OtelHttpProtocol {
/// HTTP protocol with binary protobuf
Binary,
/// HTTP protocol with JSON payload
Json,
}
#[derive(Clone, Debug, Default)]
pub struct OtelTlsConfig {
pub ca_certificate: Option<AbsolutePathBuf>,
pub client_certificate: Option<AbsolutePathBuf>,
pub client_private_key: Option<AbsolutePathBuf>,
}
#[derive(Clone, Debug)]
pub enum OtelExporter {
None,
/// Statsig metrics ingestion exporter using Codex-internal defaults.
///
/// This is intended for metrics only.
Statsig,
OtlpGrpc {
endpoint: String,
headers: HashMap<String, String>,
tls: Option<OtelTlsConfig>,
},
OtlpHttp {
endpoint: String,
headers: HashMap<String, String>,
protocol: OtelHttpProtocol,
tls: Option<OtelTlsConfig>,
},
}
#[cfg(test)]
mod tests {
use super::OtelExporter;
use super::resolve_exporter;
#[test]
fn statsig_default_metrics_exporter_is_disabled_in_debug_builds() {
assert!(matches!(
resolve_exporter(&OtelExporter::Statsig),
OtelExporter::None
));
}
}

View File

@@ -0,0 +1,2 @@
pub(crate) mod session_telemetry;
pub(crate) mod shared;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,70 @@
use chrono::SecondsFormat;
use chrono::Utc;
use codex_protocol::DEFAULT_FUNCTION_NAMESPACE;
use codex_protocol::ToolName;
pub(crate) fn tool_namespace(tool_name: &ToolName) -> &str {
tool_name
.namespace
.as_deref()
.filter(|namespace| !namespace.is_empty())
.unwrap_or(DEFAULT_FUNCTION_NAMESPACE)
}
macro_rules! log_event {
($self:expr, $($fields:tt)*) => {{
tracing::event!(
target: $crate::targets::OTEL_LOG_ONLY_TARGET,
tracing::Level::INFO,
$($fields)*
event.timestamp = %$crate::events::shared::timestamp(),
conversation.id = %$self.metadata.conversation_id,
app.version = %$self.metadata.app_version,
auth_mode = $self.metadata.auth_mode,
originator = %$self.metadata.originator,
user.account_id = $self.metadata.account_id,
user.email = $self.metadata.account_email,
terminal.type = %$self.metadata.terminal_type,
model = %$self.metadata.model,
slug = %$self.metadata.slug,
);
}};
}
macro_rules! trace_event {
($self:expr, $($fields:tt)*) => {{
tracing::event!(
target: $crate::targets::OTEL_TRACE_SAFE_TARGET,
tracing::Level::INFO,
$($fields)*
event.timestamp = %$crate::events::shared::timestamp(),
conversation.id = %$self.metadata.conversation_id,
app.version = %$self.metadata.app_version,
auth_mode = $self.metadata.auth_mode,
originator = %$self.metadata.originator,
terminal.type = %$self.metadata.terminal_type,
model = %$self.metadata.model,
slug = %$self.metadata.slug,
);
}};
}
macro_rules! log_and_trace_event {
(
$self:expr,
common: { $($common:tt)* },
log: { $($log:tt)* },
trace: { $($trace:tt)* },
) => {{
log_event!($self, $($common)* $($log)*);
trace_event!($self, $($common)* $($trace)*);
}};
}
pub(crate) use log_and_trace_event;
pub(crate) use log_event;
pub(crate) use trace_event;
pub(crate) fn timestamp() -> String {
Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true)
}

View File

@@ -0,0 +1,68 @@
//! Exports opted-in terminal Guardian assessments with bounded rationale text.
//! Hosts supply the effective model outcome; review failures have no model outcome.
use crate::SessionTelemetry;
use crate::events::shared::log_event;
use codex_protocol::protocol::GuardianAssessmentEvent;
use codex_protocol::protocol::GuardianAssessmentOutcome;
use codex_protocol::protocol::GuardianAssessmentStatus;
use codex_protocol::protocol::GuardianRiskLevel;
use codex_protocol::protocol::GuardianUserAuthorization;
use codex_utils_string::take_bytes_at_char_boundary;
const MAX_RATIONALE_BYTES: usize = 65_536;
impl SessionTelemetry {
/// Record one terminal review after the host checks the opt-in and OTLP destination.
/// `outcome` is absent for errors, timeouts and cancellations, including fail-closed denials.
pub fn guardian_assessment(
&self,
assessment: &GuardianAssessmentEvent,
outcome: Option<GuardianAssessmentOutcome>,
) {
let status = match assessment.status {
GuardianAssessmentStatus::InProgress => return,
GuardianAssessmentStatus::Approved => "approved",
GuardianAssessmentStatus::Denied => "denied",
GuardianAssessmentStatus::TimedOut => "timed_out",
GuardianAssessmentStatus::Aborted => "aborted",
};
let outcome = outcome.map(|outcome| match outcome {
GuardianAssessmentOutcome::Allow => "allow",
GuardianAssessmentOutcome::Deny => "deny",
});
let risk_level = assessment.risk_level.map(|risk| match risk {
GuardianRiskLevel::Low => "low",
GuardianRiskLevel::Medium => "medium",
GuardianRiskLevel::High => "high",
GuardianRiskLevel::Critical => "critical",
});
let user_authorization =
assessment
.user_authorization
.map(|authorization| match authorization {
GuardianUserAuthorization::Unknown => "unknown",
GuardianUserAuthorization::Low => "low",
GuardianUserAuthorization::Medium => "medium",
GuardianUserAuthorization::High => "high",
});
let rationale = assessment.rationale.as_deref();
log_event!(
self,
event.name = "codex.guardian_assessment",
review.id = assessment.id.as_str(),
turn.id = assessment.turn_id.as_str(),
item.id = assessment.target_item_id.as_deref(),
status = status,
outcome = outcome,
risk_level = risk_level,
user_authorization = user_authorization,
started_at_ms = assessment.started_at_ms,
completed_at_ms = assessment.completed_at_ms,
rationale =
rationale.map(|text| take_bytes_at_char_boundary(text, MAX_RATIONALE_BYTES)),
rationale_length = rationale.map(|text| text.len() as u64),
rationale_truncated = rationale.map(|text| text.len() > MAX_RATIONALE_BYTES),
);
}
}

103
codex-rs/otel/src/lib.rs Normal file
View File

@@ -0,0 +1,103 @@
pub mod auth_storage;
pub(crate) mod config;
mod events;
pub(crate) mod metrics;
pub(crate) mod provider;
pub(crate) mod trace_context;
mod agent_response;
mod guardian_assessment;
mod network_policy;
mod otlp;
mod skill_invocation;
mod targets;
mod tool_result;
use crate::metrics::Result as MetricsResult;
use codex_protocol::auth::AuthMode;
use serde::Serialize;
use strum_macros::Display;
pub use crate::agent_response::AgentResponseContext;
pub use crate::agent_response::AgentResponseLogger;
pub use crate::config::OtelExporter;
pub use crate::config::OtelHttpProtocol;
pub use crate::config::OtelSettings;
pub use crate::config::OtelTlsConfig;
pub use crate::config::StatsigMetricsSettings;
pub use crate::config::validate_span_attributes;
pub use crate::events::session_telemetry::AuthEnvTelemetryMetadata;
pub use crate::events::session_telemetry::SessionTelemetry;
pub use crate::events::session_telemetry::SessionTelemetryMetadata;
pub use crate::events::session_telemetry::bounded_product_sku;
pub use crate::metrics::runtime_metrics::RuntimeMetricTotals;
pub use crate::metrics::runtime_metrics::RuntimeMetricsSummary;
pub use crate::metrics::timer::Timer;
pub use crate::metrics::*;
pub use crate::provider::OtelProvider;
pub use crate::skill_invocation::SkillInvocationEvent;
pub use crate::skill_invocation::SkillInvocationType;
pub use crate::trace_context::context_from_w3c_trace_context;
pub use crate::trace_context::current_span_trace_id;
pub use crate::trace_context::current_span_w3c_trace_context;
pub use crate::trace_context::inject_span_w3c_trace_headers;
pub use crate::trace_context::set_parent_from_context;
pub use crate::trace_context::set_parent_from_w3c_trace_context;
pub use crate::trace_context::span_w3c_trace_context;
pub use crate::trace_context::traceparent_context_from_env;
pub use crate::trace_context::validate_tracestate_entries;
pub use crate::trace_context::validate_tracestate_member;
pub use codex_utils_string::sanitize_metric_tag_value;
#[derive(Debug, Clone, Serialize, Display)]
#[serde(rename_all = "snake_case")]
pub enum ToolDecisionSource {
AutomatedReviewer,
Config,
User,
}
/// Coarsens the authentication domain into the dimensions used by telemetry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
pub enum TelemetryAuthMode {
ApiKey,
Chatgpt,
}
impl From<AuthMode> for TelemetryAuthMode {
fn from(mode: AuthMode) -> Self {
match mode {
AuthMode::ApiKey | AuthMode::BedrockApiKey | AuthMode::BedrockAccessKeys => {
Self::ApiKey
}
AuthMode::Chatgpt
| AuthMode::ChatgptAuthTokens
| AuthMode::Headers
| AuthMode::AgentIdentity
| AuthMode::PersonalAccessToken => Self::Chatgpt,
}
}
}
/// Install externally managed, non-Statsig process-global metrics.
///
/// Call this once during single-threaded startup, before any instruments are
/// registered. Keep the returned handle to flush and shut down the exporter
/// owned by this installation.
pub fn install_global_metrics(metrics: MetricsClient) -> MetricsClient {
crate::metrics::install_global(metrics)
}
/// Start a metrics timer using the globally installed metrics client.
pub fn start_global_timer(name: &str, tags: &[(&str, &str)]) -> MetricsResult<Timer> {
let Some(metrics) = crate::metrics::global() else {
return Err(MetricsError::ExporterDisabled);
};
metrics.start_timer(name, tags)
}
/// Returns the resolved Statsig metrics settings for the globally installed
/// OTEL metrics client, if the active metrics exporter is Statsig.
pub fn global_statsig_metrics_settings() -> Option<StatsigMetricsSettings> {
crate::metrics::global_statsig_settings()
}

View File

@@ -0,0 +1,177 @@
//! Buffers bounded operation counts and durations until process metrics are configured.
//! Each pair is admitted together; lifecycle transitions serialize with local SDK recording.
//! Shutting down the active installation resumes buffering until its replacement is ready.
use super::MetricsClient;
use super::MetricsError;
use super::Result;
use super::validation::validate_metric_name;
use super::validation::validate_tag_key;
use super::validation::validate_tag_value;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
const MAX_PENDING_OPERATIONS: usize = 256;
const MAX_METADATA_BYTES: usize = 1024;
const MAX_TAGS: usize = 16;
struct PendingOperation {
count_name: Box<str>,
duration_name: Box<str>,
duration: Duration,
tags: Vec<(Box<str>, Box<str>)>,
}
enum State {
Startup(Vec<PendingOperation>),
Ready(MetricsClient),
Disabled,
}
pub(crate) struct BufferedMetrics {
state: Mutex<State>,
}
pub(crate) static GLOBAL: BufferedMetrics = BufferedMetrics::new();
/// Records one operation count and its duration in milliseconds through `MetricsClient`.
/// While awaiting an active provider, retains at most 256 pairs, each with at most 16 tags and
/// 1024 bytes of metric names, tag keys, and tag values. Overflow drops the entire pair.
/// Supply bounded classifications, never credentials or user-provided identifiers.
/// Disabling metrics discards pending pairs and suppresses subsequent recording.
pub fn record_global_operation(
count_name: &str,
duration_name: &str,
duration: Duration,
tags: &[(&str, &str)],
) -> Result<()> {
GLOBAL.record(count_name, duration_name, duration, tags)
}
impl BufferedMetrics {
const fn new() -> Self {
Self {
state: Mutex::new(State::Startup(Vec::new())),
}
}
fn record(
&self,
count_name: &str,
duration_name: &str,
duration: Duration,
tags: &[(&str, &str)],
) -> Result<()> {
if tags.len() > MAX_TAGS
|| tags.iter().fold(
count_name.len().saturating_add(duration_name.len()),
|bytes, (key, value)| bytes.saturating_add(key.len()).saturating_add(value.len()),
) > MAX_METADATA_BYTES
{
return Err(MetricsError::OperationMetadataTooLarge);
}
// Validate both instruments before accepting either half of the pair.
for name in [count_name, duration_name] {
validate_metric_name(name)?;
// The SDK otherwise silently builds a no-op instrument for these names.
if name.len() > 255 || !name.as_bytes()[0].is_ascii_alphabetic() {
return Err(MetricsError::InvalidMetricName {
name: name.to_owned(),
});
}
}
for (key, value) in tags {
validate_tag_key(key)?;
validate_tag_value(value)?;
}
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match &mut *state {
State::Startup(pending) => {
if pending.len() < MAX_PENDING_OPERATIONS {
pending.push(PendingOperation {
count_name: count_name.into(),
duration_name: duration_name.into(),
duration,
tags: tags
.iter()
.map(|(key, value)| ((*key).into(), (*value).into()))
.collect(),
});
}
Ok(())
}
State::Ready(metrics) => record(metrics, count_name, duration_name, duration, tags),
State::Disabled => Ok(()),
}
}
pub(crate) fn enable(&self, metrics: &MetricsClient) {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
// Bind to this installation so a provider replacement cannot split a pair
// between exporters through the redirectable global MetricsClient handle.
let metrics = MetricsClient {
inner: Arc::clone(&metrics.inner),
active: None,
};
if let State::Startup(pending) = &mut *state {
for operation in pending.drain(..) {
let tags: Vec<_> = operation
.tags
.iter()
.map(|(key, value)| (key.as_ref(), value.as_ref()))
.collect();
let _ = record(
&metrics,
&operation.count_name,
&operation.duration_name,
operation.duration,
&tags,
);
}
}
*state = State::Ready(metrics);
}
pub(crate) fn disable(&self) {
*self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = State::Disabled;
}
pub(super) fn suspend(&self, metrics: &MetricsClient) {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
// A replaced provider may shut down after its successor is installed.
// It must neither detach that successor nor undo an explicit opt-out.
if let State::Ready(current) = &*state
&& Arc::ptr_eq(&current.inner, &metrics.inner)
{
*state = State::Startup(Vec::new());
}
}
}
fn record(
metrics: &MetricsClient,
count_name: &str,
duration_name: &str,
duration: Duration,
tags: &[(&str, &str)],
) -> Result<()> {
metrics.counter(count_name, /*inc*/ 1, tags)?;
metrics.record_duration(duration_name, duration, tags)
}
#[cfg(test)]
#[path = "buffered_tests.rs"]
mod tests;

View File

@@ -0,0 +1,175 @@
use super::*;
use crate::MetricsConfig;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use std::sync::Barrier;
use std::sync::RwLock;
fn client() -> MetricsClient {
MetricsClient::new(
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
)
.unwrap()
}
fn observe(buffer: &BufferedMetrics) {
buffer
.record(
"test.operations",
"test.duration",
Duration::from_millis(/*millis*/ 7),
&[("component", "test")],
)
.unwrap();
}
fn totals(metrics: &MetricsClient) -> (u64, u64, f64) {
let snapshot = metrics.snapshot().unwrap();
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 startup_limits_and_validation_preserve_whole_pairs() {
let buffer = BufferedMetrics::new();
let oversized = "x".repeat(MAX_METADATA_BYTES + 1);
assert!(matches!(
buffer.record("count", "duration", Duration::ZERO, &[("tag", &oversized)]),
Err(MetricsError::OperationMetadataTooLarge)
));
assert!(matches!(
buffer.record(
"count",
"duration",
Duration::ZERO,
&[("tag", "value"); MAX_TAGS + 1]
),
Err(MetricsError::OperationMetadataTooLarge)
));
for name in ["invalid duration", "1duration", &"d".repeat(256)] {
assert!(buffer.record("count", name, Duration::ZERO, &[]).is_err());
assert!(
buffer
.record(name, "duration", Duration::ZERO, &[])
.is_err()
);
}
assert!(
buffer
.record(
"count",
"duration",
Duration::ZERO,
&[("tag", "invalid value")]
)
.is_err()
);
for _ in 0..MAX_PENDING_OPERATIONS + 1 {
observe(&buffer);
}
let metrics = client();
buffer.enable(&metrics);
assert_eq!(totals(&metrics), (256, 256, 1792.0));
buffer.enable(&metrics);
assert_eq!(totals(&metrics), (0, 0, 0.0));
for name in ["invalid duration", "1duration", &"d".repeat(256)] {
assert!(buffer.record("count", name, Duration::ZERO, &[]).is_err());
assert!(
buffer
.record(name, "duration", Duration::ZERO, &[])
.is_err()
);
}
assert_eq!(totals(&metrics), (0, 0, 0.0));
}
#[test]
fn opt_out_discards_pending_and_live_observations_until_reenabled() {
let buffer = BufferedMetrics::new();
observe(&buffer);
buffer.disable();
observe(&buffer);
let first = client();
buffer.enable(&first);
assert_eq!(totals(&first), (0, 0, 0.0));
observe(&buffer);
assert_eq!(totals(&first), (1, 1, 7.0));
buffer.disable();
observe(&buffer);
assert_eq!(totals(&first), (0, 0, 0.0));
let second = client();
buffer.enable(&second);
observe(&buffer);
assert_eq!(totals(&second), (1, 1, 7.0));
assert_eq!(totals(&first), (0, 0, 0.0));
}
#[test]
fn concurrent_installation_and_replacement_record_each_pair_once() {
let buffer = BufferedMetrics::new();
let first = client();
let second = client();
let barrier = Barrier::new(/*n*/ 5);
observe(&buffer);
std::thread::scope(|scope| {
for _ in 0..4 {
scope.spawn(|| {
barrier.wait();
for _ in 0..16 {
observe(&buffer);
}
});
}
barrier.wait();
buffer.enable(&first);
buffer.enable(&second);
});
let a = totals(&first);
let b = totals(&second);
assert_eq!((a.0 + b.0, a.1 + b.1, a.2 + b.2), (65, 65, 455.0));
assert_eq!((a.0, b.0), (a.1, b.1));
buffer.enable(&second);
assert_eq!(totals(&second), (0, 0, 0.0));
}
#[test]
fn redirecting_a_global_handle_does_not_change_the_buffers_installation() {
let buffer = BufferedMetrics::new();
let first = client();
let second = client();
let active = Arc::new(RwLock::new(Arc::clone(&first.inner)));
let redirected = MetricsClient {
inner: Arc::clone(&first.inner),
active: Some(Arc::clone(&active)),
};
buffer.enable(&redirected);
*active.write().unwrap() = Arc::clone(&second.inner);
observe(&buffer);
assert_eq!(totals(&first), (1, 1, 7.0));
assert_eq!(totals(&second), (0, 0, 0.0));
buffer.enable(&second);
observe(&buffer);
assert_eq!(totals(&first), (0, 0, 0.0));
assert_eq!(totals(&second), (1, 1, 7.0));
}

View File

@@ -0,0 +1,742 @@
use crate::config::OtelExporter;
use crate::config::OtelHttpProtocol;
use crate::metrics::MetricsError;
use crate::metrics::Result;
use crate::metrics::config::MetricsConfig;
use crate::metrics::config::MetricsExporter;
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_otlp::OTEL_EXPORTER_OTLP_METRICS_TIMEOUT;
use opentelemetry_otlp::Protocol;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_otlp::WithHttpConfig;
use opentelemetry_otlp::WithTonicConfig;
use opentelemetry_otlp::tonic_types::metadata::MetadataMap;
use opentelemetry_otlp::tonic_types::transport::ClientTlsConfig;
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;
#[cfg(test)]
#[path = "client_tests.rs"]
mod tests;
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<Vec<f64>> = 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<String>,
}
#[derive(Clone, Debug)]
struct SharedManualReader {
inner: Arc<ManualReader>,
}
impl SharedManualReader {
fn new(inner: Arc<ManualReader>) -> Self {
Self { inner }
}
}
impl MetricReader for SharedManualReader {
fn register_pipeline(&self, pipeline: Weak<Pipeline>) {
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 {
pub(super) network_policy: codex_http_client::NetworkPolicy,
meter_provider: SdkMeterProvider,
meter: Meter,
counters: Mutex<HashMap<InstrumentKey, Counter<u64>>>,
gauges: Mutex<HashMap<InstrumentKey, Gauge<i64>>>,
histograms: Mutex<HashMap<String, Histogram<f64>>>,
duration_histograms: Mutex<HashMap<InstrumentKey, Histogram<f64>>>,
runtime_reader: Option<Arc<ManualReader>>,
requires_analytics_consent: bool,
statsig_disabled_metrics: &'static [&'static str],
default_tags: BTreeMap<String, String>,
}
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)?;
if self.statsig_disabled_metrics.contains(&name) {
return Ok(());
}
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)?;
if self.statsig_disabled_metrics.contains(&name) {
return Ok(());
}
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)?;
if self.statsig_disabled_metrics.contains(&name) {
return Ok(());
}
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)?;
if self.statsig_disabled_metrics.contains(&name) {
return Ok(());
}
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)?;
if self.statsig_disabled_metrics.contains(&name) {
return Ok(());
}
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<Vec<KeyValue>> {
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(())
}
}
/// OpenTelemetry metrics client used by Codex.
#[derive(Clone, Debug)]
pub struct MetricsClient {
// Keep the original provider so its owner only shuts down its own exporter.
pub(super) inner: Arc<MetricsClientInner>,
// Installed clients share this slot, so existing clones follow account changes.
pub(super) active: Option<Arc<RwLock<Arc<MetricsClientInner>>>>,
}
impl MetricsClient {
/// Build a metrics client from configuration and validate defaults.
pub fn new(config: MetricsConfig) -> Result<Self> {
let MetricsConfig {
http_client_factory,
environment,
service_name,
service_version,
exporter,
export_interval,
runtime_reader,
statsig_disabled_metrics,
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 requires_analytics_consent =
matches!(exporter, MetricsExporter::Otlp(OtelExporter::Statsig));
let (meter_provider, meter) = match exporter {
MetricsExporter::InMemory(exporter) => {
build_provider(resource, exporter, export_interval, runtime_reader.clone())
}
MetricsExporter::Otlp(exporter) => {
let temporality = otlp_metrics_temporality(
&exporter,
std::env::var("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE")
.ok()
.as_deref(),
);
let exporter = crate::network_policy::PolicyExporter {
exporter: build_otlp_metric_exporter(
exporter,
temporality,
&http_client_factory,
)?,
policy: http_client_factory.network_policy().clone(),
};
build_provider(resource, exporter, export_interval, runtime_reader.clone())
}
};
Ok(Self {
inner: Arc::new(MetricsClientInner {
network_policy: http_client_factory.network_policy().clone(),
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,
requires_analytics_consent,
statsig_disabled_metrics,
default_tags,
}),
active: None,
})
}
pub(super) fn active_inner(&self) -> Arc<MetricsClientInner> {
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)
}
/// Record a counter while applying analytics consent only to the built-in exporter.
/// The consent check and recording use the same exporter even during provider replacement.
pub fn counter_with_analytics_consent(
&self,
name: &str,
inc: i64,
tags: &[(&str, &str)],
analytics_enabled: bool,
) -> Result<()> {
let inner = self.active_inner();
if inner.requires_analytics_consent && !analytics_enabled {
return Ok(());
}
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<Timer, MetricsError> {
Ok(Timer::new(name, tags, self))
}
/// Collect a runtime metrics snapshot without shutting down the provider.
pub fn snapshot(&self) -> Result<ResourceMetrics> {
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<KeyValue> {
// Provider creation must not repeat OS discovery subprocesses.
static OS_INFO: LazyLock<os_info::Info> = 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<E>(
resource: Resource,
exporter: E,
interval: Option<Duration>,
runtime_reader: Option<Arc<ManualReader>>,
) -> (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)
}
fn otlp_metrics_temporality(exporter: &OtelExporter, preference: Option<&str>) -> Temporality {
// Select before resolving Statsig to OTLP so its built-in route stays Delta.
match exporter {
OtelExporter::None | OtelExporter::Statsig => Temporality::Delta,
OtelExporter::OtlpGrpc { .. } | OtelExporter::OtlpHttp { .. } => match preference {
Some(value) if value.eq_ignore_ascii_case("cumulative") => Temporality::Cumulative,
Some(value) if value.eq_ignore_ascii_case("lowmemory") => Temporality::LowMemory,
// Preserve Codex's existing default for unset, empty, or unknown values.
_ => Temporality::Delta,
},
}
}
fn build_otlp_metric_exporter(
exporter: OtelExporter,
temporality: Temporality,
factory: &codex_http_client::HttpClientFactory,
) -> Result<opentelemetry_otlp::MetricExporter> {
match exporter {
OtelExporter::None => Err(MetricsError::ExporterDisabled),
OtelExporter::Statsig => build_otlp_metric_exporter(
crate::config::resolve_exporter(&OtelExporter::Statsig),
temporality,
factory,
),
OtelExporter::OtlpGrpc {
endpoint,
headers,
tls,
} => {
debug!("Using OTLP Grpc exporter for metrics: {endpoint}");
let header_map = crate::otlp::build_header_map(&headers);
let base_tls_config = ClientTlsConfig::new()
.with_enabled_roots()
.assume_http2(true);
let tls_config = match tls.as_ref() {
Some(tls) => crate::otlp::build_grpc_tls_config(&endpoint, base_tls_config, tls)
.map_err(|err| MetricsError::InvalidConfig {
message: err.to_string(),
})?,
None => base_tls_config,
};
opentelemetry_otlp::MetricExporter::builder()
.with_tonic()
.with_endpoint(endpoint)
.with_temporality(temporality)
.with_metadata(MetadataMap::from_headers(header_map))
.with_tls_config(tls_config)
.build()
.map_err(|source| MetricsError::ExporterBuild { source })
}
OtelExporter::OtlpHttp {
endpoint,
headers,
protocol,
tls,
} => {
debug!("Using OTLP Http exporter for metrics: {endpoint}");
let protocol = match protocol {
OtelHttpProtocol::Binary => Protocol::HttpBinary,
OtelHttpProtocol::Json => Protocol::HttpJson,
};
let mut exporter_builder = opentelemetry_otlp::MetricExporter::builder()
.with_http()
.with_endpoint(endpoint)
.with_temporality(temporality)
.with_protocol(protocol)
.with_headers(headers);
if factory.network_policy().is_managed() {
let client = crate::otlp::build_async_http_client(
factory,
tls.as_ref(),
OTEL_EXPORTER_OTLP_METRICS_TIMEOUT,
)
.map_err(|err| MetricsError::InvalidConfig {
message: err.to_string(),
})?;
exporter_builder = exporter_builder.with_http_client(client);
} else if let Some(tls) = tls.as_ref() {
let client =
crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_METRICS_TIMEOUT)
.map_err(|err| MetricsError::InvalidConfig {
message: err.to_string(),
})?;
exporter_builder = exporter_builder.with_http_client(client);
}
exporter_builder
.build()
.map_err(|source| MetricsError::ExporterBuild { source })
}
}
}

View File

@@ -0,0 +1,57 @@
//! Consent follows the actual counter destination across exporter replacements.
use super::*;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::metrics::data::ScopeMetrics;
use opentelemetry_sdk::metrics::data::SumDataPoint;
use pretty_assertions::assert_eq;
#[test]
fn counter_consent_uses_the_active_exporter() -> Result<()> {
let mut builtin = MetricsClient::new(
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
)?;
// Use the existing in-memory exporter to observe the built-in consent policy without
// contacting Statsig (the real Statsig exporter is disabled in debug builds).
Arc::get_mut(&mut builtin.inner)
.expect("unique provider")
.requires_analytics_consent = true;
let custom = MetricsClient::new(
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
)?;
let active = Arc::new(RwLock::new(Arc::clone(&builtin.inner)));
let metrics = MetricsClient {
inner: Arc::clone(&builtin.inner),
active: Some(Arc::clone(&active)),
};
// A config reload alone does not replace the installed built-in exporter.
for analytics_enabled in [false, true] {
metrics.counter_with_analytics_consent(
"test.observations",
/*inc*/ 1,
&[],
analytics_enabled,
)?;
}
*active.write().unwrap() = Arc::clone(&custom.inner);
metrics.counter_with_analytics_consent(
"test.observations",
/*inc*/ 1,
&[],
/*analytics_enabled*/ false,
)?;
let mut counts = Vec::new();
for destination in [&builtin, &custom] {
let snapshot = destination.snapshot()?;
for metric in snapshot.scope_metrics().flat_map(ScopeMetrics::metrics) {
if let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() {
counts.extend(sum.data_points().map(SumDataPoint::value));
}
}
}
assert_eq!(counts, vec![1, 1]);
Ok(())
}

View File

@@ -0,0 +1,135 @@
use crate::config::OtelExporter;
use crate::metrics::Result;
use crate::metrics::names::API_CALL_COUNT_METRIC;
use crate::metrics::names::API_CALL_DURATION_METRIC;
use crate::metrics::names::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC;
use crate::metrics::names::RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC;
use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC;
use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC;
use crate::metrics::names::TOOL_CALL_COUNT_METRIC;
use crate::metrics::names::TOOL_CALL_DURATION_METRIC;
use crate::metrics::names::TURN_COST_MICROUSD_METRIC;
use crate::metrics::names::TURN_TOKEN_USAGE_METRIC;
use crate::metrics::validation::validate_tag_key;
use crate::metrics::validation::validate_tag_value;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use std::collections::BTreeMap;
use std::time::Duration;
const CONVERSATION_TURN_COUNT_METRIC: &str = "codex.conversation.turn.count";
// Metrics intentionally not sent through Codex's built-in Statsig route.
// Keep this as an exact-name list so custom OTLP exporters still receive them.
const STATSIG_DISABLED_METRICS: &[&str] = &[
API_CALL_COUNT_METRIC,
API_CALL_DURATION_METRIC,
CONVERSATION_TURN_COUNT_METRIC,
// Caller-side executor volume belongs in configured observability collectors.
EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC,
RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC,
RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC,
RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC,
TOOL_CALL_COUNT_METRIC,
TOOL_CALL_DURATION_METRIC,
TURN_COST_MICROUSD_METRIC,
TURN_TOKEN_USAGE_METRIC,
];
#[derive(Clone, Debug)]
pub enum MetricsExporter {
Otlp(OtelExporter),
InMemory(InMemoryMetricExporter),
}
#[derive(Clone, Debug)]
pub struct MetricsConfig {
pub(crate) http_client_factory: codex_http_client::HttpClientFactory,
pub(crate) environment: String,
pub(crate) service_name: String,
pub(crate) service_version: String,
pub(crate) exporter: MetricsExporter,
pub(crate) export_interval: Option<Duration>,
pub(crate) runtime_reader: bool,
pub(crate) statsig_disabled_metrics: &'static [&'static str],
pub(crate) default_tags: BTreeMap<String, String>,
}
impl MetricsConfig {
pub fn with_http_client_factory(
mut self,
factory: codex_http_client::HttpClientFactory,
) -> Self {
self.http_client_factory = factory;
self
}
pub fn otlp(
environment: impl Into<String>,
service_name: impl Into<String>,
service_version: impl Into<String>,
exporter: OtelExporter,
) -> Self {
let statsig_disabled_metrics = if matches!(exporter, OtelExporter::Statsig) {
STATSIG_DISABLED_METRICS
} else {
&[]
};
Self {
http_client_factory: codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
environment: environment.into(),
service_name: service_name.into(),
service_version: service_version.into(),
exporter: MetricsExporter::Otlp(exporter),
export_interval: None,
runtime_reader: false,
statsig_disabled_metrics,
default_tags: BTreeMap::new(),
}
}
/// Create an in-memory config (used in tests).
pub fn in_memory(
environment: impl Into<String>,
service_name: impl Into<String>,
service_version: impl Into<String>,
exporter: InMemoryMetricExporter,
) -> Self {
Self {
http_client_factory: codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
),
environment: environment.into(),
service_name: service_name.into(),
service_version: service_version.into(),
exporter: MetricsExporter::InMemory(exporter),
export_interval: None,
runtime_reader: false,
statsig_disabled_metrics: &[],
default_tags: BTreeMap::new(),
}
}
/// Override the interval between periodic metric exports.
pub fn with_export_interval(mut self, interval: Duration) -> Self {
self.export_interval = Some(interval);
self
}
/// Enable a manual reader for on-demand runtime snapshots.
pub fn with_runtime_reader(mut self) -> Self {
self.runtime_reader = true;
self
}
/// Add a default tag that will be sent with every metric.
pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Result<Self> {
let key = key.into();
let value = value.into();
validate_tag_key(&key)?;
validate_tag_value(&value)?;
self.default_tags.insert(key, value);
Ok(self)
}
}

View File

@@ -0,0 +1,49 @@
use thiserror::Error;
pub type Result<T> = std::result::Result<T, MetricsError>;
#[derive(Debug, Error)]
pub enum MetricsError {
#[error("operation metrics exceed the metadata size or tag count limit")]
OperationMetadataTooLarge,
// Metrics.
#[error("metric name cannot be empty")]
EmptyMetricName,
#[error("metric name contains invalid characters: {name}")]
InvalidMetricName { name: String },
#[error("{label} cannot be empty")]
EmptyTagComponent { label: String },
#[error("{label} contains invalid characters: {value}")]
InvalidTagComponent { label: String, value: String },
#[error("metrics exporter is disabled")]
ExporterDisabled,
#[error("counter increment must be non-negative for {name}: {inc}")]
NegativeCounterIncrement { name: String, inc: i64 },
#[error("failed to build OTLP metrics exporter")]
ExporterBuild {
#[source]
source: opentelemetry_otlp::ExporterBuildError,
},
#[error("invalid OTLP metrics configuration: {message}")]
InvalidConfig { message: String },
#[error("failed to flush or shutdown metrics provider")]
ProviderShutdown {
#[source]
source: opentelemetry_sdk::error::OTelSdkError,
},
#[error("runtime metrics snapshot reader is not enabled")]
RuntimeSnapshotUnavailable,
#[error("failed to collect runtime metrics snapshot from metrics reader")]
RuntimeSnapshotCollect {
#[source]
source: opentelemetry_sdk::error::OTelSdkError,
},
}

View File

@@ -0,0 +1,61 @@
pub(crate) mod buffered;
mod client;
mod config;
mod error;
pub(crate) mod names;
mod process;
pub(crate) mod runtime_metrics;
pub(crate) mod tags;
pub(crate) mod timer;
pub(crate) mod validation;
use crate::config::StatsigMetricsSettings;
pub use crate::metrics::buffered::record_global_operation;
pub use crate::metrics::client::MetricsClient;
pub use crate::metrics::config::MetricsConfig;
pub use crate::metrics::config::MetricsExporter;
pub use crate::metrics::error::MetricsError;
pub use crate::metrics::error::Result;
pub use crate::metrics::process::record_process_start_once;
pub use names::*;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::RwLock;
pub use tags::ORIGINATOR_TAG;
pub use tags::SessionMetricTagValues;
pub use tags::bounded_originator_tag_value;
static GLOBAL_METRICS: OnceLock<MetricsClient> = OnceLock::new();
static GLOBAL_STATSIG_METRICS_SETTINGS: OnceLock<StatsigMetricsSettings> = OnceLock::new();
pub(crate) fn install_global(mut metrics: MetricsClient) -> MetricsClient {
let active = GLOBAL_METRICS
.get()
.and_then(|current| current.active.clone())
.unwrap_or_else(|| Arc::new(RwLock::new(Arc::clone(&metrics.inner))));
*active
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::clone(&metrics.inner);
metrics.active = Some(active);
let _ = GLOBAL_METRICS.set(metrics.clone());
buffered::GLOBAL.enable(&metrics);
metrics
}
pub fn global() -> Option<MetricsClient> {
GLOBAL_METRICS.get().cloned()
}
pub(crate) fn install_global_statsig_settings(settings: StatsigMetricsSettings) {
let _ = GLOBAL_STATSIG_METRICS_SETTINGS.set(settings);
}
pub(crate) fn global_statsig_settings() -> Option<StatsigMetricsSettings> {
if GLOBAL_METRICS
.get()
.is_some_and(|metrics| metrics.active_inner().network_policy.is_managed())
{
return None;
}
GLOBAL_STATSIG_METRICS_SETTINGS.get().cloned()
}

View File

@@ -0,0 +1,148 @@
use std::sync::LazyLock;
pub const TOOL_CALL_COUNT_METRIC: &str = "codex.tool.call";
pub const TOOL_CALL_DURATION_METRIC: &str = "codex.tool.call.duration_ms";
pub const TOOL_CALL_UNIFIED_EXEC_METRIC: &str = "codex.tool.unified_exec";
pub const MULTI_AGENT_SPAWN_FAILURE_METRIC: &str = "codex.multi_agent.spawn.failure";
pub const MULTI_AGENT_SPAWN_PHASE_DURATION_METRIC: &str =
"codex.multi_agent.spawn.phase.duration_ms";
pub const ARTIFACT_OPERATION_STARTED_METRIC: &str = "codex.artifact.operation.started";
pub const ARTIFACT_OPERATION_EXPECTED_OUTPUT_COUNT_METRIC: &str =
"codex.artifact.operation.expected_output_count";
pub const PROCESS_START_METRIC: &str = "codex.process.start";
/// Caller-side exec-server RPC attempts, including local admission and transport failures.
pub const EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC: &str = "exec_server_client_requests_total";
pub const API_CALL_COUNT_METRIC: &str = "codex.api_request";
pub const API_CALL_DURATION_METRIC: &str = "codex.api_request.duration_ms";
pub const SSE_EVENT_COUNT_METRIC: &str = "codex.sse_event";
pub const SSE_EVENT_DURATION_METRIC: &str = "codex.sse_event.duration_ms";
pub const WEBSOCKET_CONNECT_COUNT_METRIC: &str = "codex.websocket.connect";
pub const WEBSOCKET_CONNECT_DURATION_METRIC: &str = "codex.websocket.connect.duration_ms";
pub const WEBSOCKET_REQUEST_COUNT_METRIC: &str = "codex.websocket.request";
pub const WEBSOCKET_CONTINUATION_COUNT_METRIC: &str = "codex.websocket.continuation";
pub const WEBSOCKET_REQUEST_DURATION_METRIC: &str = "codex.websocket.request.duration_ms";
pub const WEBSOCKET_EVENT_COUNT_METRIC: &str = "codex.websocket.event";
pub const WEBSOCKET_EVENT_DURATION_METRIC: &str = "codex.websocket.event.duration_ms";
pub const RESPONSES_API_OVERHEAD_DURATION_METRIC: &str = "codex.responses_api_overhead.duration_ms";
pub const RESPONSES_API_INFERENCE_TIME_DURATION_METRIC: &str =
"codex.responses_api_inference_time.duration_ms";
pub const RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC: &str =
"codex.responses_api_engine_iapi_ttft.duration_ms";
pub const RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC: &str =
"codex.responses_api_engine_service_ttft.duration_ms";
pub const RESPONSES_API_ENGINE_IAPI_TBT_DURATION_METRIC: &str =
"codex.responses_api_engine_iapi_tbt.duration_ms";
pub const RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC: &str =
"codex.responses_api_engine_service_tbt.duration_ms";
pub const TURN_E2E_DURATION_METRIC: &str = "codex.turn.e2e_duration_ms";
pub const TURN_TTFT_DURATION_METRIC: &str = "codex.turn.ttft.duration_ms";
pub const TURN_TTFM_DURATION_METRIC: &str = "codex.turn.ttfm.duration_ms";
pub const TURN_CRITICAL_PATH_CAPTURE_METRIC: &str = "codex.turn.critical_path.capture";
pub const TURN_CRITICAL_PATH_DURATION_METRIC: &str = "codex.turn.critical_path.duration_ms";
pub const TURN_CRITICAL_PATH_COMPONENT_METRIC: &str = "codex.turn.critical_path.component_ms";
pub const TURN_NETWORK_PROXY_METRIC: &str = "codex.turn.network_proxy";
pub const TURN_MEMORY_METRIC: &str = "codex.turn.memory";
pub const TURN_TOOL_CALL_METRIC: &str = "codex.turn.tool.call";
pub const TURN_TOKEN_USAGE_METRIC: &str = "codex.turn.token_usage";
pub const TURN_COST_MICROUSD_METRIC: &str = "codex.turn.cost_microusd";
pub const TURN_UNIFIED_EXEC_RUNNING_PROCESSES_METRIC: &str =
"codex.turn.unified_exec.running_processes";
pub const GUARDIAN_REVIEW_COUNT_METRIC: &str = "codex.guardian.review";
pub const GUARDIAN_REVIEW_DURATION_METRIC: &str = "codex.guardian.review.duration_ms";
pub const GUARDIAN_REVIEW_TTFT_DURATION_METRIC: &str = "codex.guardian.review.ttft.duration_ms";
pub const GUARDIAN_REVIEW_TOKEN_USAGE_METRIC: &str = "codex.guardian.review.token_usage";
pub const GUARDIAN_REVIEW_TRUNCATION_METRIC: &str = "codex.guardian.review.truncation";
pub const GUARDIAN_REVIEW_TRUNCATION_BYTES_METRIC: &str = "codex.guardian.review.truncation.bytes";
pub const GOAL_CREATED_METRIC: &str = "codex.goal.created";
pub const GOAL_RESUMED_METRIC: &str = "codex.goal.resumed";
pub const GOAL_COMPLETED_METRIC: &str = "codex.goal.completed";
pub const GOAL_BUDGET_LIMITED_METRIC: &str = "codex.goal.budget_limited";
pub const GOAL_USAGE_LIMITED_METRIC: &str = "codex.goal.usage_limited";
pub const GOAL_BLOCKED_METRIC: &str = "codex.goal.blocked";
pub const GOAL_TOKEN_COUNT_METRIC: &str = "codex.goal.token_count";
pub const GOAL_DURATION_SECONDS_METRIC: &str = "codex.goal.duration_s";
pub const PLUGIN_INSTALL_ELICITATION_SENT_METRIC: &str = "codex.plugins.install_elicitation.sent";
pub const PLUGIN_INSTALL_SUGGESTION_METRIC: &str = "codex.plugins.install_suggestion";
pub const CURATED_PLUGINS_STARTUP_SYNC_METRIC: &str = "codex.plugins.startup_sync";
pub const CURATED_PLUGINS_STARTUP_SYNC_FINAL_METRIC: &str = "codex.plugins.startup_sync.final";
pub const HOOK_RUN_METRIC: &str = "codex.hooks.run";
pub const HOOK_RUN_DURATION_METRIC: &str = "codex.hooks.run.duration_ms";
/// Duration for coarse startup phases, tagged by low-cardinality phase and status.
pub const STARTUP_PHASE_DURATION_METRIC: &str = "codex.startup.phase.duration_ms";
/// Total runtime of a startup prewarm attempt until it completes, tagged by final status.
pub const STARTUP_PREWARM_DURATION_METRIC: &str = "codex.startup_prewarm.duration_ms";
/// Age of the startup prewarm attempt when the first real turn resolves it, tagged by outcome.
pub const STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC: &str =
"codex.startup_prewarm.age_at_first_turn_ms";
pub const THREAD_STARTED_METRIC: &str = "codex.thread.started";
/// Submitted additional-context entries, including unchanged entries, by kind and truncation status.
/// The name tag is included only when explicitly supplied; opaque source keys are never tags.
pub const ADDITIONAL_CONTEXT_COUNT_METRIC: &str = "codex.additional_context";
/// UTF-8 value bytes before/after truncation, excluding message wrappers; after includes the marker.
pub const ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC: &str = "codex.additional_context.value_bytes";
/// Logarithmic byte buckets through 4 MiB, with a 4 KiB boundary near the truncation cap.
pub static ADDITIONAL_CONTEXT_VALUE_BYTES_BUCKETS: LazyLock<Vec<f64>> = LazyLock::new(|| {
let mut buckets = context_log_buckets(/*max_exponent*/ 22.0)
.into_iter()
.chain([4096.0])
.collect::<Vec<_>>();
buckets.sort_by(f64::total_cmp);
buckets.dedup();
buckets
});
pub const THREAD_SKILLS_ENABLED_TOTAL_METRIC: &str = "codex.thread.skills.enabled_total";
pub const THREAD_SKILLS_KEPT_TOTAL_METRIC: &str = "codex.thread.skills.kept_total";
pub const THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC: &str =
"codex.thread.skills.description_truncated_chars";
pub const THREAD_SKILLS_TRUNCATED_METRIC: &str = "codex.thread.skills.truncated";
// Tools measure the rendered block; kind=snapshot|delta distinguishes full catalogs from updates.
pub const THREAD_TOOLS_NAMESPACES_TOTAL_METRIC: &str = "codex.thread.tools.namespaces_total";
pub const THREAD_TOOLS_FRAGMENT_BYTES_METRIC: &str = "codex.thread.tools.fragment_bytes";
/// Finalized tool registrations per sampling request, tagged by exposure, tool_mode,
/// and effective incremental_tools mode.
pub const TOOL_REGISTRATIONS_METRIC: &str = "codex.tools.registered";
pub const TOOL_REGISTRATIONS_METRIC_BUCKETS: &[f64] = &[
0.0, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0, 50.0, 75.0, 100.0, 150.0, 200.0, 300.0, 500.0, 750.0,
1_000.0, 2_000.0, 5_000.0, 10_000.0, 20_000.0,
];
/// Logarithmic boundaries up to 32,768 for tools bytes and namespace counts.
pub static THREAD_TOOLS_METRIC_BUCKETS: LazyLock<[f64; 511]> =
LazyLock::new(|| context_log_buckets(/*max_exponent*/ 15.0));
/// Rendered incremental tool deltas by action and qualified tool; excludes initial catalogs.
/// schema_changed includes any definition change, such as description edits.
pub const TOOL_INCREMENTAL_UPDATES_METRIC: &str = "codex.tools.incremental_updates";
/// UTF-8 description bytes on replacement by qualified tool; skips missing descriptions.
pub const TOOL_SPEC_DESCRIPTION_BYTES_METRIC: &str = "codex.tools.spec_description_bytes";
/// Logarithmic boundaries up to 1 MiB.
pub static TOOL_SPEC_DESCRIPTION_BYTES_METRIC_BUCKETS: LazyLock<[f64; 511]> =
LazyLock::new(|| context_log_buckets(/*max_exponent*/ 20.0));
/// Rendered exec entry deltas (tools and namespace instructions), by action.
/// Excludes full declarations; schema_changed includes any entry replacement.
pub const EXEC_TOOL_ENTRY_UPDATES_METRIC: &str = "codex.tools.exec_entry_updates";
/// UTF-8 bytes per rendered added/changed exec batch, including hint and framing.
/// Excludes full declarations and removal notices.
pub const EXEC_TOOL_UPDATE_BYTES_METRIC: &str = "codex.tools.exec_update_bytes";
pub static THREAD_SKILLS_COUNT_METRIC_BUCKETS: LazyLock<[f64; 513]> =
LazyLock::new(|| std::array::from_fn(|index| index as f64));
/// Logarithmic boundaries up to 131,072 removed description characters.
pub static THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_BUCKETS: LazyLock<[f64; 511]> =
LazyLock::new(|| context_log_buckets(/*max_exponent*/ 17.0));
pub const THREAD_SKILLS_TRUNCATED_BUCKETS: &[f64] = &[0.0, 1.0];
fn context_log_buckets(max_exponent: f64) -> [f64; 511] {
std::array::from_fn(|index| {
if index == 0 {
0.0
} else {
2.0_f64.powf(max_exponent * (index - 1) as f64 / 509.0)
}
})
}

View File

@@ -0,0 +1,27 @@
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use super::client::MetricsClient;
use super::error::Result;
use super::names::PROCESS_START_METRIC;
use super::tags::ORIGINATOR_TAG;
use super::tags::bounded_originator_tag_value;
static PROCESS_START_RECORDED: AtomicBool = AtomicBool::new(false);
/// Record the process start counter at most once for this process.
pub fn record_process_start_once(metrics: &MetricsClient, originator: &str) -> Result<bool> {
if PROCESS_START_RECORDED
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return Ok(false);
}
metrics.counter(
PROCESS_START_METRIC,
/*inc*/ 1,
&[(ORIGINATOR_TAG, bounded_originator_tag_value(originator))],
)?;
Ok(true)
}

View File

@@ -0,0 +1,220 @@
use crate::metrics::names::API_CALL_COUNT_METRIC;
use crate::metrics::names::API_CALL_DURATION_METRIC;
use crate::metrics::names::RESPONSES_API_ENGINE_IAPI_TBT_DURATION_METRIC;
use crate::metrics::names::RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC;
use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC;
use crate::metrics::names::RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC;
use crate::metrics::names::RESPONSES_API_INFERENCE_TIME_DURATION_METRIC;
use crate::metrics::names::RESPONSES_API_OVERHEAD_DURATION_METRIC;
use crate::metrics::names::SSE_EVENT_COUNT_METRIC;
use crate::metrics::names::SSE_EVENT_DURATION_METRIC;
use crate::metrics::names::TOOL_CALL_COUNT_METRIC;
use crate::metrics::names::TOOL_CALL_DURATION_METRIC;
use crate::metrics::names::TURN_TTFM_DURATION_METRIC;
use crate::metrics::names::TURN_TTFT_DURATION_METRIC;
use crate::metrics::names::WEBSOCKET_EVENT_COUNT_METRIC;
use crate::metrics::names::WEBSOCKET_EVENT_DURATION_METRIC;
use crate::metrics::names::WEBSOCKET_REQUEST_COUNT_METRIC;
use crate::metrics::names::WEBSOCKET_REQUEST_DURATION_METRIC;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::Metric;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::metrics::data::ResourceMetrics;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RuntimeMetricTotals {
pub count: u64,
pub duration_ms: u64,
}
impl RuntimeMetricTotals {
pub fn is_empty(self) -> bool {
self.count == 0 && self.duration_ms == 0
}
pub fn merge(&mut self, other: Self) {
self.count = self.count.saturating_add(other.count);
self.duration_ms = self.duration_ms.saturating_add(other.duration_ms);
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct RuntimeMetricsSummary {
pub tool_calls: RuntimeMetricTotals,
pub api_calls: RuntimeMetricTotals,
pub streaming_events: RuntimeMetricTotals,
pub websocket_calls: RuntimeMetricTotals,
pub websocket_events: RuntimeMetricTotals,
pub responses_api_overhead_ms: u64,
pub responses_api_inference_time_ms: u64,
pub responses_api_engine_iapi_ttft_ms: u64,
pub responses_api_engine_service_ttft_ms: u64,
pub responses_api_engine_iapi_tbt_ms: f64,
pub responses_api_engine_service_tbt_ms: f64,
pub turn_ttft_ms: u64,
pub turn_ttfm_ms: u64,
}
impl RuntimeMetricsSummary {
pub fn is_empty(self) -> bool {
self.tool_calls.is_empty()
&& self.api_calls.is_empty()
&& self.streaming_events.is_empty()
&& self.websocket_calls.is_empty()
&& self.websocket_events.is_empty()
&& self.responses_api_overhead_ms == 0
&& self.responses_api_inference_time_ms == 0
&& self.responses_api_engine_iapi_ttft_ms == 0
&& self.responses_api_engine_service_ttft_ms == 0
&& self.responses_api_engine_iapi_tbt_ms == 0.0
&& self.responses_api_engine_service_tbt_ms == 0.0
&& self.turn_ttft_ms == 0
&& self.turn_ttfm_ms == 0
}
pub fn merge(&mut self, other: Self) {
self.tool_calls.merge(other.tool_calls);
self.api_calls.merge(other.api_calls);
self.streaming_events.merge(other.streaming_events);
self.websocket_calls.merge(other.websocket_calls);
self.websocket_events.merge(other.websocket_events);
if other.responses_api_overhead_ms > 0 {
self.responses_api_overhead_ms = other.responses_api_overhead_ms;
}
if other.responses_api_inference_time_ms > 0 {
self.responses_api_inference_time_ms = other.responses_api_inference_time_ms;
}
if other.responses_api_engine_iapi_ttft_ms > 0 {
self.responses_api_engine_iapi_ttft_ms = other.responses_api_engine_iapi_ttft_ms;
}
if other.responses_api_engine_service_ttft_ms > 0 {
self.responses_api_engine_service_ttft_ms = other.responses_api_engine_service_ttft_ms;
}
if other.responses_api_engine_iapi_tbt_ms > 0.0 {
self.responses_api_engine_iapi_tbt_ms = other.responses_api_engine_iapi_tbt_ms;
}
if other.responses_api_engine_service_tbt_ms > 0.0 {
self.responses_api_engine_service_tbt_ms = other.responses_api_engine_service_tbt_ms;
}
if other.turn_ttft_ms > 0 {
self.turn_ttft_ms = other.turn_ttft_ms;
}
if other.turn_ttfm_ms > 0 {
self.turn_ttfm_ms = other.turn_ttfm_ms;
}
}
pub fn responses_api_summary(&self) -> RuntimeMetricsSummary {
Self {
responses_api_overhead_ms: self.responses_api_overhead_ms,
responses_api_inference_time_ms: self.responses_api_inference_time_ms,
responses_api_engine_iapi_ttft_ms: self.responses_api_engine_iapi_ttft_ms,
responses_api_engine_service_ttft_ms: self.responses_api_engine_service_ttft_ms,
responses_api_engine_iapi_tbt_ms: self.responses_api_engine_iapi_tbt_ms,
responses_api_engine_service_tbt_ms: self.responses_api_engine_service_tbt_ms,
..RuntimeMetricsSummary::default()
}
}
pub(crate) fn from_snapshot(snapshot: &ResourceMetrics) -> Self {
let tool_calls = RuntimeMetricTotals {
count: sum_counter(snapshot, TOOL_CALL_COUNT_METRIC),
duration_ms: sum_histogram_ms(snapshot, TOOL_CALL_DURATION_METRIC),
};
let api_calls = RuntimeMetricTotals {
count: sum_counter(snapshot, API_CALL_COUNT_METRIC),
duration_ms: sum_histogram_ms(snapshot, API_CALL_DURATION_METRIC),
};
let streaming_events = RuntimeMetricTotals {
count: sum_counter(snapshot, SSE_EVENT_COUNT_METRIC),
duration_ms: sum_histogram_ms(snapshot, SSE_EVENT_DURATION_METRIC),
};
let websocket_calls = RuntimeMetricTotals {
count: sum_counter(snapshot, WEBSOCKET_REQUEST_COUNT_METRIC),
duration_ms: sum_histogram_ms(snapshot, WEBSOCKET_REQUEST_DURATION_METRIC),
};
let websocket_events = RuntimeMetricTotals {
count: sum_counter(snapshot, WEBSOCKET_EVENT_COUNT_METRIC),
duration_ms: sum_histogram_ms(snapshot, WEBSOCKET_EVENT_DURATION_METRIC),
};
let responses_api_overhead_ms =
sum_histogram_ms(snapshot, RESPONSES_API_OVERHEAD_DURATION_METRIC);
let responses_api_inference_time_ms =
sum_histogram_ms(snapshot, RESPONSES_API_INFERENCE_TIME_DURATION_METRIC);
let responses_api_engine_iapi_ttft_ms =
sum_histogram_ms(snapshot, RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC);
let responses_api_engine_service_ttft_ms =
sum_histogram_ms(snapshot, RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC);
let responses_api_engine_iapi_tbt_ms =
sum_histogram_f64(snapshot, RESPONSES_API_ENGINE_IAPI_TBT_DURATION_METRIC);
let responses_api_engine_service_tbt_ms =
sum_histogram_f64(snapshot, RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC);
let turn_ttft_ms = sum_histogram_ms(snapshot, TURN_TTFT_DURATION_METRIC);
let turn_ttfm_ms = sum_histogram_ms(snapshot, TURN_TTFM_DURATION_METRIC);
Self {
tool_calls,
api_calls,
streaming_events,
websocket_calls,
websocket_events,
responses_api_overhead_ms,
responses_api_inference_time_ms,
responses_api_engine_iapi_ttft_ms,
responses_api_engine_service_ttft_ms,
responses_api_engine_iapi_tbt_ms,
responses_api_engine_service_tbt_ms,
turn_ttft_ms,
turn_ttfm_ms,
}
}
}
fn sum_counter(snapshot: &ResourceMetrics, name: &str) -> u64 {
snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.filter(|metric| metric.name() == name)
.map(sum_counter_metric)
.sum()
}
fn sum_counter_metric(metric: &Metric) -> u64 {
match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => sum
.data_points()
.map(opentelemetry_sdk::metrics::data::SumDataPoint::value)
.sum(),
_ => 0,
}
}
fn sum_histogram_ms(snapshot: &ResourceMetrics, name: &str) -> u64 {
f64_to_u64(sum_histogram_f64(snapshot, name))
}
fn sum_histogram_f64(snapshot: &ResourceMetrics, name: &str) -> f64 {
snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.filter(|metric| metric.name() == name)
.map(sum_histogram_metric)
.sum()
}
fn sum_histogram_metric(metric: &Metric) -> f64 {
match metric.data() {
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram
.data_points()
.map(opentelemetry_sdk::metrics::data::HistogramDataPoint::sum)
.sum(),
_ => 0.0,
}
}
fn f64_to_u64(value: f64) -> u64 {
if !value.is_finite() || value <= 0.0 {
return 0;
}
let clamped = value.min(u64::MAX as f64);
clamped.round() as u64
}

View File

@@ -0,0 +1,136 @@
use crate::metrics::Result;
use crate::metrics::validation::validate_tag_key;
use crate::metrics::validation::validate_tag_value;
use codex_utils_string::sanitize_metric_tag_value;
pub const APP_VERSION_TAG: &str = "app.version";
pub const AUTH_MODE_TAG: &str = "auth_mode";
pub const MODEL_TAG: &str = "model";
pub const ORIGINATOR_TAG: &str = "originator";
pub const SERVICE_NAME_TAG: &str = "service_name";
pub const SESSION_SOURCE_TAG: &str = "session_source";
const OTHER_ORIGINATOR_TAG_VALUE: &str = "other";
const KNOWN_ORIGINATOR_TAG_VALUES: &[&str] = &[
"codex_desktop",
"codex-app-server",
"codex_mcp_server",
"codex_cli_rs",
"codex-tui",
"codex_vscode",
"none",
"codex_exec",
"codex-cli",
"codex_sdk_ts",
"codex-app-server-sdk",
];
/// Return a known low-cardinality originator tag value, or `other`.
pub fn bounded_originator_tag_value(originator: &str) -> &'static str {
let sanitized = sanitize_metric_tag_value(originator);
KNOWN_ORIGINATOR_TAG_VALUES
.iter()
.copied()
.find(|known| *known == sanitized.as_str())
.unwrap_or(OTHER_ORIGINATOR_TAG_VALUE)
}
pub struct SessionMetricTagValues<'a> {
pub auth_mode: Option<&'a str>,
pub session_source: &'a str,
pub originator: &'a str,
pub service_name: Option<&'a str>,
pub model: &'a str,
pub app_version: &'a str,
}
impl<'a> SessionMetricTagValues<'a> {
pub fn into_tags(self) -> Result<Vec<(&'static str, &'a str)>> {
let mut tags = Vec::with_capacity(6);
Self::push_optional_tag(&mut tags, AUTH_MODE_TAG, self.auth_mode)?;
Self::push_optional_tag(&mut tags, SESSION_SOURCE_TAG, Some(self.session_source))?;
Self::push_optional_tag(&mut tags, ORIGINATOR_TAG, Some(self.originator))?;
Self::push_optional_tag(&mut tags, SERVICE_NAME_TAG, self.service_name)?;
Self::push_optional_tag(&mut tags, MODEL_TAG, Some(self.model))?;
Self::push_optional_tag(&mut tags, APP_VERSION_TAG, Some(self.app_version))?;
Ok(tags)
}
fn push_optional_tag(
tags: &mut Vec<(&'static str, &'a str)>,
key: &'static str,
value: Option<&'a str>,
) -> Result<()> {
let Some(value) = value else {
return Ok(());
};
validate_tag_key(key)?;
validate_tag_value(value)?;
tags.push((key, value));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::APP_VERSION_TAG;
use super::AUTH_MODE_TAG;
use super::MODEL_TAG;
use super::ORIGINATOR_TAG;
use super::SERVICE_NAME_TAG;
use super::SESSION_SOURCE_TAG;
use super::SessionMetricTagValues;
use pretty_assertions::assert_eq;
#[test]
fn session_metric_tags_include_expected_tags_in_order() {
for app_version in ["1.2.3", "0.164.0-alpha.1+internal"] {
let tags = SessionMetricTagValues {
auth_mode: Some("api_key"),
session_source: "cli",
originator: "codex_cli",
service_name: Some("desktop_app"),
model: "gpt-5.1",
app_version,
}
.into_tags()
.expect("tags");
assert_eq!(
tags,
vec![
(AUTH_MODE_TAG, "api_key"),
(SESSION_SOURCE_TAG, "cli"),
(ORIGINATOR_TAG, "codex_cli"),
(SERVICE_NAME_TAG, "desktop_app"),
(MODEL_TAG, "gpt-5.1"),
(APP_VERSION_TAG, app_version),
]
);
}
}
#[test]
fn session_metric_tags_skip_missing_optional_tags() {
let tags = SessionMetricTagValues {
auth_mode: None,
session_source: "exec",
originator: "codex_exec",
service_name: None,
model: "gpt-5.1",
app_version: "1.2.3",
}
.into_tags()
.expect("tags");
assert_eq!(
tags,
vec![
(SESSION_SOURCE_TAG, "exec"),
(ORIGINATOR_TAG, "codex_exec"),
(MODEL_TAG, "gpt-5.1"),
(APP_VERSION_TAG, "1.2.3"),
]
);
}
}

View File

@@ -0,0 +1,41 @@
use crate::metrics::MetricsClient;
use crate::metrics::error::Result;
use std::time::Instant;
#[derive(Debug)]
pub struct Timer {
name: String,
tags: Vec<(String, String)>,
client: MetricsClient,
start_time: Instant,
}
impl Drop for Timer {
fn drop(&mut self) {
if let Err(e) = self.record(&[]) {
tracing::error!("metrics client error: {}", e);
}
}
}
impl Timer {
pub(crate) fn new(name: &str, tags: &[(&str, &str)], client: &MetricsClient) -> Self {
Self {
name: name.to_string(),
tags: tags
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
client: client.clone(),
start_time: Instant::now(),
}
}
pub fn record(&self, additional_tags: &[(&str, &str)]) -> Result<()> {
let mut tags = Vec::with_capacity(self.tags.len() + additional_tags.len());
tags.extend(additional_tags);
tags.extend(self.tags.iter().map(|(k, v)| (k.as_str(), v.as_str())));
self.client
.record_duration(&self.name, self.start_time.elapsed(), &tags)
}
}

View File

@@ -0,0 +1,55 @@
use crate::metrics::error::MetricsError;
use crate::metrics::error::Result;
use std::collections::BTreeMap;
pub(crate) fn validate_tags(tags: &BTreeMap<String, String>) -> Result<()> {
for (key, value) in tags {
validate_tag_key(key)?;
validate_tag_value(value)?;
}
Ok(())
}
pub(crate) fn validate_metric_name(name: &str) -> Result<()> {
if name.is_empty() {
return Err(MetricsError::EmptyMetricName);
}
if !name.chars().all(is_metric_char) {
return Err(MetricsError::InvalidMetricName {
name: name.to_string(),
});
}
Ok(())
}
pub(crate) fn validate_tag_key(key: &str) -> Result<()> {
validate_tag_component(key, "tag key")?;
Ok(())
}
pub(crate) fn validate_tag_value(value: &str) -> Result<()> {
validate_tag_component(value, "tag value")
}
fn validate_tag_component(value: &str, label: &str) -> Result<()> {
if value.is_empty() {
return Err(MetricsError::EmptyTagComponent {
label: label.to_string(),
});
}
if !value.chars().all(is_tag_char) {
return Err(MetricsError::InvalidTagComponent {
label: label.to_string(),
value: value.to_string(),
});
}
Ok(())
}
fn is_metric_char(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')
}
fn is_tag_char(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/' | '+')
}

View File

@@ -0,0 +1,127 @@
//! OTLP SDK transports remain disabled under application destination restrictions.
//! Export futures are revocable, including HTTP exporters driven from SDK worker threads.
use bytes::Bytes;
use codex_http_client::NetworkPolicy;
use opentelemetry_http::HttpError;
use opentelemetry_sdk::Resource;
use opentelemetry_sdk::error::OTelSdkError;
use opentelemetry_sdk::error::OTelSdkResult;
use opentelemetry_sdk::logs::LogBatch;
use opentelemetry_sdk::logs::LogExporter;
use opentelemetry_sdk::metrics::Temporality;
use opentelemetry_sdk::metrics::data::ResourceMetrics;
use opentelemetry_sdk::metrics::exporter::PushMetricExporter;
use opentelemetry_sdk::trace::SpanData;
use opentelemetry_sdk::trace::SpanExporter;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
#[derive(Debug)]
pub(crate) struct PolicyExporter<E> {
pub(crate) exporter: E,
pub(crate) policy: NetworkPolicy,
}
fn denied(error: codex_http_client::NetworkPolicyDenied) -> OTelSdkError {
OTelSdkError::InternalFailure(error.to_string())
}
impl<E: SpanExporter> SpanExporter for PolicyExporter<E> {
async fn export(&self, batch: Vec<SpanData>) -> OTelSdkResult {
let permit = self.policy.acquire_for_unsupported_sdk().map_err(denied)?;
let export = self.exporter.export(batch);
permit.run(export).await.map_err(denied)?
}
fn shutdown_with_timeout(&mut self, timeout: Duration) -> OTelSdkResult {
self.exporter.shutdown_with_timeout(timeout)
}
fn force_flush(&mut self) -> OTelSdkResult {
self.exporter.force_flush()
}
fn set_resource(&mut self, resource: &Resource) {
self.exporter.set_resource(resource);
}
}
impl<E: LogExporter> LogExporter for PolicyExporter<E> {
async fn export(&self, batch: LogBatch<'_>) -> OTelSdkResult {
let permit = self.policy.acquire_for_unsupported_sdk().map_err(denied)?;
let export = self.exporter.export(batch);
permit.run(export).await.map_err(denied)?
}
fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult {
self.exporter.shutdown_with_timeout(timeout)
}
fn set_resource(&mut self, resource: &Resource) {
self.exporter.set_resource(resource);
}
}
impl<E: PushMetricExporter> PushMetricExporter for PolicyExporter<E> {
async fn export(&self, metrics: &ResourceMetrics) -> OTelSdkResult {
let permit = self.policy.acquire_for_unsupported_sdk().map_err(denied)?;
let export = self.exporter.export(metrics);
permit.run(export).await.map_err(denied)?
}
fn force_flush(&self) -> OTelSdkResult {
self.exporter.force_flush()
}
fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult {
self.exporter.shutdown_with_timeout(timeout)
}
fn temporality(&self) -> Temporality {
self.exporter.temporality()
}
}
/// Keeps blocking SDK worker threads from performing uncancellable HTTP I/O.
#[derive(Debug)]
pub(crate) struct RuntimeHttpClient {
pub(crate) client: codex_http_client::HttpClient,
pub(crate) timeout: Duration,
pub(crate) runtime: tokio::runtime::Handle,
}
impl opentelemetry_http::HttpClient for RuntimeHttpClient {
fn send_bytes<'client, 'request>(
&'client self,
request: http::Request<Bytes>,
) -> Pin<Box<dyn Future<Output = Result<http::Response<Bytes>, HttpError>> + Send + 'request>>
where
'client: 'request,
Self: 'request,
{
Box::pin(async move {
let client = self.client.clone();
let timeout = self.timeout;
let mut requests = tokio::task::JoinSet::new();
requests.spawn_on(
async move {
let (parts, body) = request.into_parts();
let response = client
.request(parts.method, parts.uri.to_string())
.version(parts.version)
.headers(parts.headers)
.body(body)
.timeout(timeout)
.send()
.await?
.error_for_status()?;
let mut builder = http::Response::builder().status(response.status());
if let Some(headers) = builder.headers_mut() {
*headers = response.headers().clone();
}
Ok::<_, HttpError>(builder.body(response.bytes().await?)?)
},
&self.runtime,
);
// Dropping the SDK export future drops this set and aborts the HTTP request.
requests
.join_next()
.await
.ok_or("telemetry request task disappeared")??
})
}
}

330
codex-rs/otel/src/otlp.rs Normal file
View File

@@ -0,0 +1,330 @@
use crate::config::OtelTlsConfig;
use codex_utils_absolute_path::AbsolutePathBuf;
use http::Uri;
use opentelemetry_otlp::OTEL_EXPORTER_OTLP_TIMEOUT;
use opentelemetry_otlp::OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT;
use opentelemetry_otlp::tonic_types::transport::Certificate as TonicCertificate;
use opentelemetry_otlp::tonic_types::transport::ClientTlsConfig;
use opentelemetry_otlp::tonic_types::transport::Identity as TonicIdentity;
use reqwest::Certificate as ReqwestCertificate;
use reqwest::Identity as ReqwestIdentity;
use reqwest::header::HeaderMap;
use reqwest::header::HeaderName;
use reqwest::header::HeaderValue;
use std::env;
use std::error::Error;
use std::fs;
use std::io;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::time::Duration;
pub(crate) fn build_header_map(headers: &std::collections::HashMap<String, String>) -> HeaderMap {
let mut header_map = HeaderMap::new();
for (key, value) in headers {
if let Ok(name) = HeaderName::from_bytes(key.as_bytes())
&& let Ok(val) = HeaderValue::from_str(value)
{
header_map.insert(name, val);
}
}
header_map
}
pub(crate) fn build_grpc_tls_config(
endpoint: &str,
tls_config: ClientTlsConfig,
tls: &OtelTlsConfig,
) -> Result<ClientTlsConfig, Box<dyn Error>> {
let uri: Uri = endpoint.parse()?;
let host = uri.host().ok_or_else(|| {
config_error(format!(
"OTLP gRPC endpoint {endpoint} does not include a host"
))
})?;
let mut config = tls_config.domain_name(host.to_owned());
if let Some(path) = tls.ca_certificate.as_ref() {
let (pem, _) = read_bytes(path)?;
config = config.ca_certificate(TonicCertificate::from_pem(pem));
}
match (&tls.client_certificate, &tls.client_private_key) {
(Some(cert_path), Some(key_path)) => {
let (cert_pem, _) = read_bytes(cert_path)?;
let (key_pem, _) = read_bytes(key_path)?;
config = config.identity(TonicIdentity::from_pem(cert_pem, key_pem));
}
(Some(_), None) | (None, Some(_)) => {
return Err(config_error(
"client_certificate and client_private_key must both be provided for mTLS",
));
}
(None, None) => {}
}
Ok(config)
}
/// Build a blocking HTTP client with TLS configuration for OTLP HTTP exporters.
///
/// We use `reqwest::blocking::Client` because OTEL exporters run on dedicated
/// OS threads that are not necessarily backed by tokio.
pub(crate) fn build_http_client(
tls: &OtelTlsConfig,
timeout_var: &str,
) -> Result<reqwest::blocking::Client, Box<dyn Error>> {
if current_tokio_runtime_is_multi_thread() {
tokio::task::block_in_place(|| build_http_client_inner(tls, timeout_var))
} else if tokio::runtime::Handle::try_current().is_ok() {
let tls = tls.clone();
let timeout_var = timeout_var.to_string();
std::thread::spawn(move || {
build_http_client_inner(&tls, &timeout_var).map_err(|err| err.to_string())
})
.join()
.map_err(|_| config_error("failed to join OTLP blocking HTTP client builder thread"))?
.map_err(config_error)
} else {
build_http_client_inner(tls, timeout_var)
}
}
pub(crate) fn current_tokio_runtime_is_multi_thread() -> bool {
match tokio::runtime::Handle::try_current() {
Ok(handle) => handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread,
Err(_) => false,
}
}
fn build_http_client_inner(
tls: &OtelTlsConfig,
timeout_var: &str,
) -> Result<reqwest::blocking::Client, Box<dyn Error>> {
let mut builder =
reqwest::blocking::Client::builder().timeout(resolve_otlp_timeout(timeout_var));
if let Some(path) = tls.ca_certificate.as_ref() {
let (pem, location) = read_bytes(path)?;
let certificate = ReqwestCertificate::from_pem(pem.as_slice()).map_err(|error| {
config_error(format!(
"failed to parse certificate {}: {error}",
location.display()
))
})?;
builder = builder
.tls_built_in_root_certs(false)
.add_root_certificate(certificate);
}
match (&tls.client_certificate, &tls.client_private_key) {
(Some(cert_path), Some(key_path)) => {
let (mut cert_pem, cert_location) = read_bytes(cert_path)?;
let (key_pem, key_location) = read_bytes(key_path)?;
cert_pem.extend_from_slice(key_pem.as_slice());
let identity = ReqwestIdentity::from_pem(cert_pem.as_slice()).map_err(|error| {
config_error(format!(
"failed to parse client identity using {} and {}: {error}",
cert_location.display(),
key_location.display()
))
})?;
builder = builder.use_rustls_tls().identity(identity).https_only(true);
}
(Some(_), None) | (None, Some(_)) => {
return Err(config_error(
"client_certificate and client_private_key must both be provided for mTLS",
));
}
(None, None) => {}
}
builder
.build()
.map_err(|error| Box::new(error) as Box<dyn Error>)
}
pub(crate) fn build_async_http_client(
factory: &codex_http_client::HttpClientFactory,
tls: Option<&OtelTlsConfig>,
timeout_var: &str,
) -> Result<crate::network_policy::RuntimeHttpClient, Box<dyn Error>> {
let mut config = codex_http_client::HttpClientTlsConfig::default();
if let Some(tls) = tls {
if let Some(path) = tls.ca_certificate.as_ref() {
let (pem, location) = read_bytes(path)?;
config = config
.with_root_certificate_pem(pem.as_slice())
.map_err(|error| {
config_error(format!(
"failed to parse certificate {}: {error}",
location.display()
))
})?;
}
match (&tls.client_certificate, &tls.client_private_key) {
(Some(cert_path), Some(key_path)) => {
let (mut cert_pem, cert_location) = read_bytes(cert_path)?;
let (key_pem, key_location) = read_bytes(key_path)?;
cert_pem.extend_from_slice(key_pem.as_slice());
config = config
.with_client_identity_pem(cert_pem.as_slice())
.map_err(|error| {
config_error(format!(
"failed to parse client identity using {} and {}: {error}",
cert_location.display(),
key_location.display()
))
})?;
}
(Some(_), None) | (None, Some(_)) => {
return Err(config_error(
"client_certificate and client_private_key must both be provided for mTLS",
));
}
(None, None) => {}
}
}
Ok(crate::network_policy::RuntimeHttpClient {
client: codex_http_client::HttpClientBuilder::new()
.without_request_logging()
.build_with_tls(factory, codex_http_client::ClientRouteClass::Other, config),
timeout: resolve_otlp_timeout(timeout_var),
runtime: tokio::runtime::Handle::try_current()?,
})
}
pub(crate) fn resolve_otlp_timeout(signal_var: &str) -> Duration {
if let Some(timeout) = read_timeout_env(signal_var) {
return timeout;
}
if let Some(timeout) = read_timeout_env(OTEL_EXPORTER_OTLP_TIMEOUT) {
return timeout;
}
OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT
}
fn read_timeout_env(var: &str) -> Option<Duration> {
let value = env::var(var).ok()?;
let parsed = value.parse::<i64>().ok()?;
if parsed < 0 {
return None;
}
Some(Duration::from_millis(parsed as u64))
}
fn read_bytes(path: &AbsolutePathBuf) -> Result<(Vec<u8>, PathBuf), Box<dyn Error>> {
match fs::read(path) {
Ok(bytes) => Ok((bytes, path.to_path_buf())),
Err(error) => Err(Box::new(io::Error::new(
error.kind(),
format!("failed to read {}: {error}", path.display()),
))),
}
}
fn config_error(message: impl Into<String>) -> Box<dyn Error> {
Box::new(io::Error::new(ErrorKind::InvalidData, message.into()))
}
#[cfg(test)]
mod tests {
use super::*;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use rcgen::CertifiedKey;
use rcgen::generate_simple_self_signed;
use std::fs;
use tempfile::TempDir;
use tokio::runtime::Builder;
#[test]
fn current_tokio_runtime_is_multi_thread_detects_runtime_flavor() {
assert!(!current_tokio_runtime_is_multi_thread());
let current_thread_runtime = Builder::new_current_thread()
.enable_all()
.build()
.expect("current-thread runtime");
assert_eq!(
current_thread_runtime.block_on(async { current_tokio_runtime_is_multi_thread() }),
false
);
let multi_thread_runtime = Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.expect("multi-thread runtime");
assert_eq!(
multi_thread_runtime.block_on(async { current_tokio_runtime_is_multi_thread() }),
true
);
}
#[test]
fn build_http_client_works_in_current_thread_runtime() {
let runtime = Builder::new_current_thread()
.enable_all()
.build()
.expect("current-thread runtime");
let client = runtime.block_on(async {
build_http_client(&OtelTlsConfig::default(), OTEL_EXPORTER_OTLP_TIMEOUT)
});
assert!(client.is_ok());
}
#[test]
fn build_http_client_accepts_pem_client_identity() {
let (_temp_dir, tls) = write_test_mtls_config();
build_http_client(&tls, OTEL_EXPORTER_OTLP_TIMEOUT)
.expect("blocking HTTP client should accept PEM client identity");
}
#[tokio::test]
async fn build_async_http_client_accepts_pem_client_identity() {
let (_temp_dir, tls) = write_test_mtls_config();
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
build_async_http_client(&factory, Some(&tls), OTEL_EXPORTER_OTLP_TIMEOUT)
.expect("async HTTP client should accept PEM client identity");
}
fn write_test_mtls_config() -> (TempDir, OtelTlsConfig) {
let temp_dir = tempfile::tempdir().expect("temporary TLS fixture directory");
let CertifiedKey { cert, signing_key } =
generate_simple_self_signed(vec!["localhost".to_string()])
.expect("test certificate should generate");
let certificate_path = temp_dir.path().join("client.pem");
let private_key_path = temp_dir.path().join("client-key.pem");
fs::write(&certificate_path, cert.pem()).expect("client certificate should write");
fs::write(&private_key_path, signing_key.serialize_pem())
.expect("client private key should write");
(
temp_dir,
OtelTlsConfig {
ca_certificate: Some(
AbsolutePathBuf::from_absolute_path(&certificate_path)
.expect("CA certificate path should be absolute"),
),
client_certificate: Some(
AbsolutePathBuf::from_absolute_path(&certificate_path)
.expect("client certificate path should be absolute"),
),
client_private_key: Some(
AbsolutePathBuf::from_absolute_path(&private_key_path)
.expect("client private key path should be absolute"),
),
},
)
}
}

View File

@@ -0,0 +1,884 @@
use crate::config::OtelExporter;
use crate::config::OtelHttpProtocol;
use crate::config::OtelSettings;
use crate::config::StatsigMetricsSettings;
use crate::metrics::MetricsClient;
use crate::metrics::MetricsConfig;
use crate::targets::is_log_export_target;
use crate::targets::is_trace_safe_target;
use gethostname::gethostname;
use opentelemetry::Context;
use opentelemetry::KeyValue;
use opentelemetry::global;
use opentelemetry::trace::Span as _;
use opentelemetry::trace::SpanBuilder;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry::trace::noop::NoopTracerProvider;
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::LogExporter;
use opentelemetry_otlp::OTEL_EXPORTER_OTLP_LOGS_TIMEOUT;
use opentelemetry_otlp::OTEL_EXPORTER_OTLP_TRACES_TIMEOUT;
use opentelemetry_otlp::Protocol;
use opentelemetry_otlp::SpanExporter;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_otlp::WithHttpConfig;
use opentelemetry_otlp::WithTonicConfig;
use opentelemetry_otlp::tonic_types::metadata::MetadataMap;
use opentelemetry_otlp::tonic_types::transport::ClientTlsConfig;
use opentelemetry_sdk::Resource;
use opentelemetry_sdk::error::OTelSdkResult;
use opentelemetry_sdk::logs::SdkLoggerProvider;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use opentelemetry_sdk::runtime;
use opentelemetry_sdk::trace::BatchSpanProcessor;
use opentelemetry_sdk::trace::SdkTracerProvider;
use opentelemetry_sdk::trace::Span;
use opentelemetry_sdk::trace::SpanData;
use opentelemetry_sdk::trace::SpanProcessor;
use opentelemetry_sdk::trace::Tracer;
use opentelemetry_sdk::trace::TracerProviderBuilder;
use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor as TokioBatchSpanProcessor;
use opentelemetry_semantic_conventions as semconv;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::error::Error;
use std::io;
use std::mem::ManuallyDrop;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::time::Duration;
use tracing::debug;
use tracing_subscriber::Layer;
use tracing_subscriber::registry::LookupSpan;
const ENV_ATTRIBUTE: &str = "env";
const HOST_NAME_ATTRIBUTE: &str = "host.name";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ResourceKind {
Logs,
Traces,
}
pub struct OtelProvider {
pub logger: Option<SdkLoggerProvider>,
pub tracer_provider: Option<SdkTracerProvider>,
pub tracer: Option<Tracer>,
pub metrics: Option<MetricsClient>,
shutdown_started: AtomicBool,
shutdown_worker: Option<mpsc::SyncSender<ShutdownWorker>>,
}
struct ShutdownWorker {
provider: ManuallyDrop<OtelProvider>,
completed_tx: tokio::sync::oneshot::Sender<()>,
}
struct ShutdownWorkerStartup {
worker_rx: mpsc::Receiver<ShutdownWorker>,
ready_tx: mpsc::SyncSender<()>,
}
#[derive(Debug)]
struct GlobalTracer {
service_name: &'static str,
}
impl opentelemetry::trace::Tracer for GlobalTracer {
type Span = global::BoxedSpan;
fn build_with_context(&self, builder: SpanBuilder, parent: &Context) -> Self::Span {
global::tracer(self.service_name).build_with_context(builder, parent)
}
}
impl OtelProvider {
/// Flushes and shuts down configured exporters at most once.
pub fn shutdown(&self) {
if self.shutdown_started.swap(/*val*/ true, Ordering::AcqRel) {
return;
}
if let Some(tracer_provider) = &self.tracer_provider {
let _ = tracer_provider.shutdown();
}
if let Some(metrics) = &self.metrics {
let _ = metrics.shutdown();
}
if let Some(logger) = &self.logger {
let _ = logger.shutdown();
}
}
/// Starts the detached shutdown worker before shutdown-time resource pressure.
fn prepare_shutdown_worker(&mut self) -> io::Result<()> {
self.prepare_shutdown_worker_with_spawner(|startup| {
std::thread::Builder::new()
.name("codex-otel-shutdown".to_string())
.spawn(move || {
if startup.ready_tx.send(()).is_err() {
return;
}
let Ok(worker) = startup.worker_rx.recv() else {
return;
};
let provider = ManuallyDrop::into_inner(worker.provider);
provider.shutdown();
drop(provider);
let _ = worker.completed_tx.send(());
})
})
}
fn prepare_shutdown_worker_with_spawner<F>(&mut self, spawn: F) -> io::Result<()>
where
F: FnOnce(ShutdownWorkerStartup) -> io::Result<std::thread::JoinHandle<()>>,
{
if self.shutdown_worker.is_some() {
return Ok(());
}
let (worker_tx, worker_rx) = mpsc::sync_channel(/*bound*/ 1);
let (ready_tx, ready_rx) = mpsc::sync_channel(/*bound*/ 1);
let startup = ShutdownWorkerStartup {
worker_rx,
ready_tx,
};
let _shutdown_worker = spawn(startup)?;
ready_rx.recv().map_err(|_| {
io::Error::new(
io::ErrorKind::BrokenPipe,
"telemetry shutdown worker stopped before initializing",
)
})?;
self.shutdown_worker = Some(worker_tx);
Ok(())
}
/// Shuts down exporters on a prepared detached thread within a time budget.
pub async fn shutdown_with_timeout(mut self, timeout: Duration) -> io::Result<()> {
let Some(worker_tx) = self.shutdown_worker.take() else {
// Best-effort shutdown must not run a potentially blocking destructor
// when its worker could not be prepared.
let _provider = ManuallyDrop::new(self);
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"telemetry shutdown worker was not initialized",
));
};
let (completed_tx, completed_rx) = tokio::sync::oneshot::channel();
let worker = ShutdownWorker {
provider: ManuallyDrop::new(self),
completed_tx,
};
worker_tx.send(worker).map_err(|_| {
io::Error::new(
io::ErrorKind::BrokenPipe,
"telemetry shutdown worker stopped before receiving the provider",
)
})?;
match tokio::time::timeout(timeout, completed_rx).await {
Ok(Ok(())) => Ok(()),
Ok(Err(_)) => Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"telemetry shutdown worker stopped before completing",
)),
Err(_) => Err(io::Error::new(
io::ErrorKind::TimedOut,
"telemetry shutdown exceeded its time budget",
)),
}
}
pub fn try_new(settings: &OtelSettings) -> Result<Option<Self>, Box<dyn Error>> {
let log_enabled = !matches!(settings.exporter, OtelExporter::None);
let trace_enabled = !matches!(settings.trace_exporter, OtelExporter::None);
let metric_exporter = crate::config::resolve_exporter(&settings.metrics_exporter);
let metrics_enabled = !matches!(metric_exporter, OtelExporter::None);
if !log_enabled && !trace_enabled && !metrics_enabled {
// Tracestate propagation is process-global; clear it when these
// settings do not install an active provider.
crate::trace_context::set_tracestate_entries(BTreeMap::new())?;
crate::metrics::buffered::GLOBAL.disable();
install_global_tracer_provider(/*tracer_provider*/ None);
debug!("No OTEL exporter enabled in settings.");
return Ok(None);
}
// Provider setup installs process-global OTEL state that cannot be
// rolled back. Validate trace metadata before any setup path can
// mutate those globals, and keep span attribute checks aligned with
// config loading when traces are exported.
if trace_enabled {
crate::config::validate_span_attributes(&settings.span_attributes)?;
}
crate::trace_context::validate_tracestate_entries(&settings.tracestate)?;
let metrics = if matches!(metric_exporter, OtelExporter::None) {
None
} else {
let mut config = MetricsConfig::otlp(
settings.environment.clone(),
settings.service_name.clone(),
settings.service_version.clone(),
settings.metrics_exporter.clone(),
)
.with_http_client_factory(settings.http_client_factory.clone());
if settings.runtime_metrics {
config = config.with_runtime_reader();
}
Some(MetricsClient::new(config)?)
};
let log_resource = make_resource(settings, ResourceKind::Logs);
let trace_resource = make_resource(settings, ResourceKind::Traces);
let logger = log_enabled
.then(|| {
build_logger(
&log_resource,
&settings.exporter,
&settings.http_client_factory,
)
})
.transpose()?;
let tracer_provider = trace_enabled
.then(|| {
build_tracer_provider(
&trace_resource,
&settings.trace_exporter,
settings.span_attributes.clone(),
&settings.http_client_factory,
)
})
.transpose()?;
let tracer = tracer_provider
.as_ref()
.map(|provider| provider.tracer(settings.service_name.clone()));
let mut provider = Self {
logger,
tracer_provider,
tracer,
metrics,
shutdown_started: AtomicBool::default(),
shutdown_worker: None,
};
provider.prepare_shutdown_worker()?;
crate::trace_context::set_tracestate_entries(settings.tracestate.clone())?;
install_global_tracer_provider(provider.tracer_provider.clone());
if let Some(metrics) = provider.metrics.as_mut() {
*metrics = crate::metrics::install_global(metrics.clone());
if matches!(settings.metrics_exporter, OtelExporter::Statsig) {
crate::metrics::install_global_statsig_settings(StatsigMetricsSettings {
environment: settings.environment.clone(),
});
}
} else {
crate::metrics::buffered::GLOBAL.disable();
}
Ok(Some(provider))
}
pub fn logger_layer<S>(&self) -> Option<impl Layer<S> + Send + Sync>
where
S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync,
{
self.logger_export_layer().map(|layer| {
layer.with_filter(tracing_subscriber::filter::filter_fn(
OtelProvider::log_export_filter,
))
})
}
/// Returns a log-export bridge that must be installed beneath the log export filter.
pub fn logger_export_layer<S>(&self) -> Option<impl Layer<S> + Send + Sync>
where
S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync,
{
self.logger.as_ref().map(OpenTelemetryTracingBridge::new)
}
pub fn tracing_layer<S>(&self) -> Option<impl Layer<S> + Send + Sync>
where
S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync,
{
self.tracer.as_ref().map(|tracer| {
tracing_opentelemetry::layer()
.with_tracer(tracer.clone())
.with_filter(tracing_subscriber::filter::filter_fn(
OtelProvider::trace_export_filter,
))
})
}
/// Returns a permanent trace layer that follows the process-global tracer provider.
pub fn reloadable_tracing_layer<S>(service_name: &'static str) -> impl Layer<S> + Send + Sync
where
S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync,
{
tracing_opentelemetry::layer()
.with_tracer(GlobalTracer { service_name })
.with_filter(tracing_subscriber::filter::filter_fn(
Self::trace_export_filter,
))
}
pub fn codex_export_filter(meta: &tracing::Metadata<'_>) -> bool {
Self::log_export_filter(meta)
}
pub fn log_export_filter(meta: &tracing::Metadata<'_>) -> bool {
is_log_export_target(meta.target())
}
pub fn trace_export_filter(meta: &tracing::Metadata<'_>) -> bool {
let target = meta.target();
if meta.is_span() {
// The exporter uses h2 and Tokio. Their root spans escape the
// SDK's suppression and would generate further OTLP exports.
!matches!(target.split("::").next(), Some("h2" | "tokio" | "runtime"))
} else {
is_trace_safe_target(target)
}
}
pub fn metrics(&self) -> Option<&MetricsClient> {
self.metrics.as_ref()
}
}
fn install_global_tracer_provider(tracer_provider: Option<SdkTracerProvider>) {
if let Some(tracer_provider) = tracer_provider {
global::set_tracer_provider(tracer_provider);
global::set_text_map_propagator(TraceContextPropagator::new());
} else {
global::set_tracer_provider(NoopTracerProvider::new());
}
}
impl Drop for OtelProvider {
fn drop(&mut self) {
self.shutdown();
}
}
fn make_resource(settings: &OtelSettings, kind: ResourceKind) -> Resource {
Resource::builder()
.with_service_name(settings.service_name.clone())
.with_attributes(resource_attributes(
settings,
detected_host_name().as_deref(),
kind,
))
.build()
}
fn resource_attributes(
settings: &OtelSettings,
host_name: Option<&str>,
kind: ResourceKind,
) -> Vec<KeyValue> {
let mut attributes = vec![
KeyValue::new(
semconv::attribute::SERVICE_VERSION,
settings.service_version.clone(),
),
KeyValue::new(ENV_ATTRIBUTE, settings.environment.clone()),
];
if kind == ResourceKind::Logs
&& let Some(host_name) = host_name.and_then(normalize_host_name)
{
attributes.push(KeyValue::new(HOST_NAME_ATTRIBUTE, host_name));
}
attributes
}
fn detected_host_name() -> Option<String> {
let host_name = gethostname();
normalize_host_name(host_name.to_string_lossy().as_ref())
}
fn normalize_host_name(host_name: &str) -> Option<String> {
let host_name = host_name.trim();
(!host_name.is_empty()).then(|| host_name.to_owned())
}
fn tracer_provider_builder(
resource: &Resource,
span_attributes: HashMap<String, String>,
) -> TracerProviderBuilder {
let builder = SdkTracerProvider::builder().with_resource(resource.clone());
if span_attributes.is_empty() {
builder
} else {
builder.with_span_processor(SpanAttributesProcessor {
attributes: span_attributes,
})
}
}
/// Applies configured attributes when spans start.
///
/// Resource attributes describe the provider process. These attributes are
/// per-span metadata, so they need to be attached before each span is exported.
#[derive(Debug)]
struct SpanAttributesProcessor {
attributes: HashMap<String, String>,
}
impl SpanProcessor for SpanAttributesProcessor {
fn on_start(&self, span: &mut Span, _cx: &Context) {
for (key, value) in self.attributes.iter() {
span.set_attribute(KeyValue::new(key.clone(), value.clone()));
}
}
fn on_end(&self, _span: SpanData) {}
fn force_flush(&self) -> OTelSdkResult {
Ok(())
}
fn shutdown_with_timeout(&self, _timeout: Duration) -> OTelSdkResult {
Ok(())
}
}
fn build_logger(
resource: &Resource,
exporter: &OtelExporter,
factory: &codex_http_client::HttpClientFactory,
) -> Result<SdkLoggerProvider, Box<dyn Error>> {
let mut builder = SdkLoggerProvider::builder().with_resource(resource.clone());
match crate::config::resolve_exporter(exporter) {
OtelExporter::None => return Ok(builder.build()),
OtelExporter::Statsig => unreachable!("statsig exporter should be resolved"),
OtelExporter::OtlpGrpc {
endpoint,
headers,
tls,
} => {
debug!("Using OTLP Grpc exporter: {endpoint}");
let header_map = crate::otlp::build_header_map(&headers);
let base_tls_config = ClientTlsConfig::new()
.with_enabled_roots()
.assume_http2(true);
let tls_config = match tls.as_ref() {
Some(tls) => crate::otlp::build_grpc_tls_config(&endpoint, base_tls_config, tls)?,
None => base_tls_config,
};
let exporter = LogExporter::builder()
.with_tonic()
.with_endpoint(endpoint)
.with_metadata(MetadataMap::from_headers(header_map))
.with_tls_config(tls_config)
.build()?;
builder = builder.with_batch_exporter(crate::network_policy::PolicyExporter {
exporter,
policy: factory.network_policy().clone(),
});
}
OtelExporter::OtlpHttp {
endpoint,
headers,
protocol,
tls,
} => {
debug!("Using OTLP Http exporter: {endpoint}");
let protocol = match protocol {
OtelHttpProtocol::Binary => Protocol::HttpBinary,
OtelHttpProtocol::Json => Protocol::HttpJson,
};
let mut exporter_builder = LogExporter::builder()
.with_http()
.with_endpoint(endpoint)
.with_protocol(protocol)
.with_headers(headers);
if factory.network_policy().is_managed() {
let client = crate::otlp::build_async_http_client(
factory,
tls.as_ref(),
OTEL_EXPORTER_OTLP_LOGS_TIMEOUT,
)?;
exporter_builder = exporter_builder.with_http_client(client);
} else if let Some(tls) = tls.as_ref() {
let client = crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_LOGS_TIMEOUT)?;
exporter_builder = exporter_builder.with_http_client(client);
}
let exporter = exporter_builder.build()?;
builder = builder.with_batch_exporter(crate::network_policy::PolicyExporter {
exporter,
policy: factory.network_policy().clone(),
});
}
}
Ok(builder.build())
}
fn build_tracer_provider(
resource: &Resource,
exporter: &OtelExporter,
span_attributes: HashMap<String, String>,
factory: &codex_http_client::HttpClientFactory,
) -> Result<SdkTracerProvider, Box<dyn Error>> {
let span_exporter = match crate::config::resolve_exporter(exporter) {
OtelExporter::None => return Ok(tracer_provider_builder(resource, span_attributes).build()),
OtelExporter::Statsig => unreachable!("statsig exporter should be resolved"),
OtelExporter::OtlpGrpc {
endpoint,
headers,
tls,
} => {
debug!("Using OTLP Grpc exporter for traces: {endpoint}");
let header_map = crate::otlp::build_header_map(&headers);
let base_tls_config = ClientTlsConfig::new()
.with_enabled_roots()
.assume_http2(true);
let tls_config = match tls.as_ref() {
Some(tls) => crate::otlp::build_grpc_tls_config(&endpoint, base_tls_config, tls)?,
None => base_tls_config,
};
SpanExporter::builder()
.with_tonic()
.with_endpoint(endpoint)
.with_metadata(MetadataMap::from_headers(header_map))
.with_tls_config(tls_config)
.build()?
}
OtelExporter::OtlpHttp {
endpoint,
headers,
protocol,
tls,
} => {
debug!("Using OTLP Http exporter for traces: {endpoint}");
if crate::otlp::current_tokio_runtime_is_multi_thread() {
let protocol = match protocol {
OtelHttpProtocol::Binary => Protocol::HttpBinary,
OtelHttpProtocol::Json => Protocol::HttpJson,
};
let mut exporter_builder = SpanExporter::builder()
.with_http()
.with_endpoint(endpoint)
.with_protocol(protocol)
.with_headers(headers);
let client = crate::otlp::build_async_http_client(
factory,
tls.as_ref(),
OTEL_EXPORTER_OTLP_TRACES_TIMEOUT,
)?;
exporter_builder = exporter_builder.with_http_client(client);
let processor = TokioBatchSpanProcessor::builder(
crate::network_policy::PolicyExporter {
exporter: exporter_builder.build()?,
policy: factory.network_policy().clone(),
},
runtime::Tokio,
)
.build();
return Ok(tracer_provider_builder(resource, span_attributes)
.with_span_processor(processor)
.build());
}
let protocol = match protocol {
OtelHttpProtocol::Binary => Protocol::HttpBinary,
OtelHttpProtocol::Json => Protocol::HttpJson,
};
let mut exporter_builder = SpanExporter::builder()
.with_http()
.with_endpoint(endpoint)
.with_protocol(protocol)
.with_headers(headers);
if factory.network_policy().is_managed() {
let client = crate::otlp::build_async_http_client(
factory,
tls.as_ref(),
OTEL_EXPORTER_OTLP_TRACES_TIMEOUT,
)?;
exporter_builder = exporter_builder.with_http_client(client);
} else if let Some(tls) = tls.as_ref() {
let client =
crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)?;
exporter_builder = exporter_builder.with_http_client(client);
}
exporter_builder.build()?
}
};
let processor = BatchSpanProcessor::builder(crate::network_policy::PolicyExporter {
exporter: span_exporter,
policy: factory.network_policy().clone(),
})
.build();
Ok(tracer_provider_builder(resource, span_attributes)
.with_span_processor(processor)
.build())
}
#[cfg(test)]
#[path = "provider_shutdown_tests.rs"]
mod shutdown_tests;
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::API_CALL_COUNT_METRIC;
use crate::metrics::API_CALL_DURATION_METRIC;
use crate::metrics::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC;
use crate::metrics::MetricsExporter;
use crate::metrics::RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC;
use crate::metrics::RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC;
use crate::metrics::RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC;
use crate::metrics::TOOL_CALL_COUNT_METRIC;
use crate::metrics::TOOL_CALL_DURATION_METRIC;
use crate::metrics::TURN_COST_MICROUSD_METRIC;
use crate::metrics::TURN_TOKEN_USAGE_METRIC;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use opentelemetry::trace::Tracer as _;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
#[test]
fn resource_attributes_include_host_name_when_present() {
let attrs = resource_attributes(
&test_otel_settings(),
Some("opentelemetry-test"),
ResourceKind::Logs,
);
let host_name = attrs
.iter()
.find(|kv| kv.key.as_str() == HOST_NAME_ATTRIBUTE)
.map(|kv| kv.value.as_str().to_string());
assert_eq!(host_name, Some("opentelemetry-test".to_string()));
}
#[test]
fn resource_attributes_omit_host_name_when_missing_or_empty() {
let missing = resource_attributes(
&test_otel_settings(),
/*host_name*/ None,
ResourceKind::Logs,
);
let empty = resource_attributes(&test_otel_settings(), Some(" "), ResourceKind::Logs);
let trace_attrs = resource_attributes(
&test_otel_settings(),
Some("opentelemetry-test"),
ResourceKind::Traces,
);
assert!(
!missing
.iter()
.any(|kv| kv.key.as_str() == HOST_NAME_ATTRIBUTE)
);
assert!(
!empty
.iter()
.any(|kv| kv.key.as_str() == HOST_NAME_ATTRIBUTE)
);
assert!(
!trace_attrs
.iter()
.any(|kv| kv.key.as_str() == HOST_NAME_ATTRIBUTE)
);
}
#[test]
fn log_export_target_excludes_trace_safe_events() {
assert!(is_log_export_target("codex_otel.log_only"));
assert!(is_log_export_target("codex_otel.network_proxy"));
assert!(!is_log_export_target("codex_otel.trace_safe"));
assert!(!is_log_export_target("codex_otel.trace_safe.debug"));
}
#[test]
fn trace_export_target_only_includes_trace_safe_prefix() {
assert!(is_trace_safe_target("codex_otel.trace_safe"));
assert!(is_trace_safe_target("codex_otel.trace_safe.summary"));
assert!(!is_trace_safe_target("codex_otel.log_only"));
assert!(!is_trace_safe_target("codex_otel.network_proxy"));
}
#[test]
fn disabled_trace_settings_replace_global_tracer_with_noop() -> Result<(), Box<dyn Error>> {
global::set_tracer_provider(SdkTracerProvider::builder().build());
let before = global::tracer("codex-otel-test").start("before-disable");
assert!(
before.is_recording(),
"the test provider should record before tracing is disabled"
);
let provider = OtelProvider::try_new(&test_otel_settings())?;
assert!(provider.is_none());
let after = global::tracer("codex-otel-test").start("after-disable");
assert!(
!after.is_recording(),
"new spans should not record after tracing is disabled"
);
Ok(())
}
#[test]
fn cached_global_metrics_follow_reinstalled_provider() -> Result<(), Box<dyn Error>> {
let initial =
crate::metrics::install_global(MetricsClient::new(MetricsConfig::in_memory(
"test",
"codex-test",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
))?);
crate::metrics::install_global_statsig_settings(StatsigMetricsSettings {
environment: "test".to_string(),
});
assert!(crate::metrics::global_statsig_settings().is_some());
let controller = codex_http_client::NetworkPolicyController::default();
let policy = controller.policy();
controller.publish(
policy.revision(),
codex_http_client::DestinationPolicy::Unrestricted,
);
let cached = crate::metrics::global().expect("initial global metrics client");
let exporter = InMemoryMetricExporter::default();
let replacement = crate::metrics::install_global(MetricsClient::new(
MetricsConfig::in_memory(
"test",
"codex-test",
env!("CARGO_PKG_VERSION"),
exporter.clone(),
)
.with_http_client_factory(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy),
),
)?);
assert!(crate::metrics::global_statsig_settings().is_none());
cached.counter("codex.after_transition", /*inc*/ 1, &[])?;
initial.shutdown()?;
replacement.shutdown()?;
let exported_metrics = exporter.get_finished_metrics()?;
let mut names: Vec<_> = exported_metrics
.iter()
.flat_map(opentelemetry_sdk::metrics::data::ResourceMetrics::scope_metrics)
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.map(opentelemetry_sdk::metrics::data::Metric::name)
.collect();
names.sort_unstable();
names.dedup();
assert_eq!(names, vec!["codex.after_transition"]);
Ok(())
}
#[test]
fn statsig_disabled_metrics_are_not_exported() -> Result<(), Box<dyn Error>> {
let exporter = InMemoryMetricExporter::default();
let mut config = MetricsConfig::otlp(
"test",
"codex-cli",
env!("CARGO_PKG_VERSION"),
OtelExporter::Statsig,
);
config.exporter = MetricsExporter::InMemory(exporter.clone());
let metrics = MetricsClient::new(config)?;
metrics.counter(API_CALL_COUNT_METRIC, /*inc*/ 1, &[])?;
metrics.record_duration(API_CALL_DURATION_METRIC, Duration::from_millis(100), &[])?;
metrics.counter_with_description(
EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC,
"Client-side exec-server RPC attempts.",
/*inc*/ 1,
&[("method", "fs/readFile")],
)?;
metrics.counter("codex.conversation.turn.count", /*inc*/ 1, &[])?;
metrics.record_duration(
RESPONSES_API_ENGINE_IAPI_TTFT_DURATION_METRIC,
Duration::from_millis(100),
&[],
)?;
metrics.record_duration(
RESPONSES_API_ENGINE_SERVICE_TBT_DURATION_METRIC,
Duration::from_millis(100),
&[],
)?;
metrics.record_duration(
RESPONSES_API_ENGINE_SERVICE_TTFT_DURATION_METRIC,
Duration::from_millis(100),
&[],
)?;
metrics.counter(TOOL_CALL_COUNT_METRIC, /*inc*/ 1, &[])?;
metrics.record_duration(TOOL_CALL_DURATION_METRIC, Duration::from_millis(25), &[])?;
metrics.counter(TURN_COST_MICROUSD_METRIC, /*inc*/ 1, &[])?;
metrics.histogram(TURN_TOKEN_USAGE_METRIC, /*value*/ 100, &[])?;
metrics.counter("codex.turns", /*inc*/ 1, &[])?;
metrics.shutdown()?;
let exported_metrics = exporter.get_finished_metrics()?;
let mut names: Vec<_> = exported_metrics
.iter()
.flat_map(opentelemetry_sdk::metrics::data::ResourceMetrics::scope_metrics)
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.map(opentelemetry_sdk::metrics::data::Metric::name)
.collect();
names.sort_unstable();
names.dedup();
assert_eq!(names, vec!["codex.turns"]);
Ok(())
}
fn test_otel_settings() -> OtelSettings {
OtelSettings {
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
environment: "test".to_string(),
service_name: "codex-test".to_string(),
service_version: "0.0.0".to_string(),
codex_home: PathBuf::from("."),
exporter: OtelExporter::None,
trace_exporter: OtelExporter::None,
metrics_exporter: OtelExporter::None,
runtime_metrics: false,
span_attributes: HashMap::new(),
tracestate: BTreeMap::new(),
}
}
}

View File

@@ -0,0 +1,469 @@
use super::Context;
use super::OTelSdkResult;
use super::OtelProvider;
use super::SdkTracerProvider;
use super::Span;
use super::SpanData;
use super::SpanProcessor;
use pretty_assertions::assert_eq;
use std::io::ErrorKind;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use std::process::Command;
use std::sync::Arc;
use std::sync::Condvar;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::time::Duration;
#[cfg(any(target_os = "linux", target_os = "macos"))]
const GUARD_PAGE_FAILURE_CHILD_TEST: &str =
"provider::shutdown_tests::bounded_shutdown_survives_worker_guard_page_failure_child";
#[cfg(target_os = "macos")]
static GUARD_PAGE_INJECTION_ENABLED: AtomicBool = AtomicBool::new(false);
#[cfg(target_os = "macos")]
static GUARD_PAGE_INJECTION_ARMED: AtomicBool = AtomicBool::new(false);
#[cfg(target_os = "macos")]
static GUARD_PAGE_INJECTION_OBSERVED: AtomicBool = AtomicBool::new(false);
#[cfg(target_os = "macos")]
#[unsafe(export_name = "mprotect")]
unsafe extern "C" fn fault_injected_mprotect(
address: *mut libc::c_void,
length: usize,
protection: libc::c_int,
) -> libc::c_int {
let original_symbol = unsafe { libc::dlsym(libc::RTLD_NEXT, c"mprotect".as_ptr()) };
let original_mprotect: unsafe extern "C" fn(
*mut libc::c_void,
usize,
libc::c_int,
) -> libc::c_int = unsafe { std::mem::transmute(original_symbol) };
if GUARD_PAGE_INJECTION_ENABLED.load(Ordering::Relaxed)
&& protection == libc::PROT_NONE
&& length == unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize
{
let mut thread_name = [0; 64];
let named_shutdown_worker = unsafe {
libc::pthread_getname_np(
libc::pthread_self(),
thread_name.as_mut_ptr(),
thread_name.len(),
)
} == 0
&& unsafe { std::ffi::CStr::from_ptr(thread_name.as_ptr()) }
.to_bytes()
.starts_with(b"codex-otel-shut");
if named_shutdown_worker {
GUARD_PAGE_INJECTION_OBSERVED.store(/*val*/ true, Ordering::Relaxed);
if GUARD_PAGE_INJECTION_ARMED.load(Ordering::Relaxed) {
unsafe { *libc::__error() = libc::ENOMEM };
return -1;
}
}
}
unsafe { original_mprotect(address, length, protection) }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ShutdownBehavior {
Complete,
WaitForRelease,
}
#[derive(Debug, Default)]
struct ShutdownState {
force_flushes: AtomicUsize,
shutdowns: AtomicUsize,
released: Mutex<bool>,
release_notification: Condvar,
started: Mutex<Option<mpsc::Sender<()>>>,
completed: Mutex<Option<mpsc::Sender<()>>>,
}
#[derive(Debug)]
struct ControlledSpanProcessor {
behavior: ShutdownBehavior,
state: Arc<ShutdownState>,
}
impl SpanProcessor for ControlledSpanProcessor {
fn on_start(&self, _span: &mut Span, _context: &Context) {}
fn on_end(&self, _span: SpanData) {}
fn force_flush(&self) -> OTelSdkResult {
self.state
.force_flushes
.fetch_add(/*val*/ 1, Ordering::Relaxed);
Ok(())
}
fn shutdown_with_timeout(&self, _timeout: Duration) -> OTelSdkResult {
self.state.shutdowns.fetch_add(/*val*/ 1, Ordering::Relaxed);
if let Some(started) = self.state.started.lock().expect("started lock").take() {
let _ = started.send(());
}
if self.behavior == ShutdownBehavior::WaitForRelease {
drop(
self.state
.release_notification
.wait_while(
self.state.released.lock().expect("release lock"),
|released| !*released,
)
.expect("release notification"),
);
}
if let Some(completed) = self.state.completed.lock().expect("completed lock").take() {
let _ = completed.send(());
}
Ok(())
}
}
struct TestProvider {
provider: OtelProvider,
state: Arc<ShutdownState>,
started: mpsc::Receiver<()>,
completed: mpsc::Receiver<()>,
}
fn test_provider(behavior: ShutdownBehavior) -> TestProvider {
let (started_tx, started) = mpsc::channel();
let (completed_tx, completed) = mpsc::channel();
let state = Arc::new(ShutdownState {
started: Mutex::new(Some(started_tx)),
completed: Mutex::new(Some(completed_tx)),
..ShutdownState::default()
});
let processor = ControlledSpanProcessor {
behavior,
state: Arc::clone(&state),
};
let tracer_provider = SdkTracerProvider::builder()
.with_span_processor(processor)
.build();
TestProvider {
provider: OtelProvider {
logger: None,
tracer_provider: Some(tracer_provider),
tracer: None,
metrics: None,
shutdown_started: AtomicBool::default(),
shutdown_worker: None,
},
state,
started,
completed,
}
}
#[tokio::test(flavor = "current_thread")]
async fn bounded_shutdown_does_not_flush_when_worker_creation_fails() {
let TestProvider {
mut provider,
state,
started,
completed,
} = test_provider(ShutdownBehavior::Complete);
let preparation = provider.prepare_shutdown_worker_with_spawner(|_startup| {
Err(std::io::Error::new(
ErrorKind::WouldBlock,
"shutdown worker could not be created",
))
});
assert_eq!(
preparation.as_ref().map_err(std::io::Error::kind),
Err(ErrorKind::WouldBlock)
);
let result = provider
.shutdown_with_timeout(Duration::from_secs(/*secs*/ 1))
.await;
assert_eq!(
result.as_ref().map_err(std::io::Error::kind),
Err(ErrorKind::NotConnected)
);
assert_eq!(state.shutdowns.load(Ordering::Relaxed), 0);
assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0);
assert_eq!(started.try_recv(), Err(mpsc::TryRecvError::Empty));
assert_eq!(completed.try_recv(), Err(mpsc::TryRecvError::Empty));
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn bounded_shutdown_survives_worker_guard_page_failure() {
let unique_suffix = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("current time follows Unix epoch")
.as_nanos();
let temporary_directory = std::env::temp_dir().join(format!(
"codex-otel-guard-page-{}-{unique_suffix}",
std::process::id()
));
std::fs::create_dir(&temporary_directory).expect("create fault injector directory");
let observed_path = temporary_directory.join("guard_page_fault.observed");
let mut subprocess = Command::new(std::env::current_exe().expect("current test binary"));
subprocess
.arg("--exact")
.arg(GUARD_PAGE_FAILURE_CHILD_TEST)
.arg("--ignored")
.arg("--nocapture")
.arg("--test-threads=1")
.env("CODEX_OTEL_GUARD_PAGE_FAILURE_CHILD", "1")
.env("CODEX_OTEL_GUARD_PAGE_FAILURE_OBSERVED", &observed_path);
let output = subprocess
.output()
.expect("run guard-page failure subprocess");
let injection_was_observed = observed_path.is_file();
let _ = std::fs::remove_dir_all(&temporary_directory);
assert!(
output.status.success(),
"bounded telemetry shutdown crashed when its worker guard page could not be allocated\n\
status: {}\nstdout:\n{}\nstderr:\n{}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(
injection_was_observed,
"guard-page fault injection never became active on {}-{}",
std::env::consts::ARCH,
std::env::consts::OS
);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
// The parent regression invokes this ignored test in a fresh subprocess with
// `--exact --ignored`, isolating fatal native-thread initialization failures.
#[ignore]
fn bounded_shutdown_survives_worker_guard_page_failure_child() {
if std::env::var_os("CODEX_OTEL_GUARD_PAGE_FAILURE_CHILD").is_none() {
return;
}
let TestProvider {
mut provider,
state,
..
} = test_provider(ShutdownBehavior::Complete);
#[cfg(target_os = "macos")]
GUARD_PAGE_INJECTION_ENABLED.store(/*val*/ true, Ordering::Relaxed);
provider
.prepare_shutdown_worker()
.expect("pre-initialize bounded shutdown worker");
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.expect("create current-thread runtime");
#[cfg(target_os = "macos")]
{
assert!(
GUARD_PAGE_INJECTION_OBSERVED.load(Ordering::Relaxed),
"Rust mprotect interposer did not observe shutdown-worker guard-page setup"
);
GUARD_PAGE_INJECTION_ARMED.store(/*val*/ true, Ordering::Relaxed);
}
#[cfg(target_os = "linux")]
{
use seccompiler::BpfProgram;
use seccompiler::SeccompAction;
use seccompiler::SeccompCmpArgLen;
use seccompiler::SeccompCmpOp;
use seccompiler::SeccompCondition;
use seccompiler::SeccompFilter;
use seccompiler::SeccompRule;
let page_size =
usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).expect("valid page size");
let mapped_page = unsafe {
libc::mmap(
std::ptr::null_mut(),
page_size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
/*fd*/ -1,
/*offset*/ 0,
)
};
assert_ne!(
mapped_page,
libc::MAP_FAILED,
"map a page to verify guard-page fault injection: {}",
std::io::Error::last_os_error()
);
let protection_is_none = SeccompCondition::new(
/*arg_index*/ 2,
SeccompCmpArgLen::Dword,
SeccompCmpOp::Eq,
libc::PROT_NONE as u64,
)
.expect("create guard-page seccomp condition");
let rule =
SeccompRule::new(vec![protection_is_none]).expect("create guard-page seccomp rule");
let filter = SeccompFilter::new(
std::collections::BTreeMap::from([(libc::SYS_mprotect, vec![rule])]),
SeccompAction::Allow,
SeccompAction::Errno(libc::ENOMEM as u32),
std::env::consts::ARCH
.try_into()
.expect("supported seccomp architecture"),
)
.expect("create guard-page seccomp filter");
let program: BpfProgram = filter
.try_into()
.expect("compile guard-page seccomp filter");
seccompiler::apply_filter(&program).expect("install guard-page seccomp filter");
let protection_result = unsafe { libc::mprotect(mapped_page, page_size, libc::PROT_NONE) };
let protection_error = std::io::Error::last_os_error();
assert_eq!(protection_result, -1);
assert_eq!(protection_error.raw_os_error(), Some(libc::ENOMEM));
assert_eq!(unsafe { libc::munmap(mapped_page, page_size) }, 0);
}
let observed_path = std::env::var_os("CODEX_OTEL_GUARD_PAGE_FAILURE_OBSERVED")
.expect("guard-page fault observation path");
std::fs::write(observed_path, "observed").expect("record guard-page fault injection");
runtime
.block_on(provider.shutdown_with_timeout(Duration::from_secs(/*secs*/ 1)))
.expect("bounded telemetry shutdown should not create a new native thread");
assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1);
}
#[tokio::test(flavor = "current_thread")]
async fn bounded_shutdown_times_out_without_blocking_the_runtime() {
let TestProvider {
mut provider,
state,
started,
completed,
} = test_provider(ShutdownBehavior::WaitForRelease);
provider
.prepare_shutdown_worker()
.expect("pre-initialize bounded shutdown worker");
let result = provider
.shutdown_with_timeout(Duration::from_millis(/*millis*/ 50))
.await;
assert_eq!(
result.as_ref().map_err(std::io::Error::kind),
Err(ErrorKind::TimedOut)
);
started
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("shutdown worker started");
assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1);
assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0);
*state.released.lock().expect("release lock") = true;
state.release_notification.notify_one();
completed
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("shutdown worker completed after release");
}
async fn assert_bounded_shutdown_completes() {
let TestProvider {
mut provider,
state,
started,
completed,
} = test_provider(ShutdownBehavior::Complete);
provider
.prepare_shutdown_worker()
.expect("pre-initialize bounded shutdown worker");
provider
.shutdown_with_timeout(Duration::from_secs(/*secs*/ 1))
.await
.expect("healthy processor shuts down");
started
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("shutdown worker started");
completed
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("shutdown worker completed");
assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1);
assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0);
}
#[tokio::test(flavor = "current_thread")]
async fn bounded_shutdown_completes_on_current_thread_runtime() {
assert_bounded_shutdown_completes().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn bounded_shutdown_completes_on_multi_thread_runtime() {
assert_bounded_shutdown_completes().await;
}
#[test]
fn explicit_shutdown_and_drop_shut_down_exporters_once_without_force_flush() {
let TestProvider {
provider,
state,
started,
completed,
} = test_provider(ShutdownBehavior::Complete);
provider.shutdown();
provider.shutdown();
drop(provider);
started
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("shutdown started");
completed
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("shutdown completed");
assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1);
assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0);
}
#[test]
fn drop_shuts_down_exporters_without_force_flush() {
let TestProvider {
provider,
state,
started,
completed,
} = test_provider(ShutdownBehavior::Complete);
drop(provider);
started
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("shutdown started");
completed
.recv_timeout(Duration::from_secs(/*secs*/ 1))
.expect("shutdown completed");
assert_eq!(state.shutdowns.load(Ordering::Relaxed), 1);
assert_eq!(state.force_flushes.load(Ordering::Relaxed), 0);
}

View File

@@ -0,0 +1,61 @@
//! Exports skill-use metadata without skill contents, filesystem paths, or tool payloads.
//! Detection belongs to the caller; an invocation does not imply successful task completion.
use crate::SessionTelemetry;
use crate::events::shared::timestamp;
use crate::targets::OTEL_LOG_ONLY_TARGET;
use codex_protocol::protocol::SkillScope;
/// How Codex detected the skill's use.
pub enum SkillInvocationType {
Explicit,
Implicit,
}
/// Metadata for a detected skill invocation. Never include skill contents or resource paths.
pub struct SkillInvocationEvent<'a> {
pub turn_id: &'a str,
pub skill_name: &'a str,
pub scope: Option<SkillScope>,
pub plugin_id: Option<&'a str>,
pub invocation_type: SkillInvocationType,
}
impl SessionTelemetry {
pub fn with_user_id(mut self, user_id: Option<String>) -> Self {
self.metadata.user_id = user_id;
self
}
pub fn skill_invocation(&self, event: SkillInvocationEvent<'_>) {
let invocation_type = match event.invocation_type {
SkillInvocationType::Explicit => "explicit",
SkillInvocationType::Implicit => "implicit",
};
let scope = event.scope.map(|scope| match scope {
SkillScope::User => "user",
SkillScope::Repo => "repo",
SkillScope::System => "system",
SkillScope::Admin => "admin",
});
tracing::event!(
name: "codex.skill_invocation",
target: OTEL_LOG_ONLY_TARGET,
tracing::Level::INFO,
event.name = "codex.skill_invocation",
event.timestamp = %timestamp(),
conversation.id = %self.metadata.conversation_id,
turn.id = event.turn_id,
user.id = self.metadata.user_id.as_deref(),
user.account_id = self.metadata.account_id.as_deref(),
skill.name = event.skill_name,
skill.scope = scope,
skill.plugin_id = event.plugin_id,
skill.invocation_type = invocation_type,
model = %self.metadata.model,
app.version = self.metadata.app_version,
originator = %self.metadata.originator,
auth_mode = self.metadata.auth_mode.as_deref(),
);
}
}

View File

@@ -0,0 +1,11 @@
pub(crate) const OTEL_TARGET_PREFIX: &str = "codex_otel";
pub(crate) const OTEL_LOG_ONLY_TARGET: &str = "codex_otel.log_only";
pub(crate) const OTEL_TRACE_SAFE_TARGET: &str = "codex_otel.trace_safe";
pub(crate) fn is_log_export_target(target: &str) -> bool {
target.starts_with(OTEL_TARGET_PREFIX) && !is_trace_safe_target(target)
}
pub(crate) fn is_trace_safe_target(target: &str) -> bool {
target.starts_with(OTEL_TRACE_SAFE_TARGET)
}

View File

@@ -0,0 +1,115 @@
use crate::SessionTelemetry;
use crate::events::shared::log_and_trace_event;
use crate::events::shared::log_event;
use crate::events::shared::tool_namespace;
use crate::events::shared::trace_event;
use codex_protocol::ToolName;
use codex_protocol::config_types::ToolResultLogConfig;
use codex_utils_string::take_bytes_at_char_boundary;
use std::borrow::Cow;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
const TRUNCATION_NOTICE: &str = "[... telemetry preview truncated ...]";
/// Result-recording order across all sessions in this process, not tool-start order.
/// Independent of the optional rollout-trace writer and reset on process restart.
fn next_tool_result_seq() -> u64 {
static NEXT_SEQ: AtomicU64 = AtomicU64::new(1);
NEXT_SEQ.fetch_add(/*val*/ 1, Ordering::Relaxed)
}
pub(crate) struct ToolResultEvent<'a> {
pub tool_name: &'a ToolName,
pub call_id: &'a str,
pub arguments: &'a str,
pub mcp_server: &'a str,
pub mcp_server_origin: &'a str,
pub duration: Duration,
pub success: bool,
pub output: &'a str,
}
/// Emits diagnostic logs and trace-safe metadata without changing tool-call metrics.
pub(crate) fn emit_tool_result(
telemetry: &SessionTelemetry,
limits: ToolResultLogConfig,
event: ToolResultEvent<'_>,
) {
let ToolResultEvent {
tool_name,
call_id,
arguments,
mcp_server,
mcp_server_origin,
duration,
success,
output,
} = event;
let tool_namespace = tool_namespace(tool_name);
let preview = telemetry_preview(output, limits);
let tool_result_seq = next_tool_result_seq();
log_and_trace_event!(
telemetry,
common: {
event.name = "codex.tool_result",
tool_result_seq = tool_result_seq,
tool_name = %tool_name.name,
tool_namespace = %tool_namespace,
call_id = %call_id,
product_sku = telemetry.metadata.product_sku,
duration_ms = %duration.as_millis(),
success = %success,
output_truncated = preview.truncated,
},
log: {
agent_name = %telemetry.metadata.agent_name,
arguments = %arguments,
output = %preview.text,
mcp_server = %mcp_server,
mcp_server_origin = %mcp_server_origin,
},
trace: {
arguments_length = arguments.len() as i64,
output_length = output.len() as i64,
output_line_count = output.lines().count() as i64,
tool_origin = if mcp_server.is_empty() { "builtin" } else { "mcp" },
mcp_tool = !mcp_server.is_empty(),
},
);
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct ToolResultPreview<'a> {
pub text: Cow<'a, str>,
/// Whether this telemetry limit removed text, not whether the tool result was lossless.
pub truncated: bool,
}
pub(crate) fn telemetry_preview(
content: &str,
limits: ToolResultLogConfig,
) -> ToolResultPreview<'_> {
let prefix = take_bytes_at_char_boundary(content, limits.max_bytes);
if prefix.len() == content.len() {
return ToolResultPreview {
text: Cow::Borrowed(content),
truncated: false,
};
}
let separator = if prefix.is_empty() || prefix.ends_with('\n') {
""
} else {
"\n"
};
ToolResultPreview {
text: Cow::Owned(format!("{prefix}{separator}{TRUNCATION_NOTICE}")),
truncated: true,
}
}
#[cfg(test)]
#[path = "tool_result_tests.rs"]
mod tests;

View File

@@ -0,0 +1,67 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn telemetry_preview_returns_original_within_limits() {
// A literal marker in the tool's own output must not imply telemetry truncation.
for content in ["", "first\r\nsecond\r\n", TRUNCATION_NOTICE] {
let preview = telemetry_preview(content, ToolResultLogConfig::default());
assert!(matches!(preview.text, Cow::Borrowed(_)));
assert_eq!(
preview,
ToolResultPreview {
text: Cow::Borrowed(content),
truncated: false
}
);
}
}
#[test]
fn telemetry_preview_truncates_by_bytes() {
let limits = ToolResultLogConfig::default();
let content = "x".repeat(limits.max_bytes + 8);
let preview = telemetry_preview(&content, limits);
assert!(preview.truncated);
assert!(preview.text.contains(TRUNCATION_NOTICE));
assert!(preview.text.len() <= limits.max_bytes + TRUNCATION_NOTICE.len() + 1);
assert_eq!(
telemetry_preview(
&content,
ToolResultLogConfig {
max_bytes: content.len(),
}
),
ToolResultPreview {
text: Cow::Borrowed(&content),
truncated: false
}
);
assert_eq!(
telemetry_preview("éé", ToolResultLogConfig { max_bytes: 3 }),
ToolResultPreview {
text: Cow::Owned(format!("é\n{TRUNCATION_NOTICE}")),
truncated: true
}
);
for (content, max_bytes, expected, truncated) in [
("", 0, "".to_string(), false),
("\nsecret", 0, TRUNCATION_NOTICE.to_string(), true),
(
"first\r\nsecond",
7,
format!("first\r\n{TRUNCATION_NOTICE}"),
true,
),
("first\r\n", 7, "first\r\n".to_string(), false),
("\n\nsecret", 1, format!("\n{TRUNCATION_NOTICE}"), true),
] {
assert_eq!(
telemetry_preview(content, ToolResultLogConfig { max_bytes }),
ToolResultPreview {
text: Cow::Owned(expected),
truncated
}
);
}
}

View File

@@ -0,0 +1,411 @@
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::env;
use std::str::FromStr;
use std::sync::OnceLock;
use std::sync::RwLock;
use codex_protocol::protocol::W3cTraceContext;
use opentelemetry::Context;
use opentelemetry::propagation::TextMapPropagator;
use opentelemetry::trace::TraceContextExt;
use opentelemetry::trace::TraceState;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use tracing::Span;
use tracing::debug;
use tracing::warn;
use tracing_opentelemetry::OpenTelemetrySpanExt;
const TRACEPARENT_ENV_VAR: &str = "TRACEPARENT";
const TRACESTATE_ENV_VAR: &str = "TRACESTATE";
static TRACEPARENT_CONTEXT: OnceLock<Option<Context>> = OnceLock::new();
// Trace context propagation can happen outside the provider object, so configured
// tracestate lives beside the process-global tracer provider.
static TRACESTATE_ENTRIES: OnceLock<RwLock<BTreeMap<String, BTreeMap<String, String>>>> =
OnceLock::new();
pub fn current_span_w3c_trace_context() -> Option<W3cTraceContext> {
span_w3c_trace_context(&Span::current())
}
pub fn span_w3c_trace_context(span: &Span) -> Option<W3cTraceContext> {
let context = span.context();
if !context.span().span_context().is_valid() {
return None;
}
let mut headers = HashMap::new();
TraceContextPropagator::new().inject_context(&context, &mut headers);
let tracestate = headers.remove("tracestate");
let configured_tracestate_guard = tracestate_entries()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
Some(W3cTraceContext {
traceparent: headers.remove("traceparent"),
tracestate: merge_tracestate_entries(tracestate.as_deref(), &configured_tracestate_guard),
})
}
/// Injects the W3C trace context for `span` into HTTP headers.
///
/// Existing `traceparent` and `tracestate` values are replaced so callers can
/// safely reuse a request header map while keeping the supplied span as the
/// source of truth.
pub fn inject_span_w3c_trace_headers(span: &Span, headers: &mut http::HeaderMap) -> bool {
let Some(trace) = span_w3c_trace_context(span) else {
return false;
};
match trace.traceparent {
Some(traceparent) => {
if let Ok(value) = http::HeaderValue::from_str(&traceparent) {
headers.insert("traceparent", value);
}
}
None => {
headers.remove("traceparent");
}
}
match trace.tracestate {
Some(tracestate) => {
if let Ok(value) = http::HeaderValue::from_str(&tracestate) {
headers.insert("tracestate", value);
}
}
None => {
headers.remove("tracestate");
}
}
true
}
pub(crate) fn set_tracestate_entries(
entries: BTreeMap<String, BTreeMap<String, String>>,
) -> Result<(), Box<dyn std::error::Error>> {
validate_tracestate_entries(&entries)?;
let mut guard = tracestate_entries()
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
*guard = entries;
Ok(())
}
pub fn current_span_trace_id() -> Option<String> {
let context = Span::current().context();
let span = context.span();
let span_context = span.span_context();
if !span_context.is_valid() {
return None;
}
Some(span_context.trace_id().to_string())
}
pub fn context_from_w3c_trace_context(trace: &W3cTraceContext) -> Option<Context> {
context_from_trace_headers(trace.traceparent.as_deref(), trace.tracestate.as_deref())
}
pub fn set_parent_from_w3c_trace_context(span: &Span, trace: &W3cTraceContext) -> bool {
if let Some(context) = context_from_w3c_trace_context(trace) {
set_parent_from_context(span, context);
true
} else {
false
}
}
pub fn set_parent_from_context(span: &Span, context: Context) {
let _ = span.set_parent(context);
}
pub fn traceparent_context_from_env() -> Option<Context> {
TRACEPARENT_CONTEXT
.get_or_init(load_traceparent_context)
.clone()
}
pub(crate) fn context_from_trace_headers(
traceparent: Option<&str>,
tracestate: Option<&str>,
) -> Option<Context> {
let traceparent = traceparent?;
let mut headers = HashMap::new();
headers.insert("traceparent".to_string(), traceparent.to_string());
if let Some(tracestate) = tracestate {
headers.insert("tracestate".to_string(), tracestate.to_string());
}
// Invalid incoming headers must not fall back to an unrelated active span.
let context = TraceContextPropagator::new().extract_with_context(&Context::new(), &headers);
if !context.span().span_context().is_valid() {
return None;
}
Some(context)
}
fn load_traceparent_context() -> Option<Context> {
let traceparent = env::var(TRACEPARENT_ENV_VAR).ok()?;
let tracestate = env::var(TRACESTATE_ENV_VAR).ok();
match context_from_trace_headers(Some(&traceparent), tracestate.as_deref()) {
Some(context) => {
debug!("TRACEPARENT detected; continuing trace from parent context");
Some(context)
}
None => {
warn!("TRACEPARENT is set but invalid; ignoring trace context");
None
}
}
}
fn tracestate_entries() -> &'static RwLock<BTreeMap<String, BTreeMap<String, String>>> {
TRACESTATE_ENTRIES.get_or_init(|| RwLock::new(BTreeMap::new()))
}
fn merge_tracestate_entries(
tracestate: Option<&str>,
configured_entries: &BTreeMap<String, BTreeMap<String, String>>,
) -> Option<String> {
let mut trace_state = tracestate
.and_then(|tracestate| match TraceState::from_str(tracestate) {
Ok(trace_state) => Some(trace_state),
Err(err) => {
warn!("ignoring invalid tracestate while propagating trace context: {err}");
None
}
})
.unwrap_or_default();
// TraceState::insert places members at the front. Reverse iteration keeps
// deterministic map order while upserting fields inside configured members.
for (key, fields) in configured_entries.iter().rev() {
let value = merge_tracestate_member_fields(trace_state.get(key), fields);
trace_state = match trace_state.insert(key.clone(), value) {
Ok(trace_state) => trace_state,
Err(err) => {
warn!("ignoring configured tracestate while propagating trace context: {err}");
break;
}
};
}
let tracestate = trace_state.header();
(!tracestate.is_empty()).then_some(tracestate)
}
/// Validates configured tracestate members before they are propagated in W3C trace context.
pub fn validate_tracestate_entries(
entries: &BTreeMap<String, BTreeMap<String, String>>,
) -> Result<(), Box<dyn std::error::Error>> {
// Reject malformed entries before installing them so propagated trace
// context remains acceptable to other W3C Trace Context extractors. The
// SDK validates member keys and list structure, but configured member
// fields are joined into header values here and need stricter validation.
let entries = entries
.iter()
.map(|(key, fields)| encode_tracestate_member_fields(key, fields))
.collect::<Result<Vec<_>, _>>()?;
TraceState::from_key_value(
entries
.iter()
.map(|(key, value)| (key.as_str(), value.as_str())),
)
.map_err(|err| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("invalid configured tracestate: {err}"),
)
})?;
Ok(())
}
/// Validates one configured tracestate member and its encoded field value.
pub fn validate_tracestate_member(
member_key: &str,
fields: &BTreeMap<String, String>,
) -> Result<(), Box<dyn std::error::Error>> {
let (key, value) = encode_tracestate_member_fields(member_key, fields)?;
TraceState::from_key_value([(key.as_str(), value.as_str())]).map_err(|err| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("invalid configured tracestate: {err}"),
)
})?;
Ok(())
}
fn encode_tracestate_member_fields(
member_key: &str,
fields: &BTreeMap<String, String>,
) -> Result<(String, String), Box<dyn std::error::Error>> {
// Configured fields are encoded into one opaque tracestate member value.
// Validate both the field grammar and the final header value so malformed
// config cannot produce propagated trace context that downstream W3C
// extractors reject.
let mut encoded = Vec::with_capacity(fields.len());
for (field_key, value) in fields {
if !is_configured_tracestate_field_key(field_key) {
return Err(invalid_tracestate_config(format!(
"invalid configured tracestate field key {member_key}.{field_key}"
)));
}
if !is_configured_tracestate_field_value(value) {
return Err(invalid_tracestate_config(format!(
"invalid configured tracestate value for {member_key}.{field_key}"
)));
}
encoded.push(format!("{field_key}:{value}"));
}
let value = encoded.join(";");
if !is_header_safe_tracestate_member_value(&value) {
return Err(invalid_tracestate_config(format!(
"invalid configured tracestate value for {member_key}"
)));
}
Ok((member_key.to_string(), value))
}
fn is_configured_tracestate_field_key(field_key: &str) -> bool {
!field_key.is_empty()
&& field_key
.bytes()
.all(|byte| matches!(byte, b'!'..=b'~') && !matches!(byte, b':' | b';' | b',' | b'='))
}
fn is_configured_tracestate_field_value(value: &str) -> bool {
value
.bytes()
.all(|byte| is_tracestate_member_value_byte(byte) && byte != b';')
}
fn is_header_safe_tracestate_member_value(value: &str) -> bool {
value.is_empty()
|| (value.bytes().all(is_tracestate_member_value_byte)
&& value.as_bytes().last().is_some_and(|byte| *byte != b' '))
}
fn is_tracestate_member_value_byte(byte: u8) -> bool {
matches!(byte, b' '..=b'~') && !matches!(byte, b',' | b'=')
}
fn invalid_tracestate_config(message: String) -> Box<dyn std::error::Error> {
Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
message,
))
}
fn merge_tracestate_member_fields(
existing: Option<&str>,
configured_fields: &BTreeMap<String, String>,
) -> String {
// W3C TraceState treats member values as opaque strings. The config models
// values as semicolon-separated key:value fields so selected fields can be
// upserted without replacing unrelated fields in the same member.
let mut fields = Vec::new();
let mut seen = BTreeSet::new();
if let Some(existing) = existing {
for field in existing.split(';').filter(|field| !field.is_empty()) {
if let Some((field_key, _)) = field.split_once(':') {
if let Some(value) = configured_fields.get(field_key) {
if seen.insert(field_key) {
fields.push(format!("{field_key}:{value}"));
}
continue;
}
seen.insert(field_key);
}
fields.push(field.to_string());
}
}
fields.extend(
configured_fields
.iter()
.filter(|(field_key, _)| !seen.contains(field_key.as_str()))
.map(|(field_key, value)| format!("{field_key}:{value}")),
);
fields.join(";")
}
#[cfg(test)]
mod tests {
use super::context_from_trace_headers;
use super::context_from_w3c_trace_context;
use super::current_span_trace_id;
use codex_protocol::protocol::W3cTraceContext;
use opentelemetry::trace::SpanId;
use opentelemetry::trace::TraceContextExt;
use opentelemetry::trace::TraceId;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::SdkTracerProvider;
use pretty_assertions::assert_eq;
use tracing::trace_span;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
#[test]
fn parses_valid_w3c_trace_context() {
let trace_id = "00000000000000000000000000000001";
let span_id = "0000000000000002";
let context = context_from_w3c_trace_context(&W3cTraceContext {
traceparent: Some(format!("00-{trace_id}-{span_id}-01")),
tracestate: None,
})
.expect("trace context");
let span = context.span();
let span_context = span.span_context();
assert_eq!(
span_context.trace_id(),
TraceId::from_hex(trace_id).unwrap()
);
assert_eq!(span_context.span_id(), SpanId::from_hex(span_id).unwrap());
assert!(span_context.is_remote());
}
#[test]
fn invalid_traceparent_returns_none() {
let parent = context_from_trace_headers(
Some("00-11111111111111111111111111111111-2222222222222222-01"),
/*tracestate*/ None,
)
.expect("valid ambient context");
let _guard = parent.attach();
assert!(
context_from_trace_headers(Some("not-a-traceparent"), /*tracestate*/ None).is_none()
);
}
#[test]
fn missing_traceparent_returns_none() {
assert!(
context_from_w3c_trace_context(&W3cTraceContext {
traceparent: None,
tracestate: Some("vendor=value".to_string()),
})
.is_none()
);
}
#[test]
fn current_span_trace_id_returns_hex_trace_id() {
let provider = SdkTracerProvider::builder().build();
let tracer = provider.tracer("codex-otel-tests");
let subscriber =
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
let _guard = subscriber.set_default();
let span = trace_span!("test_span");
let _entered = span.enter();
let trace_id = current_span_trace_id().expect("trace id");
assert_eq!(trace_id.len(), 32);
assert!(trace_id.chars().all(|ch| ch.is_ascii_hexdigit()));
assert_ne!(trace_id, "00000000000000000000000000000000");
}
}