mirror of
https://github.com/openai/codex.git
synced 2026-11-26 23:40:43 +00:00
Add metrics for Statsig updates and evaluations (#64184)
## Why A Statsig gate can return `false` while bootstrap is in progress or because the cached evaluation is disabled. Update failures also share a generic debug message, which makes recurring failures hard to diagnose. ## What changed Record OpenTelemetry counts and durations for bootstrap and refresh, tagged by outcome and failure category. Record gate and dynamic config counts after successful updates. Skip update metrics while waiting for authentication. Count gate and dynamic config reads by name, kind, and reason. Use fixed reason labels to distinguish fallback reads from evaluated reads while keeping targeting values out of the metrics. ## Testing Check that a gate read during bootstrap and a read after bootstrap emit distinct reasons, and that wrapped network policy denials retain the `policy` category. GitOrigin-RevId: ca4a248ee8ec7ed1318b2b2d320b9e9df08cbe5e
This commit is contained in:
Generated
+1
-1
File diff suppressed because one or more lines are too long
Generated
+5
-2
@@ -5226,12 +5226,15 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
"codex-api",
|
||||
"codex-backend-client",
|
||||
"codex-http-client",
|
||||
"codex-login",
|
||||
"codex-model-provider",
|
||||
"codex-otel",
|
||||
"http 1.4.0",
|
||||
"oai-statsig-rust-client",
|
||||
"opentelemetry_sdk",
|
||||
"pretty_assertions",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -11344,9 +11347,9 @@ checksum = "6aa2c4e539b869820a2b82e1aef6ff40aa85e65decdd5185e83fb4b1249cd00f"
|
||||
|
||||
[[package]]
|
||||
name = "oai-statsig-rust-client"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5adc8fe6756bcf80f8039f2312efe1a6f268406f1e9647e8e5ed16ef4fcf60d"
|
||||
checksum = "bfd7aa16fc69922f38a8b0050ca8c6855079aa68a29e3df6caf78bcce5cb5dc9"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"arc-swap",
|
||||
|
||||
@@ -14,18 +14,21 @@ workspace = true
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-backend-client = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-model-provider = { workspace = true }
|
||||
codex-otel = { workspace = true }
|
||||
http = { workspace = true }
|
||||
oai-statsig-rust-client = { version = "0.1.0", default-features = false }
|
||||
oai-statsig-rust-client = { version = "0.1.1", default-features = false }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
opentelemetry_sdk = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
wiremock = { workspace = true }
|
||||
|
||||
@@ -4,7 +4,9 @@ use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::sync::Weak;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_backend_client::Client;
|
||||
@@ -31,6 +33,7 @@ use tokio::task::JoinHandle;
|
||||
|
||||
use crate::StatsigBootstrapContext;
|
||||
use crate::StatsigHttpClient;
|
||||
use crate::telemetry;
|
||||
|
||||
const EVALUATION_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const INITIALIZE_RETRY_INTERVAL: Duration = Duration::from_secs(60);
|
||||
@@ -49,7 +52,15 @@ impl Gate {
|
||||
|
||||
/// Reads the latest cached decision, defaulting to false until evaluations are available.
|
||||
pub fn is_enabled(self) -> bool {
|
||||
current_evaluations().is_some_and(|values| values.sdk.check_gate(self.0))
|
||||
let (value, reason) = match current_evaluations() {
|
||||
Ok(values) => {
|
||||
let gate = values.sdk.get_feature_gate(self.0);
|
||||
(gate.value(), sdk_reason(gate.details().reason()))
|
||||
}
|
||||
Err(reason) => (false, reason),
|
||||
};
|
||||
telemetry::evaluation(self.0, "gate", reason);
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,17 +75,39 @@ impl DynamicConfig {
|
||||
|
||||
/// Reads the latest cached JSON object, defaulting to an empty object until available.
|
||||
pub fn value(self) -> Map<String, Value> {
|
||||
let Some(values) = current_evaluations() else {
|
||||
return Map::new();
|
||||
let (value, reason) = match current_evaluations() {
|
||||
Ok(values) => {
|
||||
let config = values.sdk.get_dynamic_config(self.0);
|
||||
(
|
||||
config.value().clone(),
|
||||
sdk_reason(config.details().reason()),
|
||||
)
|
||||
}
|
||||
Err(reason) => (Map::new(), reason),
|
||||
};
|
||||
values.sdk.get_dynamic_config(self.0).value().clone()
|
||||
telemetry::evaluation(self.0, "config", reason);
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
fn current_evaluations() -> Option<Arc<StatsigEvaluations>> {
|
||||
let runtime = StatsigRuntime::current()?;
|
||||
fn current_evaluations() -> Result<Arc<StatsigEvaluations>, &'static str> {
|
||||
// `pre_setup` also includes Statsig being intentionally disabled.
|
||||
let runtime = StatsigRuntime::current().ok_or("pre_setup")?;
|
||||
let values = runtime.evaluations.borrow().clone()?;
|
||||
values.is_current().then_some(values)
|
||||
values
|
||||
.is_current()
|
||||
.then_some(values)
|
||||
.ok_or("identity_changed")
|
||||
}
|
||||
|
||||
fn sdk_reason(reason: &str) -> &'static str {
|
||||
if reason.ends_with(":Unrecognized") {
|
||||
"unrecognized"
|
||||
} else if matches!(reason, "NoValues" | "Uninitialized") {
|
||||
"no_values"
|
||||
} else {
|
||||
"evaluated"
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity this process is authorized to use for Statsig.
|
||||
@@ -85,7 +118,7 @@ pub enum StatsigIdentity {
|
||||
|
||||
/// Owns one background refresh worker for a harness and exposes its local decisions.
|
||||
pub struct StatsigRuntime {
|
||||
evaluations: watch::Receiver<Option<Arc<StatsigEvaluations>>>,
|
||||
evaluations: watch::Receiver<Result<Arc<StatsigEvaluations>, &'static str>>,
|
||||
worker: JoinHandle<()>,
|
||||
}
|
||||
|
||||
@@ -112,7 +145,9 @@ impl StatsigRuntime {
|
||||
if let Some(runtime) = active.upgrade() {
|
||||
return runtime;
|
||||
}
|
||||
let (publish, evaluations) = watch::channel::<Option<Arc<StatsigEvaluations>>>(None);
|
||||
let (publish, evaluations) = watch::channel::<Result<Arc<StatsigEvaluations>, &'static str>>(
|
||||
Err("bootstrap_in_progress"),
|
||||
);
|
||||
let mut auth_changes = match &identity {
|
||||
StatsigIdentity::Account(auth) => Some(auth.credentials.auth_change_state_receiver()),
|
||||
StatsigIdentity::Installation(_) => None,
|
||||
@@ -124,11 +159,14 @@ impl StatsigRuntime {
|
||||
_ = publish.closed() => break,
|
||||
() = async {
|
||||
let generation = auth_changes.as_mut().map(|changes| *changes.borrow_and_update());
|
||||
let current = publish.borrow().clone();
|
||||
let update = if let Some(current) = current.filter(|values| values.is_current()) {
|
||||
let current = publish.borrow().as_ref().ok().cloned();
|
||||
let current = current.filter(|values| values.is_current());
|
||||
let refresh = current.is_some();
|
||||
let started = Instant::now();
|
||||
let update = if let Some(current) = current {
|
||||
current.refresh().await
|
||||
} else {
|
||||
if let Some(previous) = publish.send_replace(None) {
|
||||
if let Ok(previous) = publish.send_replace(Err("bootstrap_in_progress")) {
|
||||
previous.shutdown().await;
|
||||
}
|
||||
StatsigEvaluations::start(
|
||||
@@ -142,13 +180,26 @@ impl StatsigRuntime {
|
||||
.with_sdk_exception_url("https://ab.chatgpt.com/v1/sdk_exception")
|
||||
.with_disable_all_logging(!exposure_logging_enabled),
|
||||
).await.map(|values| {
|
||||
publish.send_replace(Some(Arc::new(values)));
|
||||
let _ = publish.send_replace(Ok(Arc::new(values)));
|
||||
})
|
||||
};
|
||||
let failure = update.as_ref().err().map(telemetry::failure_category);
|
||||
if !refresh && let Some(failure) = failure {
|
||||
let _ = publish.send_replace(Err(failure));
|
||||
}
|
||||
if !matches!(failure, Some(telemetry::WAITING_AUTH)) {
|
||||
let values = publish.borrow().as_ref().ok().cloned();
|
||||
telemetry::update(
|
||||
if refresh { "refresh" } else { "bootstrap" },
|
||||
started.elapsed(),
|
||||
failure,
|
||||
values.as_ref().map(|values| &values.sdk),
|
||||
);
|
||||
}
|
||||
if update.is_err() {
|
||||
tracing::debug!("Statsig evaluations update failed");
|
||||
}
|
||||
let interval = if publish.borrow().is_some() {
|
||||
let interval = if publish.borrow().is_ok() {
|
||||
REFRESH_INTERVAL
|
||||
} else {
|
||||
INITIALIZE_RETRY_INTERVAL
|
||||
@@ -167,7 +218,7 @@ impl StatsigRuntime {
|
||||
} => {}
|
||||
}
|
||||
}
|
||||
if let Some(current) = publish.send_replace(None) {
|
||||
if let Ok(current) = publish.send_replace(Err("shutdown")) {
|
||||
current.shutdown().await;
|
||||
}
|
||||
});
|
||||
@@ -219,7 +270,7 @@ impl StatsigEvaluations {
|
||||
let (auth, factory) = auth_manager
|
||||
.auth_with_http_client_factory()
|
||||
.await
|
||||
.ok_or_else(|| anyhow!("Sign in to Codex before starting Statsig"))?;
|
||||
.context(telemetry::WAITING_AUTH)?;
|
||||
let owner = auth_manager
|
||||
.auth_owner_for(&auth)
|
||||
.ok_or_else(|| anyhow!("Codex authentication changed during Statsig setup"))?;
|
||||
@@ -232,8 +283,14 @@ impl StatsigEvaluations {
|
||||
context_auth.runtime_auth.as_ref(),
|
||||
&Default::default(),
|
||||
)
|
||||
.await?;
|
||||
Some(backend.statsig_bootstrap(&context).await?)
|
||||
.await
|
||||
.context(telemetry::AUTH)?;
|
||||
Some(
|
||||
backend
|
||||
.statsig_bootstrap(&context)
|
||||
.await
|
||||
.context(telemetry::HTTP)?,
|
||||
)
|
||||
}
|
||||
CodexAuth::ApiKey(_) => None,
|
||||
_ => anyhow::bail!("This Codex sign-in method is unsupported by Statsig"),
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ScopeMetrics;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use statsig_client::StatsigOptions;
|
||||
@@ -17,6 +20,17 @@ use super::StatsigBootstrapContext;
|
||||
use super::StatsigEvaluations;
|
||||
use super::StatsigIdentity;
|
||||
|
||||
#[test]
|
||||
fn wrapped_policy_denials_keep_their_category() {
|
||||
let denied = codex_http_client::NetworkPolicyDenied::Destination;
|
||||
for error in [
|
||||
anyhow::Error::new(codex_api::AuthError::Policy(denied)).context("auth"),
|
||||
anyhow::Error::new(codex_backend_client::RequestError::Policy(denied)).context("http"),
|
||||
] {
|
||||
assert_eq!(super::telemetry::failure_category(&error), "policy");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bootstraps_once_and_refreshes_directly_through_the_sdk() -> anyhow::Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
@@ -60,6 +74,10 @@ async fn bootstraps_once_and_refreshes_directly_through_the_sdk() -> anyhow::Res
|
||||
.expect(1)
|
||||
.mount_as_scoped(&server)
|
||||
.await;
|
||||
let metrics = codex_otel::install_global_metrics(codex_otel::MetricsClient::new(
|
||||
codex_otel::MetricsConfig::in_memory("test", "test", "1", Default::default())
|
||||
.with_runtime_reader(),
|
||||
)?);
|
||||
let runtime = super::StatsigRuntime::start_process(
|
||||
StatsigIdentity::Account(account.clone()),
|
||||
server.uri(),
|
||||
@@ -104,16 +122,38 @@ async fn bootstraps_once_and_refreshes_directly_through_the_sdk() -> anyhow::Res
|
||||
let mut evaluations = runtime.evaluations.clone();
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
evaluations.wait_for(Option::is_some),
|
||||
evaluations.wait_for(Result::is_ok),
|
||||
)
|
||||
.await??;
|
||||
assert!(PROBE.is_enabled());
|
||||
let mut checks = Vec::new();
|
||||
let snapshot = metrics.snapshot()?;
|
||||
for metric in snapshot.scope_metrics().flat_map(ScopeMetrics::metrics) {
|
||||
if metric.name() == "codex.statsig.evaluation.count"
|
||||
&& let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data()
|
||||
{
|
||||
for point in sum.data_points() {
|
||||
let tags = ["kind", "name", "reason"].map(|key| {
|
||||
let tag = point.attributes().find(|attr| attr.key.as_str() == key);
|
||||
tag.expect(key).value.to_string()
|
||||
});
|
||||
checks.push((tags, point.value()));
|
||||
}
|
||||
}
|
||||
}
|
||||
checks.sort();
|
||||
assert_eq!(
|
||||
checks,
|
||||
["bootstrap_in_progress", "evaluated"]
|
||||
.map(|reason| (["gate", "probe", reason].map(str::to_owned), 1))
|
||||
);
|
||||
assert_eq!(
|
||||
super::DynamicConfig::new("probe").value(),
|
||||
json!({"limit": 1}).as_object().unwrap().clone()
|
||||
);
|
||||
drop(evaluations);
|
||||
super::StatsigRuntime::finish(Some(runtime)).await;
|
||||
metrics.shutdown()?;
|
||||
for response in [
|
||||
ResponseTemplate::new(503),
|
||||
ResponseTemplate::new(200).set_body_json(values(false, 2)),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Codex's account-scoped store of Statsig evaluations and its policy-aware HTTP adapter.
|
||||
|
||||
mod evaluations;
|
||||
mod telemetry;
|
||||
|
||||
pub use codex_backend_client::StatsigBootstrapContext;
|
||||
pub use evaluations::DynamicConfig;
|
||||
@@ -88,6 +89,8 @@ impl HttpClient for StatsigHttpClient {
|
||||
fn map_error(error: HttpError, timeout: Duration) -> StatsigError {
|
||||
if error.is_timeout() {
|
||||
StatsigError::NetworkTimeout(timeout)
|
||||
} else if matches!(error, HttpError::Policy(_)) {
|
||||
StatsigError::Network(telemetry::POLICY_DENIED.into())
|
||||
} else {
|
||||
StatsigError::Network(error.without_url().to_string())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Records bounded Statsig update and evaluation metrics without logging targeting values.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_api::AuthError;
|
||||
use codex_http_client::HttpError;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_otel::MetricsError;
|
||||
use statsig_client::StatsigClient;
|
||||
use statsig_client::StatsigError;
|
||||
|
||||
pub(crate) const POLICY_DENIED: &str = "Statsig request denied by network policy";
|
||||
|
||||
pub(crate) const WAITING_AUTH: &str = "waiting_auth";
|
||||
pub(crate) const AUTH: &str = "auth";
|
||||
pub(crate) const HTTP: &str = "http";
|
||||
|
||||
pub(crate) fn failure_category(error: &anyhow::Error) -> &'static str {
|
||||
if error.chain().any(|cause| {
|
||||
cause.is::<NetworkPolicyDenied>()
|
||||
|| matches!(cause.downcast_ref(), Some(AuthError::Policy(_)))
|
||||
}) {
|
||||
return "policy";
|
||||
}
|
||||
if let Some(error) = error.downcast_ref::<HttpError>() {
|
||||
return if error.is_timeout() {
|
||||
"timeout"
|
||||
} else if matches!(error, HttpError::Policy(_)) {
|
||||
"policy"
|
||||
} else {
|
||||
"network"
|
||||
};
|
||||
}
|
||||
if let Some(error) = error.downcast_ref::<StatsigError>() {
|
||||
return match error {
|
||||
StatsigError::NetworkTimeout(_) | StatsigError::OperationTimeout { .. } => "timeout",
|
||||
StatsigError::Network(message) if message == POLICY_DENIED => "policy",
|
||||
StatsigError::Network(_) => "network",
|
||||
StatsigError::Http { .. } => HTTP,
|
||||
StatsigError::NoValues => "no_values",
|
||||
StatsigError::Json(_)
|
||||
| StatsigError::InvalidBootstrap { .. }
|
||||
| StatsigError::Utf8(_) => "invalid_response",
|
||||
_ => "other",
|
||||
};
|
||||
}
|
||||
if error.downcast_ref::<serde_json::Error>().is_some() {
|
||||
return "invalid_response";
|
||||
}
|
||||
// Only these fixed contexts can become metric labels.
|
||||
match error.downcast_ref::<&'static str>().copied() {
|
||||
Some(label @ (WAITING_AUTH | AUTH | HTTP)) => label,
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn evaluation(name: &'static str, kind: &'static str, reason: &'static str) {
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let record = |name| {
|
||||
metrics.counter(
|
||||
"codex.statsig.evaluation.count",
|
||||
/*inc*/ 1,
|
||||
&[("name", name), ("kind", kind), ("reason", reason)],
|
||||
)
|
||||
};
|
||||
if let Err(
|
||||
MetricsError::InvalidTagComponent { .. } | MetricsError::EmptyTagComponent { .. },
|
||||
) = record(name)
|
||||
{
|
||||
let _ = record("invalid_name");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn update(
|
||||
operation: &'static str,
|
||||
duration: Duration,
|
||||
failure: Option<&'static str>,
|
||||
sdk: Option<&StatsigClient>,
|
||||
) {
|
||||
let Some(metrics) = codex_otel::global() else {
|
||||
return;
|
||||
};
|
||||
let result = match failure {
|
||||
None => "success",
|
||||
Some("timeout") => "timeout",
|
||||
Some(_) => "error",
|
||||
};
|
||||
let tags = [
|
||||
("operation", operation),
|
||||
("result", result),
|
||||
("failure_category", failure.unwrap_or("none")),
|
||||
];
|
||||
let _ = metrics.counter("codex.statsig.update.count", /*inc*/ 1, &tags);
|
||||
let _ = metrics.record_duration("codex.statsig.update.duration", duration, &tags);
|
||||
if failure.is_none()
|
||||
&& let Some(sdk) = sdk
|
||||
{
|
||||
let state = sdk.current_state();
|
||||
for (name, count) in [
|
||||
("codex.statsig.snapshot.gates", state.feature_gate_count()),
|
||||
(
|
||||
"codex.statsig.snapshot.configs",
|
||||
state.dynamic_config_count(),
|
||||
),
|
||||
] {
|
||||
let _ = metrics.histogram(name, count.min(i64::MAX as usize) as i64, &tags);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user