aKode fase 2c: eliminato il codice di invio dati (crate analytics, otel-trace-websocket, sentry, esportatori OTLP); /feedback salva solo in locale; chiavi legacy [analytics]/[otel] accettate e ignorate; test di analytics/OTLP/upload rimossi
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
This commit is contained in:
@@ -13,44 +13,23 @@ path = "src/lib.rs"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
bytes = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
opentelemetry-http = "0.31.0"
|
||||
chrono = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-stream-parser = { workspace = true }
|
||||
codex-utils-string = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
eventsource-stream = { workspace = true }
|
||||
gethostname = { workspace = true }
|
||||
opentelemetry = { workspace = true, features = ["logs", "metrics", "trace"] }
|
||||
opentelemetry-appender-tracing = { workspace = true }
|
||||
opentelemetry-otlp = { workspace = true, features = [
|
||||
"grpc-tonic",
|
||||
"http-proto",
|
||||
"http-json",
|
||||
"logs",
|
||||
"metrics",
|
||||
"trace",
|
||||
"reqwest-blocking-client",
|
||||
"reqwest-rustls",
|
||||
"tls",
|
||||
"tls-roots",
|
||||
]}
|
||||
opentelemetry = { workspace = true, features = ["metrics", "trace"] }
|
||||
opentelemetry-semantic-conventions = { workspace = true }
|
||||
opentelemetry_sdk = { workspace = true, features = [
|
||||
"experimental_trace_batch_span_processor_with_async_runtime",
|
||||
"experimental_metrics_custom_reader",
|
||||
"logs",
|
||||
"metrics",
|
||||
"rt-tokio",
|
||||
"testing",
|
||||
"trace",
|
||||
] }
|
||||
http = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
os_info = { workspace = true }
|
||||
reqwest = { workspace = true, features = ["blocking", "rustls-tls"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
strum_macros = { workspace = true }
|
||||
@@ -61,16 +40,4 @@ tracing-opentelemetry = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
opentelemetry_sdk = { workspace = true, features = [
|
||||
"experimental_metrics_custom_reader",
|
||||
"testing",
|
||||
] }
|
||||
pretty_assertions = { workspace = true }
|
||||
rcgen = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dev-dependencies]
|
||||
seccompiler = { workspace = true }
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
//! 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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// aKode: the upstream built-in Statsig exporter (ab.chatgpt.com with an
|
||||
/// embedded API key) has been removed. The `Statsig` variant is kept only so
|
||||
/// old configuration files still parse; it always resolves to `None`, so no
|
||||
/// telemetry is ever sent unless the user configures an explicit exporter.
|
||||
pub(crate) fn resolve_exporter(exporter: &OtelExporter) -> OtelExporter {
|
||||
match exporter {
|
||||
OtelExporter::Statsig => OtelExporter::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
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,6 @@ use crate::metrics::WEBSOCKET_REQUEST_COUNT_METRIC;
|
||||
use crate::metrics::WEBSOCKET_REQUEST_DURATION_METRIC;
|
||||
use crate::metrics::runtime_metrics::RuntimeMetricsSummary;
|
||||
use crate::metrics::timer::Timer;
|
||||
use crate::provider::OtelProvider;
|
||||
use crate::sanitize_metric_tag_value;
|
||||
use crate::tool_result::ToolResultEvent;
|
||||
use crate::tool_result::emit_tool_result;
|
||||
@@ -204,13 +203,6 @@ impl SessionTelemetry {
|
||||
Ok(self.with_metrics(metrics))
|
||||
}
|
||||
|
||||
pub fn with_provider_metrics(self, provider: &OtelProvider) -> Self {
|
||||
match provider.metrics() {
|
||||
Some(metrics) => self.with_metrics(metrics.clone()),
|
||||
None => self,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) {
|
||||
let res: MetricsResult<()> = (|| {
|
||||
let Some(metrics) = &self.metrics else {
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
//! 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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
//! Local-only telemetry helpers for aKode.
|
||||
//!
|
||||
//! This crate records structured tracing events, W3C trace-context helpers and
|
||||
//! optional in-process metrics. It contains no network exporter: nothing
|
||||
//! recorded here ever leaves the machine.
|
||||
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;
|
||||
@@ -18,14 +17,6 @@ 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;
|
||||
@@ -34,19 +25,16 @@ 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::targets::trace_export_filter;
|
||||
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)]
|
||||
@@ -79,7 +67,7 @@ impl From<AuthMode> for TelemetryAuthMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Install externally managed, non-Statsig process-global metrics.
|
||||
/// Install process-global, local-only metrics (for example an in-memory reader).
|
||||
///
|
||||
/// Call this once during single-threaded startup, before any instruments are
|
||||
/// registered. Keep the returned handle to flush and shut down the exporter
|
||||
@@ -95,9 +83,3 @@ pub fn start_global_timer(name: &str, tags: &[(&str, &str)]) -> MetricsResult<Ti
|
||||
};
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ struct PendingOperation {
|
||||
enum State {
|
||||
Startup(Vec<PendingOperation>),
|
||||
Ready(MetricsClient),
|
||||
Disabled,
|
||||
}
|
||||
|
||||
pub(crate) struct BufferedMetrics {
|
||||
@@ -105,7 +104,6 @@ impl BufferedMetrics {
|
||||
Ok(())
|
||||
}
|
||||
State::Ready(metrics) => record(metrics, count_name, duration_name, duration, tags),
|
||||
State::Disabled => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,13 +137,6 @@ impl BufferedMetrics {
|
||||
*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
|
||||
|
||||
@@ -104,27 +104,6 @@ fn startup_limits_and_validation_preserve_whole_pairs() {
|
||||
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();
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
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;
|
||||
@@ -18,13 +15,6 @@ 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;
|
||||
@@ -45,10 +35,6 @@ 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";
|
||||
@@ -121,7 +107,6 @@ impl MetricReader for SharedManualReader {
|
||||
|
||||
#[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>>>,
|
||||
@@ -129,8 +114,6 @@ pub(super) struct MetricsClientInner {
|
||||
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>,
|
||||
}
|
||||
|
||||
@@ -151,10 +134,6 @@ impl MetricsClientInner {
|
||||
}
|
||||
let attributes = self.attributes(tags)?;
|
||||
|
||||
if self.statsig_disabled_metrics.contains(&name) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut counters = self
|
||||
.counters
|
||||
.lock()
|
||||
@@ -185,10 +164,6 @@ impl MetricsClientInner {
|
||||
validate_metric_name(name)?;
|
||||
let attributes = self.attributes(tags)?;
|
||||
|
||||
if self.statsig_disabled_metrics.contains(&name) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut histograms = self
|
||||
.histograms
|
||||
.lock()
|
||||
@@ -214,10 +189,6 @@ impl MetricsClientInner {
|
||||
validate_metric_name(name)?;
|
||||
let attributes = self.attributes(tags)?;
|
||||
|
||||
if self.statsig_disabled_metrics.contains(&name) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut gauges = self
|
||||
.gauges
|
||||
.lock()
|
||||
@@ -248,10 +219,6 @@ impl MetricsClientInner {
|
||||
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())
|
||||
@@ -273,10 +240,6 @@ impl MetricsClientInner {
|
||||
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()
|
||||
@@ -332,10 +295,10 @@ impl MetricsClientInner {
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenTelemetry metrics client used by Codex.
|
||||
/// Local, in-process OpenTelemetry metrics client. It never exports over the network.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MetricsClient {
|
||||
// Keep the original provider so its owner only shuts down its own exporter.
|
||||
// Keep the original provider so its owner only shuts down its own reader.
|
||||
pub(super) inner: Arc<MetricsClientInner>,
|
||||
// Installed clients share this slot, so existing clones follow account changes.
|
||||
pub(super) active: Option<Arc<RwLock<Arc<MetricsClientInner>>>>,
|
||||
@@ -345,14 +308,12 @@ 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;
|
||||
|
||||
@@ -379,34 +340,11 @@ impl MetricsClient {
|
||||
)
|
||||
});
|
||||
|
||||
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())
|
||||
}
|
||||
};
|
||||
let (meter_provider, meter) =
|
||||
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()),
|
||||
@@ -414,8 +352,6 @@ impl MetricsClient {
|
||||
histograms: Mutex::new(HashMap::new()),
|
||||
duration_histograms: Mutex::new(HashMap::new()),
|
||||
runtime_reader,
|
||||
requires_analytics_consent,
|
||||
statsig_disabled_metrics,
|
||||
default_tags,
|
||||
}),
|
||||
active: None,
|
||||
@@ -438,22 +374,6 @@ impl MetricsClient {
|
||||
.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,
|
||||
@@ -639,104 +559,3 @@ where
|
||||
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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
//! 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(())
|
||||
}
|
||||
@@ -1,95 +1,24 @@
|
||||
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),
|
||||
}
|
||||
|
||||
/// Configuration for a local, in-process metrics client. There is no network exporter.
|
||||
#[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) exporter: InMemoryMetricExporter,
|
||||
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).
|
||||
/// Create an in-memory config.
|
||||
pub fn in_memory(
|
||||
environment: impl Into<String>,
|
||||
service_name: impl Into<String>,
|
||||
@@ -97,16 +26,12 @@ impl MetricsConfig {
|
||||
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),
|
||||
exporter,
|
||||
export_interval: None,
|
||||
runtime_reader: false,
|
||||
statsig_disabled_metrics: &[],
|
||||
default_tags: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -123,7 +48,7 @@ impl MetricsConfig {
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a default tag that will be sent with every metric.
|
||||
/// Add a default tag that will be recorded 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();
|
||||
|
||||
@@ -17,21 +17,12 @@ pub enum MetricsError {
|
||||
#[error("{label} contains invalid characters: {value}")]
|
||||
InvalidTagComponent { label: String, value: String },
|
||||
|
||||
#[error("metrics exporter is disabled")]
|
||||
#[error("metrics are not installed")]
|
||||
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]
|
||||
|
||||
@@ -9,11 +9,9 @@ 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;
|
||||
@@ -26,7 +24,6 @@ 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
|
||||
@@ -45,17 +42,3 @@ pub(crate) fn install_global(mut metrics: MetricsClient) -> MetricsClient {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
//! 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")??
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
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"),
|
||||
),
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,884 +0,0 @@
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,469 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Exports skill-use metadata without skill contents, filesystem paths, or tool payloads.
|
||||
//! Logs skill-use metadata locally without skill contents, filesystem paths, or tool payloads.
|
||||
//! Detection belongs to the caller; an invocation does not imply successful task completion.
|
||||
|
||||
use crate::SessionTelemetry;
|
||||
@@ -7,6 +7,7 @@ use crate::targets::OTEL_LOG_ONLY_TARGET;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
|
||||
/// How Codex detected the skill's use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SkillInvocationType {
|
||||
Explicit,
|
||||
Implicit,
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
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)
|
||||
}
|
||||
|
||||
/// Filters spans and events that are safe to attach to local trace layers.
|
||||
pub fn trace_export_filter(meta: &tracing::Metadata<'_>) -> bool {
|
||||
let target = meta.target();
|
||||
if meta.is_span() {
|
||||
!matches!(target.split("::").next(), Some("h2" | "tokio" | "runtime"))
|
||||
} else {
|
||||
is_trace_safe_target(target)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
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;
|
||||
@@ -21,11 +16,6 @@ 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())
|
||||
}
|
||||
@@ -38,60 +28,12 @@ pub fn span_w3c_trace_context(span: &Span) -> Option<W3cTraceContext> {
|
||||
|
||||
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),
|
||||
tracestate: headers.remove("tracestate"),
|
||||
})
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -161,177 +103,6 @@ fn load_traceparent_context() -> Option<Context> {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -1,20 +1,12 @@
|
||||
//! Exercises global operation buffering across shutdown and rejected configuration changes.
|
||||
//! Exercises global operation buffering across shutdown and replacement installations.
|
||||
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use codex_otel::OtelExporter;
|
||||
use codex_otel::OtelHttpProtocol;
|
||||
use codex_otel::OtelProvider;
|
||||
use codex_otel::OtelSettings;
|
||||
use codex_otel::install_global_metrics;
|
||||
use codex_otel::record_global_operation;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
fn install() -> MetricsClient {
|
||||
@@ -76,51 +68,3 @@ fn shutdown_buffers_until_replacement_and_preserves_newer_installations() {
|
||||
assert_eq!(totals(&third), (1, 1, 7.0));
|
||||
third.shutdown().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_opt_out_preserves_recording_and_accepted_opt_out_survives_shutdown() {
|
||||
let metrics = install();
|
||||
let mut settings = OtelSettings {
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
environment: "test".to_string(),
|
||||
service_name: "test".to_string(),
|
||||
service_version: "1".to_string(),
|
||||
codex_home: ".".into(),
|
||||
exporter: OtelExporter::None,
|
||||
trace_exporter: OtelExporter::OtlpHttp {
|
||||
endpoint: "http://127.0.0.1:1/v1/traces".to_string(),
|
||||
headers: Default::default(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
metrics_exporter: OtelExporter::None,
|
||||
runtime_metrics: false,
|
||||
span_attributes: HashMap::from([(String::new(), "invalid".to_string())]),
|
||||
tracestate: BTreeMap::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
OtelProvider::try_new(&settings).err().unwrap().to_string(),
|
||||
"configured span attribute key must not be empty"
|
||||
);
|
||||
observe();
|
||||
assert_eq!(totals(&metrics), (1, 1, 7.0));
|
||||
|
||||
metrics.shutdown().unwrap();
|
||||
observe();
|
||||
assert!(OtelProvider::try_new(&settings).is_err());
|
||||
let replacement = install();
|
||||
assert_eq!(totals(&replacement), (1, 1, 7.0));
|
||||
replacement.shutdown().unwrap();
|
||||
|
||||
settings.span_attributes.clear();
|
||||
for trace_exporter in [settings.trace_exporter.clone(), OtelExporter::None] {
|
||||
let metrics = install();
|
||||
settings.trace_exporter = trace_exporter;
|
||||
let _provider = OtelProvider::try_new(&settings).unwrap();
|
||||
metrics.shutdown().unwrap();
|
||||
observe();
|
||||
let replacement = install();
|
||||
assert_eq!(totals(&replacement), (0, 0, 0.0));
|
||||
replacement.shutdown().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
#[path = "buffered_operations_tests.rs"]
|
||||
mod buffered_operations;
|
||||
mod manager_metrics;
|
||||
mod otel_export_routing_policy;
|
||||
mod otlp_http_loopback;
|
||||
mod runtime_summary;
|
||||
mod send;
|
||||
mod snapshot;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,947 +0,0 @@
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_otel::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use codex_otel::OtelExporter;
|
||||
use codex_otel::OtelHttpProtocol;
|
||||
use codex_otel::OtelProvider;
|
||||
use codex_otel::OtelSettings;
|
||||
use codex_otel::Result;
|
||||
use codex_otel::current_span_w3c_trace_context;
|
||||
use codex_otel::set_parent_from_w3c_trace_context;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read as _;
|
||||
use std::io::Write as _;
|
||||
use std::net::TcpListener;
|
||||
use std::net::TcpStream;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
static TRACE_CONTEXT_CONFIG_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
struct CapturedRequest {
|
||||
path: String,
|
||||
content_type: Option<String>,
|
||||
body: Vec<u8>,
|
||||
}
|
||||
|
||||
fn read_http_request(
|
||||
stream: &mut TcpStream,
|
||||
) -> std::io::Result<(String, HashMap<String, String>, Vec<u8>)> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
|
||||
let mut read_next = |buf: &mut [u8]| -> std::io::Result<usize> {
|
||||
loop {
|
||||
match stream.read(buf) {
|
||||
Ok(n) => return Ok(n),
|
||||
Err(err)
|
||||
if err.kind() == std::io::ErrorKind::WouldBlock
|
||||
|| err.kind() == std::io::ErrorKind::Interrupted =>
|
||||
{
|
||||
if Instant::now() >= deadline {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::TimedOut,
|
||||
"timed out waiting for request data",
|
||||
));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut buf = Vec::new();
|
||||
let mut scratch = [0u8; 8192];
|
||||
let header_end = loop {
|
||||
let n = read_next(&mut scratch)?;
|
||||
if n == 0 {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
"EOF before headers",
|
||||
));
|
||||
}
|
||||
buf.extend_from_slice(&scratch[..n]);
|
||||
if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
|
||||
break end;
|
||||
}
|
||||
if buf.len() > 1024 * 1024 {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"headers too large",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let headers_bytes = &buf[..header_end];
|
||||
let mut body_bytes = buf[header_end + 4..].to_vec();
|
||||
|
||||
let headers_str = std::str::from_utf8(headers_bytes).map_err(|err| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("headers not utf-8: {err}"),
|
||||
)
|
||||
})?;
|
||||
let mut lines = headers_str.split("\r\n");
|
||||
let start = lines.next().ok_or_else(|| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, "missing request line")
|
||||
})?;
|
||||
let mut parts = start.split_whitespace();
|
||||
let _method = parts.next().unwrap_or_default();
|
||||
let path = parts
|
||||
.next()
|
||||
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "missing path"))?
|
||||
.to_string();
|
||||
|
||||
let mut headers = HashMap::new();
|
||||
for line in lines {
|
||||
let Some((k, v)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_string());
|
||||
}
|
||||
|
||||
if let Some(len) = headers
|
||||
.get("content-length")
|
||||
.and_then(|v| v.parse::<usize>().ok())
|
||||
{
|
||||
while body_bytes.len() < len {
|
||||
let n = read_next(&mut scratch)?;
|
||||
if n == 0 {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
"EOF before body complete",
|
||||
));
|
||||
}
|
||||
body_bytes.extend_from_slice(&scratch[..n]);
|
||||
if body_bytes.len() > len + 1024 * 1024 {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"body too large",
|
||||
));
|
||||
}
|
||||
}
|
||||
body_bytes.truncate(len);
|
||||
}
|
||||
|
||||
Ok((path, headers, body_bytes))
|
||||
}
|
||||
|
||||
fn write_http_response(stream: &mut TcpStream, status: &str) -> std::io::Result<()> {
|
||||
let response = format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(response.as_bytes())?;
|
||||
stream.flush()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn otlp_http_exporter_honors_cumulative_temporality_env() -> Result<()> {
|
||||
// Isolate the environment setting from other tests, including under Bazel/libtest.
|
||||
const CHILD_ENV: &str = "CODEX_OTEL_TEMPORALITY_TEST_CHILD";
|
||||
if std::env::var_os(CHILD_ENV).is_none() {
|
||||
let current_thread = thread::current();
|
||||
let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
|
||||
.args([
|
||||
"--exact",
|
||||
current_thread.name().expect("test name"),
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_ENV, "1")
|
||||
.env(
|
||||
"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",
|
||||
"cumulative",
|
||||
)
|
||||
.env("OTEL_METRIC_EXPORT_INTERVAL", "60000")
|
||||
.output()
|
||||
.expect("run test with cumulative temporality configured");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("local_addr");
|
||||
listener.set_nonblocking(true).expect("set_nonblocking");
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
|
||||
let server = thread::spawn(move || {
|
||||
let mut captured = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
let result = read_http_request(&mut stream);
|
||||
let _ = write_http_response(&mut stream, "202 Accepted");
|
||||
if let Ok((path, headers, body)) = result {
|
||||
captured.push(CapturedRequest {
|
||||
path,
|
||||
content_type: headers.get("content-type").cloned(),
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tx.send(captured);
|
||||
});
|
||||
|
||||
let metrics = MetricsClient::new(MetricsConfig::otlp(
|
||||
"test",
|
||||
"codex-cli",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
OtelExporter::OtlpHttp {
|
||||
endpoint: format!("http://{addr}/v1/metrics"),
|
||||
headers: HashMap::new(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
))?;
|
||||
|
||||
metrics.counter("codex.turns", /*inc*/ 1, &[("source", "test")])?;
|
||||
metrics.counter("codex.api_request", /*inc*/ 1, &[("status", "200")])?;
|
||||
metrics.counter_with_description(
|
||||
EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC,
|
||||
"Client-side exec-server RPC attempts.",
|
||||
/*inc*/ 1,
|
||||
&[("method", "fs/readFile")],
|
||||
)?;
|
||||
metrics.record_duration(
|
||||
"codex.api_request.duration_ms",
|
||||
Duration::from_millis(100),
|
||||
&[("status", "200")],
|
||||
)?;
|
||||
metrics.counter("codex.conversation.turn.count", /*inc*/ 1, &[])?;
|
||||
metrics.record_duration(
|
||||
"codex.responses_api_engine_iapi_ttft.duration_ms",
|
||||
Duration::from_millis(100),
|
||||
&[],
|
||||
)?;
|
||||
metrics.record_duration(
|
||||
"codex.responses_api_engine_service_tbt.duration_ms",
|
||||
Duration::from_millis(100),
|
||||
&[],
|
||||
)?;
|
||||
metrics.record_duration(
|
||||
"codex.responses_api_engine_service_ttft.duration_ms",
|
||||
Duration::from_millis(100),
|
||||
&[],
|
||||
)?;
|
||||
metrics.counter("codex.tool.call", /*inc*/ 1, &[("tool", "test")])?;
|
||||
metrics.record_duration(
|
||||
"codex.tool.call.duration_ms",
|
||||
Duration::from_millis(42),
|
||||
&[("tool", "test")],
|
||||
)?;
|
||||
metrics.histogram(
|
||||
"codex.turn.token_usage",
|
||||
/*value*/ 100,
|
||||
&[("token_type", "total")],
|
||||
)?;
|
||||
metrics.gauge_with_description(
|
||||
"codex.active",
|
||||
"Number of active Codex operations.",
|
||||
/*value*/ 1,
|
||||
&[("component", "test")],
|
||||
)?;
|
||||
metrics.shutdown()?;
|
||||
|
||||
server.join().expect("server join");
|
||||
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
|
||||
|
||||
let request = captured
|
||||
.iter()
|
||||
.find(|req| req.path == "/v1/metrics")
|
||||
.expect("/v1/metrics request should be captured");
|
||||
let content_type = request
|
||||
.content_type
|
||||
.as_deref()
|
||||
.unwrap_or("<missing content-type>");
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"unexpected content-type: {content_type}"
|
||||
);
|
||||
|
||||
let payload: serde_json::Value = serde_json::from_slice(&request.body).expect("OTLP JSON");
|
||||
let counter = payload["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]
|
||||
.as_array()
|
||||
.expect("exported metrics")
|
||||
.iter()
|
||||
.find(|metric| metric["name"] == "codex.turns")
|
||||
.expect("exported counter");
|
||||
assert_eq!(
|
||||
counter["sum"]["aggregationTemporality"],
|
||||
serde_json::json!(2)
|
||||
);
|
||||
|
||||
let body = String::from_utf8_lossy(&request.body);
|
||||
assert!(
|
||||
body.contains("codex.turns"),
|
||||
"expected metric name not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("codex.active"),
|
||||
"expected gauge not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.api_request\""),
|
||||
"expected API-request counter not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains(EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC),
|
||||
"custom OTLP must retain the exec-server client counter excluded from built-in Statsig"
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.api_request.duration_ms\""),
|
||||
"expected API-request duration not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.conversation.turn.count\""),
|
||||
"expected conversation turn count not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.responses_api_engine_iapi_ttft.duration_ms\""),
|
||||
"expected engine IAPI TTFT duration not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.responses_api_engine_service_tbt.duration_ms\""),
|
||||
"expected engine service TBT duration not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.responses_api_engine_service_ttft.duration_ms\""),
|
||||
"expected engine service TTFT duration not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.tool.call\""),
|
||||
"expected tool-call counter not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.turn.token_usage\""),
|
||||
"expected turn-token histogram not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"codex.tool.call.duration_ms\""),
|
||||
"expected tool-call duration not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("component") && body.contains("test"),
|
||||
"expected gauge tag not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn otlp_http_exporter_sends_logs_to_collector()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("local_addr");
|
||||
listener.set_nonblocking(true).expect("set_nonblocking");
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
|
||||
let server = thread::spawn(move || {
|
||||
let mut captured = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
let result = read_http_request(&mut stream);
|
||||
let _ = write_http_response(&mut stream, "202 Accepted");
|
||||
if let Ok((path, headers, body)) = result {
|
||||
captured.push(CapturedRequest {
|
||||
path,
|
||||
content_type: headers.get("content-type").cloned(),
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tx.send(captured);
|
||||
});
|
||||
|
||||
let otel = OtelProvider::try_new(&OtelSettings {
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
environment: "test".to_string(),
|
||||
service_name: "codex-cli".to_string(),
|
||||
service_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
codex_home: PathBuf::from("."),
|
||||
exporter: OtelExporter::OtlpHttp {
|
||||
endpoint: format!("http://{addr}/v1/logs"),
|
||||
headers: HashMap::new(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
trace_exporter: OtelExporter::None,
|
||||
metrics_exporter: OtelExporter::None,
|
||||
runtime_metrics: false,
|
||||
span_attributes: HashMap::new(),
|
||||
tracestate: BTreeMap::new(),
|
||||
})?
|
||||
.expect("otel provider");
|
||||
let logger_layer = otel.logger_layer().expect("logger layer");
|
||||
let subscriber = tracing_subscriber::registry().with(logger_layer);
|
||||
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
tracing::callsite::rebuild_interest_cache();
|
||||
tracing::event!(
|
||||
target: "codex_otel.log_only",
|
||||
tracing::Level::INFO,
|
||||
event.name = "codex.test.log_exported",
|
||||
"test OTEL log export"
|
||||
);
|
||||
});
|
||||
otel.shutdown();
|
||||
|
||||
server.join().expect("server join");
|
||||
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
|
||||
|
||||
let request = captured
|
||||
.iter()
|
||||
.find(|req| req.path == "/v1/logs")
|
||||
.expect("/v1/logs request should be captured");
|
||||
let content_type = request
|
||||
.content_type
|
||||
.as_deref()
|
||||
.unwrap_or("<missing content-type>");
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"unexpected content-type: {content_type}"
|
||||
);
|
||||
|
||||
let body = String::from_utf8_lossy(&request.body);
|
||||
assert!(
|
||||
body.contains("codex.test.log_exported"),
|
||||
"expected exported log event not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn otel_provider_rejects_header_unsafe_configured_tracestate() {
|
||||
let result = OtelProvider::try_new(&OtelSettings {
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
environment: "test".to_string(),
|
||||
service_name: "codex-cli".to_string(),
|
||||
service_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
codex_home: PathBuf::from("."),
|
||||
exporter: OtelExporter::None,
|
||||
trace_exporter: OtelExporter::OtlpHttp {
|
||||
endpoint: "http://127.0.0.1:1/v1/traces".to_string(),
|
||||
headers: HashMap::new(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
metrics_exporter: OtelExporter::None,
|
||||
runtime_metrics: false,
|
||||
span_attributes: HashMap::new(),
|
||||
tracestate: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
BTreeMap::from([("alpha".to_string(), "one\ntwo".to_string())]),
|
||||
)]),
|
||||
});
|
||||
|
||||
let err = result
|
||||
.err()
|
||||
.expect("header-unsafe configured tracestate should be rejected");
|
||||
assert!(err.to_string().contains("configured tracestate value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn otlp_http_exporter_sends_traces_to_collector()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("local_addr");
|
||||
listener.set_nonblocking(true).expect("set_nonblocking");
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
|
||||
let server = thread::spawn(move || {
|
||||
let mut captured = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
let result = read_http_request(&mut stream);
|
||||
let _ = write_http_response(&mut stream, "202 Accepted");
|
||||
if let Ok((path, headers, body)) = result {
|
||||
captured.push(CapturedRequest {
|
||||
path,
|
||||
content_type: headers.get("content-type").cloned(),
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tx.send(captured);
|
||||
});
|
||||
|
||||
let otel = OtelProvider::try_new(&OtelSettings {
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
environment: "test".to_string(),
|
||||
service_name: "codex-cli".to_string(),
|
||||
service_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
codex_home: PathBuf::from("."),
|
||||
exporter: OtelExporter::None,
|
||||
trace_exporter: OtelExporter::OtlpHttp {
|
||||
endpoint: format!("http://{addr}/v1/traces"),
|
||||
headers: HashMap::new(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
metrics_exporter: OtelExporter::None,
|
||||
runtime_metrics: false,
|
||||
span_attributes: HashMap::from([(
|
||||
"test.configured_attribute".to_string(),
|
||||
"configured-value".to_string(),
|
||||
)]),
|
||||
tracestate: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
BTreeMap::from([
|
||||
("alpha".to_string(), "one".to_string()),
|
||||
("beta".to_string(), "two".to_string()),
|
||||
]),
|
||||
)]),
|
||||
})?
|
||||
.expect("otel provider");
|
||||
let tracing_layer = otel.tracing_layer().expect("tracing layer");
|
||||
let subscriber = tracing_subscriber::registry().with(tracing_layer);
|
||||
|
||||
let propagated_trace = tracing::subscriber::with_default(subscriber, || {
|
||||
let span = tracing::info_span!(
|
||||
"trace-loopback",
|
||||
otel.name = "trace-loopback",
|
||||
otel.kind = "server",
|
||||
rpc.system = "jsonrpc",
|
||||
rpc.method = "trace-loopback",
|
||||
);
|
||||
assert!(set_parent_from_w3c_trace_context(
|
||||
&span,
|
||||
&W3cTraceContext {
|
||||
traceparent: Some(
|
||||
"00-00000000000000000000000000000001-0000000000000002-01".to_string(),
|
||||
),
|
||||
tracestate: Some("example=alpha:zero;keep:yes,other=value".to_string()),
|
||||
},
|
||||
));
|
||||
let _guard = span.enter();
|
||||
let propagated_trace =
|
||||
current_span_w3c_trace_context().expect("current span should have trace context");
|
||||
tracing::event!(
|
||||
target: "codex_otel.trace_safe",
|
||||
tracing::Level::INFO,
|
||||
event.name = "codex.test.trace_event",
|
||||
"test OTEL trace event"
|
||||
);
|
||||
tracing::info!("trace loopback event");
|
||||
propagated_trace
|
||||
});
|
||||
otel.shutdown();
|
||||
|
||||
assert_eq!(
|
||||
propagated_trace.tracestate.as_deref(),
|
||||
Some("example=alpha:one;keep:yes;beta:two,other=value")
|
||||
);
|
||||
|
||||
server.join().expect("server join");
|
||||
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
|
||||
|
||||
let request = captured
|
||||
.iter()
|
||||
.find(|req| req.path == "/v1/traces")
|
||||
.expect("/v1/traces request should be captured");
|
||||
let content_type = request
|
||||
.content_type
|
||||
.as_deref()
|
||||
.unwrap_or("<missing content-type>");
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"unexpected content-type: {content_type}"
|
||||
);
|
||||
|
||||
let body = String::from_utf8_lossy(&request.body);
|
||||
assert!(
|
||||
body.contains("trace-loopback"),
|
||||
"expected span name not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("codex-cli"),
|
||||
"expected service name not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("test.configured_attribute") && body.contains("configured-value"),
|
||||
"expected configured span attribute not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("codex.test.trace_event"),
|
||||
"expected trace event not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn otlp_http_exporter_sends_traces_to_collector_with_bounded_shutdown_in_tokio_runtime()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("local_addr");
|
||||
listener.set_nonblocking(true).expect("set_nonblocking");
|
||||
|
||||
let otel = OtelProvider::try_new(&OtelSettings {
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
environment: "test".to_string(),
|
||||
service_name: "codex-cli".to_string(),
|
||||
service_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
codex_home: PathBuf::from("."),
|
||||
exporter: OtelExporter::None,
|
||||
trace_exporter: OtelExporter::OtlpHttp {
|
||||
endpoint: format!("http://{addr}/v1/traces"),
|
||||
headers: HashMap::new(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
metrics_exporter: OtelExporter::None,
|
||||
runtime_metrics: false,
|
||||
span_attributes: HashMap::new(),
|
||||
tracestate: BTreeMap::new(),
|
||||
})?
|
||||
.expect("otel provider");
|
||||
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
|
||||
let (stop_tx, stop_rx) = mpsc::channel();
|
||||
let server = thread::spawn(move || {
|
||||
let mut captured = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
match stop_rx.try_recv() {
|
||||
Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
|
||||
Err(mpsc::TryRecvError::Empty) => {}
|
||||
}
|
||||
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
let result = read_http_request(&mut stream);
|
||||
let _ = write_http_response(&mut stream, "202 Accepted");
|
||||
if let Ok((path, headers, body)) = result {
|
||||
captured.push(CapturedRequest {
|
||||
path,
|
||||
content_type: headers.get("content-type").cloned(),
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tx.send(captured);
|
||||
});
|
||||
let tracing_layer = otel.tracing_layer().expect("tracing layer");
|
||||
let subscriber = tracing_subscriber::registry().with(tracing_layer);
|
||||
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
let span = tracing::info_span!(
|
||||
"trace-loopback-tokio",
|
||||
otel.name = "trace-loopback-tokio",
|
||||
otel.kind = "server",
|
||||
rpc.system = "jsonrpc",
|
||||
rpc.method = "trace-loopback-tokio",
|
||||
);
|
||||
let _guard = span.enter();
|
||||
tracing::info!("trace loopback event from tokio runtime");
|
||||
});
|
||||
let shutdown_result = tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current()
|
||||
.block_on(otel.shutdown_with_timeout(Duration::from_secs(/*secs*/ 2)))
|
||||
});
|
||||
|
||||
let _ = stop_tx.send(());
|
||||
server.join().expect("server join");
|
||||
shutdown_result?;
|
||||
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
|
||||
|
||||
let request = captured
|
||||
.iter()
|
||||
.find(|req| req.path == "/v1/traces")
|
||||
.expect("/v1/traces request should be captured");
|
||||
let content_type = request
|
||||
.content_type
|
||||
.as_deref()
|
||||
.unwrap_or("<missing content-type>");
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"unexpected content-type: {content_type}"
|
||||
);
|
||||
|
||||
let body = String::from_utf8_lossy(&request.body);
|
||||
assert!(
|
||||
body.contains("trace-loopback-tokio"),
|
||||
"expected span name not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("codex-cli"),
|
||||
"expected service name not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn otlp_http_exporter_times_out_when_collector_stalls_during_bounded_shutdown() {
|
||||
let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("local_addr");
|
||||
let (request_started_tx, request_started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
|
||||
let server = thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().expect("accept trace request");
|
||||
let (path, _, _) = read_http_request(&mut stream).expect("read trace request");
|
||||
request_started_tx.send(path).expect("request started");
|
||||
release_rx
|
||||
.recv_timeout(Duration::from_secs(/*secs*/ 2))
|
||||
.expect("collector released");
|
||||
write_http_response(&mut stream, "202 Accepted").expect("write trace response");
|
||||
});
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("build tokio runtime");
|
||||
let (result, elapsed) = runtime.block_on(async move {
|
||||
let otel = OtelProvider::try_new(&OtelSettings {
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
environment: "test".to_string(),
|
||||
service_name: "codex-cli".to_string(),
|
||||
service_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
codex_home: PathBuf::from("."),
|
||||
exporter: OtelExporter::None,
|
||||
trace_exporter: OtelExporter::OtlpHttp {
|
||||
endpoint: format!("http://{addr}/v1/traces"),
|
||||
headers: HashMap::new(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
metrics_exporter: OtelExporter::None,
|
||||
runtime_metrics: false,
|
||||
span_attributes: HashMap::new(),
|
||||
tracestate: BTreeMap::new(),
|
||||
})
|
||||
.expect("build otel provider")
|
||||
.expect("otel provider");
|
||||
let tracing_layer = otel.tracing_layer().expect("tracing layer");
|
||||
let subscriber = tracing_subscriber::registry().with(tracing_layer);
|
||||
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
let span = tracing::info_span!("trace-loopback-stalled");
|
||||
let _guard = span.enter();
|
||||
tracing::info!("trace loopback event for stalled collector");
|
||||
});
|
||||
|
||||
let started = Instant::now();
|
||||
let result = otel
|
||||
.shutdown_with_timeout(Duration::from_millis(/*millis*/ 50))
|
||||
.await;
|
||||
(result, started.elapsed())
|
||||
});
|
||||
|
||||
let path = request_started_rx
|
||||
.recv_timeout(Duration::from_secs(/*secs*/ 1))
|
||||
.expect("trace request reached collector");
|
||||
release_tx.send(()).expect("release collector");
|
||||
server.join().expect("server join");
|
||||
runtime.shutdown_timeout(Duration::from_secs(/*secs*/ 1));
|
||||
|
||||
assert_eq!(path, "/v1/traces");
|
||||
assert_eq!(
|
||||
result.as_ref().map_err(std::io::Error::kind),
|
||||
Err(std::io::ErrorKind::TimedOut)
|
||||
);
|
||||
assert!(
|
||||
elapsed < Duration::from_secs(/*secs*/ 1),
|
||||
"bounded shutdown blocked for {elapsed:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn otlp_http_exporter_sends_traces_to_collector_in_current_thread_tokio_runtime()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let addr = listener.local_addr().expect("local_addr");
|
||||
listener.set_nonblocking(true).expect("set_nonblocking");
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Vec<CapturedRequest>>();
|
||||
let server = thread::spawn(move || {
|
||||
let mut captured = Vec::new();
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
let result = read_http_request(&mut stream);
|
||||
let _ = write_http_response(&mut stream, "202 Accepted");
|
||||
if let Ok((path, headers, body)) = result {
|
||||
captured.push(CapturedRequest {
|
||||
path,
|
||||
content_type: headers.get("content-type").cloned(),
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tx.send(captured);
|
||||
});
|
||||
|
||||
let (runtime_result_tx, runtime_result_rx) = mpsc::channel::<std::result::Result<(), String>>();
|
||||
let runtime_thread = thread::spawn(move || {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("current-thread runtime");
|
||||
|
||||
let result = runtime.block_on(async move {
|
||||
let otel = OtelProvider::try_new(&OtelSettings {
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
environment: "test".to_string(),
|
||||
service_name: "codex-cli".to_string(),
|
||||
service_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
codex_home: PathBuf::from("."),
|
||||
exporter: OtelExporter::None,
|
||||
trace_exporter: OtelExporter::OtlpHttp {
|
||||
endpoint: format!("http://{addr}/v1/traces"),
|
||||
headers: HashMap::new(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
metrics_exporter: OtelExporter::None,
|
||||
runtime_metrics: false,
|
||||
span_attributes: HashMap::new(),
|
||||
tracestate: BTreeMap::new(),
|
||||
})
|
||||
.map_err(|err| err.to_string())?
|
||||
.expect("otel provider");
|
||||
let tracing_layer = otel.tracing_layer().expect("tracing layer");
|
||||
let subscriber = tracing_subscriber::registry().with(tracing_layer);
|
||||
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
let span = tracing::info_span!(
|
||||
"trace-loopback-current-thread",
|
||||
otel.name = "trace-loopback-current-thread",
|
||||
otel.kind = "server",
|
||||
rpc.system = "jsonrpc",
|
||||
rpc.method = "trace-loopback-current-thread",
|
||||
);
|
||||
let _guard = span.enter();
|
||||
tracing::info!("trace loopback event from current-thread tokio runtime");
|
||||
});
|
||||
otel.shutdown();
|
||||
Ok::<(), String>(())
|
||||
});
|
||||
let _ = runtime_result_tx.send(result);
|
||||
});
|
||||
|
||||
runtime_result_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("current-thread runtime should complete")
|
||||
.map_err(std::io::Error::other)?;
|
||||
runtime_thread.join().expect("runtime thread");
|
||||
|
||||
server.join().expect("server join");
|
||||
let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured");
|
||||
|
||||
let request = captured
|
||||
.iter()
|
||||
.find(|req| req.path == "/v1/traces")
|
||||
.expect("/v1/traces request should be captured");
|
||||
let content_type = request
|
||||
.content_type
|
||||
.as_deref()
|
||||
.unwrap_or("<missing content-type>");
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"unexpected content-type: {content_type}"
|
||||
);
|
||||
|
||||
let body = String::from_utf8_lossy(&request.body);
|
||||
assert!(
|
||||
body.contains("trace-loopback-current-thread"),
|
||||
"expected span name not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
assert!(
|
||||
body.contains("codex-cli"),
|
||||
"expected service name not found; body prefix: {}",
|
||||
&body.chars().take(2000).collect::<String>()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user