Skip to content

test(package-manager): stop the concurrency probes timing out under load - #13339

Merged
zkochan merged 2 commits into
mainfrom
fix/flaky-add-concurrency-test
Jul 25, 2026
Merged

zkochan merged 2 commits into
mainfrom
fix/flaky-add-concurrency-test

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

add_resolves_package_selectors_concurrently_and_reports_in_selector_order failed intermittently during a full-suite run and passed on a re-run and in isolation, as reported in #13328.

Its three mock latest handlers block on a condvar until all three requests have started, capped at 2 seconds, and the wait_timeout_while result was discarded. A timeout was therefore indistinguishable from "all three started": on a machine loaded enough that the third request was not dispatched within 2 s, the handlers unblocked early, max_active never reached 3, and the overlap assertion failed with nothing pointing at the real cause.

The assertion is worth keeping — it is what pins the concurrent-resolution behaviour from #13097 — so only the deadline changes:

  • The barrier now gets a budget that outlasts scheduling latency on a machine running the whole suite in parallel.
  • The expiry is recorded rather than dropped. The first handler to give up marks the barrier dead, so its peers stop waiting — a genuine regression costs one timeout instead of one per selector — and the test now fails with "the selectors' latest requests never overlapped within 15s" instead of a bare count mismatch.

Verified by making the resolution loop sequential (FuturesOrdered replaced with await-in-loop): the test fails in 15.4 s with that message, and passes again once the implementation is restored.

Two more instances of the same fragile idiom, both flagged in the issue or found alongside it:

  • add_does_not_wait_for_a_slower_later_resolution_after_an_error reads the gap between a fast failing selector and a slow peer through a wall-clock deadline. 100 ms against 3 s left only ~2 s of slack for the fast path; the peer moves to 20 s and the deadline to 5 s, which keeps the same claim with room for a loaded machine. The mock's sleep does not delay teardown — the test still completes in ~0.13 s — so the longer delay costs nothing.
  • LinkConcurrencyProbe (behind cold_batch_links_slots_in_parallel) carried the same 2-second overlap barrier and gets the same budget.

No changeset: test-only, nothing published changes.

Closes #13328

Squash Commit Body

add_resolves_package_selectors_concurrently_and_reports_in_selector_order
failed intermittently during a full-suite run and passed on a re-run. Its
mock handlers block on a condvar until all three latest requests have
started, capped at 2 seconds, and the wait result was discarded — so a
machine too loaded to dispatch the third request in time was
indistinguishable from a genuine loss of concurrency, and the overlap
assertion failed with nothing pointing at the real cause.

Give the barrier a budget that outlasts scheduling latency on a machine
running the whole suite in parallel, and record the expiry: the first
handler to give up marks the barrier dead so its peers stop waiting, which
keeps a real regression to one timeout instead of one per selector, and the
assertion now says the requests never overlapped instead of only reporting
a count mismatch. Verified by making the resolution loop sequential, which
fails with that message.

add_does_not_wait_for_a_slower_later_resolution_after_an_error reads the gap
between a fast failing selector and a slow peer through a wall-clock
deadline. 100 ms against 3 s left only ~2 s of slack for the fast path;
widening the peer to 20 s and the deadline to 5 s keeps the same claim with
room for a loaded machine. The mock's sleep does not delay teardown, so the
longer delay costs nothing.

LinkConcurrencyProbe carried the same 2-second barrier for
cold_batch_links_slots_in_parallel and gets the same treatment.

Closes pnpm/pnpm#13328

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added or updated tests.

Written by an agent (Claude Code, claude-opus-5[1m]).


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Tests
    • Improved concurrency test stability by adding an overlap barrier with a 15s timeout, ensuring deterministic behavior under scheduling latency.
    • Refined error-handling timing assertions by increasing the slower selector delay and extending the overall timeout window.
    • Updated link-concurrency overlap waiting to use an explicit 15s timeout to reduce intermittent timing-related failures.

add_resolves_package_selectors_concurrently_and_reports_in_selector_order
failed intermittently during a full-suite run and passed on a re-run. Its
mock handlers block on a condvar until all three latest requests have
started, capped at 2 seconds, and the wait result was discarded — so a
machine too loaded to dispatch the third request in time was
indistinguishable from a genuine loss of concurrency, and the overlap
assertion failed with nothing pointing at the real cause.

Give the barrier a budget that outlasts scheduling latency on a machine
running the whole suite in parallel, and record the expiry: the first
handler to give up marks the barrier dead so its peers stop waiting, which
keeps a real regression to one timeout instead of one per selector, and the
assertion now says the requests never overlapped instead of only reporting
a count mismatch. Verified by making the resolution loop sequential, which
fails with that message.

add_does_not_wait_for_a_slower_later_resolution_after_an_error reads the gap
between a fast failing selector and a slow peer through a wall-clock
deadline. 100 ms against 3 s left only ~2 s of slack for the fast path;
widening the peer to 20 s and the deadline to 5 s keeps the same claim with
room for a loaded machine. The mock's sleep does not delay teardown, so the
longer delay costs nothing.

LinkConcurrencyProbe carried the same 2-second barrier for
cold_batch_links_slots_in_parallel and gets the same treatment.

Closes #13328
Copilot AI review requested due to automatic review settings July 25, 2026 12:24

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: bdcc7cac-fa3c-482e-972b-3018f736bbbc

📥 Commits

Reviewing files that changed from the base of the PR and between ab25bea and 51b3783.

📒 Files selected for processing (1)
  • pnpm/crates/package-manager/src/add/tests.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • pnpm/crates/package-manager/src/add/tests.rs

📝 Walkthrough

Walkthrough

Concurrency tests now use explicit 15-second overlap timeouts, track barrier expiry, and widen timing windows for slower selector failure scenarios. Virtual-directory link concurrency replaces its hardcoded overlap wait with a named timeout constant.

Changes

Concurrency test timing hardening

Layer / File(s) Summary
Selector resolution timing and fail-fast assertions
pnpm/crates/package-manager/src/add/tests.rs
Selector overlap tests coordinate waiters with barrier expiry tracking and a 15-second timeout; the slower-resolution failure test increases its delay and assertion deadline.
Virtual-directory overlap timeout
pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot/tests.rs
LinkConcurrencyProbe uses a named 15-second overlap timeout instead of a hardcoded two-second duration.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#13097 — Covers related concurrent selector resolution and overlap/error-order test behavior.

Suggested labels: product: pacquet

Suggested reviewers: copilot

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/flaky-add-concurrency-test

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix flaky concurrency probe timeouts in package-manager tests

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Extend overlap-barrier deadlines so concurrency assertions survive loaded CI machines.
• Record and surface barrier timeouts to fail with a clear diagnostic message.
• Widen a wall-clock timeout test to preserve intent while reducing scheduling flakiness.
Diagram

graph TD
  A["add/tests.rs concurrency tests"] --> B["Mock latest handlers"] --> C["Overlap barrier (Condvar)"] --> D{"Barrier timed out?"}
  D -->|yes| E["Mark barrier_expired + wake peers"] --> F["Fail with explicit message"]
  D -->|no| G["Measure max_active overlap"] --> H["Assert overlap + order"]
  I["LinkConcurrencyProbe"] --> J["OVERLAP_TIMEOUT=15s"] --> C
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use an explicit Barrier primitive (tokio::sync::Barrier or channel rendezvous)
  • ➕ More direct expression of “wait until N started” than condvar + counters
  • ➕ Less risk of incorrectly handling timed_out results
  • ➖ May require refactoring the mock handler/threading model to be fully async
  • ➖ Bigger change than needed for a flake fix
2. Remove wall-clock barriers and assert concurrency via instrumentation only
  • ➕ Eliminates time-based flakiness entirely
  • ➕ Simplifies handler logic (no condvar waiting)
  • ➖ Harder to ensure requests truly overlapped (max_active may stay < N without a coordinated start)
  • ➖ Could weaken the regression protection this test provides

Recommendation: Keep the PR’s approach: extend the barrier budget and, crucially, persist the timeout as a shared failure signal. It preserves the original concurrency regression guard while turning scheduling delays into an actionable, deterministic test failure message with minimal churn.

Files changed (2) +33 / -6

Tests (2) +33 / -6
tests.rsHarden add-selector concurrency barrier and improve failure diagnostics +26/-5

Harden add-selector concurrency barrier and improve failure diagnostics

• Introduces a shared 'barrier_expired' flag and extends the overlap barrier timeout to 15s, ensuring slow scheduling doesn’t masquerade as a concurrency regression. Captures the 'wait_timeout_while' result to mark the barrier expired and wake peers early, and adds an assertion that fails with a clear message when overlap never occurs. Also widens the wall-clock timeout test to keep its intent while adding slack under load.

pnpm/crates/package-manager/src/add/tests.rs

tests.rsIncrease LinkConcurrencyProbe overlap wait budget +7/-1

Increase LinkConcurrencyProbe overlap wait budget

• Adds a named 15s 'OVERLAP_TIMEOUT' constant and uses it for the link-overlap condvar wait. This matches the updated philosophy in add tests: deadlines should outlast scheduling latency, while the true verdict remains based on observed concurrency.

pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot/tests.rs

@greptile-apps

greptile-apps Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (2): Last reviewed commit: "test(package-manager): describe what the..." | Re-trigger Greptile

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pnpm/crates/package-manager/src/add/tests.rs`:
- Around line 127-130: Update the comment above OVERLAP_BARRIER_TIMEOUT to
accurately describe max_active as the overlap metric and the timeout as a
bounded failure guard, removing the claim that the verdict comes only from
max_active.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: df993d1e-822d-4c07-8ca6-a50d23e40242

📥 Commits

Reviewing files that changed from the base of the PR and between cf8fdc4 and ab25bea.

📒 Files selected for processing (2)
  • pnpm/crates/package-manager/src/add/tests.rs
  • pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot/tests.rs

@qodo-code-review

qodo-code-review Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. Barrier expiry race 🐞 Bug ☼ Reliability
Description
The overlap handler marks barrier_expired on wait.timed_out() without re-checking whether
requests.started already reached packages.len(), so a timeout/notify boundary race can flip the
flag even when the last request started in time and would have allowed overlap. This can cause a
spurious failure via the new assert!(!requests.barrier_expired) despite concurrency being present.
Code

pnpm/crates/package-manager/src/add/tests.rs[R177-185]

+                let (mut requests, wait) = ready
+                    .wait_timeout_while(requests, OVERLAP_BARRIER_TIMEOUT, |requests| {
+                        requests.started < packages.len() && !requests.barrier_expired
                    })
                    .unwrap();
+                if wait.timed_out() {
+                    requests.barrier_expired = true;
+                    ready.notify_all();
+                }
Relevance

⭐⭐ Medium

Subtle condvar timeout/notify edge; no close precedent showing team handles this timed_out re-check
race.

PR-#13097

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The handler sets barrier_expired solely from wait.timed_out(), and the test later fails if that
flag is set; there is no subsequent check that started was still below the expected count before
expiring the barrier.

pnpm/crates/package-manager/src/add/tests.rs[170-245]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`barrier_expired` is set purely based on `wait.timed_out()`. At the timeout boundary, it’s possible for the timeout to elapse and the final handler to increment `started`/notify at essentially the same time; in that case the barrier can be marked expired even though `started == packages.len()`.

### Issue Context
This flag is asserted at the end of the test and is meant to distinguish scheduling slowness from true loss of concurrency.

### Fix Focus Areas
- pnpm/crates/package-manager/src/add/tests.rs[170-245]

### Suggested change
After `wait_timeout_while` returns, only set `barrier_expired` if the predicate is still true (e.g., `wait.timed_out() && requests.started < packages.len()`). This keeps the improved failure message while avoiding a timeout-boundary false positive.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

2. Long blocked mock worker 🐞 Bug ➹ Performance
Description
The test increases the slow selector’s mock handler delay to 20s using std::thread::sleep, while
Add resolves selectors concurrently and returns early on the first error, canceling remaining
futures. If the slow request is already dispatched before the fast error is observed, the mock
server-side handler can remain blocked for up to 20s even though the test finishes quickly,
potentially reducing parallel test throughput.
Code

pnpm/crates/package-manager/src/add/tests.rs[R452-456]

+    // The gap between the two delays is what the deadline below reads:
+    // the failing selector must return well inside it while the slower
+    // peer is still sleeping, with enough slack that a loaded machine
+    // cannot push the fast path past the deadline.
+    let packages = [("first", "a", 100), ("second", "b", 20_000)];
Relevance

⭐ Low

Team previously rejected changing these add tests to avoid/blocking sleeps in mock handlers; 20s
sleep likely kept intentional.

PR-#13097

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test’s mock handler sleeps for response_delay_ms (now 20_000ms) before writing a response;
Add prepares all selector futures up-front via FuturesOrdered and returns early on the first
error (result?), which can drop/cancel the slower future after it has already begun its network
request.

pnpm/crates/package-manager/src/add/tests.rs[442-519]
pnpm/crates/package-manager/src/add.rs[471-538]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`add_does_not_wait_for_a_slower_later_resolution_after_an_error` now configures a 20s server-side `std::thread::sleep` in the mocked `/latest` handler. Because `Add` starts resolutions concurrently and exits on the first error, the slower request may already be in-flight and then gets canceled client-side; the server handler may still block a worker thread for the full sleep duration.

### Issue Context
The test only needs the slow path to remain slower than the outer `timeout(Duration::from_secs(5), ...)`, not necessarily 20 seconds.

### Fix Focus Areas
- pnpm/crates/package-manager/src/add/tests.rs[452-511]

### Suggested change
Lower the slow delay to something safely above the timeout (e.g., 6–10 seconds) to preserve the intent (fast failure doesn’t wait on a slower peer) while reducing worst-case blocked-worker time. Alternatively, restructure the mock to avoid `std::thread::sleep` in the handler (e.g., a condvar-based gate that can be released early when the test completes, if mockito’s API allows it).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

…ecides

The comment claimed the deadline played no part in the verdict, which
stopped being true once expiry became its own assertion. Say what the
budget is for, and record the std guarantee the expiry flag rests on:
wait_timeout_while re-checks its predicate before reporting a timeout, so
a peer arriving exactly on the deadline cannot be read as an expiry.
Copilot AI review requested due to automatic review settings July 25, 2026 12:37

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zkochan

zkochan commented Jul 25, 2026

Copy link
Copy Markdown
Member Author

Addressed the CodeRabbit comment in 51b3783. The two Qodo bugs I am not acting on, with reasons.

Barrier expiry race — not a race. Condvar::wait_timeout_while evaluates the predicate at the top of every loop iteration and only returns WaitTimeoutResult(true) on an iteration where the predicate still held and the budget was already exhausted (std source). So the boundary case the finding describes — the last handler incrementing started just as the deadline elapses — returns timed_out() == false, because the predicate is re-checked before the timeout is reported. barrier_expired cannot be set while started == packages.len(). Guarding the assignment with requests.started < packages.len() would be dead code implying a race the API rules out. 51b3783 records that invariant in a comment instead, since it is not obvious from the call site.

Long blocked mock worker — measured, no cost. The sleeping handler does not hold the test up or consume a core: it is a thread::sleep in a mockito worker, teardown does not join it, and the test completes in ~0.13 s with the 20 s peer (timed before and after the change). Under nextest each test is its own process, which exits without waiting on the detached thread; under cargo test a sleeping thread costs a stack, not throughput. The wide gap is the point — it is what buys the fast path enough slack that a loaded machine cannot push it past the 5 s deadline, which is the flake this PR exists to remove.


Written by an agent (Claude Code, claude-opus-5[1m]).

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 51b3783

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

@zkochan
zkochan merged commit f7e1fee into main Jul 25, 2026
19 checks passed
@zkochan
zkochan deleted the fix/flaky-add-concurrency-test branch July 25, 2026 12:40
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…oad (pnpm#13339)

add_resolves_package_selectors_concurrently_and_reports_in_selector_order
failed intermittently during a full-suite run and passed on a re-run. Its
mock handlers block on a condvar until all three latest requests have
started, capped at 2 seconds, and the wait result was discarded — so a
machine too loaded to dispatch the third request in time was
indistinguishable from a genuine loss of concurrency, and the overlap
assertion failed with nothing pointing at the real cause.

Give the barrier a budget that outlasts scheduling latency on a machine
running the whole suite in parallel, and record the expiry: the first
handler to give up marks the barrier dead so its peers stop waiting, which
keeps a real regression to one timeout instead of one per selector, and the
assertion now says the requests never overlapped instead of only reporting
a count mismatch. Verified by making the resolution loop sequential, which
fails with that message.

add_does_not_wait_for_a_slower_later_resolution_after_an_error reads the gap
between a fast failing selector and a slow peer through a wall-clock
deadline. 100 ms against 3 s left only ~2 s of slack for the fast path;
widening the peer to 20 s and the deadline to 5 s keeps the same claim with
room for a loaded machine. The mock's sleep does not delay teardown, so the
longer delay costs nothing.

LinkConcurrencyProbe carried the same 2-second barrier for
cold_batch_links_slots_in_parallel and gets the same treatment.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: add_resolves_package_selectors_concurrently_and_reports_in_selector_order fails under full-suite load

2 participants