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:
257
akode-rs/otel/src/auth_storage.rs
Normal file
257
akode-rs/otel/src/auth_storage.rs
Normal 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;
|
||||
45
akode-rs/otel/src/auth_storage/originator.rs
Normal file
45
akode-rs/otel/src/auth_storage/originator.rs
Normal 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;
|
||||
49
akode-rs/otel/src/auth_storage/originator_tests.rs
Normal file
49
akode-rs/otel/src/auth_storage/originator_tests.rs
Normal 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");
|
||||
}
|
||||
248
akode-rs/otel/src/auth_storage_tests.rs
Normal file
248
akode-rs/otel/src/auth_storage_tests.rs
Normal 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(())
|
||||
}
|
||||
}
|
||||
2
akode-rs/otel/src/events/mod.rs
Normal file
2
akode-rs/otel/src/events/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub(crate) mod session_telemetry;
|
||||
pub(crate) mod shared;
|
||||
1452
akode-rs/otel/src/events/session_telemetry.rs
Normal file
1452
akode-rs/otel/src/events/session_telemetry.rs
Normal file
File diff suppressed because it is too large
Load Diff
70
akode-rs/otel/src/events/shared.rs
Normal file
70
akode-rs/otel/src/events/shared.rs
Normal 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
79
akode-rs/otel/src/lib.rs
Normal 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)
|
||||
}
|
||||
168
akode-rs/otel/src/metrics/buffered.rs
Normal file
168
akode-rs/otel/src/metrics/buffered.rs
Normal 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(¤t.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;
|
||||
154
akode-rs/otel/src/metrics/buffered_tests.rs
Normal file
154
akode-rs/otel/src/metrics/buffered_tests.rs
Normal 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));
|
||||
}
|
||||
561
akode-rs/otel/src/metrics/client.rs
Normal file
561
akode-rs/otel/src/metrics/client.rs
Normal 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)
|
||||
}
|
||||
60
akode-rs/otel/src/metrics/config.rs
Normal file
60
akode-rs/otel/src/metrics/config.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
40
akode-rs/otel/src/metrics/error.rs
Normal file
40
akode-rs/otel/src/metrics/error.rs
Normal 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,
|
||||
},
|
||||
}
|
||||
44
akode-rs/otel/src/metrics/mod.rs
Normal file
44
akode-rs/otel/src/metrics/mod.rs
Normal 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()
|
||||
}
|
||||
148
akode-rs/otel/src/metrics/names.rs
Normal file
148
akode-rs/otel/src/metrics/names.rs
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
27
akode-rs/otel/src/metrics/process.rs
Normal file
27
akode-rs/otel/src/metrics/process.rs
Normal 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)
|
||||
}
|
||||
220
akode-rs/otel/src/metrics/runtime_metrics.rs
Normal file
220
akode-rs/otel/src/metrics/runtime_metrics.rs
Normal 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
|
||||
}
|
||||
136
akode-rs/otel/src/metrics/tags.rs
Normal file
136
akode-rs/otel/src/metrics/tags.rs
Normal 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"),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
41
akode-rs/otel/src/metrics/timer.rs
Normal file
41
akode-rs/otel/src/metrics/timer.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
55
akode-rs/otel/src/metrics/validation.rs
Normal file
55
akode-rs/otel/src/metrics/validation.rs
Normal 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, '.' | '_' | '-' | '/' | '+')
|
||||
}
|
||||
62
akode-rs/otel/src/skill_invocation.rs
Normal file
62
akode-rs/otel/src/skill_invocation.rs
Normal 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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
16
akode-rs/otel/src/targets.rs
Normal file
16
akode-rs/otel/src/targets.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
115
akode-rs/otel/src/tool_result.rs
Normal file
115
akode-rs/otel/src/tool_result.rs
Normal 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;
|
||||
67
akode-rs/otel/src/tool_result_tests.rs
Normal file
67
akode-rs/otel/src/tool_result_tests.rs
Normal 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
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
182
akode-rs/otel/src/trace_context.rs
Normal file
182
akode-rs/otel/src/trace_context.rs
Normal 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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user