Skip to content

fix(xtask): serialise subprocess-spawning tests against cwd-manipulating tests (#2044) - #2051

Merged
EffortlessSteven merged 1 commit into
mainfrom
codex/xtask-cwd-flake-2044
Jul 21, 2026
Merged

EffortlessSteven merged 1 commit into
mainfrom
codex/xtask-cwd-flake-2044

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Problem

The xtask test suite had a parallel-execution race (#2044). Two test families run concurrently under cargo test -p xtask:

  • main.rs — with_temp_cwd / with_repo_cwd call std::env::set_current_dir(temp) and remove_dir_all(temp) on teardown
  • run.rs — run_output*, capture_output*, capture_stdout_to_file_with_timeout, terminate_after_timeout, timeout_was_enforced spawn rustc/cargo/sh which inherit the process cwd

A subprocess spawn could land in the tiny window between set_current_dir(temp) and remove_dir_all(temp), producing intermittent failures like:

run_output_owned_includes_stderr_on_failure: rustc --version failed
  ... 'Unable to proceed. Could not locate working directory.'
run_output_reports_stdout_and_failure: rustc --version failed with exit status: 1
capture_output_returns_status_stdout_and_stderr: rustc --version should succeed

The same tests passed in isolation and on full-suite re-runs. Denominator evidence on current main: run 1 = 3 failed/1268 passed, run 2 = 0 failed.

Change

  1. Hoist CWD_LOCK from main.rs's tests module to a crate-root pub(crate) static plus a pub(crate) fn acquire_test_cwd_lock() -> MutexGuard<'static, ()> helper. The helper uses unwrap_or_else(|poison| poison.into_inner()) to recover from a poisoned mutex (no panic-family call).
  2. with_temp_cwd and with_repo_cwd now call acquire_test_cwd_lock() instead of the inline CWD_LOCK.get_or_init(...).lock().unwrap().
  3. The run.rs test module imports acquire_test_cwd_lock and acquires the guard at the top of every subprocess-spawning test body.

Both modules now share the same process-wide mutex and cannot race.

  1. Removed the stale panic-0003 allowlist entry from policy/no-panic-allowlist.toml: it matched the old CWD_LOCK.get_or_init(...).lock().unwrap() call which no longer exists. The no-panic gate fails on stale entries, so this removal is required for the gate to stay green.

Why a process-wide lock instead of --test-threads=1?

--test-threads=1 would mask the race but slow every other test (the suite is 1268 tests). The lock serialises only the cwd-sensitive subset — about 12 spawning tests plus the cwd-mutating tests — while everything else still runs in parallel. The lock is process-wide because cwd is process-wide; there is no narrower scope.

Evidence

cargo test -p xtask                       PASS (1268 tests, no flakes across multiple parallel runs)
cargo clippy --workspace --all-targets -- -D warnings   PASS
cargo xtask check-no-panic-family         PASS (0 stale, 0 unallowed)
cargo xtask check-file-policy             PASS
cargo xtask check-static-language         PASS

Scope

Three-file change: xtask/src/main.rs (hoist lock + helper + update two callers), xtask/src/run.rs (import helper + acquire in 13 spawning tests), policy/no-panic-allowlist.toml (remove one stale entry). No production code change. Closes #2044.

Non-goals

  • Does NOT change the production run_output/capture_output helpers to take an explicit current_dir. That would be a wider refactor and is not needed — the lock fully closes the race for the test surface.
  • Does NOT partition the test suite via --test-threads. The lock is sufficient and keeps parallelism for unrelated tests.

…ing tests (#2044)

The xtask test suite had a parallel-execution race: main.rs tests
(`with_temp_cwd`, `with_repo_cwd`) call `std::env::set_current_dir`
and delete the temporary directory on teardown. Meanwhile run.rs tests
spawn rustc/cargo/sh which inherit the process cwd. A subprocess spawn
could land in the tiny window between `set_current_dir(temp)` and
`remove_dir_all(temp)`, producing intermittent failures:

  run_output_owned_includes_stderr_on_failure: rustc --version failed
    ... 'Unable to proceed. Could not locate working directory.'
  run_output_reports_stdout_and_failure: rustc --version failed with exit status: 1
  capture_output_returns_status_stdout_and_stderr: rustc --version should succeed

The same tests passed in isolation and on full-suite re-runs.
Denominator evidence on current main: run 1 = 3 failed/1268 passed,
run 2 = 0 failed.

## Fix

Hoist the CWD_LOCK static from main.rs's tests module to a crate-root
`pub(crate) static` plus a `pub(crate) fn acquire_test_cwd_lock()`
helper. The run.rs test module imports the helper and acquires the
guard at the top of every subprocess-spawning test body. Now both
modules share the same process-wide mutex and cannot race:

  - main.rs's with_temp_cwd/with_repo_cwd hold the lock while they
    mutate cwd and tear down temp dirs
  - run.rs's spawning tests (run_output*, capture_output*,
    capture_stdout_to_file_with_timeout, terminate_after_timeout,
    timeout_was_enforced, etc.) hold the same lock while subprocesses
    inherit cwd

Removed the stale `panic-0003` allowlist entry from
policy/no-panic-allowlist.toml: it matched the old
`CWD_LOCK.get_or_init(...).lock().unwrap()` call which is now
replaced by acquire_test_cwd_lock()'s poison-recovering
`unwrap_or_else(|poison| poison.into_inner())` (no panic-family
call remains).

## Verified

  cargo test -p xtask                       PASS (1268 tests, no flakes
                                            across multiple parallel runs)
  cargo clippy --workspace --all-targets -D warnings   PASS
  cargo xtask check-no-panic-family         PASS (0 stale, 0 unallowed)
  cargo xtask check-file-policy             PASS
  cargo xtask check-static-language         PASS

Closes #2044.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@EffortlessSteven, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 1 minute

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e1d4158a-01fd-437e-8cfb-2af50f9459af

📥 Commits

Reviewing files that changed from the base of the PR and between 4409b14 and 09a3fb0.

📒 Files selected for processing (3)
  • policy/no-panic-allowlist.toml
  • xtask/src/main.rs
  • xtask/src/run.rs
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/xtask-cwd-flake-2044

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request removes a panic allowlist entry from policy/no-panic-allowlist.toml and updates various test cases in xtask/src/run.rs to acquire a shared current working directory (CWD) lock (acquire_test_cwd_lock()). This prevents concurrent tests that manipulate the CWD from racing with subprocess spawns. There are no review comments, so I have no additional feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@codecov

codecov Bot commented Jul 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Decision

  • Needs reviewer attention before upstream: findings remain.

Confirmed findings

  • Architecture boundary is clean and minimal; lock acquisition is duplicated 13 times in run.rs but this is the smallest correct fix (no shared test util module is warranted for one helper call). A future refactor could extract a spawn_test_cwd helper but it would not reduce the actual lock-acquire cost and risks obscuring the invariant.

Verification questions

  • Confirm pR body says 13 spawning tests acquired; diff shows guard added to 13 test bodies in run.rs (counted in patch).
  • Confirm no new behavior assertion added: lock acquisition is side-effect-free, so no test distinguishes old vs new behavior. Green build only proves races are rarer, not closed.
  • Confirm cWD_LOCK and acquire_test_cwd_lock are now crate-root #[cfg(test)] items, making the guard process-wide and shared across main.rs/run.rs test binaries (each binary is its own process so this remains correct).
  • Confirm with_temp_cwd/with_repo_cwd both now route through acquire_test_cwd_lock, so any future test calling these helpers inherits serialisation without code change.
  • Confirm load-bearing evidence (cargo-test green across multiple parallel runs; intermittent-failure denominator) is not in any sensor receipt: artifact-verifier failed and cargo-test is scheduled-late. Race-closure is an empirical claim; gate should not approve without that receipt.
  • Confirm cargo-test receipt is scheduled-late; race-fix verification depends on it landing green before the gate. Heavy witnesses (build/clippy/fmt/miri) are skipped, so parallelism regressions or new unwraps in test code are not independently proven by the available sensors.

Refuted

  • The PR's race-closure proof is incomplete because no test in run.rs references the cwd guard's effect.; refuted because: TestsRedGreen scope is red/green discrimination; the guard is a synchronization primitive with no observable return value, so a discriminating assertion is structurally absent. PR evidence relies on empirical multi-run cargo test, not a deterministic oracle. Treat as test-gap, not test-absent.
  • A narrow test-only Mutex should live inside the test module, not crate-root, to minimise surface area; refuted because: Crate-root placement is required because main.rs tests module and run.rs tests module are separate modules and need to share the same Mutex<()>. Inline per-module locks would re-introduce the race. cfg(test) keeps it out of production.
  • Lock is not actually shared because OnceLock is per-module; refuted because: Diff hoists CWD_LOCK to crate-root with #[cfg(test)] pub(crate) static; run.rs imports the helper and resolves through crate path, so both modules see the same OnceLock instance.

Parked follow-ups

  • Process-wide scope is justified: cwd is process-wide and lock only gates ~12 spawn tests + cwd-mutators while leaving the remaining 1256 tests parallel.

Evidence gaps

[review body truncated; see review artifacts]

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

flake(xtask): run_output/capture_output tests race on deleted working directories under parallel test execution

1 participant