Skip to content

fix(tarball): fix a lost-wakeup hang in the tarball mem cache - #13166

Merged
zkochan merged 3 commits into
mainfrom
fix-timout
Jul 20, 2026
Merged

zkochan merged 3 commits into
mainfrom
fix-timout

Conversation

@zkochan

@zkochan zkochan commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Summary

The Rust CI job for the 11.15.1 release commit hung for 62 minutes until it was cancelled: https://github.com/pnpm/pnpm/actions/runs/29705938247/job/88242852400. The last test of the run, pacquet-cli::add save_prefix_empty_writes_exact_version (normally 0.2s), never finished — the spawned pacquet process was still alive when the job died.

Root cause: a lost wakeup in DownloadTarballToStore::run_with_mem_cache. A task that finds the per-URL cache slot InProgress released the RwLock read guard and only then polled Notify::notified(). notify_waiters() stores no permit — it wakes only futures registered at that instant — so if the owning fetch flips the slot to Available/Failed and notifies inside that window, the waiter parks forever (nothing ever notifies the slot again). The window requires the owner to complete its flip on another worker thread while the waiter is preempted mid-poll, which is why it surfaced only once, on an oversubscribed CI runner. The waiter path is exercised on every cold add/install: the resolve-time prefetcher owns the fetch and the install pass waits on the same slot (or vice versa — a parked detached prefetch task pins the store-index writer channel and hangs the final writer_task.await instead).

The fix follows the documented tokio pattern: pin the Notified future and enable() it to register interest before re-checking the slot, awaiting only if the slot is still InProgress, in a loop.

Two CI guardrails ride along so any similar hang can never wedge a job again:

  • A workspace .config/nextest.toml with slow-timeout = { period = "60s", terminate-after = 5 }: a test stuck past 300s is killed and reported as TIMEOUT with its captured output, and the rest of the run completes. 300s keeps ~3.5× headroom over the suite's slowest legitimate tests (the fetch-timeout retry-ladder tests: ~70s on Linux/Windows, ~85s on macOS).
  • timeout-minutes: 60 on the Rust CI test job as a backstop for hangs outside nextest (warm-cache runs finish in ~5 minutes; cold-cache rebuilds get the rest of the hour).

Rust-only: the TypeScript CLI dedupes concurrent tarball fetches through shared promises, which cannot lose a completion, so there is nothing to port.

Squash Commit Body

A task that found the per-URL tarball mem-cache slot InProgress released
the RwLock read guard and only then polled Notify::notified().
notify_waiters() stores no permit - it wakes only futures already
registered at that instant - so an owner that flipped the slot to
Available/Failed and notified inside that window left the waiter parked
forever. The window needs the owner to complete its flip on another
worker thread while the waiter is preempted between the guard drop and
its first poll, which is why it surfaced only as a rare hang on an
oversubscribed CI runner: pacquet-cli::add
save_prefix_empty_writes_exact_version (a 0.2s test) hung for over an
hour and wedged the Rust CI job at
https://github.com/pnpm/pnpm/actions/runs/29705938247.

The waiter path runs on every cold add/install: the resolve-time
prefetcher owns the fetch and the install pass waits on the same slot.
A detached prefetch task losing the same race instead pinned the
store-index writer channel open and hung the final writer_task.await -
same root cause, either direction.

Fix per the documented tokio pattern: pin the Notified future and
enable() it to register interest before re-checking the slot state,
awaiting only while the slot is still InProgress, in a loop.

The exact interleaving cannot be reproduced deterministically without
loom (it requires preempting the waiter mid-poll), so no regression
test accompanies the fix. Instead, CI gains guardrails so a recurrence
is a visible failure, not a wedged job: a workspace .config/nextest.toml
sets slow-timeout terminate-after = 5 (a test stuck past 300s is killed
and reported as TIMEOUT with output; ~3.5x headroom over the slowest
legitimate retry-ladder tests), and the Rust CI test job is capped at
timeout-minutes: 60 as a backstop for non-test hangs.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests — the lost wakeup needs the waiter preempted
    mid-poll between two specific instructions, which cannot be scheduled
    deterministically without loom; the existing waiter-path tests cover the new
    loop, and the nextest terminate-after guardrail turns any recurrence into a
    5-minute TIMEOUT failure with output.

Written by an agent (Claude Code, claude-fable-5).


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed a rare hang that could occur during package installation or addition when concurrent operations fetched the same tarball.
    • Improved reliability when waiting for shared package downloads to complete or fail.
  • Tests

    • Added safeguards to detect stalled tests and prevent CI jobs from running indefinitely.

zkochan added 3 commits July 20, 2026 10:31
…he slot

A task that found the per-URL cache slot InProgress released the RwLock
read guard and only then polled Notify::notified(). notify_waiters()
stores no permit - it wakes only futures already registered at that
instant - so an owner that flipped the slot to Available/Failed and
notified inside that window left the waiter parked forever with nothing
ever notifying the slot again. The window needs the owner to complete
its flip on another worker thread while the waiter is preempted between
the guard drop and its first poll, which is why it only surfaced as a
rare hang on oversubscribed CI runners: pacquet-cli::add
save_prefix_empty_writes_exact_version (a 0.2s test) hung for over an
hour and wedged the Rust CI job at
https://github.com/pnpm/pnpm/actions/runs/29705938247.

The waiter path hits this window on every cold add/install of a single
package: the resolve-time prefetcher spawns the owning fetch and the
install pass then waits on the same slot. A detached prefetch task
losing the same race also pinned the store-index writer channel open,
hanging the final writer_task.await instead - same root cause, either
direction.

Fix per the documented tokio pattern: pin the Notified future and
enable() it to register interest before re-checking the slot state,
awaiting only if the slot is still InProgress, in a loop. A wakeup that
lands between the re-check and the await now completes the already
registered future instead of vanishing.

The exact interleaving cannot be reproduced deterministically without
loom (it requires preempting the waiter mid-poll), so no regression
test accompanies the fix; the nextest terminate-after guardrail added
alongside turns any recurrence into a visible 5-minute test failure.
nextest's default slow-timeout only marks a test SLOW every 60s and
waits forever, so a single hung test binary wedged the whole job until
someone cancelled it from outside, with no output from the offender.
Set terminate-after = 5 in a workspace .config/nextest.toml: a test
stuck past 300s is now killed and reported as TIMEOUT with its captured
output, and the rest of the run completes. The threshold keeps 3.5x
headroom over the suite's slowest legitimate tests (the fetch-timeout
retry-ladder tests, ~70s on Linux/Windows and ~85s on macOS).

Also cap the test job at 60 minutes as a backstop for hangs outside
nextest (stuck cargo build or tool download): warm-cache runs finish in
about 5 minutes, cold-cache workspace rebuilds get the rest of the
hour, and the GitHub default is 360 minutes.
The perfectionist::impure_macro_arguments dylint requires impure
expressions to be bound outside the macro call.
Copilot AI review requested due to automatic review settings July 20, 2026 08:42

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 20, 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: 45c01d82-e656-41e1-9350-ced70f9bd229

📥 Commits

Reviewing files that changed from the base of the PR and between 9bc24c9 and 769b27b.

📒 Files selected for processing (4)
  • .changeset/tarball-mem-cache-lost-wakeup.md
  • .config/nextest.toml
  • .github/workflows/pacquet-ci.yml
  • pnpm/crates/tarball/src/lib.rs

📝 Walkthrough

Walkthrough

The tarball memory-cache waiter now prevents missed wakeups by registering notifications before state checks and retrying while downloads remain in progress. Nextest and CI receive timeout safeguards, and a patch changeset documents the fix.

Changes

Tarball cache reliability

Layer / File(s) Summary
Memory-cache waiter wakeup fix
pnpm/crates/tarball/src/lib.rs, .changeset/tarball-mem-cache-lost-wakeup.md
The waiter loop registers notifications before re-checking cache state, returns terminal Available or Failed states immediately, and continues waiting for InProgress; the changeset records the patch release and hang fix.
Test and CI timeout safeguards
.config/nextest.toml, .github/workflows/pacquet-ci.yml
Nextest terminates repeatedly slow tests after 60-second periods, while the Rust test job has a 60-minute timeout backstop.

Estimated code review effort: 3 (Moderate) | ~20 minutes

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-timout

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 tarball mem-cache lost wakeup and add Rust CI timeout guardrails

🐞 Bug fix ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• Fix a tokio Notify lost-wakeup race in tarball mem-cache waiters.
• Add workspace nextest slow-timeout to terminate and report hung tests.
• Add a GitHub Actions job timeout to prevent indefinitely wedged CI runs.
Diagram

graph TD
  F["Rust CI"] --> A["pnpm add/install (Rust)"] --> B["DownloadTarballToStore"] --> C[("Per-URL mem-cache slot")]
  C --> D["Owner fetch (flip+notify_waiters)"]
  C --> E["Waiter tasks (Notified.enable + recheck)"] --> C
  F --> G["Guardrails: nextest slow-timeout + job timeout"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Replace Notify with watch/oneshot-based state propagation
  • ➕ Eliminates lost-wakeup class entirely by storing the latest state/value
  • ➕ Can make waiter logic simpler (await state change, then read state)
  • ➖ More per-slot allocation/state (sender/receiver management)
  • ➖ More invasive refactor vs. minimal, well-known tokio Notify pattern
  • ➖ Needs careful handling for multiple waiters and terminal state cleanup
2. Use notify_one with stored permits (instead of notify_waiters)
  • ➕ Permits can be stored, reducing missed notifications for single waiter
  • ➖ Doesn’t fit multi-waiter scenario without looping notify_one N times
  • ➖ Harder to ensure all waiters are woken exactly once in a dedupe slot

Recommendation: Keep the PR’s approach: pinning Notified and calling enable() before re-checking the slot is the documented tokio pattern for avoiding lost wakeups with Notify, and it preserves the existing design with minimal churn. The added CI timeouts are appropriate defense-in-depth for future deadlocks/hangs outside this specific bug.

Files changed (4) +64 / -16

Bug fix (1) +36 / -16
lib.rsFix lost-wakeup race when waiting on tarball mem-cache slot +36/-16

Fix lost-wakeup race when waiting on tarball mem-cache slot

• Reworks the InProgress waiter path to avoid a tokio::sync::Notify lost-wakeup window by pinning the Notified future and calling enable() before re-checking cache state. Waiters now loop: register interest, re-check for terminal state, then await only if still InProgress.

pnpm/crates/tarball/src/lib.rs

Documentation (1) +5 / -0
tarball-mem-cache-lost-wakeup.mdAdd changeset entry documenting the rare concurrent-fetch hang fix +5/-0

Add changeset entry documenting the rare concurrent-fetch hang fix

• Introduces a patch-level changeset for pacquet describing a rare hang during concurrent tarball fetches. Communicates the user-visible symptom (install/add waiting forever) and the concurrency root cause at a high level.

.changeset/tarball-mem-cache-lost-wakeup.md

Other (2) +23 / -0
nextest.tomlConfigure nextest to terminate and report stuck tests +17/-0

Configure nextest to terminate and report stuck tests

• Adds workspace-wide cargo-nextest configuration enabling slow-timeout termination (60s period, terminate after 5 intervals). Prevents a single hung test binary from wedging the entire run and ensures captured output is reported as TIMEOUT.

.config/nextest.toml

pacquet-ci.ymlAdd job-level timeout to Rust CI test workflow +6/-0

Add job-level timeout to Rust CI test workflow

• Sets timeout-minutes: 60 on the Rust CI test job as a backstop for hangs outside nextest (e.g., stuck builds or tool downloads). Limits worst-case CI runtime versus the default multi-hour GitHub Actions timeout.

.github/workflows/pacquet-ci.yml

@greptile-apps

greptile-apps Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge — the fix correctly resolves a rare but real hang with no observable behavior change for the normal fast path.

The waiter loop follows the tokio-documented notify_waiters pattern precisely: enable() is called before the state check, the read guard is released before the await, and the defensive InProgress loop iteration is harmless. The owner branch is unchanged. CI guardrails are correctly sized and add no functional risk.

No files require special attention.

Reviews (1): Last reviewed commit: "style(tarball): let-bind the Notified fu..." | Re-trigger Greptile

@github-actions

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.01     10.3±0.18ms    36.4 MB/sec    1.00     10.2±0.21ms    36.8 MB/sec
packument/parse                1.00     36.5±0.63µs  1815.3 MB/sec    1.00     36.4±0.45µs  1824.2 MB/sec
tarball/download_dependency    1.01      2.7±0.12ms  1579.2 KB/sec    1.00      2.7±0.10ms  1598.7 KB/sec

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 20, 2026
@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Informational

1. Lost fail-fast invariant check 🐞 Bug ◔ Observability
Description
After a waiter registers and wakes, the code now silently tolerates seeing CacheValue::InProgress
and re-parks, whereas the prior code would panic on this impossible state; if a future refactor/bug
ever notifies before flipping the slot, this can regress from a loud failure into another silent
hang. This is currently unreachable given the owner’s “flip then notify_waiters” ordering, but
removing the assertion reduces diagnosability and makes future concurrency bugs harder to detect.
Code

pnpm/crates/tarball/src/lib.rs[R2241-2248]

+                    // The owner notifies only after flipping the slot
+                    // to `Available` or `Failed`, so a wake with the
+                    // slot still `InProgress` cannot happen — but a
+                    // stale registration completing early is harmless
+                    // either way: re-register and park again.
+                    CacheValue::InProgress(_) => {}
                }
-                // The owner only flips us to `Available` or `Failed`
-                // before notifying. Hitting this is a programmer
-                // error in the owner branch below.
-                CacheValue::InProgress(_) => unreachable!(
-                    "owner notified waiters but left the cache in InProgress for {package_url:?}",
-                ),
+                notified.await;
Evidence
The waiter loop explicitly treats CacheValue::InProgress(_) as a harmless case and immediately
re-awaits, so if a wake occurs while the slot is still InProgress and no further notifications
happen, the task can remain blocked indefinitely. The owner code shows the intended invariant (write
Available/Failed then notify_waiters()), so an InProgress observation after a wake indicates
an invariant violation that is now no longer surfaced loudly.

pnpm/crates/tarball/src/lib.rs[2211-2249]
pnpm/crates/tarball/src/lib.rs[2271-2286]

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

### Issue description
The waiter loop no longer fails fast if it observes `CacheValue::InProgress` after being woken. If the invariant is ever violated (e.g., a future change that calls `notify_waiters()` before flipping the slot), the waiter can re-register and await again with no further notifications, recreating a silent hang and obscuring the root cause.

### Issue Context
The owner path currently transitions the slot to `Available`/`Failed` and only then calls `notify.notify_waiters()`, so `InProgress` after a wake should be impossible. Preserving a fail-fast check here provides a strong guardrail and better debugging signal if that invariant is ever broken.

### Fix Focus Areas
- pnpm/crates/tarball/src/lib.rs[2212-2249]
- pnpm/crates/tarball/src/lib.rs[2271-2286]

### Suggested change
After `notified.await`, re-check the slot once and `unreachable!()` / `debug_assert!()` (or log+panic) if it is still `InProgress`. This keeps the lost-wakeup fix while restoring the invariant enforcement.

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


Grey Divider

Qodo Logo

@zkochan
zkochan merged commit b92edcb into main Jul 20, 2026
32 checks passed
@zkochan
zkochan deleted the fix-timout branch July 20, 2026 08:48
@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.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.44%. Comparing base (331c26a) to head (769b27b).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pnpm/crates/tarball/src/lib.rs 80.00% 3 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13166   +/-   ##
=======================================
  Coverage   86.44%   86.44%           
=======================================
  Files         508      508           
  Lines       85078    85086    +8     
=======================================
+ Hits        73542    73554   +12     
+ Misses      11536    11532    -4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

zzstar101 added a commit to zzstar101/pnpm that referenced this pull request Sep 27, 2026
`node --test pnpm/scripts/*.test.mjs` now fails when a nextest profile
declares `slow-timeout` without `terminate-after`. Without it, nextest only
marks a test SLOW every `period` and then waits for it forever, so a single
hung test binary wedges the run until the CI job is killed from outside — the
80-minute `Rust CI / Test` job recorded in pnpm/tasks#32.

The backstop is already in place: `.config/nextest.toml` has carried
`slow-timeout = { period = "60s", terminate-after = 5 }` since
pnpm#13166, and profiles that declare no `slow-timeout` inherit it from
`default`. Nothing asserted that, so an edit could drop `terminate-after` and
bring the wedge back in silence. This pins the existing backstop rather than
adding a second deadline: the bounds the task asked for are already there, in
pnpr's per-request upstream timeout and in pacquet's fetch-timeout.

Refs pnpm/tasks#32
zkochan pushed a commit that referenced this pull request Sep 30, 2026
* test(ci): pin the nextest terminate-after backstop

`node --test pnpm/scripts/*.test.mjs` now fails when a nextest profile
declares `slow-timeout` without `terminate-after`. Without it, nextest only
marks a test SLOW every `period` and then waits for it forever, so a single
hung test binary wedges the run until the CI job is killed from outside — the
80-minute `Rust CI / Test` job recorded in pnpm/tasks#32.

The backstop is already in place: `.config/nextest.toml` has carried
`slow-timeout = { period = "60s", terminate-after = 5 }` since
#13166, and profiles that declare no `slow-timeout` inherit it from
`default`. Nothing asserted that, so an edit could drop `terminate-after` and
bring the wedge back in silence. This pins the existing backstop rather than
adding a second deadline: the bounds the task asked for are already there, in
pnpr's per-request upstream timeout and in pacquet's fetch-timeout.

Refs pnpm/tasks#32

* test(ci): cover per-test slow-timeout overrides in the backstop guard

`[[profile.*.overrides]]` sections land inside the body of the profile they
belong to, and the guard only looked at the first `slow-timeout` declaration
there, so an override that named a period without `terminate-after` slipped
through.

That case is real: nextest resolves `slow-timeout` as one setting
(`nextest-runner/src/config/overrides/imp.rs`, `TestSettings::slow_timeout`),
and `SlowTimeout::terminate_after` is an `Option`, so an override that sets
only `period` replaces the profile's policy and a test it matches can be
marked SLOW and then waited for forever.

Scan every `[[profile.*.overrides]]` section as well, while still skipping
profiles and overrides that declare no `slow-timeout`. Verified against the
real config and with both negative controls: an override declaring
`slow-timeout = "10s"` fails the guard naming `[profile.probe.overrides]`,
while `slow-timeout = { period = "10s", terminate-after = 3 }` passes it.

Refs pnpm/tasks#32.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants