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
This commit is contained in:
iceweasel-oai
2026-11-25 22:46:26 +00:00
committed by copyberry
parent f3c6076ac2
commit f39c3c78d7
11 changed files with 380 additions and 27 deletions
+4 -1
View File
@@ -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[@]}")
@@ -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
+1
View File
@@ -5426,6 +5426,7 @@ dependencies = [
"codex-shell-command",
"codex-skills",
"codex-state",
"codex-statsig",
"codex-terminal-detection",
"codex-uds",
"codex-user-input",
+15
View File
@@ -529,6 +529,20 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
.await?;
let channel_capacity = args.channel_capacity.max(1);
let installation_id = resolve_installation_id(&args.config.codex_home).await?;
let statsig = args
.config
.start_statsig(
match &args.session_source {
SessionSource::Cli => 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::<InProcessClientMessage>(channel_capacity);
let (event_tx, event_rx) = mpsc::channel::<InProcessServerEvent>(channel_capacity);
let thread_permissions_reader = ThreadPermissionsReader::default();
@@ -931,6 +945,7 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
}
analytics_events_flush_client.flush().await;
codex_core::statsig::StatsigRuntime::finish(statsig).await;
if let Some(done_tx) = shutdown_ack {
let _ = done_tx.send(());
+10
View File
@@ -822,6 +822,15 @@ pub async fn run_main_with_transport_options(
));
}
let installation_id = resolve_installation_id(&config.codex_home).await?;
let statsig = config
.start_statsig(
codex_core::statsig::StatsigSurface::AppServer,
codex_core::statsig::HostIdentity::ServingAccount {
auth: Arc::clone(&auth_manager),
default_analytics_enabled,
},
)
.await;
let transport_shutdown_token = CancellationToken::new();
// Remote enrollment must cancel before RPC drain without shutting down telemetry.
let remote_control_shutdown_token = transport_shutdown_token.child_token();
@@ -1435,6 +1444,7 @@ pub async fn run_main_with_transport_options(
let _ = handle.await;
}
codex_core::statsig::StatsigRuntime::finish(statsig).await;
Ok(AppServerExit::Graceful)
}
+35 -7
View File
@@ -8,6 +8,7 @@ use std::path::PathBuf;
use std::process::Stdio;
use anyhow::Context as _;
use codex_app_server::in_process::EmbeddedNetworkPolicy;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_core::config::Config;
@@ -271,6 +272,7 @@ async fn run_command_under_sandbox(
pub struct StartedSandboxChild {
child: Child,
_network_proxy: Option<codex_core::config::StartedNetworkProxy>,
statsig: Option<std::sync::Arc<codex_core::statsig::StatsigRuntime>>,
#[cfg(target_os = "macos")]
denial_logger: Option<DenialLogger>,
}
@@ -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::<std::io::Result<Vec<_>>>()
.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<AbsolutePathBuf>,
env: std::collections::HashMap<String, String>,
) -> ! {
) -> 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(
+224
View File
@@ -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", &registry, "--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
}
+33 -18
View File
@@ -49,6 +49,34 @@ pub async fn run_harness_through_proxy_until(
realtime_target: Option<std::net::SocketAddr>,
environment: &[(&str, Option<&str>)],
observer_completion: impl Future<Output = Result<()>>,
) -> 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<std::net::SocketAddr>,
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
}
+30 -1
View File
@@ -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
}
}
+1
View File
@@ -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 }
+25
View File
@@ -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