Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,7 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "otel",
crate_name = "akode_otel",
integration_test_args = ["--test-threads=1"],
)

43
akode-rs/otel/Cargo.toml Normal file
View File

@@ -0,0 +1,43 @@
[package]
name = "akode-otel"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
doctest = false
name = "akode_otel"
path = "src/lib.rs"
[lints]
workspace = true
[dependencies]
chrono = { workspace = true }
akode-utils-stream-parser = { workspace = true }
akode-utils-string = { workspace = true }
akode-api = { workspace = true }
akode-protocol = { workspace = true }
eventsource-stream = { workspace = true }
opentelemetry = { workspace = true, features = ["metrics", "trace"] }
opentelemetry-semantic-conventions = { workspace = true }
opentelemetry_sdk = { workspace = true, features = [
"experimental_metrics_custom_reader",
"metrics",
"testing",
"trace",
] }
http = { workspace = true }
reqwest = { workspace = true }
os_info = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
strum_macros = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-opentelemetry = { workspace = true }
tracing-subscriber = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }

266
akode-rs/otel/README.md Normal file
View File

@@ -0,0 +1,266 @@
# akode-otel
`akode-otel` is the OpenTelemetry integration crate for Codex. It provides:
- Provider wiring for log/trace/metric exporters (`akode_otel::OtelProvider`
and `akode_otel::provider`).
- Session-scoped business event emission via `akode_otel::SessionTelemetry`.
- Low-level metrics APIs via `akode_otel::metrics`.
- Trace-context helpers via `akode_otel::trace_context` and crate-root re-exports.
## Tracing and logs
Create an OTEL provider from `OtelSettings`. The provider also configures
metrics (when enabled), then attach its layers to your `tracing_subscriber`
registry:
```rust
use akode_otel::config::OtelExporter;
use akode_otel::config::OtelHttpProtocol;
use akode_otel::config::OtelSettings;
use akode_otel::OtelProvider;
use tracing_subscriber::prelude::*;
let settings = OtelSettings {
environment: "dev".to_string(),
service_name: "akode-cli".to_string(),
service_version: env!("CARGO_PKG_VERSION").to_string(),
codex_home: std::path::PathBuf::from("/tmp"),
exporter: OtelExporter::OtlpHttp {
endpoint: "https://otlp.example.com".to_string(),
headers: std::collections::HashMap::new(),
protocol: OtelHttpProtocol::Binary,
tls: None,
},
trace_exporter: OtelExporter::OtlpHttp {
endpoint: "https://otlp.example.com".to_string(),
headers: std::collections::HashMap::new(),
protocol: OtelHttpProtocol::Binary,
tls: None,
},
metrics_exporter: OtelExporter::None,
span_attributes: std::collections::HashMap::new(),
tracestate: std::collections::BTreeMap::new(),
};
if let Some(provider) = OtelProvider::try_new(&settings)? {
let registry = tracing_subscriber::registry()
.with(provider.logger_layer())
.with(provider.tracing_layer());
registry.init();
}
```
Configured span attributes and W3C tracestate member fields are applied to
exported trace spans and propagated trace context:
```toml
[otel.span_attributes]
"example.trace_attr" = "enabled"
[otel.tracestate.example]
alpha = "one"
beta = "two"
```
Configured tracestate members and encoded values must be valid W3C tracestate.
Each nested table is encoded as semicolon-separated `key:value` fields inside
that member. If propagated trace context already has the named member, Codex
upserts configured fields and preserves other fields in that member. This
config shape does not support setting opaque tracestate member values. Invalid
trace metadata entries are ignored during config load and reported as startup
warnings.
## SessionTelemetry (events)
`SessionTelemetry` adds consistent metadata to tracing events and helps record
Codex-specific session events. Rich session/business events should go through
`SessionTelemetry`; subsystem-owned audit events can stay with the owning subsystem.
```rust
use akode_otel::SessionTelemetry;
let manager = SessionTelemetry::new(
conversation_id,
model,
slug,
account_id,
account_email,
auth_mode,
originator,
log_user_prompts,
terminal_type,
session_source,
);
manager.user_prompt(&prompt_items);
```
### Skill invocation logs
`codex.skill_invocation` records explicit skill injection and detected implicit use,
including reads through the skills tools. It contains `skill.name`,
`skill.invocation_type` (`explicit` or `implicit`), `conversation.id`, `turn.id`,
model and client metadata, and available `skill.scope`, `skill.plugin_id`,
`user.id`, and `user.account_id`. The user ID identifies the authenticated ChatGPT
user; the account ID identifies the workspace. Missing identity fields are omitted,
including the user ID for API-key authentication.
The event excludes skill contents, descriptions, resource paths, email addresses,
prompts, tool arguments, and tool output. It reports detected use, not successful
task completion. Shell-based implicit detection is best effort and is deduplicated
per skill within a turn; explicit injection and later implicit access are distinct
events. Skill-tool reads retain their existing invocation behavior.
Skill events use the existing OTEL log exporter and are included automatically
when `otel.exporter` points to an OTLP HTTP or gRPC destination. The default
`otel.exporter = "none"` exports no logs. No additional configuration or skill-event
opt-in is required; the destination also receives the other existing log events.
```toml
[otel]
exporter = { otlp-http = { endpoint = "https://collector.example.com/v1/logs", protocol = "json" } }
```
### Agent response logs
Set `otel.log_agent_responses = true` with an OTLP HTTP or gRPC log exporter to
emit `codex.agent_response` for completed assistant messages explicitly marked
`final_answer`. The default is false, independent of `otel.log_user_prompt`;
disabled response logging emits no event. Main agents and spawned task agents
are included. Internal/review/compaction/memory agents, commentary, untagged
messages, streaming deltas, tool-generated async messages, and history replay
are excluded. Plans are preserved and memory-citation markup is removed from
the exported copy without changing the stored answer.
Opting in exports potentially sensitive response text, including subagent work
absent from the main answer, to your log destination. Text is sent only to logs,
capped at 65,536 UTF-8 bytes at a character boundary, without a truncation notice.
`response_length` is the original byte count after citation removal, and
`response_truncated` indicates whether the cap removed text.
The log-only target is excluded from trace export, local state logs, and the
feedback log buffer.
Events include standard session attributes, `agent.type` (`main` or `subagent`),
`turn.id`, and `item.id`. `conversation.id` identifies the emitting thread.
Available lineage includes `parent.conversation.id`, `parent.turn.id`,
`root.turn.id`, and `initiating.agent.path`. The parent conversation is the
structural owner; the parent turn is the trigger and may belong to another
agent. They are not a guaranteed matching pair or a supported Compliance API join.
Completion is logged even if the turn later fails. Duplicate item completions
are suppressed within a turn; delivery retains the existing best-effort exporter
behavior, without an exactly-once guarantee.
`AgentResponseLogger` owns filtering, text preparation, and per-turn deduplication.
Core supplies completed raw items and step attribution, retaining the logger in
the existing turn extension data; it does not own response-logging policy.
### Guardian assessment logs
Set `otel.log_guardian_assessments = true` with an OTLP HTTP or gRPC log exporter
to emit `codex.guardian_assessment` once a synchronous Guardian review finishes.
The default is false. Events include the reviewed conversation, turn, review and
target item IDs, status, risk level, user authorization and rationale. `outcome`
is `allow` or `deny` for a completed model assessment and absent for review errors,
timeouts and cancellations, including fail-closed denials. Low-risk approvals
may contain the reviewer's generic fallback explanation.
Rationales can contain sensitive content. The exported copy is capped at 65,536
UTF-8 bytes at a character boundary; `rationale_length` records the original byte
count and `rationale_truncated` indicates truncation. The log-only target is
excluded from trace export, local state logs and the feedback log buffer. This
does not add content to the main model's conversation or grant it log read access.
Cached V2 approvals do not create a synchronous assessment and are not included.
Delivery uses the existing best-effort OTLP exporter.
## Metrics (OTLP or in-memory)
Modes:
- OTLP: exports metrics via the OpenTelemetry OTLP exporter (HTTP or gRPC).
- In-memory: records via `opentelemetry_sdk::metrics::InMemoryMetricExporter` for tests/assertions; call `shutdown()` to flush.
Configured OTLP metrics exporters (HTTP or gRPC) default to delta temporality. Set
`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=cumulative` for backends that require
cumulative metrics. The values `delta`, `cumulative`, and `lowmemory` are case-insensitive;
unset, empty, or unrecognized values retain the delta default. This setting does not change
the built-in Statsig exporter or on-demand runtime snapshots.
`akode-otel` also provides `OtelExporter::Statsig`, a shorthand for exporting OTLP/HTTP JSON metrics
to Statsig using Codex-internal defaults.
Statsig ingestion (OTLP/HTTP JSON) example:
```rust
use akode_otel::config::{OtelExporter, OtelHttpProtocol};
let metrics = MetricsClient::new(MetricsConfig::otlp(
"dev",
"akode-cli",
env!("CARGO_PKG_VERSION"),
OtelExporter::OtlpHttp {
endpoint: "https://api.statsig.com/otlp".to_string(),
headers: std::collections::HashMap::from([(
"statsig-api-key".to_string(),
std::env::var("STATSIG_SERVER_SDK_SECRET")?,
)]),
protocol: OtelHttpProtocol::Json,
tls: None,
},
))?;
metrics.counter("codex.session_started", 1, &[("source", "tui")])?;
metrics.histogram("codex.request_latency", 83, &[("route", "chat")])?;
```
In-memory (tests):
```rust
let exporter = InMemoryMetricExporter::default();
let metrics = MetricsClient::new(MetricsConfig::in_memory(
"test",
"akode-cli",
env!("CARGO_PKG_VERSION"),
exporter.clone(),
))?;
metrics.counter("codex.turns", 1, &[("model", "gpt-5.1")])?;
metrics.shutdown()?; // flushes in-memory exporter
```
## WebSocket continuation
`codex.websocket.continuation` counts `response.create` send attempts, including
failed sends. It carries existing session tags plus `mode` (`incremental`/`full`),
`phase` (`warmup`/`generation`), and `reason`:
| Reason | Meaning |
| --------------------- | -------------------------------------------------------------------------------------------- |
| `incremental` | Send the previous response ID and new input. |
| `no_previous_request` | First request from a fresh client. |
| `restored_history` | First request after loading resumed or forked history. |
| `connection_closed` | Full input after observing the previous socket closed. |
| `other` | Full input for another reason, such as changed input/settings or unavailable response state. |
Per-socket backend metrics label a resend after reconnect as `initial`; this client
metric retains the first reset reason through reconnect failures and turn boundaries.
Include warmups (`generate=false`), which can send full input before an incremental
generation. Closes may be intentional; restored history includes manual resumes/forks.
This measures client send attempts, not disconnect rates or engine cache reuse.
## Trace context
Trace propagation helpers remain separate from the session event emitter:
```rust
use akode_otel::current_span_w3c_trace_context;
use akode_otel::set_parent_from_w3c_trace_context;
```
## Shutdown
- `OtelProvider::shutdown()` stops the OTEL exporter.
- `SessionTelemetry::shutdown_metrics()` flushes and shuts down the metrics provider.
Both are optional because drop performs best-effort shutdown, but calling them
explicitly gives deterministic flushing (or a shutdown error if flushing does
not complete in time).

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

79
akode-rs/otel/src/lib.rs Normal file
View File

@@ -0,0 +1,79 @@
//! 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;
mod events;
pub(crate) mod metrics;
pub(crate) mod trace_context;
mod skill_invocation;
mod targets;
mod tool_result;
use crate::metrics::Result as MetricsResult;
use akode_protocol::auth::AuthMode;
use serde::Serialize;
use strum_macros::Display;
pub use crate::events::session_telemetry::AuthEnvTelemetryMetadata;
pub use crate::events::session_telemetry::SessionTelemetry;
pub use crate::events::session_telemetry::SessionTelemetryMetadata;
pub use crate::events::session_telemetry::bounded_product_sku;
pub use crate::metrics::runtime_metrics::RuntimeMetricTotals;
pub use crate::metrics::runtime_metrics::RuntimeMetricsSummary;
pub use crate::metrics::timer::Timer;
pub use crate::metrics::*;
pub use crate::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::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 akode_utils_string::sanitize_metric_tag_value;
#[derive(Debug, Clone, Serialize, Display)]
#[serde(rename_all = "snake_case")]
pub enum ToolDecisionSource {
AutomatedReviewer,
Config,
User,
}
/// Coarsens the authentication domain into the dimensions used by telemetry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
pub enum TelemetryAuthMode {
ApiKey,
Headers,
}
impl From<AuthMode> for TelemetryAuthMode {
fn from(mode: AuthMode) -> Self {
match mode {
AuthMode::ApiKey => Self::ApiKey,
AuthMode::Headers => Self::Headers,
}
}
}
/// 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
/// owned by this installation.
pub fn install_global_metrics(metrics: MetricsClient) -> MetricsClient {
crate::metrics::install_global(metrics)
}
/// Start a metrics timer using the globally installed metrics client.
pub fn start_global_timer(name: &str, tags: &[(&str, &str)]) -> MetricsResult<Timer> {
let Some(metrics) = crate::metrics::global() else {
return Err(MetricsError::ExporterDisabled);
};
metrics.start_timer(name, tags)
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,60 @@
use crate::metrics::Result;
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;
/// Configuration for a local, in-process metrics client. There is no network exporter.
#[derive(Clone, Debug)]
pub struct MetricsConfig {
pub(crate) environment: String,
pub(crate) service_name: String,
pub(crate) service_version: String,
pub(crate) exporter: InMemoryMetricExporter,
pub(crate) export_interval: Option<Duration>,
pub(crate) runtime_reader: bool,
pub(crate) default_tags: BTreeMap<String, String>,
}
impl MetricsConfig {
/// Create an in-memory config.
pub fn in_memory(
environment: impl Into<String>,
service_name: impl Into<String>,
service_version: impl Into<String>,
exporter: InMemoryMetricExporter,
) -> Self {
Self {
environment: environment.into(),
service_name: service_name.into(),
service_version: service_version.into(),
exporter,
export_interval: None,
runtime_reader: false,
default_tags: BTreeMap::new(),
}
}
/// Override the interval between periodic metric exports.
pub fn with_export_interval(mut self, interval: Duration) -> Self {
self.export_interval = Some(interval);
self
}
/// Enable a manual reader for on-demand runtime snapshots.
pub fn with_runtime_reader(mut self) -> Self {
self.runtime_reader = true;
self
}
/// Add a default tag that will be 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();
validate_tag_key(&key)?;
validate_tag_value(&value)?;
self.default_tags.insert(key, value);
Ok(self)
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,62 @@
//! 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;
use crate::events::shared::timestamp;
use crate::targets::OTEL_LOG_ONLY_TARGET;
use akode_protocol::protocol::SkillScope;
/// How Codex detected the skill's use.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SkillInvocationType {
Explicit,
Implicit,
}
/// Metadata for a detected skill invocation. Never include skill contents or resource paths.
pub struct SkillInvocationEvent<'a> {
pub turn_id: &'a str,
pub skill_name: &'a str,
pub scope: Option<SkillScope>,
pub plugin_id: Option<&'a str>,
pub invocation_type: SkillInvocationType,
}
impl SessionTelemetry {
pub fn with_user_id(mut self, user_id: Option<String>) -> Self {
self.metadata.user_id = user_id;
self
}
pub fn skill_invocation(&self, event: SkillInvocationEvent<'_>) {
let invocation_type = match event.invocation_type {
SkillInvocationType::Explicit => "explicit",
SkillInvocationType::Implicit => "implicit",
};
let scope = event.scope.map(|scope| match scope {
SkillScope::User => "user",
SkillScope::Repo => "repo",
SkillScope::System => "system",
SkillScope::Admin => "admin",
});
tracing::event!(
name: "codex.skill_invocation",
target: OTEL_LOG_ONLY_TARGET,
tracing::Level::INFO,
event.name = "codex.skill_invocation",
event.timestamp = %timestamp(),
conversation.id = %self.metadata.conversation_id,
turn.id = event.turn_id,
user.id = self.metadata.user_id.as_deref(),
user.account_id = self.metadata.account_id.as_deref(),
skill.name = event.skill_name,
skill.scope = scope,
skill.plugin_id = event.plugin_id,
skill.invocation_type = invocation_type,
model = %self.metadata.model,
app.version = self.metadata.app_version,
originator = %self.metadata.originator,
auth_mode = self.metadata.auth_mode.as_deref(),
);
}
}

View File

@@ -0,0 +1,16 @@
pub(crate) const OTEL_LOG_ONLY_TARGET: &str = "akode_otel.log_only";
pub(crate) const OTEL_TRACE_SAFE_TARGET: &str = "akode_otel.trace_safe";
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)
}
}

View File

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

View File

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

View File

@@ -0,0 +1,182 @@
use std::collections::HashMap;
use std::env;
use std::sync::OnceLock;
use akode_protocol::protocol::W3cTraceContext;
use opentelemetry::Context;
use opentelemetry::propagation::TextMapPropagator;
use opentelemetry::trace::TraceContextExt;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use tracing::Span;
use tracing::debug;
use tracing::warn;
use tracing_opentelemetry::OpenTelemetrySpanExt;
const TRACEPARENT_ENV_VAR: &str = "TRACEPARENT";
const TRACESTATE_ENV_VAR: &str = "TRACESTATE";
static TRACEPARENT_CONTEXT: OnceLock<Option<Context>> = OnceLock::new();
pub fn current_span_w3c_trace_context() -> Option<W3cTraceContext> {
span_w3c_trace_context(&Span::current())
}
pub fn span_w3c_trace_context(span: &Span) -> Option<W3cTraceContext> {
let context = span.context();
if !context.span().span_context().is_valid() {
return None;
}
let mut headers = HashMap::new();
TraceContextPropagator::new().inject_context(&context, &mut headers);
Some(W3cTraceContext {
traceparent: headers.remove("traceparent"),
tracestate: headers.remove("tracestate"),
})
}
pub fn current_span_trace_id() -> Option<String> {
let context = Span::current().context();
let span = context.span();
let span_context = span.span_context();
if !span_context.is_valid() {
return None;
}
Some(span_context.trace_id().to_string())
}
pub fn context_from_w3c_trace_context(trace: &W3cTraceContext) -> Option<Context> {
context_from_trace_headers(trace.traceparent.as_deref(), trace.tracestate.as_deref())
}
pub fn set_parent_from_w3c_trace_context(span: &Span, trace: &W3cTraceContext) -> bool {
if let Some(context) = context_from_w3c_trace_context(trace) {
set_parent_from_context(span, context);
true
} else {
false
}
}
pub fn set_parent_from_context(span: &Span, context: Context) {
let _ = span.set_parent(context);
}
pub fn traceparent_context_from_env() -> Option<Context> {
TRACEPARENT_CONTEXT
.get_or_init(load_traceparent_context)
.clone()
}
pub(crate) fn context_from_trace_headers(
traceparent: Option<&str>,
tracestate: Option<&str>,
) -> Option<Context> {
let traceparent = traceparent?;
let mut headers = HashMap::new();
headers.insert("traceparent".to_string(), traceparent.to_string());
if let Some(tracestate) = tracestate {
headers.insert("tracestate".to_string(), tracestate.to_string());
}
// Invalid incoming headers must not fall back to an unrelated active span.
let context = TraceContextPropagator::new().extract_with_context(&Context::new(), &headers);
if !context.span().span_context().is_valid() {
return None;
}
Some(context)
}
fn load_traceparent_context() -> Option<Context> {
let traceparent = env::var(TRACEPARENT_ENV_VAR).ok()?;
let tracestate = env::var(TRACESTATE_ENV_VAR).ok();
match context_from_trace_headers(Some(&traceparent), tracestate.as_deref()) {
Some(context) => {
debug!("TRACEPARENT detected; continuing trace from parent context");
Some(context)
}
None => {
warn!("TRACEPARENT is set but invalid; ignoring trace context");
None
}
}
}
#[cfg(test)]
mod tests {
use super::context_from_trace_headers;
use super::context_from_w3c_trace_context;
use super::current_span_trace_id;
use akode_protocol::protocol::W3cTraceContext;
use opentelemetry::trace::SpanId;
use opentelemetry::trace::TraceContextExt;
use opentelemetry::trace::TraceId;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::SdkTracerProvider;
use pretty_assertions::assert_eq;
use tracing::trace_span;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
#[test]
fn parses_valid_w3c_trace_context() {
let trace_id = "00000000000000000000000000000001";
let span_id = "0000000000000002";
let context = context_from_w3c_trace_context(&W3cTraceContext {
traceparent: Some(format!("00-{trace_id}-{span_id}-01")),
tracestate: None,
})
.expect("trace context");
let span = context.span();
let span_context = span.span_context();
assert_eq!(
span_context.trace_id(),
TraceId::from_hex(trace_id).unwrap()
);
assert_eq!(span_context.span_id(), SpanId::from_hex(span_id).unwrap());
assert!(span_context.is_remote());
}
#[test]
fn invalid_traceparent_returns_none() {
let parent = context_from_trace_headers(
Some("00-11111111111111111111111111111111-2222222222222222-01"),
/*tracestate*/ None,
)
.expect("valid ambient context");
let _guard = parent.attach();
assert!(
context_from_trace_headers(Some("not-a-traceparent"), /*tracestate*/ None).is_none()
);
}
#[test]
fn missing_traceparent_returns_none() {
assert!(
context_from_w3c_trace_context(&W3cTraceContext {
traceparent: None,
tracestate: Some("vendor=value".to_string()),
})
.is_none()
);
}
#[test]
fn current_span_trace_id_returns_hex_trace_id() {
let provider = SdkTracerProvider::builder().build();
let tracer = provider.tracer("codex-otel-tests");
let subscriber =
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
let _guard = subscriber.set_default();
let span = trace_span!("test_span");
let _entered = span.enter();
let trace_id = current_span_trace_id().expect("trace id");
assert_eq!(trace_id.len(), 32);
assert!(trace_id.chars().all(|ch| ch.is_ascii_hexdigit()));
assert_ne!(trace_id, "00000000000000000000000000000000");
}
}

View File

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

View File

@@ -0,0 +1,70 @@
//! Exercises global operation buffering across shutdown and replacement installations.
use akode_otel::MetricsClient;
use akode_otel::MetricsConfig;
use akode_otel::install_global_metrics;
use akode_otel::record_global_operation;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use std::time::Duration;
fn install() -> MetricsClient {
install_global_metrics(
MetricsClient::new(
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
)
.expect("build in-memory metrics"),
)
}
fn observe() {
record_global_operation(
"test.operations",
"test.duration",
Duration::from_millis(/*millis*/ 7),
&[],
)
.expect("record an operation");
}
fn totals(metrics: &MetricsClient) -> (u64, u64, f64) {
let snapshot = metrics.snapshot().expect("collect runtime metrics");
let mut totals = (0, 0, 0.0);
for metric in snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
{
match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => {
totals.0 += sum
.data_points()
.map(opentelemetry_sdk::metrics::data::SumDataPoint::value)
.sum::<u64>();
}
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => {
for point in histogram.data_points() {
totals.1 += point.count();
totals.2 += point.sum();
}
}
_ => panic!("unexpected metric"),
}
}
totals
}
#[test]
fn shutdown_buffers_until_replacement_and_preserves_newer_installations() {
let first = install();
first.shutdown().unwrap();
observe();
let second = install();
assert_eq!(totals(&second), (1, 1, 7.0));
let third = install();
second.shutdown().unwrap();
observe();
assert_eq!(totals(&third), (1, 1, 7.0));
third.shutdown().unwrap();
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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