From 0adee0df26c7dcdaf4a19a4013b94f4058d26f33 Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Tue, 24 Nov 2026 21:23:59 +0000 Subject: [PATCH] Add a process-wide runtime for Statsig evaluations (#63762) ## Why Codex callers need to read feature gates and dynamic configs locally and stop using account-scoped decisions when the authentication owner changes. ## What changed - Bootstrap ChatGPT evaluations through the Codex backend. Initialize API-key and installation identities through the Statsig SDK. - Share one background worker per process to retry initialization and refresh evaluations through the SDK. Keep the last successful values on refresh failure while the authentication owner remains current. - Expose `Gate` and `DynamicConfig` readers that return `false` and an empty JSON object, respectively, when current evaluations are unavailable. ## Testing Add a mock-server test for bootstrap retries after credential changes, local gate and config reads, and value retention after a failed refresh followed by replacement on a successful refresh. GitOrigin-RevId: c02cd976a44229518a7159eb2bd35107ef280b56 --- codex-rs/Cargo.lock | 6 + codex-rs/statsig/Cargo.toml | 9 +- codex-rs/statsig/src/evaluations.rs | 317 ++++++++++++++++++++++ codex-rs/statsig/src/evaluations_tests.rs | 156 +++++++++++ codex-rs/statsig/src/lib.rs | 11 +- 5 files changed, 496 insertions(+), 3 deletions(-) create mode 100644 codex-rs/statsig/src/evaluations.rs create mode 100644 codex-rs/statsig/src/evaluations_tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index a1128f46c8..ec89b87daf 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5212,11 +5212,17 @@ version = "0.0.0" dependencies = [ "anyhow", "bytes", + "codex-backend-client", "codex-http-client", + "codex-login", + "codex-model-provider", "http 1.4.0", "oai-statsig-rust-client", "pretty_assertions", + "serde", + "serde_json", "tokio", + "tracing", "wiremock", ] diff --git a/codex-rs/statsig/Cargo.toml b/codex-rs/statsig/Cargo.toml index 3d9a05de85..bb937bfd65 100644 --- a/codex-rs/statsig/Cargo.toml +++ b/codex-rs/statsig/Cargo.toml @@ -12,13 +12,20 @@ doctest = false workspace = true [dependencies] +anyhow = { workspace = true } bytes = { workspace = true } +codex-backend-client = { workspace = true } codex-http-client = { workspace = true } +codex-login = { workspace = true } +codex-model-provider = { workspace = true } http = { workspace = true } oai-statsig-rust-client = { version = "0.1.0", default-features = false } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } +tracing = { workspace = true } [dev-dependencies] -anyhow = { workspace = true } pretty_assertions = { workspace = true } tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } wiremock = { workspace = true } diff --git a/codex-rs/statsig/src/evaluations.rs b/codex-rs/statsig/src/evaluations.rs new file mode 100644 index 0000000000..4e571f9e0c --- /dev/null +++ b/codex-rs/statsig/src/evaluations.rs @@ -0,0 +1,317 @@ +//! Loads evaluated values into the SDK and keeps reads scoped to the initial auth owner. + +use std::sync::Arc; +use std::sync::Mutex as StdMutex; +use std::sync::Weak; +use std::time::Duration; + +use anyhow::Result; +use anyhow::anyhow; +use codex_backend_client::Client; +use codex_http_client::ClientRouteClass; +use codex_http_client::HttpClientFactory; +use codex_http_client::RouteAwareClientPool; +use codex_login::AuthOwner; +use codex_login::CodexAuth; +use codex_model_provider::ProviderAuthContext; +use serde::Deserialize; +use serde_json::Map; +use serde_json::Value; +use statsig_client::FreshValuePolicy; +use statsig_client::InitializeOpts; +use statsig_client::ShutdownOpts; +use statsig_client::StatsigClient; +use statsig_client::StatsigOptions; +use statsig_client::StatsigUser; +use statsig_client::UpdateStrategy; +use statsig_client::UpdateUserOpts; +use tokio::runtime::Handle; +use tokio::sync::watch; +use tokio::task::JoinHandle; + +use crate::StatsigBootstrapContext; +use crate::StatsigHttpClient; + +const EVALUATION_TIMEOUT: Duration = Duration::from_secs(10); +const INITIALIZE_RETRY_INTERVAL: Duration = Duration::from_secs(60); +const REFRESH_INTERVAL: Duration = Duration::from_secs(10 * 60); + +static PROCESS_RUNTIME: StdMutex> = StdMutex::new(Weak::new()); + +/// A named Statsig gate that can be declared alongside its consumers. +#[derive(Clone, Copy)] +pub struct Gate(&'static str); + +impl Gate { + pub const fn new(name: &'static str) -> Self { + Self(name) + } + + /// 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)) + } +} + +/// A named Statsig dynamic config that can be declared alongside its consumers. +#[derive(Clone, Copy)] +pub struct DynamicConfig(&'static str); + +impl DynamicConfig { + pub const fn new(name: &'static str) -> Self { + Self(name) + } + + /// Reads the latest cached JSON object, defaulting to an empty object until available. + pub fn value(self) -> Map { + let Some(values) = current_evaluations() else { + return Map::new(); + }; + values.sdk.get_dynamic_config(self.0).value().clone() + } +} + +fn current_evaluations() -> Option> { + let runtime = StatsigRuntime::current()?; + let values = runtime.evaluations.borrow().clone()?; + values.is_current().then_some(values) +} + +/// The identity this process is authorized to use for Statsig. +pub enum StatsigIdentity { + Account(ProviderAuthContext), + Installation(HttpClientFactory), +} + +/// Owns one background refresh worker for a harness and exposes its local decisions. +pub struct StatsigRuntime { + evaluations: watch::Receiver>>, + worker: JoinHandle<()>, +} + +impl StatsigRuntime { + /// Retains the active process worker while the caller owns this handle. + pub fn current() -> Option> { + PROCESS_RUNTIME + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .upgrade() + } + + /// Installs one worker for the process, shared by embedded callers. + pub fn start_process( + identity: StatsigIdentity, + chatgpt_base_url: String, + sdk_key: String, + context: StatsigBootstrapContext, + exposure_logging_enabled: bool, + ) -> Arc { + let mut active = PROCESS_RUNTIME + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(runtime) = active.upgrade() { + return runtime; + } + let (publish, evaluations) = watch::channel::>>(None); + let mut auth_changes = match &identity { + StatsigIdentity::Account(auth) => Some(auth.credentials.auth_change_state_receiver()), + StatsigIdentity::Installation(_) => None, + }; + let worker = tokio::spawn(async move { + loop { + tokio::select! { + biased; + _ = 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()) { + current.refresh().await + } else { + if let Some(previous) = publish.send_replace(None) { + previous.shutdown().await; + } + StatsigEvaluations::start( + &identity, + &chatgpt_base_url, + &sdk_key, + context.clone(), + StatsigOptions::new() + .with_initialize_url("https://ab.chatgpt.com/v1/initialize") + .with_log_event_url("https://ab.chatgpt.com/v1/rgstr") + .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))); + }) + }; + if update.is_err() { + tracing::debug!("Statsig evaluations update failed"); + } + let interval = if publish.borrow().is_some() { + REFRESH_INTERVAL + } else { + INITIALIZE_RETRY_INTERVAL + }; + if let (Some(changes), Some(generation)) = (&mut auth_changes, generation) { + let _ = tokio::time::timeout( + interval, + changes.wait_for(|state| { + state.owner_generation != generation.owner_generation + || (interval == INITIALIZE_RETRY_INTERVAL && state.generation != generation.generation) + }), + ).await; + } else { + tokio::time::sleep(interval).await; + } + } => {} + } + } + if let Some(current) = publish.send_replace(None) { + current.shutdown().await; + } + }); + let runtime = Arc::new(Self { + evaluations, + worker, + }); + *active = Arc::downgrade(&runtime); + runtime + } + + /// Flushes on normal exit after the last process host releases its worker. + pub async fn finish(runtime: Option>) { + if let Some(runtime) = runtime.and_then(Arc::into_inner) { + // Closing the watch channel stops the worker and triggers the SDK flush. + drop(runtime.evaluations); + let _ = runtime.worker.await; + } + } +} + +#[derive(Deserialize)] +struct BootstrapUser { + user: StatsigUser, +} + +/// Server decisions for a single Codex identity. Gate and config reads are local. +struct StatsigEvaluations { + sdk: StatsigClient, + owner: Option, +} + +impl StatsigEvaluations { + /// Uses Codex backend bootstrap for ChatGPT sign-in and SDK initialize for API-key sign-in. + async fn start( + identity: &StatsigIdentity, + chatgpt_base_url: &str, + sdk_key: &str, + context: StatsigBootstrapContext, + options: StatsigOptions, + ) -> Result { + anyhow::ensure!( + sdk_key.starts_with("client-") && sdk_key.len() > "client-".len(), + "Statsig requires a client SDK key" + ); + let (owner, factory, bootstrap) = match identity { + StatsigIdentity::Account(context_auth) => { + let auth_manager = &context_auth.credentials; + let (auth, factory) = auth_manager + .auth_with_http_client_factory() + .await + .ok_or_else(|| anyhow!("Sign in to Codex before starting Statsig"))?; + let owner = auth_manager + .auth_owner_for(&auth) + .ok_or_else(|| anyhow!("Codex authentication changed during Statsig setup"))?; + let bootstrap = match &auth { + CodexAuth::Chatgpt(_) | CodexAuth::ChatgptAuthTokens(_) => { + let backend = Client::from_auth_with_runtime_without_redirects( + chatgpt_base_url, + &auth, + factory.clone(), + context_auth.runtime_auth.as_ref(), + &Default::default(), + ) + .await?; + Some(backend.statsig_bootstrap(&context).await?) + } + CodexAuth::ApiKey(_) => None, + _ => anyhow::bail!("This Codex sign-in method is unsupported by Statsig"), + }; + (Some(owner), factory, bootstrap) + } + StatsigIdentity::Installation(factory) => (None, factory.clone(), None), + }; + let user = match &bootstrap { + Some(values) => serde_json::from_str::(values)?.user, + None if owner.is_some() => anonymous_user(context, "apikey"), + None => anonymous_user(context, "anonymous"), + }; + let pool = RouteAwareClientPool::new_without_redirects_or_request_logging( + factory, + ClientRouteClass::Api, + ); + let options = options + .with_runtime_handle(Handle::current()) + .with_http_client(StatsigHttpClient::new(pool)) + .with_disable_all_caching(/* disabled */ true); + let sdk = StatsigClient::with_options(sdk_key, user, options)?; + if let Some(values) = bootstrap { + sdk.initialize_local(UpdateStrategy::Bootstrap(values.as_bytes()))?; + } else { + sdk.initialize_with_opts(InitializeOpts { + timeout: Some(EVALUATION_TIMEOUT), + fresh_value_policy: FreshValuePolicy::RequireFresh, + }) + .await?; + } + let values = Self { sdk, owner }; + anyhow::ensure!( + values.is_current(), + "Codex authentication changed during Statsig setup" + ); + Ok(values) + } + + /// Refreshes the SDK's full set of evaluated values for the current user. + async fn refresh(&self) -> Result<()> { + anyhow::ensure!(self.is_current(), "Codex authentication changed"); + let user = self.sdk.current_state().user().clone(); + let opts = UpdateUserOpts { + timeout: Some(EVALUATION_TIMEOUT), + fresh_value_policy: FreshValuePolicy::RequireFresh, + }; + self.sdk.update_user_with_opts(user, opts).await?; + Ok(()) + } + + fn is_current(&self) -> bool { + self.owner.as_ref().is_none_or(AuthOwner::is_current) + } + + async fn shutdown(&self) { + let opts = ShutdownOpts { + timeout: Some(Duration::from_secs(2)), + }; + let _ = self.sdk.shutdown_with_opts(opts).await; + } +} + +fn anonymous_user(context: StatsigBootstrapContext, auth_method: &str) -> StatsigUser { + let mut user = StatsigUser::new(format!("ua-{}", context.stable_id)) + .with_custom_id("stableID", &context.stable_id) + .with_custom_id("source_surface_stable_id", context.stable_id) + .with_app_version(context.app_version) + .with_custom("auth_method", auth_method) + .with_custom("auth_status", "logged_out") + .with_custom("brand_name", context.brand_name) + .with_custom("codex_window_type", context.window_type) + .with_custom("systemName", context.system_name) + .with_custom("systemVersion", context.system_version); + user.locale = context.locale; + user +} + +#[cfg(test)] +#[path = "evaluations_tests.rs"] +mod tests; diff --git a/codex-rs/statsig/src/evaluations_tests.rs b/codex-rs/statsig/src/evaluations_tests.rs new file mode 100644 index 0000000000..9f07f86f9b --- /dev/null +++ b/codex-rs/statsig/src/evaluations_tests.rs @@ -0,0 +1,156 @@ +#![cfg(test)] + +use codex_login::AuthManager; +use codex_login::CodexAuth; +use codex_model_provider::ProviderAuthContext; +use pretty_assertions::assert_eq; +use serde_json::json; +use statsig_client::StatsigOptions; +use wiremock::Mock; +use wiremock::MockServer; +use wiremock::ResponseTemplate; +use wiremock::matchers::body_partial_json; +use wiremock::matchers::method; +use wiremock::matchers::path; + +use super::StatsigBootstrapContext; +use super::StatsigEvaluations; +use super::StatsigIdentity; + +#[tokio::test] +async fn bootstraps_once_and_refreshes_directly_through_the_sdk() -> anyhow::Result<()> { + let server = MockServer::start().await; + let home = std::env::temp_dir().join(format!("statsig-auth-{}", server.address().port())); + let auth_manager = AuthManager::from_auth_for_testing_with_home( + CodexAuth::create_dummy_chatgpt_auth_for_testing(), + home.clone(), + ); + let account = ProviderAuthContext { + credentials: auth_manager.clone(), + runtime_auth: None, + }; + let context = StatsigBootstrapContext { + target_app: "test-target-app", + stable_id: "test-install".into(), + app_version: "1".into(), + locale: None, + system_name: "test-os".into(), + system_version: "1".into(), + window_type: "cli", + brand_name: "codex", + }; + const PROBE: super::Gate = super::Gate::new("probe"); + assert!(!PROBE.is_enabled()); + assert!(super::DynamicConfig::new("probe").value().is_empty()); + let user = json!({"userID": "test-user", "customIDs": {"stableID": "test-install"}}); + let values = |enabled: bool, limit: u32| { + json!({ + "has_updates": true, + "hash_used": "none", + "user": user, + "feature_gates": {"probe": {"value": enabled}}, + "dynamic_configs": {"probe": {"value": {"limit": limit}}}, + "layer_configs": {} + }) + }; + let bootstrap = json!({"statsigPayload": values(true, 1).to_string()}); + let failed = Mock::given(method("POST")) + .and(path("/api/codex/statsig/bootstrap")) + .respond_with(ResponseTemplate::new(503)) + .expect(1) + .mount_as_scoped(&server) + .await; + let runtime = super::StatsigRuntime::start_process( + StatsigIdentity::Account(account.clone()), + server.uri(), + "client-test".into(), + context.clone(), + /*exposure_logging_enabled*/ false, + ); + assert!(!PROBE.is_enabled()); + failed.wait_until_satisfied().await; + drop(failed); + let failed_retry = Mock::given(method("POST")) + .and(path("/api/codex/statsig/bootstrap")) + .respond_with(ResponseTemplate::new(503)) + .expect(1) + .mount_as_scoped(&server) + .await; + let token = "e30.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsidXNlcl9pZCI6InRlc3QtdXNlciJ9fQ"; + codex_login::auth::login_with_chatgpt_auth_tokens( + &home, + &format!("{token}.a"), + "account_id", + /*chatgpt_plan_type*/ None, + )?; + assert!(auth_manager.reload().await); + failed_retry.wait_until_satisfied().await; + drop(failed_retry); + Mock::given(method("POST")) + .and(path("/api/codex/statsig/bootstrap")) + .respond_with(ResponseTemplate::new(200).set_body_json(bootstrap)) + .expect(2) + .mount(&server) + .await; + let owner = auth_manager.auth_owner(); + codex_login::auth::login_with_chatgpt_auth_tokens( + &home, + &format!("{token}.b"), + "account_id", + /*chatgpt_plan_type*/ None, + )?; + auth_manager.reload().await; + assert!(owner.is_current()); + let mut evaluations = runtime.evaluations.clone(); + tokio::time::timeout( + std::time::Duration::from_secs(5), + evaluations.wait_for(Option::is_some), + ) + .await??; + assert!(PROBE.is_enabled()); + assert_eq!( + super::DynamicConfig::new("probe").value(), + json!({"limit": 1}).as_object().unwrap().clone() + ); + drop(evaluations); + super::StatsigRuntime::finish(Some(runtime)).await; + for response in [ + ResponseTemplate::new(503), + ResponseTemplate::new(200).set_body_json(values(false, 2)), + ] { + Mock::given(method("POST")) + .and(path("/initialize")) + .and(body_partial_json(json!({"user": user}))) + .respond_with(response) + .up_to_n_times(1) + .expect(1) + .mount(&server) + .await; + } + let options = StatsigOptions::new() + .with_initialize_url(format!("{}/initialize", server.uri())) + .with_initialization_request_attempts(/* count */ 1) + .with_disable_all_logging(/* disabled */ true); + let store = StatsigEvaluations::start( + &StatsigIdentity::Account(account), + &server.uri(), + "client-test", + context, + options, + ) + .await?; + let read = || { + ( + store.sdk.check_gate("probe"), + json!(store.sdk.get_dynamic_config("probe").value()), + ) + }; + assert_eq!(read(), (true, json!({"limit": 1}))); + assert!(store.refresh().await.is_err()); + assert_eq!(read(), (true, json!({"limit": 1}))); + store.refresh().await?; + assert_eq!(read(), (false, json!({"limit": 2}))); + server.verify().await; + store.shutdown().await; + Ok(()) +} diff --git a/codex-rs/statsig/src/lib.rs b/codex-rs/statsig/src/lib.rs index d72d034ad3..dae1462b3f 100644 --- a/codex-rs/statsig/src/lib.rs +++ b/codex-rs/statsig/src/lib.rs @@ -1,5 +1,12 @@ -//! Statsig HTTP requests use the caller's Codex routing and network policy. -//! Decoded responses are bounded; status handling and retries stay in the SDK. +//! Codex's account-scoped store of Statsig evaluations and its policy-aware HTTP adapter. + +mod evaluations; + +pub use codex_backend_client::StatsigBootstrapContext; +pub use evaluations::DynamicConfig; +pub use evaluations::Gate; +pub use evaluations::StatsigIdentity; +pub use evaluations::StatsigRuntime; use std::time::Duration;