From 3a9c914b1fe50d8a5bd7c20501e3070371ff8345 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Wed, 6 May 2026 17:05:06 -0700 Subject: [PATCH] add otel metrics around sqlite --- codex-rs/Cargo.lock | 118 ------- codex-rs/core/src/otel_init.rs | 12 +- codex-rs/mcp-server/src/lib.rs | 16 +- codex-rs/otel/src/metrics/client.rs | 44 ++- codex-rs/otel/src/metrics/mod.rs | 4 + codex-rs/otel/src/metrics/names.rs | 1 + codex-rs/otel/src/metrics/process.rs | 27 ++ codex-rs/otel/src/metrics/tags.rs | 19 ++ codex-rs/rollout/src/lib.rs | 1 + codex-rs/rollout/src/list.rs | 8 + codex-rs/rollout/src/recorder.rs | 3 + codex-rs/rollout/src/sqlite_metrics.rs | 49 +++ codex-rs/rollout/src/state_db.rs | 129 ++++++-- codex-rs/state/src/lib.rs | 33 +- codex-rs/state/src/log_db.rs | 27 +- codex-rs/state/src/runtime.rs | 179 +++++++++-- codex-rs/state/src/runtime/backfill.rs | 120 ++++--- codex-rs/state/src/runtime/logs.rs | 71 ++-- codex-rs/state/src/runtime/metrics_tests.rs | 139 ++++++++ codex-rs/state/src/runtime/threads.rs | 338 +++++++++++--------- codex-rs/state/src/telemetry.rs | 330 +++++++++++++++++++ 21 files changed, 1249 insertions(+), 419 deletions(-) create mode 100644 codex-rs/otel/src/metrics/process.rs create mode 100644 codex-rs/rollout/src/sqlite_metrics.rs create mode 100644 codex-rs/state/src/runtime/metrics_tests.rs create mode 100644 codex-rs/state/src/telemetry.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index c656a791a6..e544fdb5f3 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1180,12 +1180,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "base16ct" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" - [[package]] name = "base64" version = "0.21.7" @@ -4425,18 +4419,6 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" -[[package]] -name = "crypto-bigint" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" -dependencies = [ - "generic-array", - "rand_core 0.6.4", - "subtle", - "zeroize", -] - [[package]] name = "crypto-common" version = "0.1.7" @@ -5150,20 +5132,6 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" -[[package]] -name = "ecdsa" -version = "0.16.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" -dependencies = [ - "der", - "digest", - "elliptic-curve", - "rfc6979", - "signature", - "spki", -] - [[package]] name = "ed25519" version = "2.2.3" @@ -5197,26 +5165,6 @@ dependencies = [ "serde", ] -[[package]] -name = "elliptic-curve" -version = "0.13.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" -dependencies = [ - "base16ct", - "crypto-bigint", - "digest", - "ff", - "generic-array", - "group", - "pem-rfc7468", - "pkcs8", - "rand_core 0.6.4", - "sec1", - "subtle", - "zeroize", -] - [[package]] name = "ena" version = "0.14.3" @@ -5470,16 +5418,6 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "ff" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" -dependencies = [ - "rand_core 0.6.4", - "subtle", -] - [[package]] name = "fiat-crypto" version = "0.2.9" @@ -6874,17 +6812,6 @@ dependencies = [ "system-deps", ] -[[package]] -name = "group" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" -dependencies = [ - "ff", - "rand_core 0.6.4", - "subtle", -] - [[package]] name = "gzip-header" version = "1.0.0" @@ -9384,18 +9311,6 @@ dependencies = [ "supports-color 3.0.2", ] -[[package]] -name = "p256" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" -dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2", -] - [[package]] name = "parking" version = "2.2.1" @@ -9825,15 +9740,6 @@ dependencies = [ "syn 2.0.114", ] -[[package]] -name = "primeorder" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" -dependencies = [ - "elliptic-curve", -] - [[package]] name = "proc-macro-crate" version = "3.4.0" @@ -10784,16 +10690,6 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" -[[package]] -name = "rfc6979" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" -dependencies = [ - "hmac", - "subtle", -] - [[package]] name = "ring" version = "0.17.14" @@ -11253,20 +11149,6 @@ version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca" -[[package]] -name = "sec1" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" -dependencies = [ - "base16ct", - "der", - "generic-array", - "pkcs8", - "subtle", - "zeroize", -] - [[package]] name = "seccompiler" version = "0.5.0" diff --git a/codex-rs/core/src/otel_init.rs b/codex-rs/core/src/otel_init.rs index 0cd1f06994..4e49580c6f 100644 --- a/codex-rs/core/src/otel_init.rs +++ b/codex-rs/core/src/otel_init.rs @@ -80,7 +80,7 @@ pub fn build_provider( let service_name = service_name_override.unwrap_or(originator.value.as_str()); let runtime_metrics = config.features.enabled(Feature::RuntimeMetrics); - OtelProvider::from(&OtelSettings { + let provider = OtelProvider::from(&OtelSettings { service_name: service_name.to_string(), service_version: service_version.to_string(), codex_home: config.codex_home.to_path_buf(), @@ -91,7 +91,15 @@ pub fn build_provider( runtime_metrics, span_attributes: config.otel.span_attributes.clone(), tracestate: config.otel.tracestate.clone(), - }) + })?; + + if let Some(provider) = provider.as_ref() + && let Some(metrics) = provider.metrics() + { + let _ = codex_otel::record_process_start_once(metrics, originator.value.as_str()); + } + + Ok(provider) } /// Filter predicate for exporting only Codex-owned events via OTEL. diff --git a/codex-rs/mcp-server/src/lib.rs b/codex-rs/mcp-server/src/lib.rs index d86f67522a..0abafd88e8 100644 --- a/codex-rs/mcp-server/src/lib.rs +++ b/codex-rs/mcp-server/src/lib.rs @@ -200,10 +200,15 @@ pub async fn run_main( mod tests { use super::*; use codex_config::types::OtelExporterKind; + use codex_config::types::OtelHttpProtocol; use codex_core::config::ConfigBuilder; use pretty_assertions::assert_eq; use std::collections::HashMap; use tempfile::TempDir; + use wiremock::Mock; + use wiremock::MockServer; + use wiremock::ResponseTemplate; + use wiremock::matchers::method; #[test] fn mcp_server_defaults_analytics_to_enabled() { @@ -212,14 +217,21 @@ mod tests { #[tokio::test] async fn mcp_server_builds_otel_provider_with_logs_traces_and_metrics() -> anyhow::Result<()> { + let collector = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200)) + .mount(&collector) + .await; + let codex_home = TempDir::new()?; let mut config = ConfigBuilder::default() .codex_home(codex_home.path().to_path_buf()) .build() .await?; - let exporter = OtelExporterKind::OtlpGrpc { - endpoint: "http://localhost:4317".to_string(), + let exporter = OtelExporterKind::OtlpHttp { + endpoint: collector.uri(), headers: HashMap::new(), + protocol: OtelHttpProtocol::Binary, tls: None, }; config.otel.exporter = exporter.clone(); diff --git a/codex-rs/otel/src/metrics/client.rs b/codex-rs/otel/src/metrics/client.rs index 417c1f4bd9..f304b154a7 100644 --- a/codex-rs/otel/src/metrics/client.rs +++ b/codex-rs/otel/src/metrics/client.rs @@ -41,6 +41,7 @@ use std::time::Duration; use tracing::debug; const ENV_ATTRIBUTE: &str = "env"; +const ARCH_ATTRIBUTE: &str = "arch"; const METER_NAME: &str = "codex"; const DURATION_UNIT: &str = "ms"; const DURATION_DESCRIPTION: &str = "Duration in milliseconds."; @@ -198,13 +199,13 @@ impl MetricsClient { validate_tags(&default_tags)?; - let mut resource_attributes = Vec::with_capacity(4); + let mut resource_attributes = Vec::with_capacity(5); 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()); + resource_attributes.extend(platform_resource_attributes()); let resource = Resource::builder() .with_service_name(service_name) @@ -290,12 +291,13 @@ impl MetricsClient { } } -fn os_resource_attributes() -> Vec { +fn platform_resource_attributes() -> Vec { let os_info = os_info::get(); 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 arch = sanitize_metric_tag_value(std::env::consts::ARCH); let mut attributes = Vec::new(); if os_type != "unspecified" { attributes.push(KeyValue::new("os", os_type)); @@ -303,6 +305,9 @@ fn os_resource_attributes() -> Vec { if os_version != "unspecified" { attributes.push(KeyValue::new("os_version", os_version)); } + if arch != "unspecified" { + attributes.push(KeyValue::new(ARCH_ATTRIBUTE, arch)); + } attributes } @@ -404,3 +409,36 @@ fn build_otlp_metric_exporter( } } } + +#[cfg(test)] +mod tests { + use super::*; + use opentelemetry_sdk::metrics::InMemoryMetricExporter; + use pretty_assertions::assert_eq; + use std::collections::BTreeMap; + + #[test] + fn metrics_resource_attributes_include_arch() { + let exporter = InMemoryMetricExporter::default(); + let metrics = MetricsClient::new( + MetricsConfig::in_memory("test", "codex-test", env!("CARGO_PKG_VERSION"), exporter) + .with_runtime_reader(), + ) + .expect("metrics client"); + + metrics + .counter("test.resource_attributes", /*inc*/ 1, &[]) + .expect("counter"); + let snapshot = metrics.snapshot().expect("snapshot"); + let attributes: BTreeMap = snapshot + .resource() + .iter() + .map(|(key, value)| (key.as_str().to_string(), value.as_str().to_string())) + .collect(); + + assert_eq!( + attributes.get(ARCH_ATTRIBUTE).map(String::as_str), + Some(sanitize_metric_tag_value(std::env::consts::ARCH).as_str()) + ); + } +} diff --git a/codex-rs/otel/src/metrics/mod.rs b/codex-rs/otel/src/metrics/mod.rs index e75840bf37..07b7554224 100644 --- a/codex-rs/otel/src/metrics/mod.rs +++ b/codex-rs/otel/src/metrics/mod.rs @@ -2,6 +2,7 @@ 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; @@ -13,9 +14,12 @@ pub use crate::metrics::config::MetricsConfig; pub use crate::metrics::config::MetricsExporter; pub use crate::metrics::error::MetricsError; pub use crate::metrics::error::Result; +pub use crate::metrics::process::record_process_start_once; pub use names::*; use std::sync::OnceLock; +pub use tags::ORIGINATOR_TAG; pub use tags::SessionMetricTagValues; +pub use tags::bounded_originator_tag_value; static GLOBAL_METRICS: OnceLock = OnceLock::new(); static GLOBAL_STATSIG_METRICS_SETTINGS: OnceLock = OnceLock::new(); diff --git a/codex-rs/otel/src/metrics/names.rs b/codex-rs/otel/src/metrics/names.rs index b2f2d639ce..67ac6e19ed 100644 --- a/codex-rs/otel/src/metrics/names.rs +++ b/codex-rs/otel/src/metrics/names.rs @@ -1,6 +1,7 @@ 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 PROCESS_START_METRIC: &str = "codex.process.start"; 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"; diff --git a/codex-rs/otel/src/metrics/process.rs b/codex-rs/otel/src/metrics/process.rs new file mode 100644 index 0000000000..6c7cd18b4e --- /dev/null +++ b/codex-rs/otel/src/metrics/process.rs @@ -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 { + 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) +} diff --git a/codex-rs/otel/src/metrics/tags.rs b/codex-rs/otel/src/metrics/tags.rs index 5c166e307e..b34db01c35 100644 --- a/codex-rs/otel/src/metrics/tags.rs +++ b/codex-rs/otel/src/metrics/tags.rs @@ -1,6 +1,7 @@ use crate::metrics::Result; use crate::metrics::validation::validate_tag_key; use crate::metrics::validation::validate_tag_value; +use codex_utils_string::sanitize_metric_tag_value; pub const APP_VERSION_TAG: &str = "app.version"; pub const AUTH_MODE_TAG: &str = "auth_mode"; @@ -9,6 +10,24 @@ 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"; + +/// Returns a sanitized, low-cardinality originator value that is safe to use as a metric tag. +pub fn bounded_originator_tag_value(originator: &str) -> &'static str { + match sanitize_metric_tag_value(originator).as_str() { + "codex_desktop" => "codex_desktop", + "codex_cli_rs" => "codex_cli_rs", + "codex-tui" => "codex-tui", + "codex_vscode" => "codex_vscode", + "none" => "none", + "codex_exec" => "codex_exec", + "codex-cli" => "codex-cli", + "codex_sdk_ts" => "codex_sdk_ts", + "codex-app-server-sdk" => "codex-app-server-sdk", + _ => OTHER_ORIGINATOR_TAG_VALUE, + } +} + pub struct SessionMetricTagValues<'a> { pub auth_mode: Option<&'a str>, pub session_source: &'a str, diff --git a/codex-rs/rollout/src/lib.rs b/codex-rs/rollout/src/lib.rs index d65ddd3d5b..bb8af704b7 100644 --- a/codex-rs/rollout/src/lib.rs +++ b/codex-rs/rollout/src/lib.rs @@ -10,6 +10,7 @@ pub(crate) mod metadata; pub(crate) mod policy; pub(crate) mod recorder; pub(crate) mod session_index; +pub(crate) mod sqlite_metrics; pub mod state_db; pub(crate) mod default_client { diff --git a/codex-rs/rollout/src/list.rs b/codex-rs/rollout/src/list.rs index 8ba63a713e..e7e1da246a 100644 --- a/codex-rs/rollout/src/list.rs +++ b/codex-rs/rollout/src/list.rs @@ -1279,6 +1279,7 @@ async fn find_thread_path_by_id_str_in_subdir( tracing::warn!( "state db discrepancy during find_thread_path_by_id_str_in_subdir: mismatched_db_path" ); + crate::sqlite_metrics::record_fallback("find_thread_path", "mismatch"); } Err(err) => { tracing::debug!( @@ -1296,6 +1297,7 @@ async fn find_thread_path_by_id_str_in_subdir( tracing::warn!( "state db discrepancy during find_thread_path_by_id_str_in_subdir: stale_db_path" ); + crate::sqlite_metrics::record_fallback("find_thread_path", "stale_path"); } } @@ -1323,6 +1325,12 @@ async fn find_thread_path_by_id_str_in_subdir( tracing::warn!( "state db discrepancy during find_thread_path_by_id_str_in_subdir: falling_back" ); + let reason = if state_db_ctx.is_some() { + "missing_row" + } else { + "db_unavailable" + }; + crate::sqlite_metrics::record_fallback("find_thread_path", reason); state_db::read_repair_rollout_path( state_db_ctx, thread_id, diff --git a/codex-rs/rollout/src/recorder.rs b/codex-rs/rollout/src/recorder.rs index 6b549b745c..535b4abe2a 100644 --- a/codex-rs/rollout/src/recorder.rs +++ b/codex-rs/rollout/src/recorder.rs @@ -450,6 +450,7 @@ impl RolloutRecorder { if state_db_ctx.is_none() { // Keep legacy behavior when SQLite is unavailable: return filesystem results // at the requested page size. + crate::sqlite_metrics::record_fallback("list_threads", "db_unavailable"); return Ok(page_from_filesystem_scan( fs_page, sort_direction, @@ -569,6 +570,7 @@ impl RolloutRecorder { } if listing_has_metadata_filters { let page = page_from_filesystem_scan(fs_page, sort_direction, page_size, sort_key); + crate::sqlite_metrics::record_fallback("list_threads", "db_error"); return Ok(fill_missing_thread_item_metadata_from_state_db( state_db_ctx.as_deref(), page, @@ -578,6 +580,7 @@ impl RolloutRecorder { // If SQLite listing still fails, return the filesystem page rather than failing the list. tracing::error!("Falling back on rollout system"); tracing::warn!("state db discrepancy during list_threads_with_db_fallback: falling_back"); + crate::sqlite_metrics::record_fallback("list_threads", "db_error"); Ok(page_from_filesystem_scan( fs_page, sort_direction, diff --git a/codex-rs/rollout/src/sqlite_metrics.rs b/codex-rs/rollout/src/sqlite_metrics.rs new file mode 100644 index 0000000000..4a0b50f8d7 --- /dev/null +++ b/codex-rs/rollout/src/sqlite_metrics.rs @@ -0,0 +1,49 @@ +use std::sync::Arc; +use std::time::Duration; + +use codex_otel::ORIGINATOR_TAG; +use codex_otel::bounded_originator_tag_value; +use codex_state::DbMetricsRecorder; +use codex_state::DbMetricsRecorderHandle; + +use crate::default_client::originator; + +struct OtelDbMetrics { + metrics: codex_otel::MetricsClient, + originator: &'static str, +} + +impl DbMetricsRecorder for OtelDbMetrics { + fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) { + let tags = sqlite_originator_tags(tags, self.originator); + let _ = self.metrics.counter(name, inc, &tags); + } + + fn record_duration(&self, name: &str, duration: Duration, tags: &[(&str, &str)]) { + let tags = sqlite_originator_tags(tags, self.originator); + let _ = self.metrics.record_duration(name, duration, &tags); + } +} + +pub(crate) fn global() -> Option { + codex_otel::global().map(|metrics| { + Arc::new(OtelDbMetrics { + metrics, + originator: bounded_originator_tag_value(originator().value.as_str()), + }) as DbMetricsRecorderHandle + }) +} + +pub(crate) fn record_fallback(caller: &'static str, reason: &'static str) { + let metrics = global(); + codex_state::record_db_fallback_metric(metrics.as_deref(), caller, reason); +} + +fn sqlite_originator_tags<'a>( + tags: &[(&'a str, &'a str)], + originator: &'static str, +) -> Vec<(&'a str, &'a str)> { + let mut tags = tags.to_vec(); + tags.push((ORIGINATOR_TAG, originator)); + tags +} diff --git a/codex-rs/rollout/src/state_db.rs b/codex-rs/rollout/src/state_db.rs index d039e16d68..ea3cf118c2 100644 --- a/codex-rs/rollout/src/state_db.rs +++ b/codex-rs/rollout/src/state_db.rs @@ -4,6 +4,7 @@ use crate::list::Cursor; use crate::list::SortDirection; use crate::list::ThreadSortKey; use crate::metadata; +use crate::sqlite_metrics; use chrono::DateTime; use chrono::Utc; use codex_protocol::ThreadId; @@ -106,26 +107,45 @@ async fn try_init_with_roots_inner( default_model_provider_id: String, backfill_lease_seconds: Option, ) -> anyhow::Result { - let runtime = - codex_state::StateRuntime::init(sqlite_home.clone(), default_model_provider_id.clone()) - .await - .map_err(|err| { - anyhow::anyhow!( - "failed to initialize state runtime at {}: {err}", - sqlite_home.display() - ) - })?; + let metrics = sqlite_metrics::global(); + let runtime = codex_state::StateRuntime::init_with_metrics( + sqlite_home.clone(), + default_model_provider_id.clone(), + metrics.clone(), + ) + .await + .map_err(|err| { + anyhow::anyhow!( + "failed to initialize state runtime at {}: {err}", + sqlite_home.display() + ) + })?; + let backfill_gate_started = Instant::now(); let wait_started = Instant::now(); let mut reported_wait = false; loop { - let backfill_state = runtime.get_backfill_state().await.map_err(|err| { - anyhow::anyhow!( - "failed to read backfill state at {}: {err}", - codex_home.display() - ) - })?; + let backfill_state = match runtime.get_backfill_state().await { + Ok(state) => state, + Err(err) => { + let err = anyhow::anyhow!( + "failed to read backfill state at {}: {err}", + codex_home.display() + ); + return finish_backfill_gate( + metrics.as_deref(), + backfill_gate_started, + Err(err), + runtime, + ); + } + }; if backfill_state.status == codex_state::BackfillStatus::Complete { - return Ok(runtime); + return finish_backfill_gate( + metrics.as_deref(), + backfill_gate_started, + Ok(()), + runtime, + ); } if let Some(backfill_lease_seconds) = backfill_lease_seconds { @@ -144,22 +164,41 @@ async fn try_init_with_roots_inner( ) .await; } - let backfill_state = runtime.get_backfill_state().await.map_err(|err| { - anyhow::anyhow!( - "failed to read backfill state at {} after startup backfill: {err}", - codex_home.display() - ) - })?; + let backfill_state = match runtime.get_backfill_state().await { + Ok(state) => state, + Err(err) => { + let err = anyhow::anyhow!( + "failed to read backfill state at {} after startup backfill: {err}", + codex_home.display() + ); + return finish_backfill_gate( + metrics.as_deref(), + backfill_gate_started, + Err(err), + runtime, + ); + } + }; if backfill_state.status == codex_state::BackfillStatus::Complete { - return Ok(runtime); + return finish_backfill_gate( + metrics.as_deref(), + backfill_gate_started, + Ok(()), + runtime, + ); } if wait_started.elapsed() >= STARTUP_BACKFILL_WAIT_TIMEOUT { - return Err(anyhow::anyhow!( - "timed out waiting for state db backfill at {} after {:?} (status: {})", - codex_home.display(), - STARTUP_BACKFILL_WAIT_TIMEOUT, - backfill_state.status.as_str() - )); + return finish_backfill_gate( + metrics.as_deref(), + backfill_gate_started, + Err(anyhow::anyhow!( + "timed out waiting for state db backfill at {} after {:?} (status: {})", + codex_home.display(), + STARTUP_BACKFILL_WAIT_TIMEOUT, + backfill_state.status.as_str() + )), + runtime, + ); } let message = format!( @@ -178,6 +217,16 @@ async fn try_init_with_roots_inner( } } +fn finish_backfill_gate( + metrics: Option<&dyn codex_state::DbMetricsRecorder>, + started: Instant, + result: anyhow::Result<()>, + runtime: StateDbHandle, +) -> anyhow::Result { + codex_state::record_db_init_backfill_gate_metric(metrics, started.elapsed(), &result); + result.map(|()| runtime) +} + fn emit_startup_warning(message: &str) { warn!("{message}"); if !tracing::dispatcher::has_been_set() { @@ -193,22 +242,36 @@ fn emit_startup_warning(message: &str) { /// Unlike [`init`], this helper does not run rollout backfill. It is for /// optional local reads from non-owning contexts such as remote app-server mode. pub async fn get_state_db(config: &impl RolloutConfigView) -> Option { + let metrics = sqlite_metrics::global(); let state_path = codex_state::state_db_path(config.sqlite_home()); if !tokio::fs::try_exists(&state_path).await.unwrap_or(false) { + codex_state::record_db_fallback_metric( + metrics.as_deref(), + "get_state_db", + "db_unavailable", + ); return None; } - let runtime = codex_state::StateRuntime::init( + let runtime = match codex_state::StateRuntime::init_with_metrics( config.sqlite_home().to_path_buf(), config.model_provider_id().to_string(), + metrics.clone(), ) .await - .ok()?; - require_backfill_complete(runtime, config.sqlite_home()).await + { + Ok(runtime) => runtime, + Err(_) => { + codex_state::record_db_fallback_metric(metrics.as_deref(), "get_state_db", "db_error"); + return None; + } + }; + require_backfill_complete(runtime, config.sqlite_home(), metrics.as_deref()).await } async fn require_backfill_complete( runtime: StateDbHandle, codex_home: &Path, + metrics: Option<&dyn codex_state::DbMetricsRecorder>, ) -> Option { match runtime.get_backfill_state().await { Ok(state) if state.status == codex_state::BackfillStatus::Complete => Some(runtime), @@ -218,6 +281,7 @@ async fn require_backfill_complete( codex_home.display(), state.status.as_str() ); + codex_state::record_db_fallback_metric(metrics, "get_state_db", "backfill_incomplete"); None } Err(err) => { @@ -225,6 +289,7 @@ async fn require_backfill_complete( "failed to read backfill state at {}: {err}", codex_home.display() ); + codex_state::record_db_fallback_metric(metrics, "get_state_db", "db_error"); None } } diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs index 84582370a5..bd9b2097dd 100644 --- a/codex-rs/state/src/lib.rs +++ b/codex-rs/state/src/lib.rs @@ -10,12 +10,13 @@ mod migrations; mod model; mod paths; mod runtime; +mod telemetry; pub use model::LogEntry; pub use model::LogQuery; pub use model::LogRow; pub use model::Phase2JobClaimOutcome; -/// Preferred entrypoint: owns configuration and metrics. +/// Preferred entrypoint: owns SQLite configuration and optional metrics injection. pub use runtime::StateRuntime; /// Low-level storage engine: useful for focused tests. @@ -56,6 +57,8 @@ pub use runtime::logs_db_filename; pub use runtime::logs_db_path; pub use runtime::state_db_filename; pub use runtime::state_db_path; +pub use telemetry::DbMetricsRecorder; +pub use telemetry::DbMetricsRecorderHandle; /// Environment variable for overriding the SQLite state database home directory. pub const SQLITE_HOME_ENV: &str = "CODEX_SQLITE_HOME"; @@ -71,3 +74,31 @@ pub const DB_ERROR_METRIC: &str = "codex.db.error"; pub const DB_METRIC_BACKFILL: &str = "codex.db.backfill"; /// Metrics on backfill duration. Tags: [status] pub const DB_METRIC_BACKFILL_DURATION_MS: &str = "codex.db.backfill.duration_ms"; +/// SQLite startup initialization attempts. Tags: [status, phase, db, error_class, sqlite_code] +pub const DB_INIT_METRIC: &str = "codex.db.init"; +/// SQLite startup initialization duration. Tags: [status, phase, db, error_class, sqlite_code] +pub const DB_INIT_DURATION_METRIC: &str = "codex.db.init.duration_ms"; +/// SQLite operation attempts. Tags: [status, db, operation, access, error_class, sqlite_code] +pub const DB_OPERATION_METRIC: &str = "codex.db.operation"; +/// SQLite operation duration. Tags: [status, db, operation, access, error_class, sqlite_code] +pub const DB_OPERATION_DURATION_METRIC: &str = "codex.db.operation.duration_ms"; +/// Filesystem fallback after SQLite could not serve a request. Tags: [caller, reason] +pub const DB_FALLBACK_METRIC: &str = "codex.db.fallback"; +/// SQLite log queue loss or flush failure. Tags: [event, reason] +pub const DB_LOG_QUEUE_METRIC: &str = "codex.db.log_queue"; + +pub fn record_db_fallback_metric( + metrics: Option<&dyn DbMetricsRecorder>, + caller: &'static str, + reason: &'static str, +) { + telemetry::record_fallback(metrics, caller, reason); +} + +pub fn record_db_init_backfill_gate_metric( + metrics: Option<&dyn DbMetricsRecorder>, + duration: std::time::Duration, + result: &anyhow::Result<()>, +) { + telemetry::record_init_backfill_gate(metrics, duration, result); +} diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index 6024d6bdaa..9ce3ceaf58 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -43,6 +43,7 @@ use uuid::Uuid; use crate::LogEntry; use crate::StateRuntime; +use crate::telemetry; const LOG_QUEUE_CAPACITY: usize = 512; const LOG_BATCH_SIZE: usize = 128; @@ -94,6 +95,7 @@ where pub struct LogDbLayer { sender: mpsc::Sender, process_uuid: String, + metrics: Option, } pub fn start(state_db: std::sync::Arc) -> LogDbLayer { @@ -105,6 +107,7 @@ impl Clone for LogDbLayer { Self { sender: self.sender.clone(), process_uuid: self.process_uuid.clone(), + metrics: self.metrics.clone(), } } } @@ -120,22 +123,34 @@ impl LogDbLayer { ) -> Self { let config = config.normalized(); let (sender, receiver) = mpsc::channel(config.queue_capacity); + let metrics = state_db.metrics_handle(); tokio::spawn(run_inserter(state_db, receiver, config)); Self { sender, process_uuid: current_process_log_uuid().to_string(), + metrics, } } pub async fn flush(&self) { let (tx, rx) = oneshot::channel(); - if self.sender.send(LogDbCommand::Flush(tx)).await.is_ok() { - let _ = rx.await; + if self.sender.send(LogDbCommand::Flush(tx)).await.is_err() { + telemetry::record_log_queue(self.metrics.as_deref(), "flush_failed", "closed"); + return; + } + if rx.await.is_err() { + telemetry::record_log_queue(self.metrics.as_deref(), "flush_failed", "closed"); } } fn try_send(&self, entry: LogEntry) { - let _ = self.sender.try_send(LogDbCommand::Entry(Box::new(entry))); + if let Err(err) = self.sender.try_send(LogDbCommand::Entry(Box::new(entry))) { + let reason = match err { + mpsc::error::TrySendError::Full(_) => "full", + mpsc::error::TrySendError::Closed(_) => "closed", + }; + telemetry::record_log_queue(self.metrics.as_deref(), "dropped", reason); + } } } @@ -401,7 +416,9 @@ async fn flush(state_db: &StateRuntime, buffer: &mut Vec) { return; } let entries = buffer.split_off(0); - let _ = state_db.insert_logs(entries.as_slice()).await; + if state_db.insert_logs(entries.as_slice()).await.is_err() { + telemetry::record_log_queue(state_db.metrics(), "flush_failed", "insert_failed"); + } } #[derive(Default)] @@ -721,6 +738,7 @@ mod tests { let layer = LogDbLayer { sender, process_uuid: "process-1".to_string(), + metrics: None, }; layer.try_send(test_entry("first-queued-log")); @@ -741,6 +759,7 @@ mod tests { let layer = LogDbLayer { sender, process_uuid: "process-1".to_string(), + metrics: None, }; layer.try_send(test_entry("queued-before-flush")); diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index c8b4e7b98e..26fc98ba46 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -27,6 +27,10 @@ use crate::model::datetime_to_epoch_millis; use crate::model::datetime_to_epoch_seconds; use crate::model::epoch_millis_to_datetime; use crate::paths::file_modified_time_utc; +use crate::telemetry::DbAccess; +use crate::telemetry::DbKind; +use crate::telemetry::DbMetricsRecorder; +use crate::telemetry::DbMetricsRecorderHandle; use chrono::DateTime; use chrono::Utc; use codex_protocol::ThreadId; @@ -52,6 +56,7 @@ use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicI64; use std::time::Duration; +use std::time::Instant; use tracing::warn; mod agent_jobs; @@ -59,6 +64,8 @@ mod backfill; mod goals; mod logs; mod memories; +#[cfg(test)] +mod metrics_tests; mod remote_control; #[cfg(test)] mod test_support; @@ -86,6 +93,7 @@ pub struct StateRuntime { pool: Arc, logs_pool: Arc, thread_updated_at_millis: Arc, + metrics: Option, } impl StateRuntime { @@ -93,9 +101,30 @@ impl StateRuntime { /// /// This opens (and migrates) the SQLite databases under `codex_home`, /// keeping logs in a dedicated file to reduce lock contention with the - /// rest of the state store. + /// rest of the state store. Use [`Self::init_with_metrics`] when the caller + /// has a metrics sink to attach. pub async fn init(codex_home: PathBuf, default_provider: String) -> anyhow::Result> { - tokio::fs::create_dir_all(&codex_home).await?; + Self::init_with_metrics(codex_home, default_provider, /*metrics*/ None).await + } + + /// Initialize the state runtime with an explicit metrics client. + pub async fn init_with_metrics( + codex_home: PathBuf, + default_provider: String, + metrics: Option, + ) -> anyhow::Result> { + let started = Instant::now(); + let create_dir_result = tokio::fs::create_dir_all(&codex_home) + .await + .map_err(anyhow::Error::from); + crate::telemetry::record_init_result( + metrics.as_deref(), + DbKind::None, + "create_dir", + started.elapsed(), + &create_dir_result, + ); + create_dir_result?; let state_migrator = runtime_state_migrator(); let logs_migrator = runtime_logs_migrator(); let current_state_name = state_db_filename(); @@ -116,24 +145,45 @@ impl StateRuntime { .await; let state_path = state_db_path(codex_home.as_path()); let logs_path = logs_db_path(codex_home.as_path()); - let pool = match open_state_sqlite(&state_path, &state_migrator).await { + let pool = match open_state_sqlite(&state_path, &state_migrator, metrics.as_deref()).await { Ok(db) => Arc::new(db), Err(err) => { warn!("failed to open state db at {}: {err}", state_path.display()); return Err(err); } }; - let logs_pool = match open_logs_sqlite(&logs_path, &logs_migrator).await { + let logs_pool = match open_logs_sqlite(&logs_path, &logs_migrator, metrics.as_deref()).await + { Ok(db) => Arc::new(db), Err(err) => { warn!("failed to open logs db at {}: {err}", logs_path.display()); return Err(err); } }; - let thread_updated_at_millis: Option = + let started = Instant::now(); + let backfill_state_result = ensure_backfill_state_row_in_pool(pool.as_ref()).await; + crate::telemetry::record_init_result( + metrics.as_deref(), + DbKind::State, + "ensure_backfill_state", + started.elapsed(), + &backfill_state_result, + ); + backfill_state_result?; + let started = Instant::now(); + let thread_updated_at_millis_result: anyhow::Result> = sqlx::query_scalar("SELECT MAX(threads.updated_at_ms) FROM threads") .fetch_one(pool.as_ref()) - .await?; + .await + .map_err(anyhow::Error::from); + crate::telemetry::record_init_result( + metrics.as_deref(), + DbKind::State, + "post_init_query", + started.elapsed(), + &thread_updated_at_millis_result, + ); + let thread_updated_at_millis = thread_updated_at_millis_result?; let thread_updated_at_millis = thread_updated_at_millis.unwrap_or(0); let runtime = Arc::new(Self { pool, @@ -141,6 +191,7 @@ impl StateRuntime { codex_home, default_provider, thread_updated_at_millis: Arc::new(AtomicI64::new(thread_updated_at_millis)), + metrics, }); if let Err(err) = runtime.run_logs_startup_maintenance().await { warn!( @@ -155,6 +206,27 @@ impl StateRuntime { pub fn codex_home(&self) -> &Path { self.codex_home.as_path() } + + pub(crate) fn metrics(&self) -> Option<&dyn DbMetricsRecorder> { + self.metrics.as_deref() + } + + pub(crate) fn metrics_handle(&self) -> Option { + self.metrics.clone() + } + + pub(crate) async fn record_db_operation( + &self, + db: DbKind, + operation: &'static str, + access: DbAccess, + future: F, + ) -> anyhow::Result + where + F: std::future::Future>, + { + crate::telemetry::record_operation(self.metrics(), db, operation, access, future).await + } } fn base_sqlite_options(path: &Path) -> SqliteConnectOptions { @@ -165,29 +237,90 @@ fn base_sqlite_options(path: &Path) -> SqliteConnectOptions { .synchronous(SqliteSynchronous::Normal) .busy_timeout(Duration::from_secs(5)) .log_statements(LevelFilter::Off) + .log_slow_statements(LevelFilter::Warn, Duration::from_millis(250)) } -async fn open_state_sqlite(path: &Path, migrator: &Migrator) -> anyhow::Result { +async fn open_state_sqlite( + path: &Path, + migrator: &Migrator, + metrics: Option<&dyn DbMetricsRecorder>, +) -> anyhow::Result { // New state DBs should use incremental auto-vacuum, but retrofitting an // existing DB requires a full VACUUM. Do not attempt that during process // startup: it is maintenance work that can contend with foreground writers. + open_sqlite( + path, + migrator, + metrics, + DbKind::State, + "open_state", + "migrate_state", + ) + .await +} + +async fn open_logs_sqlite( + path: &Path, + migrator: &Migrator, + metrics: Option<&dyn DbMetricsRecorder>, +) -> anyhow::Result { + open_sqlite( + path, + migrator, + metrics, + DbKind::Logs, + "open_logs", + "migrate_logs", + ) + .await +} + +async fn open_sqlite( + path: &Path, + migrator: &Migrator, + metrics: Option<&dyn DbMetricsRecorder>, + db: DbKind, + open_phase: &'static str, + migrate_phase: &'static str, +) -> anyhow::Result { let options = base_sqlite_options(path).auto_vacuum(SqliteAutoVacuum::Incremental); - let pool = SqlitePoolOptions::new() + let started = Instant::now(); + let pool_result = SqlitePoolOptions::new() .max_connections(5) + .acquire_slow_level(LevelFilter::Warn) + .acquire_slow_threshold(Duration::from_millis(250)) .connect_with(options) - .await?; - migrator.run(&pool).await?; + .await + .map_err(anyhow::Error::from); + crate::telemetry::record_init_result(metrics, db, open_phase, started.elapsed(), &pool_result); + let pool = pool_result?; + let started = Instant::now(); + let migrate_result = migrator.run(&pool).await.map_err(anyhow::Error::from); + crate::telemetry::record_init_result( + metrics, + db, + migrate_phase, + started.elapsed(), + &migrate_result, + ); + migrate_result?; Ok(pool) } -async fn open_logs_sqlite(path: &Path, migrator: &Migrator) -> anyhow::Result { - let options = base_sqlite_options(path).auto_vacuum(SqliteAutoVacuum::Incremental); - let pool = SqlitePoolOptions::new() - .max_connections(5) - .connect_with(options) - .await?; - migrator.run(&pool).await?; - Ok(pool) +async fn ensure_backfill_state_row_in_pool(pool: &sqlx::SqlitePool) -> anyhow::Result<()> { + sqlx::query( + r#" +INSERT INTO backfill_state (id, status, last_watermark, last_success_at, updated_at) +VALUES (?, ?, NULL, NULL, ?) +ON CONFLICT(id) DO NOTHING + "#, + ) + .bind(1_i64) + .bind(crate::BackfillStatus::Pending.as_str()) + .bind(Utc::now().timestamp()) + .execute(pool) + .await?; + Ok(()) } fn db_filename(base_name: &str, version: u32) -> String { @@ -355,9 +488,13 @@ mod tests { strict_pool.close().await; let tolerant_migrator = runtime_state_migrator(); - let tolerant_pool = open_state_sqlite(state_path.as_path(), &tolerant_migrator) - .await - .expect("runtime migrator should tolerate newer applied migrations"); + let tolerant_pool = open_state_sqlite( + state_path.as_path(), + &tolerant_migrator, + /*metrics*/ None, + ) + .await + .expect("runtime migrator should tolerate newer applied migrations"); tolerant_pool.close().await; let _ = tokio::fs::remove_dir_all(codex_home).await; diff --git a/codex-rs/state/src/runtime/backfill.rs b/codex-rs/state/src/runtime/backfill.rs index cac3163f0e..621596825b 100644 --- a/codex-rs/state/src/runtime/backfill.rs +++ b/codex-rs/state/src/runtime/backfill.rs @@ -2,17 +2,19 @@ use super::*; impl StateRuntime { pub async fn get_backfill_state(&self) -> anyhow::Result { - self.ensure_backfill_state_row().await?; - let row = sqlx::query( - r#" + self.record_db_operation(DbKind::State, "get_backfill_state", DbAccess::Read, async { + let row = sqlx::query( + r#" SELECT status, last_watermark, last_success_at FROM backfill_state WHERE id = 1 "#, - ) - .fetch_one(self.pool.as_ref()) - .await?; - crate::BackfillState::try_from_row(&row) + ) + .fetch_one(self.pool.as_ref()) + .await?; + crate::BackfillState::try_from_row(&row) + }) + .await } /// Attempt to claim ownership of rollout metadata backfill. @@ -21,26 +23,34 @@ WHERE id = 1 /// Returns `false` if backfill is already complete or currently owned by a /// non-expired worker. pub async fn try_claim_backfill(&self, lease_seconds: i64) -> anyhow::Result { - self.ensure_backfill_state_row().await?; - let now = Utc::now().timestamp(); - let lease_cutoff = now.saturating_sub(lease_seconds.max(0)); - let result = sqlx::query( - r#" + self.record_db_operation( + DbKind::State, + "try_claim_backfill", + DbAccess::Write, + async { + self.ensure_backfill_state_row().await?; + let now = Utc::now().timestamp(); + let lease_cutoff = now.saturating_sub(lease_seconds.max(0)); + let result = sqlx::query( + r#" UPDATE backfill_state SET status = ?, updated_at = ? WHERE id = 1 AND status != ? AND (status != ? OR updated_at <= ?) "#, + ) + .bind(crate::BackfillStatus::Running.as_str()) + .bind(now) + .bind(crate::BackfillStatus::Complete.as_str()) + .bind(crate::BackfillStatus::Running.as_str()) + .bind(lease_cutoff) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() == 1) + }, ) - .bind(crate::BackfillStatus::Running.as_str()) - .bind(now) - .bind(crate::BackfillStatus::Complete.as_str()) - .bind(crate::BackfillStatus::Running.as_str()) - .bind(lease_cutoff) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() == 1) + .await } /// Mark rollout metadata backfill as running. @@ -62,28 +72,41 @@ WHERE id = 1 /// Persist rollout metadata backfill progress. pub async fn checkpoint_backfill(&self, watermark: &str) -> anyhow::Result<()> { - self.ensure_backfill_state_row().await?; - sqlx::query( - r#" + self.record_db_operation( + DbKind::State, + "checkpoint_backfill", + DbAccess::Write, + async { + self.ensure_backfill_state_row().await?; + sqlx::query( + r#" UPDATE backfill_state SET status = ?, last_watermark = ?, updated_at = ? WHERE id = 1 "#, + ) + .bind(crate::BackfillStatus::Running.as_str()) + .bind(watermark) + .bind(Utc::now().timestamp()) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + }, ) - .bind(crate::BackfillStatus::Running.as_str()) - .bind(watermark) - .bind(Utc::now().timestamp()) - .execute(self.pool.as_ref()) - .await?; - Ok(()) + .await } /// Mark rollout metadata backfill as complete. pub async fn mark_backfill_complete(&self, last_watermark: Option<&str>) -> anyhow::Result<()> { - self.ensure_backfill_state_row().await?; - let now = Utc::now().timestamp(); - sqlx::query( - r#" + self.record_db_operation( + DbKind::State, + "mark_backfill_complete", + DbAccess::Write, + async { + self.ensure_backfill_state_row().await?; + let now = Utc::now().timestamp(); + sqlx::query( + r#" UPDATE backfill_state SET status = ?, @@ -92,30 +115,21 @@ SET updated_at = ? WHERE id = 1 "#, + ) + .bind(crate::BackfillStatus::Complete.as_str()) + .bind(last_watermark) + .bind(now) + .bind(now) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + }, ) - .bind(crate::BackfillStatus::Complete.as_str()) - .bind(last_watermark) - .bind(now) - .bind(now) - .execute(self.pool.as_ref()) - .await?; - Ok(()) + .await } async fn ensure_backfill_state_row(&self) -> anyhow::Result<()> { - sqlx::query( - r#" -INSERT INTO backfill_state (id, status, last_watermark, last_success_at, updated_at) -VALUES (?, ?, NULL, NULL, ?) -ON CONFLICT(id) DO NOTHING - "#, - ) - .bind(1_i64) - .bind(crate::BackfillStatus::Pending.as_str()) - .bind(Utc::now().timestamp()) - .execute(self.pool.as_ref()) - .await?; - Ok(()) + ensure_backfill_state_row_in_pool(self.pool.as_ref()).await } } diff --git a/codex-rs/state/src/runtime/logs.rs b/codex-rs/state/src/runtime/logs.rs index 6c878db624..1ff538a019 100644 --- a/codex-rs/state/src/runtime/logs.rs +++ b/codex-rs/state/src/runtime/logs.rs @@ -9,41 +9,44 @@ impl StateRuntime { /// Insert a batch of log entries into the logs table. pub async fn insert_logs(&self, entries: &[LogEntry]) -> anyhow::Result<()> { - if entries.is_empty() { - return Ok(()); - } + self.record_db_operation(DbKind::Logs, "insert_logs", DbAccess::Transaction, async { + if entries.is_empty() { + return Ok(()); + } - let mut tx = self.logs_pool.begin().await?; - let mut builder = QueryBuilder::::new( - "INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id, process_uuid, module_path, file, line, estimated_bytes) ", - ); - builder.push_values(entries, |mut row, entry| { - let feedback_log_body = entry.feedback_log_body.as_ref().or(entry.message.as_ref()); - // Keep about 10 MiB of reader-visible log content per partition. - // Both `query_logs` and `/feedback` read the persisted - // `feedback_log_body`, while `LogEntry.message` is only a write-time - // fallback for callers that still populate the old field. - let estimated_bytes = feedback_log_body.map_or(0, String::len) as i64 - + entry.level.len() as i64 - + entry.target.len() as i64 - + entry.module_path.as_ref().map_or(0, String::len) as i64 - + entry.file.as_ref().map_or(0, String::len) as i64; - row.push_bind(entry.ts) - .push_bind(entry.ts_nanos) - .push_bind(&entry.level) - .push_bind(&entry.target) - .push_bind(feedback_log_body) - .push_bind(&entry.thread_id) - .push_bind(&entry.process_uuid) - .push_bind(&entry.module_path) - .push_bind(&entry.file) - .push_bind(entry.line) - .push_bind(estimated_bytes); - }); - builder.build().execute(&mut *tx).await?; - self.prune_logs_after_insert(entries, &mut tx).await?; - tx.commit().await?; - Ok(()) + let mut tx = self.logs_pool.begin().await?; + let mut builder = QueryBuilder::::new( + "INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id, process_uuid, module_path, file, line, estimated_bytes) ", + ); + builder.push_values(entries, |mut row, entry| { + let feedback_log_body = entry.feedback_log_body.as_ref().or(entry.message.as_ref()); + // Keep about 10 MiB of reader-visible log content per partition. + // Both `query_logs` and `/feedback` read the persisted + // `feedback_log_body`, while `LogEntry.message` is only a write-time + // fallback for callers that still populate the old field. + let estimated_bytes = feedback_log_body.map_or(0, String::len) as i64 + + entry.level.len() as i64 + + entry.target.len() as i64 + + entry.module_path.as_ref().map_or(0, String::len) as i64 + + entry.file.as_ref().map_or(0, String::len) as i64; + row.push_bind(entry.ts) + .push_bind(entry.ts_nanos) + .push_bind(&entry.level) + .push_bind(&entry.target) + .push_bind(feedback_log_body) + .push_bind(&entry.thread_id) + .push_bind(&entry.process_uuid) + .push_bind(&entry.module_path) + .push_bind(&entry.file) + .push_bind(entry.line) + .push_bind(estimated_bytes); + }); + builder.build().execute(&mut *tx).await?; + self.prune_logs_after_insert(entries, &mut tx).await?; + tx.commit().await?; + Ok(()) + }) + .await } /// Enforce per-partition retained-log-content caps after a successful batch insert. diff --git a/codex-rs/state/src/runtime/metrics_tests.rs b/codex-rs/state/src/runtime/metrics_tests.rs new file mode 100644 index 0000000000..a9d65246b8 --- /dev/null +++ b/codex-rs/state/src/runtime/metrics_tests.rs @@ -0,0 +1,139 @@ +use super::StateRuntime; +use super::test_support::unique_temp_dir; +use crate::DB_INIT_METRIC; +use crate::DB_OPERATION_METRIC; +use crate::DbMetricsRecorder; +use crate::DbMetricsRecorderHandle; +use pretty_assertions::assert_eq; +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::Mutex; +use std::time::Duration; + +#[derive(Clone, Debug)] +struct MetricEvent { + name: String, + tags: BTreeMap, +} + +#[derive(Default)] +struct TestMetrics { + events: Mutex>, +} + +impl TestMetrics { + fn metric_points(&self, name: &str) -> Vec> { + self.events + .lock() + .expect("metrics lock") + .iter() + .filter(|event| event.name == name) + .map(|event| event.tags.clone()) + .collect() + } +} + +impl DbMetricsRecorder for TestMetrics { + fn counter(&self, name: &str, _inc: i64, tags: &[(&str, &str)]) { + self.events.lock().expect("metrics lock").push(MetricEvent { + name: name.to_string(), + tags: tags_to_map(tags), + }); + } + + fn record_duration(&self, name: &str, _duration: Duration, tags: &[(&str, &str)]) { + self.events.lock().expect("metrics lock").push(MetricEvent { + name: name.to_string(), + tags: tags_to_map(tags), + }); + } +} + +fn build_metrics() -> Arc { + Arc::new(TestMetrics::default()) +} + +fn tags_to_map(tags: &[(&str, &str)]) -> BTreeMap { + tags.iter() + .map(|(key, value)| ((*key).to_string(), (*value).to_string())) + .collect() +} + +fn find_point( + points: &[BTreeMap], + key: &str, + value: &str, +) -> BTreeMap { + points + .iter() + .find(|attrs| attrs.get(key).is_some_and(|actual| actual == value)) + .cloned() + .unwrap_or_else(|| panic!("missing point with {key}={value}: {points:?}")) +} + +#[tokio::test] +async fn init_records_success_metrics() { + let metrics = build_metrics(); + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init_with_metrics( + codex_home.clone(), + "test-provider".to_string(), + Some(metrics.clone() as DbMetricsRecorderHandle), + ) + .await + .expect("initialize runtime"); + + let points = metrics.metric_points(DB_INIT_METRIC); + let open_state = find_point(&points, "phase", "open_state"); + assert_eq!( + open_state.get("status").map(String::as_str), + Some("success") + ); + assert_eq!(open_state.get("db").map(String::as_str), Some("state")); + assert_eq!( + open_state.get("error_class").map(String::as_str), + Some("none") + ); + assert_eq!( + open_state.get("sqlite_code").map(String::as_str), + Some("none") + ); + + runtime.pool.close().await; + runtime.logs_pool.close().await; + let _ = tokio::fs::remove_dir_all(codex_home).await; +} + +#[tokio::test] +async fn selected_operations_record_success_metrics() { + let metrics = build_metrics(); + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init_with_metrics( + codex_home.clone(), + "test-provider".to_string(), + Some(metrics.clone() as DbMetricsRecorderHandle), + ) + .await + .expect("initialize runtime"); + + runtime + .get_backfill_state() + .await + .expect("get backfill state"); + runtime + .checkpoint_backfill("sessions/test/rollout.jsonl") + .await + .expect("checkpoint backfill"); + + let points = metrics.metric_points(DB_OPERATION_METRIC); + let read = find_point(&points, "operation", "get_backfill_state"); + assert_eq!(read.get("status").map(String::as_str), Some("success")); + assert_eq!(read.get("access").map(String::as_str), Some("read")); + let write = find_point(&points, "operation", "checkpoint_backfill"); + assert_eq!(write.get("status").map(String::as_str), Some("success")); + assert_eq!(write.get("access").map(String::as_str), Some("write")); + + runtime.pool.close().await; + runtime.logs_pool.close().await; + let _ = tokio::fs::remove_dir_all(codex_home).await; +} diff --git a/codex-rs/state/src/runtime/threads.rs b/codex-rs/state/src/runtime/threads.rs index 1795a864d8..41874def94 100644 --- a/codex-rs/state/src/runtime/threads.rs +++ b/codex-rs/state/src/runtime/threads.rs @@ -5,8 +5,9 @@ use std::sync::atomic::Ordering; impl StateRuntime { pub async fn get_thread(&self, id: ThreadId) -> anyhow::Result> { - let row = sqlx::query( - r#" + self.record_db_operation(DbKind::State, "get_thread", DbAccess::Read, async { + let row = sqlx::query( + r#" SELECT threads.id, threads.rollout_path, @@ -34,12 +35,14 @@ SELECT FROM threads WHERE threads.id = ? "#, - ) - .bind(id.to_string()) - .fetch_optional(self.pool.as_ref()) - .await?; - row.map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) - .transpose() + ) + .bind(id.to_string()) + .fetch_optional(self.pool.as_ref()) + .await?; + row.map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) + .transpose() + }) + .await } pub async fn get_thread_memory_mode(&self, id: ThreadId) -> anyhow::Result> { @@ -55,33 +58,36 @@ WHERE threads.id = ? &self, thread_id: ThreadId, ) -> anyhow::Result>> { - let rows = sqlx::query( - r#" + self.record_db_operation(DbKind::State, "get_dynamic_tools", DbAccess::Read, async { + let rows = sqlx::query( + r#" SELECT namespace, name, description, input_schema, defer_loading FROM thread_dynamic_tools WHERE thread_id = ? ORDER BY position ASC "#, - ) - .bind(thread_id.to_string()) - .fetch_all(self.pool.as_ref()) - .await?; - if rows.is_empty() { - return Ok(None); - } - let mut tools = Vec::with_capacity(rows.len()); - for row in rows { - let input_schema: String = row.try_get("input_schema")?; - let input_schema = serde_json::from_str::(input_schema.as_str())?; - tools.push(DynamicToolSpec { - namespace: row.try_get("namespace")?, - name: row.try_get("name")?, - description: row.try_get("description")?, - input_schema, - defer_loading: row.try_get("defer_loading")?, - }); - } - Ok(Some(tools)) + ) + .bind(thread_id.to_string()) + .fetch_all(self.pool.as_ref()) + .await?; + if rows.is_empty() { + return Ok(None); + } + let mut tools = Vec::with_capacity(rows.len()); + for row in rows { + let input_schema: String = row.try_get("input_schema")?; + let input_schema = serde_json::from_str::(input_schema.as_str())?; + tools.push(DynamicToolSpec { + namespace: row.try_get("namespace")?, + name: row.try_get("name")?, + description: row.try_get("description")?, + input_schema, + defer_loading: row.try_get("defer_loading")?, + }); + } + Ok(Some(tools)) + }) + .await } /// Persist or replace the directional parent-child edge for a spawned thread. @@ -332,22 +338,30 @@ ON CONFLICT(child_thread_id) DO NOTHING id: ThreadId, archived_only: Option, ) -> anyhow::Result> { - let mut builder = - QueryBuilder::::new("SELECT rollout_path FROM threads WHERE id = "); - builder.push_bind(id.to_string()); - match archived_only { - Some(true) => { - builder.push(" AND archived = 1"); - } - Some(false) => { - builder.push(" AND archived = 0"); - } - None => {} - } - let row = builder.build().fetch_optional(self.pool.as_ref()).await?; - Ok(row - .and_then(|r| r.try_get::("rollout_path").ok()) - .map(PathBuf::from)) + self.record_db_operation( + DbKind::State, + "find_rollout_path_by_id", + DbAccess::Read, + async { + let mut builder = + QueryBuilder::::new("SELECT rollout_path FROM threads WHERE id = "); + builder.push_bind(id.to_string()); + match archived_only { + Some(true) => { + builder.push(" AND archived = 1"); + } + Some(false) => { + builder.push(" AND archived = 0"); + } + None => {} + } + let row = builder.build().fetch_optional(self.pool.as_ref()).await?; + Ok(row + .and_then(|r| r.try_get::("rollout_path").ok()) + .map(PathBuf::from)) + }, + ) + .await } /// Find the newest thread whose user-facing title exactly matches `title`. @@ -400,35 +414,38 @@ ON CONFLICT(child_thread_id) DO NOTHING page_size: usize, filters: ThreadFilterOptions<'_>, ) -> anyhow::Result { - let limit = page_size.saturating_add(1); - let sort_key = filters.sort_key; - let sort_direction = filters.sort_direction; + self.record_db_operation(DbKind::State, "list_threads", DbAccess::Read, async { + let limit = page_size.saturating_add(1); + let sort_key = filters.sort_key; + let sort_direction = filters.sort_direction; - let mut builder = QueryBuilder::::new(""); - push_thread_select_columns(&mut builder); - builder.push(" FROM threads"); - push_thread_filters(&mut builder, filters); - push_thread_order_and_limit(&mut builder, sort_key, sort_direction, limit); + let mut builder = QueryBuilder::::new(""); + push_thread_select_columns(&mut builder); + builder.push(" FROM threads"); + push_thread_filters(&mut builder, filters); + push_thread_order_and_limit(&mut builder, sort_key, sort_direction, limit); - let rows = builder.build().fetch_all(self.pool.as_ref()).await?; - let mut items = rows - .into_iter() - .map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) - .collect::, _>>()?; - let num_scanned_rows = items.len(); - let next_anchor = if items.len() > page_size { - items.pop(); - items - .last() - .and_then(|item| anchor_from_item(item, sort_key)) - } else { - None - }; - Ok(ThreadsPage { - items, - next_anchor, - num_scanned_rows, + let rows = builder.build().fetch_all(self.pool.as_ref()).await?; + let mut items = rows + .into_iter() + .map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) + .collect::, _>>()?; + let num_scanned_rows = items.len(); + let next_anchor = if items.len() > page_size { + items.pop(); + items + .last() + .and_then(|item| anchor_from_item(item, sort_key)) + } else { + None + }; + Ok(ThreadsPage { + items, + next_anchor, + num_scanned_rows, + }) }) + .await } /// List thread ids using the underlying database (no rollout scanning). @@ -585,15 +602,24 @@ ON CONFLICT(id) DO NOTHING thread_id: ThreadId, updated_at: DateTime, ) -> anyhow::Result { - let updated_at = self.allocate_thread_updated_at(updated_at)?; - let result = - sqlx::query("UPDATE threads SET updated_at = ?, updated_at_ms = ? WHERE id = ?") + self.record_db_operation( + DbKind::State, + "touch_thread_updated_at", + DbAccess::Write, + async { + let updated_at = self.allocate_thread_updated_at(updated_at)?; + let result = sqlx::query( + "UPDATE threads SET updated_at = ?, updated_at_ms = ? WHERE id = ?", + ) .bind(datetime_to_epoch_seconds(updated_at)) .bind(datetime_to_epoch_millis(updated_at)) .bind(thread_id.to_string()) .execute(self.pool.as_ref()) .await?; - Ok(result.rows_affected() > 0) + Ok(result.rows_affected() > 0) + }, + ) + .await } /// Allocate a persisted `updated_at` value for thread-list cursor ordering. @@ -676,12 +702,13 @@ WHERE id = ? metadata: &crate::ThreadMetadata, creation_memory_mode: Option<&str>, ) -> anyhow::Result<()> { - let updated_at = self.allocate_thread_updated_at(metadata.updated_at)?; - // Backfill/reconcile callers merge existing git info before upserting, but that - // read/modify/write is not atomic. Preserve non-null SQLite git fields here so - // an explicit metadata update cannot be lost if a stale rollout upsert lands later. - sqlx::query( - r#" + self.record_db_operation(DbKind::State, "upsert_thread", DbAccess::Write, async { + let updated_at = self.allocate_thread_updated_at(metadata.updated_at)?; + // Backfill/reconcile callers merge existing git info before upserting, but that + // read/modify/write is not atomic. Preserve non-null SQLite git fields here so + // an explicit metadata update cannot be lost if a stale rollout upsert lands later. + sqlx::query( + r#" INSERT INTO threads ( id, rollout_path, @@ -738,48 +765,53 @@ ON CONFLICT(id) DO UPDATE SET git_branch = COALESCE(threads.git_branch, excluded.git_branch), git_origin_url = COALESCE(threads.git_origin_url, excluded.git_origin_url) "#, - ) - .bind(metadata.id.to_string()) - .bind(metadata.rollout_path.display().to_string()) - .bind(datetime_to_epoch_seconds(metadata.created_at)) - .bind(datetime_to_epoch_seconds(updated_at)) - .bind(datetime_to_epoch_millis(metadata.created_at)) - .bind(datetime_to_epoch_millis(updated_at)) - .bind(metadata.source.as_str()) - .bind( - metadata - .thread_source - .map(codex_protocol::protocol::ThreadSource::as_str), - ) - .bind(metadata.agent_nickname.as_deref()) - .bind(metadata.agent_role.as_deref()) - .bind(metadata.agent_path.as_deref()) - .bind(metadata.model_provider.as_str()) - .bind(metadata.model.as_deref()) - .bind( - metadata - .reasoning_effort - .as_ref() - .map(crate::extract::enum_to_string), - ) - .bind(metadata.cwd.display().to_string()) - .bind(metadata.cli_version.as_str()) - .bind(metadata.title.as_str()) - .bind(metadata.sandbox_policy.as_str()) - .bind(metadata.approval_mode.as_str()) - .bind(metadata.tokens_used) - .bind(metadata.first_user_message.as_deref().unwrap_or_default()) - .bind(metadata.archived_at.is_some()) - .bind(metadata.archived_at.map(datetime_to_epoch_seconds)) - .bind(metadata.git_sha.as_deref()) - .bind(metadata.git_branch.as_deref()) - .bind(metadata.git_origin_url.as_deref()) - .bind(creation_memory_mode.unwrap_or("enabled")) - .execute(self.pool.as_ref()) - .await?; - self.insert_thread_spawn_edge_from_source_if_absent(metadata.id, metadata.source.as_str()) + ) + .bind(metadata.id.to_string()) + .bind(metadata.rollout_path.display().to_string()) + .bind(datetime_to_epoch_seconds(metadata.created_at)) + .bind(datetime_to_epoch_seconds(updated_at)) + .bind(datetime_to_epoch_millis(metadata.created_at)) + .bind(datetime_to_epoch_millis(updated_at)) + .bind(metadata.source.as_str()) + .bind( + metadata + .thread_source + .map(codex_protocol::protocol::ThreadSource::as_str), + ) + .bind(metadata.agent_nickname.as_deref()) + .bind(metadata.agent_role.as_deref()) + .bind(metadata.agent_path.as_deref()) + .bind(metadata.model_provider.as_str()) + .bind(metadata.model.as_deref()) + .bind( + metadata + .reasoning_effort + .as_ref() + .map(crate::extract::enum_to_string), + ) + .bind(metadata.cwd.display().to_string()) + .bind(metadata.cli_version.as_str()) + .bind(metadata.title.as_str()) + .bind(metadata.sandbox_policy.as_str()) + .bind(metadata.approval_mode.as_str()) + .bind(metadata.tokens_used) + .bind(metadata.first_user_message.as_deref().unwrap_or_default()) + .bind(metadata.archived_at.is_some()) + .bind(metadata.archived_at.map(datetime_to_epoch_seconds)) + .bind(metadata.git_sha.as_deref()) + .bind(metadata.git_branch.as_deref()) + .bind(metadata.git_origin_url.as_deref()) + .bind(creation_memory_mode.unwrap_or("enabled")) + .execute(self.pool.as_ref()) .await?; - Ok(()) + self.insert_thread_spawn_edge_from_source_if_absent( + metadata.id, + metadata.source.as_str(), + ) + .await?; + Ok(()) + }) + .await } /// Persist dynamic tools for a thread if none have been stored yet. @@ -791,19 +823,24 @@ ON CONFLICT(id) DO UPDATE SET thread_id: ThreadId, tools: Option<&[DynamicToolSpec]>, ) -> anyhow::Result<()> { - let Some(tools) = tools else { - return Ok(()); - }; - if tools.is_empty() { - return Ok(()); - } - let thread_id = thread_id.to_string(); - let mut tx = self.pool.begin().await?; - for (idx, tool) in tools.iter().enumerate() { - let position = i64::try_from(idx).unwrap_or(i64::MAX); - let input_schema = serde_json::to_string(&tool.input_schema)?; - sqlx::query( - r#" + self.record_db_operation( + DbKind::State, + "persist_dynamic_tools", + DbAccess::Transaction, + async { + let Some(tools) = tools else { + return Ok(()); + }; + if tools.is_empty() { + return Ok(()); + } + let thread_id = thread_id.to_string(); + let mut tx = self.pool.begin().await?; + for (idx, tool) in tools.iter().enumerate() { + let position = i64::try_from(idx).unwrap_or(i64::MAX); + let input_schema = serde_json::to_string(&tool.input_schema)?; + sqlx::query( + r#" INSERT INTO thread_dynamic_tools ( thread_id, position, @@ -815,19 +852,22 @@ INSERT INTO thread_dynamic_tools ( ) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(thread_id, position) DO NOTHING "#, - ) - .bind(thread_id.as_str()) - .bind(position) - .bind(tool.namespace.as_deref()) - .bind(tool.name.as_str()) - .bind(tool.description.as_str()) - .bind(input_schema) - .bind(tool.defer_loading) - .execute(&mut *tx) - .await?; - } - tx.commit().await?; - Ok(()) + ) + .bind(thread_id.as_str()) + .bind(position) + .bind(tool.namespace.as_deref()) + .bind(tool.name.as_str()) + .bind(tool.description.as_str()) + .bind(input_schema) + .bind(tool.defer_loading) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(()) + }, + ) + .await } /// Apply rollout items incrementally using the underlying database. diff --git a/codex-rs/state/src/telemetry.rs b/codex-rs/state/src/telemetry.rs new file mode 100644 index 0000000000..edd516fe5b --- /dev/null +++ b/codex-rs/state/src/telemetry.rs @@ -0,0 +1,330 @@ +use std::borrow::Cow; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; + +use crate::DB_FALLBACK_METRIC; +use crate::DB_INIT_DURATION_METRIC; +use crate::DB_INIT_METRIC; +use crate::DB_LOG_QUEUE_METRIC; +use crate::DB_OPERATION_DURATION_METRIC; +use crate::DB_OPERATION_METRIC; + +/// Low-cardinality metrics sink used by the SQLite state runtime. +/// +/// Implementations should ignore recording errors locally. Database operations +/// must never fail because telemetry delivery failed. +pub trait DbMetricsRecorder: Send + Sync + 'static { + /// Increment a counter metric by `inc` with low-cardinality tags. + fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]); + + /// Record an elapsed duration metric with low-cardinality tags. + fn record_duration(&self, name: &str, duration: Duration, tags: &[(&str, &str)]); +} + +/// Shared recorder handle stored by `StateRuntime` and cloned by log layers. +pub type DbMetricsRecorderHandle = Arc; + +#[derive(Clone, Copy)] +pub(crate) enum DbKind { + State, + Logs, + None, +} + +impl DbKind { + fn as_str(self) -> &'static str { + match self { + Self::State => "state", + Self::Logs => "logs", + Self::None => "none", + } + } +} + +#[derive(Clone, Copy)] +pub(crate) enum DbAccess { + Read, + Write, + Transaction, +} + +impl DbAccess { + fn as_str(self) -> &'static str { + match self { + Self::Read => "read", + Self::Write => "write", + Self::Transaction => "transaction", + } + } +} + +#[derive(Debug, Clone, Eq, PartialEq)] +pub(crate) struct DbErrorTags { + pub error_class: &'static str, + pub sqlite_code: String, +} + +impl DbErrorTags { + fn none() -> Self { + Self { + error_class: "none", + sqlite_code: "none".to_string(), + } + } +} + +pub(crate) async fn record_operation( + metrics: Option<&dyn DbMetricsRecorder>, + db: DbKind, + operation: &'static str, + access: DbAccess, + future: F, +) -> anyhow::Result +where + F: Future>, +{ + let started = Instant::now(); + let result = future.await; + record_operation_result(metrics, db, operation, access, started.elapsed(), &result); + result +} + +pub(crate) fn record_init_result( + metrics: Option<&dyn DbMetricsRecorder>, + db: DbKind, + phase: &'static str, + duration: Duration, + result: &anyhow::Result, +) { + let status = if result.is_ok() { "success" } else { "failed" }; + let error_tags = result + .as_ref() + .err() + .map(classify_error) + .unwrap_or_else(DbErrorTags::none); + let tags = [ + ("status", status), + ("phase", phase), + ("db", db.as_str()), + ("error_class", error_tags.error_class), + ("sqlite_code", error_tags.sqlite_code.as_str()), + ]; + record_counter(metrics, DB_INIT_METRIC, &tags); + record_duration(metrics, DB_INIT_DURATION_METRIC, duration, &tags); +} + +pub fn record_fallback( + metrics: Option<&dyn DbMetricsRecorder>, + caller: &'static str, + reason: &'static str, +) { + let tags = [("caller", caller), ("reason", reason)]; + record_counter(metrics, DB_FALLBACK_METRIC, &tags); +} + +pub fn record_init_backfill_gate( + metrics: Option<&dyn DbMetricsRecorder>, + duration: Duration, + result: &anyhow::Result<()>, +) { + record_init_result(metrics, DbKind::None, "backfill_gate", duration, result); +} + +pub(crate) fn record_log_queue( + metrics: Option<&dyn DbMetricsRecorder>, + event: &'static str, + reason: &'static str, +) { + let tags = [("event", event), ("reason", reason)]; + record_counter(metrics, DB_LOG_QUEUE_METRIC, &tags); +} + +pub(crate) fn classify_error(err: &anyhow::Error) -> DbErrorTags { + for cause in err.chain() { + if let Some(sqlx_err) = cause.downcast_ref::() { + return classify_sqlx_error(sqlx_err); + } + if cause + .downcast_ref::() + .is_some() + { + return DbErrorTags { + error_class: "migration", + sqlite_code: "none".to_string(), + }; + } + if cause.downcast_ref::().is_some() { + return DbErrorTags { + error_class: "serde", + sqlite_code: "none".to_string(), + }; + } + if cause.downcast_ref::().is_some() { + return DbErrorTags { + error_class: "io", + sqlite_code: "none".to_string(), + }; + } + } + + DbErrorTags { + error_class: "unknown", + sqlite_code: "none".to_string(), + } +} + +pub(crate) fn classify_sqlite_code(code: &str) -> &'static str { + let primary_code = code.parse::().ok().map(|code| code & 0xff); + match primary_code { + Some(5) => "sqlite_busy", + Some(6) => "sqlite_locked", + Some(8) => "sqlite_readonly", + Some(10) => "sqlite_ioerr", + Some(11) => "sqlite_corrupt", + Some(13) => "sqlite_full", + Some(14) => "sqlite_cantopen", + Some(19) => "sqlite_constraint", + Some(17) => "sqlite_schema", + _ => "unknown", + } +} + +fn record_operation_result( + metrics: Option<&dyn DbMetricsRecorder>, + db: DbKind, + operation: &'static str, + access: DbAccess, + duration: Duration, + result: &anyhow::Result, +) { + let status = if result.is_ok() { "success" } else { "failed" }; + let error_tags = result + .as_ref() + .err() + .map(classify_error) + .unwrap_or_else(DbErrorTags::none); + let tags = [ + ("status", status), + ("db", db.as_str()), + ("operation", operation), + ("access", access.as_str()), + ("error_class", error_tags.error_class), + ("sqlite_code", error_tags.sqlite_code.as_str()), + ]; + record_counter(metrics, DB_OPERATION_METRIC, &tags); + record_duration(metrics, DB_OPERATION_DURATION_METRIC, duration, &tags); +} + +fn classify_sqlx_error(err: &sqlx::Error) -> DbErrorTags { + match err { + sqlx::Error::Database(database_error) => { + let code = database_error + .code() + .unwrap_or(Cow::Borrowed("none")) + .to_string(); + DbErrorTags { + error_class: classify_sqlite_code(code.as_str()), + sqlite_code: code, + } + } + sqlx::Error::PoolTimedOut => DbErrorTags { + error_class: "pool_timeout", + sqlite_code: "none".to_string(), + }, + sqlx::Error::Io(_) => DbErrorTags { + error_class: "io", + sqlite_code: "none".to_string(), + }, + sqlx::Error::ColumnDecode { source, .. } if source.is::() => { + DbErrorTags { + error_class: "serde", + sqlite_code: "none".to_string(), + } + } + sqlx::Error::Decode(source) if source.is::() => DbErrorTags { + error_class: "serde", + sqlite_code: "none".to_string(), + }, + _ => DbErrorTags { + error_class: "unknown", + sqlite_code: "none".to_string(), + }, + } +} + +fn record_counter(metrics: Option<&dyn DbMetricsRecorder>, name: &str, tags: &[(&str, &str)]) { + if let Some(metrics) = metrics { + metrics.counter(name, /*inc*/ 1, tags); + } +} + +fn record_duration( + metrics: Option<&dyn DbMetricsRecorder>, + name: &str, + duration: Duration, + tags: &[(&str, &str)], +) { + if let Some(metrics) = metrics { + metrics.record_duration(name, duration, tags); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn classifies_sqlite_primary_codes() { + assert_eq!(classify_sqlite_code("5"), "sqlite_busy"); + assert_eq!(classify_sqlite_code("6"), "sqlite_locked"); + assert_eq!(classify_sqlite_code("14"), "sqlite_cantopen"); + assert_eq!(classify_sqlite_code("2067"), "sqlite_constraint"); + } + + #[test] + fn classifies_non_sqlite_errors() { + let io_error = + anyhow::Error::new(std::io::Error::new(std::io::ErrorKind::NotFound, "missing")); + assert_eq!( + classify_error(&io_error), + DbErrorTags { + error_class: "io", + sqlite_code: "none".to_string() + } + ); + + let serde_error = + anyhow::Error::new(serde_json::from_str::("not-json").unwrap_err()); + assert_eq!( + classify_error(&serde_error), + DbErrorTags { + error_class: "serde", + sqlite_code: "none".to_string() + } + ); + + let unknown_error = anyhow::anyhow!("plain failure"); + assert_eq!( + classify_error(&unknown_error), + DbErrorTags { + error_class: "unknown", + sqlite_code: "none".to_string() + } + ); + } + + #[test] + fn classifies_sqlx_pool_timeout() { + let err = anyhow::Error::new(sqlx::Error::PoolTimedOut); + assert_eq!( + classify_error(&err), + DbErrorTags { + error_class: "pool_timeout", + sqlite_code: "none".to_string() + } + ); + } +}