From 25460623427cd2425bd1d617d8c24c6aac6df938 Mon Sep 17 00:00:00 2001 From: Adam Perry Date: Wed, 24 Jun 2026 19:18:19 +0000 Subject: [PATCH] test: add bwrap-exec integration variants --- bazel/rules/testing/bwrap/defs.bzl | 7 ++ codex-rs/core/tests/common/lib.rs | 21 ++++++ codex-rs/core/tests/common/test_codex.rs | 13 ++-- .../core/tests/common/test_environment.rs | 30 ++++++-- .../tests/common/test_environment_tests.rs | 12 ++- codex-rs/exec-server/testing/BUILD.bazel | 16 ++++ .../testing/bwrap_remote_test_runner.rs | 73 +++++++++++++++++++ defs.bzl | 47 +++++++++++- 8 files changed, 203 insertions(+), 16 deletions(-) create mode 100644 codex-rs/exec-server/testing/bwrap_remote_test_runner.rs diff --git a/bazel/rules/testing/bwrap/defs.bzl b/bazel/rules/testing/bwrap/defs.bzl index 4e0e6f7aab..e2e00a4b14 100644 --- a/bazel/rules/testing/bwrap/defs.bzl +++ b/bazel/rules/testing/bwrap/defs.bzl @@ -4,3 +4,10 @@ BWRAP_EXEC_PROPERTIES = { # A fresh VM isolates the deliberately writable outer namespace and permits nested user namespaces. "test.workload-isolation-type": "firecracker", } + +BWRAP_INTEGRATION_TEST_EXEC_PROPERTIES = BWRAP_EXEC_PROPERTIES | { + # Round the full core/app-server runfiles plus per-test scratch space up to the 10 GB RBE tier. + "test.EstimatedFreeDiskBytes": "10GB", + # Round the overlapping Codex, exec-server, and test processes up to the 8 GB RBE tier. + "test.EstimatedMemory": "8GB", +} diff --git a/codex-rs/core/tests/common/lib.rs b/codex-rs/core/tests/common/lib.rs index 29ed4875e0..7005eabe58 100644 --- a/codex-rs/core/tests/common/lib.rs +++ b/codex-rs/core/tests/common/lib.rs @@ -38,6 +38,8 @@ pub mod zsh_fork; pub(crate) use test_environment::TestEnvironment; pub use test_environment::TestTargetOs; +#[doc(hidden)] +pub use test_environment::is_bwrap_exec_test_environment; pub use test_environment::is_remote_test_environment; #[doc(hidden)] pub use test_environment::is_wine_exec_test_environment; @@ -616,6 +618,25 @@ macro_rules! skip_if_remote { }}; } +#[macro_export] +macro_rules! skip_if_bwrap_exec { + ($reason:expr $(,)?) => {{ + $crate::skip_if_test_condition!( + $crate::is_bwrap_exec_test_environment(), + "the bwrap-exec test environment", + $reason, + ); + }}; + ($return_value:expr, $reason:expr $(,)?) => {{ + $crate::skip_if_test_condition!( + $return_value, + $crate::is_bwrap_exec_test_environment(), + "the bwrap-exec test environment", + $reason, + ); + }}; +} + #[macro_export] macro_rules! skip_if_no_remote_env { () => {{ diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index b95a003c5b..f26cfcd6ba 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -184,7 +184,9 @@ impl Drop for TestEnv { pub async fn test_env() -> Result { match test_environment() { - remote_env @ (TestEnvironment::Docker { .. } | TestEnvironment::WineExec) => { + remote_env @ (TestEnvironment::Docker { .. } + | TestEnvironment::BwrapExec + | TestEnvironment::WineExec) => { let websocket_url = remote_exec_server_url()?; let environment = codex_exec_server::Environment::create_for_tests(Some(websocket_url.clone()))?; @@ -439,10 +441,11 @@ impl TestCodexBuilder { /// Builds a test runtime using the execution environment selected by the test process. /// /// With no remote test configuration, or with `CODEX_TEST_ENVIRONMENT=local`, this uses a - /// temporary local environment just like [`Self::build`]. `CODEX_TEST_ENVIRONMENT=docker` or - /// `CODEX_TEST_ENVIRONMENT=wine-exec` selects the remote exec server configured by - /// `CODEX_TEST_REMOTE_EXEC_SERVER_URL`; the legacy `CODEX_TEST_REMOTE_ENV` Docker-container - /// configuration does the same. Only the automatically selected environment is registered. + /// temporary local environment just like [`Self::build`]. `CODEX_TEST_ENVIRONMENT=docker`, + /// `CODEX_TEST_ENVIRONMENT=bwrap-exec`, or `CODEX_TEST_ENVIRONMENT=wine-exec` selects the remote + /// exec server configured by `CODEX_TEST_REMOTE_EXEC_SERVER_URL`; the legacy + /// `CODEX_TEST_REMOTE_ENV` Docker-container configuration does the same. Only the automatically + /// selected environment is registered. /// Use [`Self::build_with_remote_and_local_env`] when a remote test also needs the local /// environment to be selectable explicitly. pub async fn build_with_auto_env( diff --git a/codex-rs/core/tests/common/test_environment.rs b/codex-rs/core/tests/common/test_environment.rs index b170da1d38..df0cf6bea1 100644 --- a/codex-rs/core/tests/common/test_environment.rs +++ b/codex-rs/core/tests/common/test_environment.rs @@ -41,6 +41,7 @@ impl TestTargetOs { pub(crate) enum TestEnvironment { Local, Docker { container_name: String }, + BwrapExec, WineExec, } @@ -52,14 +53,14 @@ impl TestEnvironment { pub(crate) fn docker_container_name(&self) -> Option<&str> { match self { Self::Docker { container_name } => Some(container_name), - Self::Local | Self::WineExec => None, + Self::Local | Self::BwrapExec | Self::WineExec => None, } } pub(crate) const fn target_os(&self) -> TestTargetOs { match self { Self::Local => TestTargetOs::host(), - Self::Docker { .. } => TestTargetOs::Linux, + Self::Docker { .. } | Self::BwrapExec => TestTargetOs::Linux, Self::WineExec => TestTargetOs::Windows, } } @@ -67,7 +68,7 @@ impl TestEnvironment { pub(crate) fn remote_cwd(&self, instance_id: &str) -> Result> { let path_uri = match self { Self::Local => return Ok(None), - Self::Docker { .. } => { + Self::Docker { .. } | Self::BwrapExec => { PathUri::parse(&format!("file:///tmp/codex-core-test-cwd-{instance_id}"))? } Self::WineExec => { @@ -95,8 +96,16 @@ pub(crate) fn test_environment() -> TestEnvironment { ) .expect("invalid test environment configuration"); - if matches!(environment, TestEnvironment::WineExec) && !cfg!(target_os = "linux") { - panic!("{TEST_ENVIRONMENT_ENV_VAR}=wine-exec is only supported on Linux"); + if !cfg!(target_os = "linux") { + match &environment { + TestEnvironment::BwrapExec => { + panic!("{TEST_ENVIRONMENT_ENV_VAR}=bwrap-exec is only supported on Linux"); + } + TestEnvironment::WineExec => { + panic!("{TEST_ENVIRONMENT_ENV_VAR}=wine-exec is only supported on Linux"); + } + TestEnvironment::Local | TestEnvironment::Docker { .. } => {} + } } environment @@ -117,10 +126,16 @@ pub fn is_remote_test_environment() -> bool { pub fn test_docker_container_name() -> Option { match test_environment() { TestEnvironment::Docker { container_name } => Some(container_name), - TestEnvironment::Local | TestEnvironment::WineExec => None, + TestEnvironment::Local | TestEnvironment::BwrapExec | TestEnvironment::WineExec => None, } } +/// Returns whether the bubblewrap-backed Linux executor is selected. +#[doc(hidden)] +pub fn is_bwrap_exec_test_environment() -> bool { + matches!(test_environment(), TestEnvironment::BwrapExec) +} + /// Returns whether the Wine-backed executor is selected. #[doc(hidden)] pub fn is_wine_exec_test_environment() -> bool { @@ -164,9 +179,10 @@ fn parse_test_environment( container_name: non_empty_utf8(container_name_env_var, container_name)?, }) } + Some("bwrap-exec") => Ok(TestEnvironment::BwrapExec), Some("wine-exec") => Ok(TestEnvironment::WineExec), Some(value) => Err(format!( - "{TEST_ENVIRONMENT_ENV_VAR} must be one of local, docker, or wine-exec; got {value:?}" + "{TEST_ENVIRONMENT_ENV_VAR} must be one of local, docker, bwrap-exec, or wine-exec; got {value:?}" )), } } diff --git a/codex-rs/core/tests/common/test_environment_tests.rs b/codex-rs/core/tests/common/test_environment_tests.rs index eaaa225d51..724eb5cfb4 100644 --- a/codex-rs/core/tests/common/test_environment_tests.rs +++ b/codex-rs/core/tests/common/test_environment_tests.rs @@ -35,6 +35,14 @@ fn parses_each_explicit_environment() { container_name: "container-1".to_string(), }) ); + assert_eq!( + parse_test_environment( + Some(OsStr::new("bwrap-exec")), + /*legacy_remote_environment*/ None, + /*docker_container*/ None, + ), + Ok(TestEnvironment::BwrapExec) + ); assert_eq!( parse_test_environment( Some(OsStr::new("wine-exec")), @@ -112,7 +120,7 @@ fn rejects_invalid_or_incomplete_configuration() { /*docker_container*/ None, ), Err(format!( - "{TEST_ENVIRONMENT_ENV_VAR} must be one of local, docker, or wine-exec; got \"other\"" + "{TEST_ENVIRONMENT_ENV_VAR} must be one of local, docker, bwrap-exec, or wine-exec; got \"other\"" )) ); } @@ -131,6 +139,7 @@ fn derives_target_operating_system_and_placement() { TestEnvironment::Docker { container_name: "container-1".to_string(), }, + TestEnvironment::BwrapExec, TestEnvironment::WineExec, ]; @@ -139,6 +148,7 @@ fn derives_target_operating_system_and_placement() { [ (expected_local_target_os, false), (TestTargetOs::Linux, true), + (TestTargetOs::Linux, true), (TestTargetOs::Windows, true), ] ); diff --git a/codex-rs/exec-server/testing/BUILD.bazel b/codex-rs/exec-server/testing/BUILD.bazel index 66d98b2370..52fddab750 100644 --- a/codex-rs/exec-server/testing/BUILD.bazel +++ b/codex-rs/exec-server/testing/BUILD.bazel @@ -21,6 +21,22 @@ rust_library( ], ) +rust_binary( + name = "bwrap-exec-test-runner", + testonly = True, + srcs = ["bwrap_remote_test_runner.rs"], + crate_name = "bwrap_exec_test_runner", + crate_root = "bwrap_remote_test_runner.rs", + target_compatible_with = ["@platforms//os:linux"], + visibility = ["//visibility:public"], + deps = [ + ":bwrap-exec-server-test-support", + "//codex-rs/utils/cargo-bin", + "@crates//:anyhow", + "@crates//:tokio", + ], +) + rust_binary( name = "bwrap-exec-smoke", testonly = True, diff --git a/codex-rs/exec-server/testing/bwrap_remote_test_runner.rs b/codex-rs/exec-server/testing/bwrap_remote_test_runner.rs new file mode 100644 index 0000000000..6d0e9de727 --- /dev/null +++ b/codex-rs/exec-server/testing/bwrap_remote_test_runner.rs @@ -0,0 +1,73 @@ +use std::ffi::OsStr; +use std::ffi::OsString; +use std::path::PathBuf; +use std::process::Stdio; + +use anyhow::Context; +use anyhow::Result; +use bwrap_exec_server_test_support::BwrapExecServer; +use tokio::process::Command; + +const TEST_BINARY_ENV_VAR: &str = "CODEX_BWRAP_EXEC_TEST_BINARY"; +const TEST_ENVIRONMENT_ENV_VAR: &str = "CODEX_TEST_ENVIRONMENT"; +const REMOTE_EXEC_SERVER_URL_ENV_VAR: &str = "CODEX_TEST_REMOTE_EXEC_SERVER_URL"; +const LEGACY_REMOTE_ENV_ENV_VAR: &str = "CODEX_TEST_REMOTE_ENV"; +const DOCKER_CONTAINER_ENV_VAR: &str = "CODEX_TEST_REMOTE_ENV_CONTAINER_NAME"; + +#[tokio::main(flavor = "multi_thread", worker_threads = 2)] +async fn main() -> Result<()> { + let test_binary = PathBuf::from( + std::env::var_os(TEST_BINARY_ENV_VAR) + .with_context(|| format!("{TEST_BINARY_ENV_VAR} must be set by the Bazel test rule"))?, + ); + let forwarded_args = std::env::args_os().skip(1).collect::>(); + let bwrap = codex_utils_cargo_bin::cargo_bin("bwrap")?; + let bwrap_dir = bwrap.parent().context("bwrap runfile has no parent")?; + let mut path_entries = vec![bwrap_dir.to_path_buf()]; + if let Some(path) = std::env::var_os("PATH") { + path_entries.extend(std::env::split_paths(&path)); + } + let path = std::env::join_paths(path_entries).context("build bwrap integration-test PATH")?; + + if is_terse_list_request(&forwarded_args) { + let status = Command::new(&test_binary) + .args(&forwarded_args) + .status() + .await + .context("list integration tests")?; + anyhow::ensure!( + status.success(), + "listing integration tests exited with {status}" + ); + return Ok(()); + } + + BwrapExecServer + .scope(|exec_server_url| async move { + let mut command = Command::new(test_binary); + command + .env(TEST_ENVIRONMENT_ENV_VAR, "bwrap-exec") + .env(REMOTE_EXEC_SERVER_URL_ENV_VAR, exec_server_url) + .env("PATH", path) + .env_remove(LEGACY_REMOTE_ENV_ENV_VAR) + .env_remove(DOCKER_CONTAINER_ENV_VAR) + .args(forwarded_args) + .stdin(Stdio::null()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .kill_on_drop(true); + + let status = command.status().await.context("run integration tests")?; + anyhow::ensure!(status.success(), "integration tests exited with {status}"); + Ok(()) + }) + .await +} + +fn is_terse_list_request(args: &[OsString]) -> bool { + args.iter().map(OsString::as_os_str).eq([ + OsStr::new("--list"), + OsStr::new("--format"), + OsStr::new("terse"), + ]) +} diff --git a/defs.bzl b/defs.bzl index 8eb70ed9e4..b555f383f1 100644 --- a/defs.bzl +++ b/defs.bzl @@ -3,6 +3,7 @@ load("@crates//:defs.bzl", "all_crate_deps") load("@rules_rust//cargo/private:cargo_build_script_wrapper.bzl", "cargo_build_script") load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library", "rust_proc_macro", "rust_test") load("//bazel/rules/testing:foreign_platform_binary.bzl", "foreign_platform_binary") +load("//bazel/rules/testing/bwrap:defs.bzl", "BWRAP_INTEGRATION_TEST_EXEC_PROPERTIES") load("//bazel/rules/testing/wine:wine_runtime.bzl", "WINE_TEST_TARGET_COMPATIBLE_WITH", "wine_test_runtime") # Match Cargo's Windows linker behavior so Bazel-built binaries and tests use @@ -201,6 +202,7 @@ def codex_rust_crate( unit_test_timeout = None, extra_binaries = [], extra_binaries_non_windows = [], + run_tests_with_bwrap_exec = False, run_tests_with_wine_exec = False): """Defines a Rust crate with library, binaries, and tests wired for Bazel + Cargo parity. @@ -249,6 +251,10 @@ def codex_rust_crate( extra_binaries_non_windows: Like `extra_binaries`, but omitted from Windows test data and environment variables. Tests using these binaries must be excluded when targeting Windows. + run_tests_with_bwrap_exec: Boolean, defaults to False. Whether to emit + a bwrap-exec variant for each integration test. Variants inherit + the native test's timeout and shard count, but intentionally do + not inherit its tags so they run under Bazel sandboxing. run_tests_with_wine_exec: Boolean, defaults to False. Whether to emit a Wine-exec variant for each integration test. Variants inherit the native test's timeout, tags, and shard count. @@ -416,7 +422,7 @@ def codex_rust_crate( "//conditions:default": cargo_env_runfiles | non_windows_cargo_env_runfiles, }) - wine_host_binaries = { + host_test_binaries = { env_var.removeprefix("CARGO_BIN_EXE_"): binary_label for binary_label, env_var in (cargo_env_runfiles | non_windows_cargo_env_runfiles).items() } @@ -449,7 +455,7 @@ def codex_rust_crate( integration_test_binary = test_name + "-bin" - # There are four generated integration-test shapes: + # There are five generated integration-test shapes: # # 1. Unsharded native tests keep the plain rust_test label for minimal # churn and the usual rules_rust Cargo-like environment. @@ -466,6 +472,10 @@ def codex_rust_crate( # owns cleanup. The outer workspace_root_test resolves the runner, # test, and server from runfiles, sets a Cargo-like cwd, and applies # the native test's shard count. + # 5. Bwrap-exec tests also reuse the native Rust test binary behind a + # shared Linux runner. The runner starts a native exec server in an + # outer bubblewrap namespace, while the public test action alone is + # assigned to a fresh Firecracker VM under RBE. if test_shard_count: # This target is intentionally a binary-like helper, not the public # test target. The wrapper below owns cwd setup, runfile env @@ -534,7 +544,7 @@ def codex_rust_crate( if run_tests_with_wine_exec: wine_test_name = test_name.removesuffix("-test") + "-wine-exec-test" native_test_binary = ":" + (integration_test_binary if test_shard_count else test_name) - wine_test_binaries = dict(wine_host_binaries) + wine_test_binaries = dict(host_test_binaries) wine_exec_server = wine_test_name + "-windows-exec-server" foreign_platform_binary( @@ -578,6 +588,37 @@ def codex_rust_crate( **wine_test_kwargs ) + if run_tests_with_bwrap_exec: + bwrap_test_name = test_name.removesuffix("-test") + "-bwrap-exec-test" + native_test_binary = ":" + (integration_test_binary if test_shard_count else test_name) + bwrap_runfile_env = { + binary_label: "CARGO_BIN_EXE_" + binary_name + for binary_name, binary_label in host_test_binaries.items() + } + bwrap_runfile_env["//codex-rs/bwrap:bwrap"] = "CARGO_BIN_EXE_bwrap" + bwrap_runfile_env["//codex-rs/cli:codex"] = "CARGO_BIN_EXE_codex" + bwrap_runfile_env[native_test_binary] = "CODEX_BWRAP_EXEC_TEST_BINARY" + + bwrap_test_kwargs = {} + bwrap_test_kwargs.update(integration_test_kwargs) + if test_shard_count: + bwrap_test_kwargs["shard_count"] = test_shard_count + bwrap_test_kwargs["flaky"] = True + + workspace_root_test( + name = bwrap_test_name, + env = test_env | {"RUST_TEST_THREADS": "1"}, + runfile_env = bwrap_runfile_env, + test_bin = "//codex-rs/exec-server/testing:bwrap-exec-test-runner", + workspace_root_marker = "//codex-rs/utils/cargo-bin:repo_root.marker", + # These apply only to the test action. Builds and every other + # test keep their normal execution environment. + exec_properties = BWRAP_INTEGRATION_TEST_EXEC_PROPERTIES, + tags = ["no-argument-comment-lint"], + target_compatible_with = ["@platforms//os:linux"], + **bwrap_test_kwargs + ) + windows_cross_test_kwargs = {} windows_cross_test_kwargs.update(integration_test_kwargs) if test_shard_count: