Skip to content

test: acquire the env lock in backend seam tests for xla-backend builds - #1169

Merged
inureyes merged 2 commits into
mainfrom
fix/issue-1159-env-lock-token-bias-backend-test
Aug 15, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/issue-1159-env-lock-token-bias-backend-test

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Closes a pre-existing test-only race in src/backend/tests.rs: under the opt-in xla-backend / experimental-backend features, select_backend() reads MLXCEL_BACKEND, and a parallel full-suite run could interleave with muse_glimmer_startup_rejects_xla_backend_selection (which transiently sets that variable while holding the crate-wide env lock added in #1157) and make a backend test observe the transient xla value instead of the default MLX selection.

What changed

  • src/backend/tests.rs: all four select_backend() call sites now acquire crate::test_support::env_lock::env_lock(), bound to a named _env_guard variable (never a bare _, since dropping it immediately would reinstate the exact race this fix closes), before calling select_backend().
  • mlx_session_threads_the_token_bias_through (the test named in the issue) is guarded: without the lock it would hit the unreachable!("select_backend defaults to MLX without MLXCEL_BACKEND=xla") arm under the race.
  • select_backend_resolves_to_mlx_under_default_features is guarded: without the lock its matches!(backend, Backend::Mlx(_)) and backend.name() == "mlx" assertions would fail under the race.
  • mlx_backend_creates_a_session_and_advertises_batched_serving is guarded: without the lock, backend.supports_batched_serving() and the session's caps.multimodal assertion would fail under the race (the XLA scaffold session reports multimodal: false, the opposite of what this test asserts for MLX).
  • seam_delegates_to_real_mlx_loader_on_missing_dir is guarded too, even though it would not fail outright under the race (both the MLX loader and the XLA scaffold's load_unsupported() return Err for a missing path): its docstring claims to prove the seam reaches the real MLX loader specifically, and without the lock a race could silently validate the XLA scaffold instead, defeating that claim without a visible test failure. All three of these sites were evaluated per the issue's discussion, and none were left unguarded.
  • Each guarded test carries a short comment explaining why the lock is needed, since under default features select_backend() reads no environment variable and the lock can otherwise look superfluous to a future reader.
  • Test-only change. src/backend/mod.rs (the feature-gated select_backend arm that reads MLXCEL_BACKEND) and src/server/muse_glimmer_startup_guard_tests.rs (already fixed by test: skip pinned muse_glimmer checkpoint tests and fix MLXCEL_BACKEND race #1157) are untouched, and no production code path changed.

Test plan

  • cargo check --lib --tests (default features)
  • cargo test --lib backend::tests (default features): 5 passed, 0 failed
  • cargo clippy --lib --tests -- -D warnings (default features): clean
  • Full-suite parallel run with --features metal,accelerate,xla-backend: not run. This machine is a CUDA/GB10 Linux box where metal is not applicable, no CI workflow builds xla-backend, and a cold mlxcel-xla build exceeds local verification time budgets. Per the issue's accepted evidence, this PR relies on code inspection (the guard follows the exact let _env_guard = crate::test_support::env_lock::env_lock(); pattern established by test: skip pinned muse_glimmer checkpoint tests and fix MLXCEL_BACKEND race #1157 in muse_glimmer_startup_guard_tests.rs) plus the targeted default-feature run above.

Closes #1159

`select_backend()` reads `MLXCEL_BACKEND` when built with the opt-in `xla-backend` or `experimental-backend` features, but `mlx_session_threads_the_token_bias_through` and three sibling tests in `src/backend/tests.rs` called it without holding the crate-wide env lock from PR #1157. Under those features, a parallel full-suite run can interleave with `muse_glimmer_startup_rejects_xla_backend_selection`, which transiently sets `MLXCEL_BACKEND=xla` while holding that lock, and make a backend test observe `xla` instead of the default MLX selection.

All four `select_backend()` call sites in the file now acquire `crate::test_support::env_lock::env_lock()` before calling it, bound to a named `_env_guard` variable so the guard's `Drop` lasts the whole test body: `select_backend_resolves_to_mlx_under_default_features` and `mlx_session_threads_the_token_bias_through` would otherwise fail their MLX-only assertions (or hit the `unreachable!` arm) under the race; `seam_delegates_to_real_mlx_loader_on_missing_dir` and `mlx_backend_creates_a_session_and_advertises_batched_serving` would not fail outright but would silently validate the wrong backend's behavior, defeating what their docstrings claim to test.

The lock is a no-op under default features (`select_backend` const-folds with no environment read there), so this is test-only and changes no behavior under the feature sets CI actually builds. Verified with `cargo check --lib --tests`, `cargo test --lib backend::tests` (5 passed), and `cargo clippy --lib --tests -- -D warnings`, all under default features on this machine; the `xla-backend` feature itself was not built locally (cold `mlxcel-xla` build), so the race fix is verified by code inspection against the #1157 pattern plus this targeted default-feature run, per the issue's accepted evidence.
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:low Low priority area:models Model architectures, weights, loading, metadata status:review Under review labels Aug 15, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Orchestrator verification: xla-backend feature run

The issue's second acceptance criterion (a parallel run with the opt-in backend feature enabled) was verified directly rather than by code inspection alone. metal and accelerate are Apple-targeted and not buildable on this Linux/CUDA machine, so the run used --features xla-backend, which is the feature that actually makes select_backend() read MLXCEL_BACKEND and therefore the one the race depends on. xla-backend builds without IREE_DIST (only xla-iree needs it), so no special setup was required.

1. Backend tests under --features xla-backend

cargo test --features xla-backend --lib backend::tests
running 7 tests
test backend::tests::mlx_backend_reports_mlx_name ... ok
test backend::tests::xla_image_capability_requires_runtime_and_host_preprocessor ... ok
test backend::tests::mlx_backend_creates_a_session_and_advertises_batched_serving ... ok
test backend::tests::mlx_session_threads_the_token_bias_through ... ok
test backend::tests::select_backend_resolves_to_mlx_under_default_features ... ok
test backend::tests::xla_backend_creates_a_single_sequence_session_scaffold ... ok
test backend::tests::seam_delegates_to_real_mlx_loader_on_missing_dir ... ok

test result: ok. 7 passed; 0 failed

This compiles the Session::Xla arm and the MLXCEL_BACKEND selection path, so the unreachable! arm in mlx_session_threads_the_token_bias_through is live code in this configuration rather than compiled out.

2. Contending tests running concurrently, repeated

The race needs the backend tests and muse_glimmer_startup_rejects_xla_backend_selection (which transiently sets MLXCEL_BACKEND=xla) in the same binary at the same time, so both modules were run together on 8 threads, five times:

for i in 1 2 3 4 5; do
  cargo test --features xla-backend --lib -- \
    backend::tests server::startup::muse_glimmer_startup_guard_tests --test-threads=8
done

All five runs: test result: ok. 12 passed; 0 failed (7 backend tests plus 5 startup-guard tests).

This also covers the main risk the change itself introduces: four additional tests now contend on the same crate-wide mutex as the env-mutating guard test, and the repeated parallel runs show no deadlock. env_lock() already recovers from a poisoned mutex via unwrap_or_else(|p| p.into_inner()), so a panicking lock holder cannot cascade into the newly guarded tests either.

3. Default features

Confirmed separately: cargo check --lib --tests clean, cargo test --lib backend::tests 5 passed, cargo clippy --lib --tests -- -D warnings clean.

Scope note

This verifies the criterion as written, that the tests pass under a parallel run with the feature enabled. It is not a reproduction of the original failure: the race is timing-dependent and was never observed failing here, which is consistent with the issue describing it as a latent interleaving rather than a reliably reproducing one.

@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Close a test-only race in src/backend/tests.rs: under the opt-in xla-backend / experimental-backend features select_backend() reads MLXCEL_BACKEND, so a parallel run can interleave with muse_glimmer_startup_rejects_xla_backend_selection and hand a backend test the transient xla value.

Findings Addressed

None. No CRITICAL, HIGH, or MEDIUM findings were found, and no fixes were required.

Verification performed in this review

The one correctness trap (bare _ binding) is clear. All four guards bind a named variable, so the MutexGuard lives to the end of the test body rather than dropping at the end of the statement: src/backend/tests.rs:53, :76, :100, :130 are each let _env_guard = crate::test_support::env_lock::env_lock();. No let _ = env_lock(); anywhere in the diff.

Placement is correct in all four. Each guard is acquired before its select_backend() call (53 before 54, 76 before 77, 100 before 101, 130 before 133) and, being the first binding in each function, drops last. The lock therefore covers the whole window in which the backend, the session, and the capabilities are inspected, including load_model at :83, the caps assertions at :116-120, and the Session match at :141-150.

No call site was missed. select_backend() appears in src/backend/tests.rs at lines 54, 77, 101, and 133; all four are guarded. The remaining tests in the file (mlx_backend_reports_mlx_name, xla_backend_creates_a_single_sequence_session_scaffold, experimental_backend_session_creation_errors, xla_image_capability_requires_runtime_and_host_preprocessor) construct their backend directly via MlxBackend::new() / XlaBackend::new() / ExperimentalBackend::new() and never read the environment, so they are correctly left alone. Every other select_backend() caller in the repository (src/server/model_worker.rs, src/commands/chat.rs, src/commands/generate.rs) is production code, not a test, so nothing outside this file needed the guard.

Guarding all four rather than only the issue's named test is justified and the reasoning checks out. XlaBackend::supports_batched_serving() at src/backend/xla.rs:117 is cfg!(feature = "xla-iree"), so under xla-backend alone it returns false and mlx_backend_creates_a_session_and_advertises_batched_serving would fail its first assertion under the race. XlaBackend::load_model at src/backend/xla.rs:75 routes to load_unsupported() and returns Err, which confirms the PR body's honest note that seam_delegates_to_real_mlx_loader_on_missing_dir would not fail outright under the race; guarding it anyway is the right call, since a silent pass against the XLA scaffold would defeat exactly the "reaches the real MLX loader" claim the test exists to make.

The mutating side is fully covered. MLXCEL_BACKEND is written in exactly one place in the test tree, src/server/muse_glimmer_startup_guard_tests.rs:155/163/164, and that test holds the same crate-wide lock across both the set and the restore. There is no remaining unguarded mutator for this key, so the two sides of the race are now mutually exclusive.

No deadlock or self-lock risk. env_lock() returns a guard on a non-reentrant std::sync::Mutex, and each of the four tests acquires it exactly once. Nothing reachable from select_backend(), load_model(), create_session(), capabilities(), or token_bias() can re-acquire it: test_support is gated on cfg(test) at the crate root (src/lib.rs:51-52), and every env_lock() call site in the crate is inside a test module. The only new effect is serialization against the other env-mutating tests.

Compiles under the feature set the fix targets. test_support is gated on cfg(test) only, not on any feature, and src/backend/tests.rs is pulled in by an unconditional #[cfg(test)] mod tests; at src/backend/mod.rs:327, so the added path resolves under xla-backend and experimental-backend as well as under default features.

Genuinely test-only. One file changed, 26 insertions, 0 deletions, all inside #[cfg(test)] code. src/backend/mod.rs and src/server/muse_glimmer_startup_guard_tests.rs are untouched, matching the issue's out-of-scope list. Under default features the guard is a no-op mutex acquire on a path that reads no environment variable, so there is no behavior change.

Conventions. The guard uses the exact _env_guard pattern established by #1157 at src/server/muse_glimmer_startup_guard_tests.rs:69 and :150, reusing the existing shared lock rather than introducing a new one. Comment style matches the file. The commit subject is 71 characters, the body is not hard-wrapped, and the diff, commit message, and PR body contain no AI attribution and no em dashes.

Remaining Items

Two observations, neither one a defect and neither requiring a change:

  • The comment at :127-129 names the unreachable! arm as the failure mode under the race. That arm is reached only if create_session("/tmp/model") succeeds on the XLA path; if it does not, the failure surfaces one line earlier at .expect("session creation must succeed"). Both outcomes are loud test failures, so the comment still serves its stated purpose of stopping a future reader from deleting the guard.
  • In seam_delegates_to_real_mlx_loader_on_missing_dir and mlx_backend_creates_a_session_and_advertises_batched_serving, the new lock rationale is appended directly onto the pre-existing test-purpose comment with no blank line between them. Purely cosmetic.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (cargo check --lib --tests, cargo test --lib backend::tests 5 passed, cargo clippy --lib --tests -- -D warnings clean, all under default features)

The --features metal,accelerate,xla-backend full-suite run named in the acceptance criteria was not run: metal and accelerate are Apple-targeted and not buildable on this Linux/CUDA host. The issue explicitly accepts code inspection plus a targeted run as evidence, and the PR body states which was done.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL, HIGH, MEDIUM, or LOW findings. Nothing changed; the PR is unmodified.

Reviewed the five dimensions a lock change can actually affect:

Deadlock / lock ordering. No cycle is reachable. The four guarded tests take exactly one Rust-level lock (ENV_LOCK) and nothing under the guard re-enters it: select_backend() is a getenv plus a ZST construction, load_model("/nonexistent/...") bails at get_model_type on read_to_string, and create_session reaches KVCache::new_with_mode (pure struct construction) plus new_thread_local_generation_stream. The only static Mutex in that subtree, sparse_v_count_file in cache/turbo/sparse_v.rs, is reachable only from record_skip_rate on the attention path, never from cache construction. env_lock lives in a #[cfg(test)]-gated module, so no production code can acquire it and no ABBA pair can form. mlxcel-core has a separate ENV_LOCK static in a separate test binary, so there is no cross-crate interaction either.

Lock-hold duration. Measured on the prebuilt xla-backend test binary: each of the five backend tests completes in under 10 ms including process startup. Nothing under a guard does network I/O, sleeps, or joins a thread; the heaviest operation is one failed read_to_string on a nonexistent path. The added serialization against the roughly 200 other env_lock sites is negligible.

Guard lifetime. All four are let _env_guard = ... named bindings placed before their select_backend() call, never a bare _ (which would drop immediately and reinstate the race). In mlx_session_threads_the_token_bias_through the guard is declared first, so reverse drop order retires it last, after the session. No guard is dropped early or held across anything that needs it released.

Masking. The guards serialize; they do not weaken any assertion. Every existing assert! and match arm still runs and can still fail.

One point in the PR's favor that the description understates: create_session reaches boundary_v_layers_from_env(), which performs two std::env::var reads, and load_model on a real checkpoint can set_var("MLX_USE_CUDA_GRAPHS") via maybe_disable_cuda_graphs_for_model. Holding the env lock across these calls is a soundness improvement under the Rust 2024 setenv/getenv rules, not merely defensive scaffolding against the MLXCEL_BACKEND race.

Optional, non-blocking, and explicitly out of scope for this PR: seam_delegates_to_real_mlx_loader_on_missing_dir still accepts any Err, so it cannot by itself distinguish the MLX loader's error from another backend's. The lock makes it deterministic but does not make the assertion stronger. If that claim should be enforced rather than protected, an assert_eq!(backend.name(), "mlx") before the load_model call would do it. This is a pre-existing property of the test, not something the PR introduced.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Aug 15, 2026
Bilingual report covering the backend seam env-lock change: the race mechanism under the opt-in xla-backend and experimental-backend features, why all four select_backend() call sites were guarded rather than only the one named in the issue, and the verification runs including the --features xla-backend contention run that the issue's second acceptance criterion asks for.
@inureyes
inureyes merged commit 6918c67 into main Aug 15, 2026
7 checks passed
@inureyes
inureyes deleted the fix/issue-1159-env-lock-token-bias-backend-test branch August 15, 2026 16:36
@inureyes inureyes self-assigned this Aug 27, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…ds (lablup#1169)

## Summary

Closes a pre-existing test-only race in `src/backend/tests.rs`: under the opt-in `xla-backend` / `experimental-backend` features, `select_backend()` reads `MLXCEL_BACKEND`, and a parallel full-suite run could interleave with `muse_glimmer_startup_rejects_xla_backend_selection` (which transiently sets that variable while holding the crate-wide env lock added in lablup#1157) and make a backend test observe the transient `xla` value instead of the default MLX selection.

## What changed

- `src/backend/tests.rs`: all four `select_backend()` call sites now acquire `crate::test_support::env_lock::env_lock()`, bound to a named `_env_guard` variable (never a bare `_`, since dropping it immediately would reinstate the exact race this fix closes), before calling `select_backend()`.
- `mlx_session_threads_the_token_bias_through` (the test named in the issue) is guarded: without the lock it would hit the `unreachable!("select_backend defaults to MLX without MLXCEL_BACKEND=xla")` arm under the race.
- `select_backend_resolves_to_mlx_under_default_features` is guarded: without the lock its `matches!(backend, Backend::Mlx(_))` and `backend.name() == "mlx"` assertions would fail under the race.
- `mlx_backend_creates_a_session_and_advertises_batched_serving` is guarded: without the lock, `backend.supports_batched_serving()` and the session's `caps.multimodal` assertion would fail under the race (the XLA scaffold session reports `multimodal: false`, the opposite of what this test asserts for MLX).
- `seam_delegates_to_real_mlx_loader_on_missing_dir` is guarded too, even though it would not fail outright under the race (both the MLX loader and the XLA scaffold's `load_unsupported()` return `Err` for a missing path): its docstring claims to prove the seam reaches the real MLX loader specifically, and without the lock a race could silently validate the XLA scaffold instead, defeating that claim without a visible test failure. All three of these sites were evaluated per the issue's discussion, and none were left unguarded.
- Each guarded test carries a short comment explaining why the lock is needed, since under default features `select_backend()` reads no environment variable and the lock can otherwise look superfluous to a future reader.
- Test-only change. `src/backend/mod.rs` (the feature-gated `select_backend` arm that reads `MLXCEL_BACKEND`) and `src/server/muse_glimmer_startup_guard_tests.rs` (already fixed by lablup#1157) are untouched, and no production code path changed.

## Test plan

- [x] `cargo check --lib --tests` (default features)
- [x] `cargo test --lib backend::tests` (default features): 5 passed, 0 failed
- [x] `cargo clippy --lib --tests -- -D warnings` (default features): clean
- [ ] Full-suite parallel run with `--features metal,accelerate,xla-backend`: not run. This machine is a CUDA/GB10 Linux box where `metal` is not applicable, no CI workflow builds `xla-backend`, and a cold `mlxcel-xla` build exceeds local verification time budgets. Per the issue's accepted evidence, this PR relies on code inspection (the guard follows the exact `let _env_guard = crate::test_support::env_lock::env_lock();` pattern established by lablup#1157 in `muse_glimmer_startup_guard_tests.rs`) plus the targeted default-feature run above.

Closes lablup#1159
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:low Low priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test: acquire the env lock in the token-bias backend test for xla-backend builds

1 participant