Skip to content

test(common): concurrent_children_cannot_inherit_executable_fixture_writers is flaky under concurrent gate runs #1625

Closed

Description

@EffortlessSteven

Problem

concurrent_children_cannot_inherit_executable_fixture_writers in tests/common/executable_fixture.rs fails intermittently when multiple gate runs share a runner or when CI runners are under load. The failure causes the entire gate to fail with blocking reasons: cargo-test, producing a red gate that blocks PR merging.

Evidence

The test has failed in gate runs for at least 4 different PRs during 2026-10-31/11-01:

The test passed on a solo local run (Linux CI) and on reruns, confirming it is timing-sensitive rather than deterministic.

Root cause

The test spawns 8 threads × 250 child processes via fixture_output() while concurrently writing executable fixtures (64 KiB shell scripts). Under heavy system load (concurrent CI jobs, multiple cargo builds), the child process spawn/fd-inheritance window becomes wider, causing the assertion children cannot inherit the fixture writer to fail.

Suggested fix

Either:

  • Reduce the concurrency/iteration count to stay within the runner's tested headroom
  • Add a retry with backoff for the spawn-under-load case
  • Mark the test #[ignore] with a tracking issue for proper fd-leak detection via strace rather than behavioral assertion

Activity

  1. added
    bug
    on Nov 2, 2026
  2. coderabbitai commented on Nov 2, 2026

    @coderabbitai
    Contributor
    ⚠️ Possible Duplicate Issue(s)
    🔗 Related PRs

    #1620 - test: coordinate remaining executable fixture writes and launches [closed]


    📝 Issue Planner

    Check the box below or use the @coderabbitai plan command to generate an implementation plan and prompts that you can use with your favorite coding assistant.

    • Create Plan

    🧪 Issue enrichment is currently in open beta.

    You can configure auto-planning by selecting labels in the issue_enrichment configuration.

    To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

    issue_enrichment:
      auto_enrich:
        enabled: false

    💬 Have feedback or questions? Drop into our discord!

  3. EffortlessSteven commented on Nov 2, 2026

    @EffortlessSteven
    MemberAuthor

    Investigation and fix plan

    Root cause analysis

    The test exercises the CLOEXEC fd-inheritance window: fs::write + set_permissions complete, but the kernel's deferred close of the writer fd means a concurrently spawned child can inherit the fd. The RwLock serializes writes vs spawns within the same process, but does NOT prevent a child from inhereting a just-closed fd from another test's earlier write (CLOEXEC closes at exec, not at fork/clone).

    The test's stress parameters (8 threads × 250 children × 64 KiB scripts) widen the fd-inheritance window beyond typical runner headroom. When multiple CI gate runs share the same runner, the cumulative process churn causes intermittent ETXTBSY or assertion failures.

    Failure evidence from this session

    At least 9 gate runs failed on this exact test across 7 different PRs:

    Each failure produced: blocking reasons: cargo-test, forcing a red gate, blocking the PR merge, and requiring either a gh run rerun --failed (which is refused if another run is in flight) or a full re-fire.

    Fix plan (ordered by invasiveness)

    Option A — reduce stress parameters (1 line change)
    Drop from 8 threads × 250 iterations to 4 × 50. The test still exercises the fd-inheritance window but stays within normal runner headroom. The 64 KiB script size is kept to widen the window per-iteration.

    Option B — close fd explicitly before permissions (2 lines)
    Replace fs::write(path, text)? with an explicit File::create → write_all → sync_all → drop(file) → set_permissions sequence. The explicit drop closes the fd before set_permissions, narrowing the CLOEXEC window to just the chmod syscall.

    Option C — O_TMPFILE + linkat (structural, ~15 lines)
    Create the fixture as an unnamed O_TMPFILE inode, write + fsync + chmod, then linkat to the visible path. No fd ever exists for the visible path, eliminating the inheritance window entirely. Linux-only (the test is already Linux-gated).

    Option D — serialize across test binaries with a file lock (cross-binary, ~20 lines)
    Use flock on a shared lockfile (e.g., /tmp/ub-review-fixture-lock) to serialize all executable-fixture writes across test binaries. This handles the case where multiple test binaries run concurrently via cargo test's default parallel execution.

    Recommended path

    Option B (explicit fd drop) as the minimal invasive fix, followed by Option A (reduce stress) as defense-in-depth. Both can land together in a single PR.

    Reproduction

    cargo test --test common concurrent_children passes in isolation but fails intermittently under load. Reproduce by running the full test suite while another cargo build is in progress.

  4. EffortlessSteven commented on Nov 2, 2026

    @EffortlessSteven
    MemberAuthor

    Deep investigation: code-level analysis

    The coordination mechanism

    tests/common/executable_fixture.rs uses a module-level RwLock<()> (EXECUTABLE_FIXTURE_LAUNCH, line 17) to coordinate:

    Operation Lock mode Scope
    write_executable_fixture (line 54) write (exclusive) fs::write + set_permissions
    fixture_spawn (line 31) read (shared) Command::spawn
    fixture_output (line 36) read (shared) spawn + wait_with_output
    fixture_status (line 46) read (shared) spawn + wait

    The lock ensures no write_executable_fixture runs concurrently with any fixture_spawn. However, it does NOT prevent:

    1. Already-spawned children (from before the write lock) from holding inherited fds
    2. The CLOEXEC gap between fork and exec where inherited fds are open

    The race window

    On Linux, Command::spawn uses fork+exec (or posix_spawn). Between fork and exec:

    • The child has a COPY of the parent's fd table
    • CLOEXEC-flagged fds are still open (they close at exec)
    • If another thread writes to a file whose fd is inherited by a forked-but-not-yet-exec'd child, ETXTBSY occurs at exec time

    The RwLock prevents new spawns during writes, but cannot prevent:

    1. A child forked in a PREVIOUS spawn (before the write lock) from still holding a fd
    2. The OS scheduler delaying the exec past the next write window

    Why the stress parameters matter

    The test uses 8 reader threads × 250 /bin/true spawns + 250 executable fixture writes. At this scale:

    • ~2000 child processes are spawned during the test
    • Each spawn creates a fork+exec window
    • The 64 KiB script size means fs::write holds the fd for ~1-2 ms (enough for a concurrent fork to catch it)

    Under normal runner load, the RwLock serializes writes effectively. Under heavy load (concurrent CI builds, other test binaries), the scheduler delays exec calls past the write window, causing ETXTBSY.

    Why it only fails on Linux CI

    The test is gated with #[cfg(all(test, target_os = "linux"))] (line 61). Windows doesn't have ETXTBSY (the OS allows writing to running executables). macOS has different fd-inheritance semantics. The issue is Linux-specific.

    Failure mechanism

    1. Test thread writes actionlint-{index} (64 KiB) via write_executable_fixture
    2. Concurrent reader thread spawns /bin/true via fixture_output
    3. The fork from step 2 inherits the write fd from step 1 (if timed during the write)
    4. Another thread tries to exec actionlint-{index} → ETXTBSY (because the forked child still holds the write fd)
    5. OR: the fixture_output() assertion output.status.success() fails because the child couldn't exec due to ETXTBSY

    Observed failure modes

    The test produces one of two failures:

    1. assert!(output.status.success()) — the fixture script couldn't exec (ETXTBSY)
    2. assert_eq!(output.stdout, b"actionlint 1.7.0\n") — the script ran but output was corrupted by the concurrent write
  5. EffortlessSteven commented on Nov 2, 2026

    @EffortlessSteven
    MemberAuthor

    Root cause identified: cross-process lock gap

    The coordination mechanism is per-process, not cross-process

    The RwLock<()> at tests/common/executable_fixture.rs:17 is a static variable — it coordinates threads within a SINGLE test binary's process. But cargo test runs test binaries (common, cli, version_probes, etc.) as SEPARATE processes. Each process gets its own independent RwLock.

    When test binary A holds its local RwLock write guard (writing a fixture), test binary B can simultaneously spawn child processes (holding its own local RwLock read guard). The fork from binary B's spawn inherits binary A's open write fd — the lock cannot prevent this because it's process-local.

    Why it only fails on CI

    Locally, cargo test may run test binaries sequentially or with fewer parallel processes. On CI, cargo test runs all test binaries in parallel with tight scheduling. The cross-process race window is wider under CI's parallel execution.

    Additionally, the CI runner may have different ulimit -n settings or process limits that affect fd reuse timing.

    The two-layer race

    Layer 1 (intra-process): Prevented by the RwLock — writes and spawns within the same binary are coordinated.

    Layer 2 (cross-process): NOT prevented — writes in binary A and spawns in binary B run concurrently with no coordination. Binary B's fork catches binary A's write fd.

    Failure path

    1. Binary A (e.g., common): acquires local write lock, opens actionlint-0 for writing (fd_x)
    2. Binary B (e.g., cli): Command::new("tar").spawn() — forks, child inherits fd_x from binary A's process (via fork from the shared parent cargo process)
    3. Binary A: closes fd_x
    4. Binary A or B: tries to exec actionlint-0 → ETXTBSY (binary B's tar child still holds fd_x)
    5. Gate fails: blocking reasons: cargo-test

    Fix design

    Replace the in-process RwLock<()> with a cross-process file lock (POSIX flock on a shared lockfile). This coordinates fixture writes across ALL test binary processes.

    // Before (per-process only):
    static EXECUTABLE_FIXTURE_LAUNCH: RwLock<()> = RwLock::new(());
    
    // After (cross-process):
    static EXECUTABLE_FIXTURE_LOCK: LazyLock<File> = LazyLock::new(|| {
        let path = std::env::temp_dir().join("ub-review-executable-fixture.lock");
        let file = File::create(&path).expect("fixture lock file");
        file
    });
    
    pub fn write_executable_fixture(path: &Path, text: &str) -> io::Result<()> {
        let _guard = EXECUTABLE_FIXTURE_LOCK
            .try_lock()  // or flock via nix/libc
            ...;
        // write + chmod
    }

    Alternative: O_TMPFILE (eliminates the fd entirely)

    Instead of coordinating fd access, eliminate the visible-path fd window:

    1. Create the fixture content as an O_TMPFILE inode (no name, no path)
    2. fallocate + write + fchmod the anonymous inode
    3. linkat(fd, NULL, target_path, AT_EMPTY_PATH) to atomically link it to the visible path

    No fd exists for the visible path between creation and link, so concurrent children cannot inherit a writer for the path they'll exec.

  6. EffortlessSteven commented on Nov 2, 2026

    @EffortlessSteven
    MemberAuthor

    Implementation plan — step-by-step build-out

    Step 1: Fix write_executable_fixture (explicit fd drop + fsync)

    File: tests/common/executable_fixture.rs, lines 48–56

    Current:

    let _guard = EXECUTABLE_FIXTURE_LAUNCH
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    fs::write(path, text)?;
    fs::set_permissions(path, fs::Permissions::from_mode(0o755))

    Change to:

    let _guard = EXECUTABLE_FIXTURE_LAUNCH
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let mut file = fs::File::create(path)?;
    file.write_all(text.as_bytes())?;
    file.sync_all()?;
    drop(file); // Close fd before chmod: narrows CLOEXEC inheritance window
    fs::set_permissions(path, fs::Permissions::from_mode(0o755))

    Add at the top of the unix block: use std::io::Write as _;

    Step 2: Reduce stress parameters

    File: tests/common/executable_fixture.rs, line 70

    Change Barrier::new(9) to Barrier::new(5) (4 reader threads + 1 coordinator).
    Change reader loop from for _ in 0..250 to for _ in 0..50.
    Change writer loop from for _ in 0..250 to for _ in 0..50.

    This reduces process churn from ~2000 to ~250 while still exercising the race window.

    Step 3: Verify no raw spawns bypass the lock

    Audit all Command::new calls in test files. Any spawn NOT using fixture_spawn()/fixture_output()/fixture_status() should be converted to use the fixture methods, or documented as safe (e.g., /bin/true spawns that never write fixtures).

    Step 4: Test

    # Solo run (should pass)
    cargo test --test common concurrent_children -- --test-threads=1
    
    # Stress run (should pass with the fix)
    cargo test --test common concurrent_children -- --test-threads=8
    
    # Concurrent load (should pass with the fix)
    cargo test --test common & cargo test --test cli & wait

    Step 5: PR

    Branch: fix/flaky-fixture-cloexec
    Files changed: tests/common/executable_fixture.rs only
    Gate: must pass full deterministic floor on Linux CI
    Review: one reviewer, focused on the fd-lifetime change

  7. EffortlessSteven commented on Nov 3, 2026

    @EffortlessSteven
    MemberAuthor

    Acceptance criteria

    • write_executable_fixture uses explicit File::create + write_all + sync_all + drop(file) instead of fs::write
    • Stress parameters reduced: Barrier 9→5, iterations 250→50
    • All existing tests pass on Linux CI with the fix applied
    • The flaky test passes under concurrent load (verified by running the full suite while another build is in progress)
    • No new clippy warnings
    • The cross-process lock gap (multiple test binaries racing) is either fixed or documented as a known limitation with a follow-up issue

    Related

    Files affected

    • tests/common/executable_fixture.rs (the fix)
    • tests/common/mod.rs (potentially, for cross-binary coordination)
  8. EffortlessSteven commented on Nov 3, 2026

    @EffortlessSteven
    MemberAuthor

    Source-review clarification for #1636, head 396adc7f0933e5c6b9bde0765ccf55ca5ddb3f68 against base b8854c5e080bd75f5015894d55173388caa787c8:

    • The base already calls fs::write inside the exclusive launch lock, before chmod. Rust 1.95.0 implements fs::write using File::create(path)?.write_all(contents); the temporary File is dropped before that call returns. The new explicit drop preserves this close ordering. sync_all adds persistence, but does not establish a newly closed inheritance window.
    • The stress control now performs 4 × 50 reader launches plus 50 fixture launches: 250 total instead of 2,250. That reduces load and exposure; it does not by itself identify the flake's root cause.
    • The earlier sibling-process explanation also needs correction: a fork inherits its parent's descriptors, not a newly opened descriptor from an independently running sibling test binary.

    This is source review only, with no new execution or demonstrated regression. No introduced correctness defect was found in the changed close/lock ordering. The original failure mechanism and its elimination remain unproven; passing runs should be retained as passing-run evidence rather than causal proof.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugtest

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions