From f39c3c78d732a2650c9a747a47ae084d6ea4eb43 Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Wed, 25 Nov 2026 18:38:06 +0000 Subject: [PATCH] Initialize Statsig feature gates across Codex launch modes (#64001) ## Why Enabling `statsig_gates` can only load evaluations if the process starts the Statsig runtime. Several Codex entry points never started it. ## What changed Start Statsig in standalone and embedded app servers, the TUI when it connects to a separate app server, eligible `codex sandbox` launches, and local and remote exec servers. This also covers `codex exec` through its embedded app server. Use the serving or local account where applicable and installation identity for remote execution. Share the runtime with the embedded TUI and flush it on normal shutdown. ## Testing Add a CLI integration test that checks which evaluation endpoint each launch mode requests, including signed-in and signed-out sandbox launches. Supply a bundled fixture key in Bazel and nextest CI builds so the test runs. GitOrigin-RevId: 64df9933c1a9783a86be8712fa012b495f34b0f8 --- .github/scripts/run-bazel-ci.sh | 5 +- .../rust-ci-full-nextest-platform.yml | 2 + codex-rs/Cargo.lock | 1 + codex-rs/app-server/src/in_process.rs | 15 ++ codex-rs/app-server/src/lib.rs | 10 + codex-rs/cli/src/debug_sandbox.rs | 42 +++- codex-rs/cli/tests/statsig_startup.rs | 224 ++++++++++++++++++ codex-rs/core/tests/common/runtime_auth.rs | 51 ++-- codex-rs/exec-server-cli/src/command.rs | 31 ++- codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/lib.rs | 25 ++ 11 files changed, 380 insertions(+), 27 deletions(-) create mode 100644 codex-rs/cli/tests/statsig_startup.rs diff --git a/.github/scripts/run-bazel-ci.sh b/.github/scripts/run-bazel-ci.sh index 4fa62cb0c0..530d5a4c09 100755 --- a/.github/scripts/run-bazel-ci.sh +++ b/.github/scripts/run-bazel-ci.sh @@ -352,7 +352,10 @@ bazel_run_args=( "${bazel_args[@]}" ) if [[ "${bazel_args[0]}" == "test" ]]; then - bazel_run_args+=("--test_env=INSTA_UPDATE=no") + bazel_run_args+=( + "--test_env=INSTA_UPDATE=no" + "--@rules_rust//rust/settings:extra_rustc_env=CODEX_BUNDLED_STATSIG_CLIENT_KEY=client-launch-fixture" + ) fi if (( ${#post_config_bazel_args[@]} > 0 )); then bazel_run_args+=("${post_config_bazel_args[@]}") diff --git a/.github/workflows/rust-ci-full-nextest-platform.yml b/.github/workflows/rust-ci-full-nextest-platform.yml index 83bb4810d9..587c7f7c77 100644 --- a/.github/workflows/rust-ci-full-nextest-platform.yml +++ b/.github/workflows/rust-ci-full-nextest-platform.yml @@ -182,6 +182,8 @@ jobs: target: ${{ inputs.target }} - name: Build nextest archive + env: + CODEX_BUNDLED_STATSIG_CLIENT_KEY: client-launch-fixture shell: bash run: | set -euo pipefail diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index d606d2af05..7fc5910622 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5426,6 +5426,7 @@ dependencies = [ "codex-shell-command", "codex-skills", "codex-state", + "codex-statsig", "codex-terminal-detection", "codex-uds", "codex-user-input", diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index 44aa23a788..fdd932d305 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -529,6 +529,20 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult codex_core::statsig::StatsigSurface::Cli, + SessionSource::Exec => codex_core::statsig::StatsigSurface::Exec, + _ => codex_core::statsig::StatsigSurface::AppServer, + }, + codex_core::statsig::HostIdentity::ServingAccount { + auth: Arc::clone(&auth_manager), + default_analytics_enabled: true, + }, + ) + .await; let (client_tx, mut client_rx) = mpsc::channel::(channel_capacity); let (event_tx, event_rx) = mpsc::channel::(channel_capacity); let thread_permissions_reader = ThreadPermissionsReader::default(); @@ -931,6 +945,7 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult, + statsig: Option>, #[cfg(target_os = "macos")] denial_logger: Option, } @@ -296,6 +298,7 @@ impl StartedSandboxChild { } } } + codex_core::statsig::StatsigRuntime::finish(self.statsig.take()).await; handle_exit_status(status); } } @@ -347,7 +350,13 @@ async fn start_command_under_sandbox( } None => codex_linux_sandbox_exe, }; - let config = load_debug_sandbox_config( + let includes_managed_requirements = sandbox_state.is_none() + && !config_options.loader_overrides.ignore_managed_requirements + && matches!( + config_options.managed_requirements_mode, + ManagedRequirementsMode::Include + ); + let mut config = load_debug_sandbox_config( config_overrides .parse_overrides() .map_err(anyhow::Error::msg)?, @@ -357,6 +366,23 @@ async fn start_command_under_sandbox( ) .await?; + let statsig = if includes_managed_requirements + && config.statsig_enabled() + && config + .config_layer_stack + .ensure_config_server_applied() + .is_ok() + { + EmbeddedNetworkPolicy::default().activate(&mut config); + config + .start_statsig( + codex_core::statsig::StatsigSurface::Sandbox, + codex_core::statsig::HostIdentity::LocalAccount, + ) + .await + } else { + None + }; let cwd = &config.cwd; let env = create_env( &config.permissions.shell_environment_policy, @@ -445,7 +471,7 @@ async fn start_command_under_sandbox( .map(PathUri::to_abs_path) .collect::>>() .context("invalid Windows sandbox workspace roots")?; - run_command_under_windows_session( + let exit_code = run_command_under_windows_session( &config, &session_profile, command, @@ -454,6 +480,8 @@ async fn start_command_under_sandbox( env, ) .await; + codex_core::statsig::StatsigRuntime::finish(statsig).await; + std::process::exit(exit_code); } #[cfg(not(windows))] SandboxType::Windows => anyhow::bail!("Windows sandbox is only available on Windows"), @@ -564,6 +592,7 @@ async fn start_command_under_sandbox( Ok(StartedSandboxChild { child, _network_proxy: network_proxy, + statsig, #[cfg(target_os = "macos")] denial_logger, }) @@ -577,7 +606,7 @@ async fn run_command_under_windows_session( cwd: AbsolutePathBuf, workspace_roots: Vec, env: std::collections::HashMap, -) -> ! { +) -> i32 { use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_protocol::config_types::WindowsSandboxLevel; use codex_windows_sandbox::WindowsSandboxProxySettingsMode; @@ -594,7 +623,7 @@ async fn run_command_under_windows_session( Ok(paths) => paths, Err(err) => { eprintln!("windows sandbox failed: {err}"); - std::process::exit(1); + return 1; } }; @@ -625,12 +654,11 @@ async fn run_command_under_windows_session( Ok(spawned) => spawned, Err(err) => { eprintln!("windows sandbox failed: {err}"); - std::process::exit(1); + return 1; } }; - let exit_code = codex_windows_sandbox::forward_sandbox_session_stdio(spawned).await; - std::process::exit(exit_code); + codex_windows_sandbox::forward_sandbox_session_stdio(spawned).await } async fn spawn_debug_sandbox_child( diff --git a/codex-rs/cli/tests/statsig_startup.rs b/codex-rs/cli/tests/statsig_startup.rs new file mode 100644 index 0000000000..565e65bda7 --- /dev/null +++ b/codex-rs/cli/tests/statsig_startup.rs @@ -0,0 +1,224 @@ +//! Checks which endpoint the shipped harness uses to initialize Statsig. + +use anyhow::Result; +use app_test_support::ChatGptAuthFixture; +use app_test_support::mount_workspace_routing; +use app_test_support::write_chatgpt_auth; +use codex_config::types::AuthCredentialsStoreMode; +use codex_utils_cargo_bin::cargo_bin; +use codex_utils_pty::ChildFds; +use codex_utils_pty::TerminalSize; +use codex_utils_pty::spawn_pipe_process; +use codex_utils_pty::spawn_pty_process; +use core_test_support::runtime_auth::with_harness_proxy; +use serde_json::json; +use std::time::Duration; +use wiremock::Mock; +use wiremock::MockServer; +use wiremock::ResponseTemplate; +use wiremock::matchers::body_partial_json; +use wiremock::matchers::header; +use wiremock::matchers::header_regex; +use wiremock::matchers::method; +use wiremock::matchers::path; + +#[tokio::test] +async fn harness_startup_requests_statsig_evaluations() -> Result<()> { + if option_env!("CODEX_BUNDLED_STATSIG_CLIENT_KEY").is_none_or(str::is_empty) { + eprintln!( + "Skipping Statsig launch coverage. Set CODEX_BUNDLED_STATSIG_CLIENT_KEY at build time." + ); + return Ok(()); + } + let binary = cargo_bin("codex")?; + let server = MockServer::start().await; + mount_workspace_routing(&server).await; + Mock::given(method("POST")) + .and(path("/agent/register")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "runtime_agent_instance_id": "fixture-runtime", "agent_host_id": "fixture-host", + "actor": {"kind": "chatgpt", "user_id": "fixture-user", "account_id": "fixture-account"}, + }))) + .mount(&server) + .await; + let registry = server.uri(); + Mock::given(method("POST")) + .and(path("/cloud/environment/fixture/register")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "environment_id": "fixture", + "url": format!("ws://{}/relay?role=environment", server.address()), + "security_profile": "noise_hybrid_ik_v1", + "executor_registration_id": "fixture", + }))) + .mount(&server) + .await; + + with_harness_proxy(&server, /*realtime_target*/ None, async |mut command| { + for key in [ + "CODEX_ACCESS_TOKEN", + "CODEX_API_KEY", + "CODEX_EXEC_SERVER_URL", + "CODEX_SQLITE_HOME", + "OPENAI_API_KEY", + "OPENAI_FEDERATION_RULE_ID", + "OPENAI_IDENTITY_TOKEN_FILE", + "OPENAI_WORKLOAD_IDENTITY_CONTEXT", + ] { + command.env_remove(key); + } + command.env("CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED", "1"); + for (mode, signed_in) in [ + ("app-server", true), + ("app-server-runtime", true), + #[cfg(unix)] + ("daemon", true), + ("exec", true), + ("tui", true), + #[cfg(unix)] + ("tui-daemon", true), + ("sandbox", true), + ("sandbox", false), + ("exec-server", true), + ("exec-server", false), + ("remote", true), + ] { + let tui = matches!(mode, "tui" | "tui-daemon"); + // Keep the managed daemon's Unix socket path short. + #[cfg(unix)] + let home = tempfile::tempdir_in("/tmp")?; + #[cfg(not(unix))] + let home = tempfile::tempdir()?; + let cwd = home.path().canonicalize()?; + let statsig_config = if mode == "app-server-runtime" { + "features.runtime_agent_instances = { enabled = true, mode = 'assertion_only' }\n" + } else if mode == "tui-daemon" { + // CLI feature flags are checked against the daemon's settings. + "features.statsig_gates = true\n" + } else { + "" + }; + std::fs::write( + cwd.join("config.toml"), + format!( + "{statsig_config}cli_auth_credentials_store = 'file'\ncheck_for_update_on_startup = false\n[analytics]\nenabled = false\n[projects.{}]\ntrust_level = 'trusted'\n", + toml::Value::String(cwd.to_string_lossy().into_owned()), + ), + )?; + if signed_in { + write_chatgpt_auth( + &cwd, + ChatGptAuthFixture::new("fixture-token") + .account_id("fixture-account") + .chatgpt_account_id("fixture-account") + .chatgpt_user_id("fixture-user") + .plan_type("plus"), + AuthCredentialsStoreMode::File, + )?; + } + let listen = format!("unix://{}/app-server.sock", cwd.display()); + let args = match mode { + "app-server" | "app-server-runtime" => vec!["app-server"], + "daemon" => vec!["app-server", "--managed-daemon", "--listen", &listen], + "exec" => vec!["exec", "--skip-git-repo-check", "fixture prompt"], + "tui" => vec!["--no-daemon", "--no-alt-screen"], + "tui-daemon" => vec!["--remote", "unix://", "--no-alt-screen"], + "sandbox" => { + // Keep managed requirements enabled without depending on a host sandbox. + let mut args = vec!["-c", "default_permissions=':danger-full-access'", "sandbox", "--"]; + if cfg!(windows) { + args.extend(["powershell.exe", "-Command", "Start-Sleep -Seconds 20"]); + } else { + args.extend(["sleep", "20"]); + } + args + } + "exec-server" => vec!["exec-server", "--listen", "ws://127.0.0.1:0"], + "remote" => vec!["exec-server", "--remote", ®istry, "--environment-id", "fixture"], + _ => unreachable!("unknown launch mode {mode}"), + }; + let flags: &[&str] = if mode == "tui-daemon" { &[] } else { &["--enable", "statsig_gates"] }; + let args: Vec<_> = flags.iter().copied().chain(args).map(str::to_owned).collect(); + let (host, endpoint) = if signed_in && mode != "remote" { + ("chatgpt.com", "/backend-api/wham/statsig/bootstrap") + } else { + ("ab.chatgpt.com", "/v1/initialize") + }; + let mut request = Mock::given(method("POST")) + .and(header("host", host)) + .and(path(endpoint)); + if mode == "app-server-runtime" { + request = request.and(header_regex("authorization", "^AgentAssertion ")); + } else if mode == "tui-daemon" { + request = request.and(body_partial_json(json!({"window_type": "tui"}))); + } + let request = request + // The SDK test covers handling the response. Reject here to avoid a retry. + .respond_with(ResponseTemplate::new(400)) + .expect(1) + .named(format!("{mode} startup")) + .mount_as_scoped(&server) + .await; + + command.env("CODEX_HOME", &cwd); + if tui { + command.env("TERM", "xterm-256color"); + } + let env = command + .as_std() + .get_envs() + .filter_map(|(key, value)| Some((key.to_str()?.to_owned(), value?.to_str()?.to_owned()))) + .collect(); + let daemon = if mode == "tui-daemon" { + let daemon_args = ["--disable", "statsig_gates", "app-server", "--listen", "unix://"] + .map(str::to_owned); + let daemon = spawn_pipe_process(&binary, &daemon_args, &cwd, &env, /*arg0*/ &None, &[]).await?; + let socket = codex_app_server::app_server_control_socket_path(&cwd)?; + tokio::time::timeout(Duration::from_secs(30), async { + while !socket.as_path().try_exists()? { + tokio::time::sleep(Duration::from_millis(10)).await; + } + Ok::<_, anyhow::Error>(()) + }).await??; + Some(daemon) + } else { + None + }; + let mut child = if tui { + spawn_pty_process( + &binary, &args, &cwd, &env, /*arg0*/ &None, + TerminalSize::default(), ChildFds::Inherited(&[]), + ).await? + } else { + spawn_pipe_process(&binary, &args, &cwd, &env, /*arg0*/ &None, &[]).await? + }; + if mode == "exec" { + child.session.close_stdin(); + } + let mut output = Vec::new(); + let wait = async { + loop { + tokio::select! { + biased; + () = request.wait_until_satisfied() => break, + status = &mut child.exit_rx => panic!("{mode} exited with {status:?} before POST {endpoint}\n{}", String::from_utf8_lossy(&output)), + Some(chunk) = child.stdout_rx.recv() => output.extend(chunk), + Some(chunk) = child.stderr_rx.recv() => output.extend(chunk), + } + } + }; + assert!( + tokio::time::timeout(Duration::from_secs(15), wait).await.is_ok(), + "{mode} did not POST {endpoint}\n{}", + String::from_utf8_lossy(&output), + ); + child.session.terminate(); + let _ = child.exit_rx.await; + if let Some(daemon) = daemon { + daemon.session.signal(codex_utils_pty::ProcessSignal::Interrupt)?; + tokio::time::timeout(Duration::from_secs(15), daemon.exit_rx).await??; + } + } + Ok(()) + }) + .await +} diff --git a/codex-rs/core/tests/common/runtime_auth.rs b/codex-rs/core/tests/common/runtime_auth.rs index 9eec29bbad..55b8af9d91 100644 --- a/codex-rs/core/tests/common/runtime_auth.rs +++ b/codex-rs/core/tests/common/runtime_auth.rs @@ -49,6 +49,34 @@ pub async fn run_harness_through_proxy_until( realtime_target: Option, environment: &[(&str, Option<&str>)], observer_completion: impl Future>, +) -> Result<()> { + with_harness_proxy(server, realtime_target, async |mut command| { + command + .args(["--exact", test_name, "--nocapture"]) + .kill_on_drop(true); + for (key, value) in environment { + match value { + Some(value) => command.env(key, value), + None => command.env_remove(key), + }; + } + let output = tokio::time::timeout(Duration::from_secs(90), command.output()).await??; + assert!( + output.status.success(), + "harness subprocess failed\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + observer_completion.await + }) + .await +} + +/// Supplies a test subprocess command with HTTPS routed to the mock server. +pub async fn with_harness_proxy( + server: &MockServer, + realtime_target: Option, + run: impl AsyncFnOnce(Command) -> Result<()>, ) -> Result<()> { // The production destination check stays intact. A test-only CA and CONNECT proxy route // the real host names to wiremock, only inside this isolated test subprocess. @@ -63,6 +91,7 @@ pub async fn run_harness_through_proxy_until( "us.chatgpt-staging.com".into(), "auth.api.openai.org".into(), "observer.internal.api.openai.org".into(), + "ab.chatgpt.com".into(), ])?; let ca_dir = tempfile::tempdir()?; let ca_path = ca_dir.path().join("ca.pem"); @@ -101,6 +130,7 @@ pub async fn run_harness_through_proxy_until( | "CONNECT us.chatgpt-staging.com:443 HTTP/1.1" | "CONNECT auth.api.openai.org:443 HTTP/1.1" | "CONNECT observer.internal.api.openai.org:443 HTTP/1.1" + | "CONNECT ab.chatgpt.com:443 HTTP/1.1" ) ), "unexpected proxy destination" @@ -148,9 +178,8 @@ pub async fn run_harness_through_proxy_until( Ok::<_, anyhow::Error>(()) }); let mut command = Command::new(std::env::current_exe()?); - command - .args(["--exact", test_name, "--nocapture"]) - .kill_on_drop(true); + // Materialize inherited variables so launchers that take an env map can use get_envs(). + command.env_clear().envs(std::env::vars_os()); for &key in codex_network_proxy::PROXY_ENV_KEYS { command.env_remove(key); } @@ -159,21 +188,7 @@ pub async fn run_harness_through_proxy_until( .env("HTTPS_PROXY", proxy_url) .env("NO_PROXY", codex_network_proxy::DEFAULT_NO_PROXY_VALUE) .env("CODEX_CA_CERTIFICATE", ca_path); - for (key, value) in environment { - match value { - Some(value) => command.env(key, value), - None => command.env_remove(key), - }; - } - let output = tokio::time::timeout(Duration::from_secs(90), command.output()).await??; - assert!( - output.status.success(), - "harness subprocess failed\n{}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - - let result = observer_completion.await; + let result = run(command).await; proxy_tasks.shutdown().await; result } diff --git a/codex-rs/exec-server-cli/src/command.rs b/codex-rs/exec-server-cli/src/command.rs index 14bfe3ed67..56f8813a76 100644 --- a/codex-rs/exec-server-cli/src/command.rs +++ b/codex-rs/exec-server-cli/src/command.rs @@ -323,6 +323,16 @@ impl ExecServerCommand { } remote_config.request_dispatch_mode = self.request_dispatch_mode; let remote_config = remote_config.with_telemetry(telemetry); + let statsig = if self.command.is_none() { + config + .start_statsig( + codex_core::statsig::StatsigSurface::RemoteExecutor, + codex_core::statsig::HostIdentity::Installation, + ) + .await + } else { + None + }; let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel(); #[cfg(target_os = "macos")] let runtime_paths = runtime_paths.with_allowed_symlinked_codex_home( @@ -360,6 +370,7 @@ impl ExecServerCommand { exec_server_telemetry::ShutdownBehavior::Graceful(shutdown_sender), ) .await; + codex_core::statsig::StatsigRuntime::finish(statsig).await; if let Some(provider) = credential_provider { provider.check_pipe_failure()?; } @@ -378,6 +389,22 @@ impl ExecServerCommand { config_result.ok() }; let (_otel, telemetry) = exec_server_telemetry::init(config.as_ref()); + let statsig = match &config { + Some(config) + if config + .config_layer_stack + .ensure_config_server_applied() + .is_ok() => + { + config + .start_statsig( + codex_core::statsig::StatsigSurface::ExecServer, + codex_core::statsig::HostIdentity::LocalAccount, + ) + .await + } + Some(_) | None => None, + }; #[cfg(target_os = "macos")] let runtime_paths = runtime_paths.with_allowed_symlinked_codex_home( config.as_ref().and_then(|config| { @@ -406,7 +433,9 @@ impl ExecServerCommand { ParentLifetime::Independent, exec_server_telemetry::ShutdownBehavior::Immediate, ); - run.await.map_err(anyhow::Error::from_boxed) + let result = run.await.map_err(anyhow::Error::from_boxed); + codex_core::statsig::StatsigRuntime::finish(statsig).await; + result } } diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 6a86e3b9c9..6e8f7f3bca 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -50,6 +50,7 @@ codex-file-search = { workspace = true } codex-git-utils = { workspace = true } codex-http-client = { workspace = true } codex-login = { workspace = true } +codex-statsig = { workspace = true } codex-mermaid = { workspace = true } codex-message-history = { workspace = true } codex-model-provider = { workspace = true } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 21a275313e..a54ea434eb 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -2112,6 +2112,30 @@ async fn run_ratatui_app( config.cwd.as_path(), ); + let statsig = if matches!(app_server_target, AppServerTarget::Embedded) { + codex_statsig::StatsigRuntime::current() + } else if config.statsig_enabled() + && config + .config_layer_stack + .ensure_config_server_applied() + .is_ok() + { + let identity = if matches!(app_server_target, AppServerTarget::Remote { .. }) { + // Remote workspace config skips local login requirements. + crate::legacy_core::config::StatsigHostIdentity::Installation + } else { + // Defer reloading credentials and policy after account changes in another process. + crate::legacy_core::config::StatsigHostIdentity::LocalAccount + }; + let mut config = config.clone(); + codex_app_server_client::EmbeddedNetworkPolicy::default().activate(&mut config); + config + .start_statsig(crate::legacy_core::config::StatsigSurface::Tui, identity) + .await + } else { + None + }; + // Count launches that reach final config resolution, regardless of screen policy. if config.analytics_enabled != Some(false) && config.otel.metrics_exporter != codex_config::types::OtelExporterKind::None @@ -2417,6 +2441,7 @@ async fn run_ratatui_app( .await; terminal_restore_guard.restore_silently(); + codex_statsig::StatsigRuntime::finish(statsig).await; // Mark the end of the recorded session. session_log::log_session_end(); // ignore error when collecting usage – report underlying error instead