Make Bazel Rust tests portable across Linux environments (#63773)

## Why

Some test fixtures depend on `python3` being on the host's `PATH` or
on reading Rust's process arguments from a constructor. Bazel workers
need a declared Python runtime, and musl does not provide those
arguments to constructors.

## What changed

- Put Bazel's Python 3.12 runtime on `PATH` for Linux test suites that
  invoke `python3`, including their Wine launchers.
- Use standalone helper binaries for exec-server and sandbox fixtures on
  musl, and read `/proc/self/cmdline` for the MCP hook fixture.
- Add launcher options for test execution tags and for routing selected
  Linux cases to a local companion target that shares the test binary.
- Adjust test fixtures for platform differences in file creation
  timestamps and shell script execution. Keep cloud-config error tests
  pointed at their mock server after startup falls back to defaults.

## Testing

Exercise marketplace upgrade negotiation at Git 2.20 and check whether
the installed Git supports limiting the refs advertised by the clone.

GitOrigin-RevId: 3a83cde954d52ca29d346d67488c9a25c0790614
This commit is contained in:
Dmitriy Kovalenko
2026-11-24 23:57:49 +00:00
committed by copyberry
parent e1492bd86d
commit 17b00277cc
30 changed files with 306 additions and 52 deletions
@@ -6,7 +6,8 @@ def exec_server_compat_test(
name,
comparison_binary = None,
current_binary = "//codex-rs/cli:codex",
release = None):
release = None,
tags = []):
"""Tests both executor directions against another Codex build or release.
Args:
@@ -14,6 +15,7 @@ def exec_server_compat_test(
comparison_binary: Built Codex executable to compare with the current build.
current_binary: Built Codex executable representing the current version.
release: External release repository exposing `:codex` and `:package`.
tags: Additional Bazel tags for the generated test target.
"""
if (comparison_binary == None) == (release == None):
fail("exactly one of comparison_binary and release must be set")
@@ -37,7 +39,7 @@ def exec_server_compat_test(
current_binary: "CODEX_TEST_CURRENT_CODEX",
":" + comparison_alias: "CODEX_TEST_RELEASED_CODEX",
},
tags = ["no-sandbox"],
tags = ["no-sandbox"] + tags,
target_compatible_with = [
"@platforms//cpu:x86_64",
"@platforms//os:linux",
+2
View File
@@ -8,11 +8,13 @@ codex_rust_crate(
"//codex-rs/bwrap:bwrap",
"//codex-rs/cli:codex",
"//codex-rs/code-mode-host:codex-code-mode-host",
"//codex-rs/linux-sandbox:codex-linux-sandbox",
"//codex-rs/message-board-mcp:codex-message-board-mcp",
"//codex-rs/rmcp-client:test_stdio_server",
],
integration_compile_data_extra = ["//codex-rs/message-board:tests/common/mod.rs"],
integration_test_timeout = "long",
linux_python_tests = ["app-server-all-test"],
run_tests_with_wine_exec = True,
test_shard_counts = {
# Note app-server-all-test has a large number of integration tests, so
@@ -526,6 +526,7 @@ async fn marketplace_upgrade_named_marketplace_only() -> Result<()> {
Ok(())
}
#[cfg_attr(unix, test_case(Some("git version 2.20.0"); "released Git"))]
#[cfg_attr(unix, test_case(Some("git version 2.19.6"); "older Git"))]
#[cfg_attr(unix, test_case(Some("unknown"); "unknown Git version"))]
#[test_case(None; "installed Git")]
@@ -535,6 +536,11 @@ async fn marketplace_upgrade_reuses_the_installed_revision_when_git_supports_it(
) -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
let supports_alternate_refs = run_git(source.path(), &["help", "--config"])
.is_ok_and(|keys| keys.lines().any(|key| key == "core.alternateRefsCommand"));
// Only present a Git that can limit advertised refs as a supported release.
let reported_version = reported_version
.filter(|version| *version != "git version 2.20.0" || supports_alternate_refs);
let installed_revision = init_marketplace_repo(source.path(), "debug", "debug old")?;
// file:// exercises fetch negotiation even though the server is local.
let url = url::Url::from_directory_path(source.path())
@@ -619,12 +625,28 @@ PATH=$TEST_GIT_PATH exec git "$@"
updated_revision
);
let packets = std::fs::read_to_string(packets)?;
let can_reuse = reported_version.is_none()
&& run_git(source.path(), &["help", "--config"])
.is_ok_and(|keys| keys.lines().any(|key| key == "core.alternateRefsCommand"));
// A custom build can advertise the option but have an unrecognized
// version. Codex must use a plain clone for those builds.
let installed_version = run_git(source.path(), &["--version"])?;
let version = reported_version.unwrap_or(&installed_version);
let release = version
.strip_prefix("git version ")
.and_then(|v| v.split_ascii_whitespace().next())
.unwrap_or_default();
let release = match release.split_once(".windows.") {
Some((release, build)) if build.parse::<u32>().is_ok() => release,
_ => release,
};
let parts = release
.split('.')
.map(str::parse::<u32>)
.collect::<Vec<_>>();
let can_reuse = supports_alternate_refs
&& matches!(parts.as_slice(), [Ok(major), Ok(minor), Ok(_)] if (*major, *minor) >= (2, 20));
assert_eq!(
packets.contains(&format!("have {installed_revision}")),
can_reuse
can_reuse,
"negotiating with {version}"
);
assert!(!packets.contains(&format!("have {private_revision}")));
assert!(!root.join(".git/objects/info/alternates").exists());
@@ -2449,6 +2449,8 @@ async fn thread_fork_surfaces_cloud_config_bundle_load_errors() -> Result<()> {
let refresh_token_url = format!("{}/oauth/token", server.uri());
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
// Startup falls back to defaults after the 401 and ignores config.toml.
.with_args(&["-c", &format!("chatgpt_base_url={chatgpt_base_url:?}")])
.without_auto_env()
.with_env_overrides(&[
("OPENAI_API_KEY", None),
@@ -6630,6 +6630,8 @@ async fn thread_resume_surfaces_cloud_config_bundle_load_errors() -> Result<()>
let refresh_token_url = format!("{}/oauth/token", server.uri());
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
// Startup falls back to defaults after the 401 and ignores config.toml.
.with_args(&["-c", &format!("chatgpt_base_url={chatgpt_base_url:?}")])
.with_env_overrides(&[
("OPENAI_API_KEY", None),
(
@@ -1665,6 +1665,8 @@ async fn config_requests_surface_cloud_config_bundle_load_errors(
let refresh_token_url = format!("{}/oauth/token", server.uri());
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
// Startup falls back to defaults after the 401 and ignores config.toml.
.with_args(&["-c", &format!("chatgpt_base_url={chatgpt_base_url:?}")])
.with_env_overrides(&[
("OPENAI_API_KEY", None),
(
+4
View File
@@ -24,6 +24,10 @@ codex_rust_crate(
"//codex-rs/prompts:templates/permissions/approval_policy/on_request_rule_request_permission.md",
],
integration_test_timeout = "long",
linux_python_tests = [
"core-all-test",
"core-unit-tests",
],
run_tests_with_wine_exec = True,
rustc_env = {
# Keep manifest-root path lookups inside the Bazel execroot for code
+14
View File
@@ -83,6 +83,20 @@ struct McpPermissionRequestHookFixture {
#[ctor]
fn maybe_run_mcp_permission_request_hook_fixture() {
// musl does not pass argv to constructors. The hook subprocess must
// recognize its fixture command before libtest parses the arguments.
#[cfg(all(target_os = "linux", target_env = "musl"))]
let cmdline = std::fs::read("/proc/self/cmdline").expect("read hook fixture arguments");
#[cfg(all(target_os = "linux", target_env = "musl"))]
let mut args = {
use std::os::unix::ffi::OsStrExt;
cmdline
.strip_suffix(&[0])
.unwrap_or(&cmdline)
.split(|byte| *byte == 0)
.map(|arg| std::ffi::OsStr::from_bytes(arg).to_owned())
};
#[cfg(not(all(target_os = "linux", target_env = "musl")))]
let mut args = std::env::args_os();
let _program = args.next();
if args.next().as_deref()
+16
View File
@@ -257,8 +257,24 @@ fn default_test_overrides() -> ConfigOverrides {
ConfigOverrides::default()
}
// On musl the test binary cannot dispatch helper arguments before libtest
// starts. Use the CLI and sandbox binaries that Bazel provides as runfiles.
pub fn exec_server_helper_exe() -> std::io::Result<PathBuf> {
if cfg!(target_env = "musl")
&& let Ok(exe) = codex_utils_cargo_bin::cargo_bin("codex")
{
return Ok(exe);
}
std::env::current_exe()
}
#[cfg(target_os = "linux")]
pub fn find_codex_linux_sandbox_exe() -> Result<PathBuf, CargoBinError> {
if cfg!(target_env = "musl")
&& let Ok(exe) = codex_utils_cargo_bin::cargo_bin("codex-linux-sandbox")
{
return Ok(exe);
}
if let Some(path) = TEST_ARG0_PATH_ENTRY
.get()
.and_then(Option::as_ref)
+1 -1
View File
@@ -824,7 +824,7 @@ impl TestCodexBuilder {
#[cfg(not(target_os = "linux"))]
let codex_linux_sandbox_exe = None;
let local_runtime_paths = codex_exec_server::ExecServerRuntimeOptions::new(
std::env::current_exe()?,
crate::exec_server_helper_exe()?,
codex_linux_sandbox_exe,
)?;
let environment_manager = Arc::new(if include_local_environment {
+1 -1
View File
@@ -1289,7 +1289,7 @@ async fn executor_stop_hook_rejects_mismatched_environment() -> Result<()> {
let executor_url = format!("ws://{executor_address}");
drop(listener);
let runtime_paths = ExecServerRuntimeOptions::new(
std::env::current_exe()?,
core_test_support::exec_server_helper_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?;
let http_client_factory = fixture.test.config.http_client_factory();
@@ -666,9 +666,12 @@ PY"#
assert!(elapsed.parse::<u128>()? > 0);
let message = &output[output.find(prefix).context("missing disconnect prefix")?..];
let message = &message[..prefix.len() + elapsed.len() + suffix.len()];
insta::assert_snapshot!(message.replacen(elapsed, "<elapsed>", 1), @r"
Network request disconnected after <elapsed> ms, before approval could complete
");
// Plain HTTP and CONNECT report the same failure in the same test process.
insta::allow_duplicates! {
insta::assert_snapshot!(message.replacen(elapsed, "<elapsed>", 1), @r"
Network request disconnected after <elapsed> ms, before approval could complete
");
}
Ok(())
}
+1 -1
View File
@@ -2714,7 +2714,7 @@ async fn ready_before_selection_resolves_resumed_thread_capability_root_after_wa
.await;
let runtime_paths = ExecServerRuntimeOptions::new(
std::env::current_exe()?,
core_test_support::exec_server_helper_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?;
let remote_config = RemoteEnvironmentConfig::new(
@@ -3643,7 +3643,7 @@ async fn production_turn_keeps_rebalanced_catalogs_stable_after_compaction_and_r
let executor_url = format!("ws://{executor_address}");
drop(listener);
let runtime_paths = codex_exec_server::ExecServerRuntimeOptions::new(
std::env::current_exe()?,
core_test_support::exec_server_helper_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?;
let http_client_factory = test.config.http_client_factory();
@@ -63,7 +63,7 @@ async fn executor_discovery_uses_current_environment_grants(
#[cfg(not(target_os = "linux"))]
let sandbox_exe = None;
let runtime_paths = codex_exec_server::ExecServerRuntimeOptions::new(
std::env::current_exe()?,
core_test_support::exec_server_helper_exe()?,
sandbox_exe,
)?;
codex_mcp_extension::install_plugins(
+30
View File
@@ -1,3 +1,4 @@
load("@rules_rust//rust:defs.bzl", "rust_binary")
load("//:defs.bzl", "codex_rust_crate")
load("//bazel/rules/testing/compat:exec_server_compat_test.bzl", "exec_server_compat_test")
@@ -25,10 +26,39 @@ codex_rust_crate(
# process-global test-binary dispatch state, and the remote exec-server
# cases already rely on serialization around the full CLI path.
integration_test_args = ["--test-threads=1"],
test_data_extra = [":musl-test-helper"],
test_tags = ["no-sandbox"],
unit_test_args = ["--test-threads=1"],
)
filegroup(
name = "musl-test-helper",
testonly = True,
srcs = select({
"@llvm//constraints/libc:musl": [":exec-server-test-helper"],
"//conditions:default": [],
}),
)
rust_binary(
name = "exec-server-test-helper",
testonly = True,
srcs = ["tests/common/mod.rs"],
crate_root = "tests/common/mod.rs",
edition = "2024",
target_compatible_with = ["@llvm//constraints/libc:musl"],
deps = [
":exec-server",
"//codex-rs/build-info",
"//codex-rs/http-client",
"//codex-rs/sandboxing",
"//codex-rs/test-binary-support",
"//codex-rs/websocket-auth",
"@crates//tokio",
"@crates//tracing-subscriber",
],
)
exec_server_compat_test(
name = "exec-server-current-version-test",
comparison_binary = "//codex-rs/cli:codex",
+21 -4
View File
@@ -17,8 +17,8 @@ use codex_sandboxing::linux::CODEX_LINUX_SANDBOX_ARG0;
use codex_test_binary_support::TestBinaryDispatchGuard;
use codex_test_binary_support::TestBinaryDispatchMode;
use codex_test_binary_support::configure_test_binary_dispatch;
use ctor::ctor;
#[cfg(test)]
pub(crate) mod exec_server;
pub(crate) const TEST_BUILD_COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
@@ -42,8 +42,19 @@ macro_rules! skip_if_mxc_unavailable {
}};
}
#[ctor]
pub static TEST_BINARY_DISPATCH_GUARD: Option<TestBinaryDispatchGuard> = {
#[cfg(test)]
#[ctor::ctor]
pub static TEST_BINARY_DISPATCH_GUARD: Option<TestBinaryDispatchGuard> = { dispatch() };
// On musl, Rust's argv is unavailable in a constructor. Bazel builds the
// same dispatch code as a child executable so it runs after Rust initializes.
#[cfg(not(test))]
fn main() {
let _guard = dispatch();
panic!("expected an exec-server test helper command");
}
fn dispatch() -> Option<TestBinaryDispatchGuard> {
let guard = configure_test_binary_dispatch("codex-exec-server-tests", |exe_name, argv1| {
if argv1 == Some(CODEX_ARG0_EXEC_HELPER_ARG1) {
return TestBinaryDispatchMode::DispatchArg0Only;
@@ -65,9 +76,15 @@ pub static TEST_BINARY_DISPATCH_GUARD: Option<TestBinaryDispatchGuard> = {
maybe_run_delayed_output_after_exit_from_test_binary();
maybe_run_exec_server_from_test_binary(guard.as_ref());
guard
};
}
#[cfg(test)]
pub(crate) fn current_test_binary_helper_paths() -> anyhow::Result<(PathBuf, Option<PathBuf>)> {
#[cfg(target_env = "musl")]
if option_env!("BAZEL_PACKAGE").is_some() {
let helper = codex_utils_cargo_bin::find_resource!("exec-server-test-helper")?;
return Ok((helper.clone(), Some(helper)));
}
let current_exe = env::current_exe()?;
let codex_linux_sandbox_exe = if cfg!(target_os = "linux") {
TEST_BINARY_DISPATCH_GUARD
+17 -1
View File
@@ -311,7 +311,23 @@ async fn file_system_no_follow_metadata_preserves_linux_birthtime(
Ok(created) => Some(i64::try_from(
created.duration_since(UNIX_EPOCH)?.as_millis(),
)?),
Err(error) if error.kind() == std::io::ErrorKind::Unsupported => None,
// On musl, std may lack birth times even when the kernel provides one.
Err(error) if error.kind() == std::io::ErrorKind::Unsupported => {
use rustix::fs::AtFlags;
use rustix::fs::CWD;
use rustix::fs::StatxFlags;
use rustix::fs::statx;
use rustix::io::Errno;
match statx(CWD, &file, AtFlags::empty(), StatxFlags::BTIME) {
Ok(stat) if stat.stx_mask & StatxFlags::BTIME.bits() != 0 => {
let time = stat.stx_btime;
Some(time.tv_sec * 1000 + i64::from(time.tv_nsec / 1_000_000))
}
Ok(_) | Err(Errno::NOSYS | Errno::PERM) => None,
Err(error) => return Err(error.into()),
}
}
Err(error) => return Err(error.into()),
};
+2 -1
View File
@@ -29,7 +29,8 @@ async fn exec_server_accepts_initialize(version: Option<&str>) -> anyhow::Result
let bin_dir = package.path().join("bin");
std::fs::create_dir(&bin_dir)?;
let executable = bin_dir.join(format!("codex{}", std::env::consts::EXE_SUFFIX));
codex_utils_cargo_bin::copy_executable(&std::env::current_exe()?, &executable)?;
let (helper, _) = common::current_test_binary_helper_paths()?;
codex_utils_cargo_bin::copy_executable(&helper, &executable)?;
let manifest = package.path().join("codex-package.json");
if let Some(version) = version {
std::fs::write(
+1
View File
@@ -3,4 +3,5 @@ load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "queue",
crate_name = "codex_queue_extension",
linux_python_tests = ["queue-queue_service-test"],
)
@@ -1,4 +1,6 @@
use super::super::*;
use crate::migration_source::MarketplaceImportSource;
use crate::source_cla;
use pretty_assertions::assert_eq;
#[tokio::test]
@@ -482,20 +484,47 @@ async fn import_plugins_supports_relative_external_agent_plugin_marketplace_path
async fn import_plugins_infers_external_official_marketplace_when_missing_from_settings() {
let (_root, external_agent_home, codex_home) = fixture_paths();
fs::create_dir_all(&external_agent_home).expect("create external agent home");
fs::create_dir_all(&codex_home).expect("create codex home");
let settings = serde_json::json!({
"enabledPlugins": { (format!("sample@{EXTERNAL_OFFICIAL_MARKETPLACE_NAME}")): true }
});
let sources = source_cla::marketplace_import_sources(
&settings,
&external_agent_home,
&external_agent_home,
);
assert_eq!(
sources.get(EXTERNAL_OFFICIAL_MARKETPLACE_NAME),
Some(&MarketplaceImportSource {
source: "anthropics/claude-plugins-official".to_string(),
ref_name: None,
})
);
fs::write(
external_agent_home.join("settings.json"),
format!(
r#"{{
"enabledPlugins": {{
"sample@{EXTERNAL_OFFICIAL_MARKETPLACE_NAME}": true
}}
}}"#
),
settings.to_string(),
)
.expect("write settings");
// Import against a local copy so the missing-plugin result is independent
// of network access and changes to the upstream catalog.
let marketplace = external_agent_home.join("plugins/marketplace");
let manifest_dir = marketplace.join(EXTERNAL_AGENT_PLUGIN_MANIFEST_DIR);
fs::create_dir_all(&manifest_dir).expect("create marketplace manifest dir");
fs::write(
manifest_dir.join("marketplace.json"),
serde_json::json!({"name": EXTERNAL_OFFICIAL_MARKETPLACE_NAME, "plugins": []}).to_string(),
)
.expect("write marketplace manifest");
fs::write(
external_agent_home.join(EXTERNAL_AGENT_KNOWN_MARKETPLACES_PATH),
serde_json::json!({
(EXTERNAL_OFFICIAL_MARKETPLACE_NAME): {"source": "directory", "path": marketplace}
})
.to_string(),
)
.expect("write local marketplace registry");
fs::create_dir_all(&codex_home).expect("create codex home");
let outcome = service_for_paths(external_agent_home, codex_home)
.import_plugins(
/*cwd*/ None,
+1
View File
@@ -10,5 +10,6 @@ codex_rust_crate(
compile_data = SCHEMA_FIXTURES,
crate_name = "codex_hooks",
integration_compile_data_extra = SCHEMA_FIXTURES,
linux_python_tests = ["hooks-unit-tests"],
test_data_extra = SCHEMA_FIXTURES,
)
+2
View File
@@ -5,4 +5,6 @@ codex_rust_crate(
compile_data = glob(["tests/fixtures/**"]),
crate_name = "codex_http_client",
integration_compile_data_extra = glob(["tests/fixtures/*.pem"]),
# The scoped tracing subscribers share a process-wide callsite registry.
unit_test_args = ["--test-threads=1"],
)
+1
View File
@@ -6,4 +6,5 @@ codex_rust_crate(
"templates/**",
]),
crate_name = "codex_memories_write",
linux_python_tests = ["write-unit-tests"],
)
+4
View File
@@ -6,4 +6,8 @@ codex_rust_crate(
extra_binaries = [
"//codex-rs/cli:codex",
],
linux_python_tests = [
"rmcp-client-stdio_descriptor_boundary-test",
"rmcp-client-stdio_stderr_cleanup-test",
],
)
@@ -90,14 +90,19 @@ for line in sys.stdin:
symlink(&python, temporary.path().join("python-fixture"))?;
let wrapper = temporary.path().join("executable-text");
// No shebang: exercise Command's shell fallback after native macOS spawn
// returns ENOEXEC, including the fallback descriptor cleanup.
codex_utils_cargo_bin::write_executable(&wrapper, "exec \"$@\"\n")?;
// musl execvp reports ENOEXEC for scripts without a shebang. On other
// platforms keep exercising the implicit shell fallback and its cleanup.
let script_body = if cfg!(target_env = "musl") {
"#!/bin/sh\nexec \"$@\"\n"
} else {
"exec \"$@\"\n"
};
codex_utils_cargo_bin::write_executable(&wrapper, script_body)?;
for (launch, program, mut args) in [
("absolute", python.clone().into_os_string(), Vec::new()),
("relative", OsString::from("./python-fixture"), Vec::new()),
(
"shell fallback",
"shell wrapper",
OsString::from("./executable-text"),
vec![python.clone().into_os_string()],
),
+2
View File
@@ -10,9 +10,11 @@ codex_rust_crate(
extra_binaries = [
"//codex-rs/bwrap:bwrap",
"//codex-rs/cli:codex",
"//codex-rs/linux-sandbox:codex-linux-sandbox",
"//codex-rs/rmcp-client:test_stdio_server",
],
integration_compile_data_extra = ["src/test_backend.rs"],
linux_python_tests = ["tui-all-test"],
rustc_flags_extra = MACOS_WEBRTC_RUSTC_LINK_FLAGS,
test_data_extra = glob([
"src/**/*.rs",
@@ -69,7 +69,10 @@ async fn open_in_codex_scenario() -> Result<()> {
let linux_sandbox_exe = None;
let environment = EnvironmentManager::create_for_tests_with_local(
/*exec_server_url*/ None,
ExecServerRuntimeOptions::new(std::env::current_exe()?, linux_sandbox_exe)?,
ExecServerRuntimeOptions::new(
core_test_support::exec_server_helper_exe()?,
linux_sandbox_exe,
)?,
)
.await;
app.environment_manager = Arc::new(environment);
+1
View File
@@ -3,4 +3,5 @@ load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "pty",
crate_name = "codex_utils_pty",
linux_python_tests = ["pty-unit-tests"],
)
+90 -18
View File
@@ -1,5 +1,6 @@
load("@crates//:data.bzl", "DEP_DATA")
load("@crates//:defs.bzl", "all_crate_deps")
load("@rules_python//python:py_runtime_info.bzl", "PyRuntimeInfo")
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")
@@ -67,6 +68,9 @@ def _workspace_root_test_impl(ctx):
)
runfiles = ctx.runfiles(files = [test_bin, workspace_root_marker]).merge(ctx.attr.test_bin[DefaultInfo].default_runfiles)
if ctx.attr.python_runtime:
python = ctx.attr.python_runtime[PyRuntimeInfo]
runfiles = runfiles.merge(ctx.runfiles(files = [python.interpreter], transitive_files = python.files))
for data_dep in ctx.attr.data:
runfiles = runfiles.merge(ctx.runfiles(files = data_dep[DefaultInfo].files.to_list()))
runfiles = runfiles.merge(data_dep[DefaultInfo].default_runfiles)
@@ -106,6 +110,12 @@ def _workspace_root_test_impl(ctx):
def _bash_runfile_env_exports(ctx):
lines = []
if ctx.attr.python_runtime:
interpreter = ctx.attr.python_runtime[PyRuntimeInfo].interpreter
lines.extend([
'python="$(resolve_runfile "{}")"'.format(_runfile_logical_path(interpreter)),
'export PATH="${python%/*}:$PATH"',
])
for runfile_dep, env_var in ctx.attr.runfile_env.items():
runfile = _runfile_env_file(runfile_dep)
lines.append('RUNFILE_ENV_ARGS+=("{}=$(resolve_runfile "{}")")'.format(env_var, _runfile_logical_path(runfile)))
@@ -140,15 +150,16 @@ def _runfile_logical_path(file):
return file.short_path.removeprefix("../")
def _bash_workspace_root_setup(ctx):
if not ctx.attr.chdir_workspace_root:
return ""
return 'export INSTA_WORKSPACE_ROOT="${workspace_root}"\ncd "${workspace_root}"'
setup = 'export INSTA_WORKSPACE_ROOT="${workspace_root}"'
if ctx.attr.chdir_workspace_root:
setup += '\ncd "${workspace_root}"'
return setup
def _windows_workspace_root_setup(ctx):
if not ctx.attr.chdir_workspace_root:
return ""
return """set "INSTA_WORKSPACE_ROOT=%workspace_root%"
cd /d "%workspace_root%" || exit /b 1"""
setup = 'set "INSTA_WORKSPACE_ROOT=%workspace_root%"'
if ctx.attr.chdir_workspace_root:
setup += '\ncd /d "%workspace_root%" || exit /b 1'
return setup
workspace_root_test = rule(
implementation = _workspace_root_test_impl,
@@ -163,6 +174,7 @@ workspace_root_test = rule(
),
"env": attr.string_dict(),
"env_inherit": attr.string_list(),
"python_runtime": attr.label(cfg = "exec", providers = [PyRuntimeInfo]),
"runfile_env": attr.label_keyed_string_dict(
allow_files = True,
cfg = "target",
@@ -221,13 +233,16 @@ def codex_rust_crate(
binary_unit_test_windows_runtime = None,
integration_test_timeout = None,
test_data_extra = [],
linux_python_tests = [],
test_shard_counts = {},
test_tags = [],
test_threads = 0,
unit_test_timeout = None,
extra_binaries = [],
extra_binaries_non_windows = [],
run_tests_with_wine_exec = False):
run_tests_with_wine_exec = False,
integration_test_tags = {},
local_linux_cases = {}):
"""Defines a Rust crate with library, binaries, and tests wired for Bazel + Cargo parity.
The macro mirrors Cargo conventions: it builds a library when `src/` exists,
@@ -283,8 +298,13 @@ def codex_rust_crate(
and then assigns each libtest case to a stable bucket by hashing
the test name. Matching tests are also marked flaky, which gives
them Bazel's default three attempts.
linux_python_tests: Unit and integration test names that run python3 on Linux.
local_linux_cases: Exact libtest names keyed by test launcher. On Linux,
run these cases in a companion launcher with no-remote-exec.
test_tags: Tags applied to unit + integration test targets.
Typically used to disable the sandbox, but see https://bazel.build/reference/be/common-definitions#common.tags
integration_test_tags: Extra execution tags keyed by native integration
test name. Compilation, Wine and Windows cross tests are unaffected.
test_threads: Optional Rust test thread limit for sharded integration tests.
unit_test_timeout: Optional Bazel timeout for the unit-test target
generated from `src/**/*.rs`.
@@ -411,9 +431,11 @@ def codex_rust_crate(
unit_test_kwargs["shard_count"] = unit_test_shard_count
unit_test_kwargs["flaky"] = True
workspace_root_test(
_partitioned_workspace_test(
name = unit_test_name,
local_cases = local_linux_cases.get(unit_test_name, []),
env = test_env | unit_test_env,
python_runtime = _test_python_runtime(linux_python_tests, unit_test_name),
runfile_env = {
binary: "CARGO_BIN_EXE_" + Label(binary).name
for binary in extra_binaries
@@ -582,15 +604,17 @@ def codex_rust_crate(
test_kwargs["flaky"] = True
integration_test_binary = test_name + "-bin"
execution_tags = integration_test_tags.get(test_name, [])
use_test_launcher = test_shard_count or execution_tags or test_name in linux_python_tests or test_name in local_linux_cases
# There are four 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.
# 2. Sharded native tests split into a manual rust_test binary plus an
# outer workspace_root_test. The outer test action receives Bazel's
# sharding environment, resolves the real binary through the
# runfiles manifest, and implements stable libtest sharding itself.
# 2. Tests with shards, execution tags, or Python use a manual rust_test
# binary plus an outer workspace_root_test. The launcher resolves
# the binary through runfiles, handles sharding, and keeps test
# execution tags off compilation and lint actions.
# 3. Windows cross tests always use the workspace_root_test wrapper so
# runfile env vars become Windows-native absolute paths before the
# Rust process starts.
@@ -600,7 +624,7 @@ 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.
if test_shard_count:
if use_test_launcher:
# This target is intentionally a binary-like helper, not the public
# test target. The wrapper below owns cwd setup, runfile env
# materialization, sharding, and flaky retry behavior.
@@ -625,9 +649,14 @@ def codex_rust_crate(
version = crate_version,
)
workspace_root_test(
_partitioned_workspace_test(
name = test_name,
local_cases = local_linux_cases.get(test_name, []),
# Unsharded rust_test binaries can embed paths relative to
# Bazel's runfiles workspace. Preserve that working directory.
chdir_workspace_root = bool(test_shard_count),
env = test_env,
python_runtime = _test_python_runtime(linux_python_tests, test_name),
# CARGO_BIN_EXE_* values are rlocation paths at analysis time.
# The launcher rewrites them to absolute paths at execution
# time so tests keep working after chdir_workspace_root and on
@@ -637,7 +666,7 @@ def codex_rust_crate(
test_threads = test_threads,
workspace_root_marker = "//codex-rs/utils/cargo-bin:repo_root.marker",
target_compatible_with = WINDOWS_GNULLVM_INCOMPATIBLE,
tags = test_tags,
tags = test_tags + execution_tags,
**test_kwargs
)
else:
@@ -670,7 +699,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)
native_test_binary = ":" + (integration_test_binary if use_test_launcher else test_name)
wine_test_binaries = dict(wine_host_binaries)
wine_exec_server = wine_test_name + "-windows-exec-server"
@@ -701,10 +730,12 @@ def codex_rust_crate(
# The Wine runner is a binary rather than a rust_test, but it still
# needs a Cargo-like cwd, Bazel sharding, and absolute runfile paths.
# `workspace_root_test` establishes all three before Wine starts.
workspace_root_test(
_partitioned_workspace_test(
name = wine_test_name,
local_cases = local_linux_cases.get(wine_test_name, []),
data = wine_runtime.data,
env = test_env,
python_runtime = _test_python_runtime(linux_python_tests, test_name),
runfile_env = wine_runfile_env,
test_bin = "//codex-rs/exec-server/testing:wine-exec-test-runner",
workspace_root_marker = "//codex-rs/utils/cargo-bin:repo_root.marker",
@@ -752,6 +783,47 @@ def codex_rust_crate(
**windows_cross_test_kwargs
)
def _partitioned_workspace_test(name, local_cases, env, tags, **kwargs):
"""Share one binary between complementary Linux test launchers."""
if not local_cases:
workspace_root_test(name = name, env = env, tags = tags, **kwargs)
return
cases = ",".join(local_cases)
workspace_root_test(
name = name,
env = select({
"@platforms//os:linux": env | {"CODEX_BAZEL_EXCLUDE_CASES": cases},
"//conditions:default": env,
}),
tags = tags,
**kwargs
)
# Keep the Wine constraints and any runtime arguments. The local subset
# is small enough to run in one action instead of duplicating all shards.
local_kwargs = dict(kwargs)
local_kwargs.pop("shard_count", None)
if name.endswith("-wine-exec-test"):
compatible = WINE_TEST_TARGET_COMPATIBLE_WITH
else:
compatible = ["@platforms//os:linux"]
local_kwargs["target_compatible_with"] = compatible
workspace_root_test(
name = name + "-linux-local",
env = env | {"CODEX_BAZEL_INCLUDE_CASES": cases},
tags = tags + ["no-remote-exec"],
**local_kwargs
)
def _test_python_runtime(linux_python_tests, test_name):
if test_name not in linux_python_tests:
return None
return select({
"@platforms//os:linux": "@python_3_12//:py3_runtime",
"//conditions:default": None,
})
def _test_shard_count(test_shard_counts, test_name):
shard_count = test_shard_counts.get(test_name)
if shard_count == None: