aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

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