Skip to content

fix(jest-config): remove the registry mock storage after the run - #13340

Merged
zkochan merged 3 commits into
mainfrom
fix-jest-registry-storage-leak
Jul 25, 2026
Merged

zkochan merged 3 commits into
mainfrom
fix-jest-registry-storage-leak

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

The with-registry jest preset never removed the storage it built, so every run of every registry-backed suite leaked a temp directory permanently.

globalSetup creates one with mkdtemp and builds verdaccio-shaped storage into it; globalTeardown only killed the server. Sizes vary with how much a suite proxies — a small suite leaves ~2 MB, suites that pull real packages through the proxy cache leave up to ~2 GB.

Where /tmp is a tmpfs these accumulate until it fills, at which point the suite starts failing with:

ERR_PNPM_LOCKFILE_WRITE_FILE
╰─▶ Failed to write lockfile content: No space left on device (os error 28)

That reads as flakiness rather than a full disk — a different arbitrary test fails on each run, each passes in isolation, and a fresh checkout passes because nothing has accumulated yet. I chased it as a code bug for a while before reading the stderr. I had 78 of these directories by the time I noticed. Context in #13328.

Approach

globalSetup hands the path it created to globalTeardown through global, the same channel it already uses for killServer. Teardown removes only that directory, so a storage path supplied from outside could never be deleted by it.

Two details:

  • Removal happens after the server is killed. pnpr writes proxy-cache entries into the storage as it serves, so removing it underneath a live server races with those writes.
  • A failed removal warns instead of throwing. A leaked temp directory should not turn an otherwise-green run red, but it should not be silent either — it is the thing that eventually fills /tmp.

Verification

Ran pnpm --filter=@pnpm/cache.commands test with and without the change, diffing /tmp around it:

dirs left behind
before 2
after 0

pnpm run lint passes.

Existing leftovers are not swept — deleting pnpm-registry-mock-storage-* wholesale would race with any concurrently running suite. Clean them once by hand with rm -rf /tmp/pnpm-registry-mock-storage-* while no tests are running; after this change nothing new accumulates.

Squash Commit Body

The `with-registry` jest preset built its verdaccio-shaped storage into
a fresh mkdtemp directory on every run, but globalTeardown only killed
the server — the directory was never removed, so every run of every
registry-backed suite leaked one permanently (~2 MB for a small suite,
up to ~2 GB for suites that proxy real packages).

On a tmpfs /tmp they accumulate until it fills, and the suite then fails
with ENOSPC in whichever test happens to write next — which reads as
flakiness, since a different test fails each run and each passes in
isolation.

globalSetup now hands the path it created to globalTeardown through
`global`, the same way it already hands over killServer, so teardown
removes only that run's directory. Removal happens after the server is
killed, since pnpr writes proxy-cache entries into the storage while
serving. A failed removal warns rather than throwing.

Related to 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.
    (No pacquet counterpart: its fixture storage is content-fingerprinted under
    target/ and reused across runs rather than created per run, so it does not
    leak.)
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. (@pnpm/jest-config is private — no changeset.)
  • Added or updated tests. (Test infrastructure; verified by diffing /tmp
    around a real suite run, with and without the change.)
  • Updated the documentation if needed.

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

  • Bug Fixes
    • Improved test environment cleanup by reliably removing temporary registry storage after Jest runs.
    • Ensured teardown continues even if server shutdown fails, with clearer error handling.
    • Prevented leftover temporary data from accumulating and causing disk-space-related test failures.
  • Tests
    • Added coverage to verify storage cleanup occurs in both normal and shutdown-failure scenarios.
  • Chores
    • Updated Jest configuration and added a dedicated test script for consistent execution.

The `with-registry` jest preset builds a verdaccio-shaped storage into a
fresh `mkdtemp` directory on every run, but `globalTeardown` only killed
the server — the directory was never removed. Every run of every
registry-backed suite therefore leaked one, permanently.

The sizes vary with how much a suite proxies: a small suite leaves
~2 MB, while suites that pull real packages through the proxy cache
leave up to ~2 GB. On a machine where `/tmp` is a tmpfs they accumulate
until it fills, and the suite then fails with

    ERR_PNPM_LOCKFILE_WRITE_FILE
    ╰─▶ Failed to write lockfile content: No space left on device (os error 28)

which reads as flakiness rather than a full disk: a different arbitrary
test fails on each run, each one passes in isolation, and a fresh
checkout passes because nothing has accumulated yet. I had 78 of these
directories before noticing.

`globalSetup` now hands the path it created to `globalTeardown` through
`global`, the same way it already hands over `killServer`, so teardown
removes only that run's directory and never one supplied from outside.
Removal happens after the server is killed, since pnpr writes
proxy-cache entries into the storage as it serves. A failure to remove
warns instead of throwing: a leaked temp directory should not turn an
otherwise-green run red.

Verified by running `pnpm --filter=@pnpm/cache.commands test` with and
without the change: two directories left behind before, none after.

No changeset — `@pnpm/jest-config` is private. No pacquet counterpart:
its fixture storage is content-fingerprinted under `target/` and reused
across runs rather than created per run, so it does not leak.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 25, 2026 12:29

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

Warning

Review limit reached

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

Next review available in: 3 minutes

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: bf58a628-3856-40de-a439-37cf2247c2bc

📥 Commits

Reviewing files that changed from the base of the PR and between 091cae4 and cee6559.

📒 Files selected for processing (5)
  • pnpm11/__utils__/jest-config/package.json
  • pnpm11/__utils__/jest-config/test/globalTeardown.test.js
  • pnpm11/__utils__/jest-config/with-registry/globalSetup.js
  • pnpm11/__utils__/jest-config/with-registry/globalTeardown.js
  • pnpm11/__utils__/jest-config/with-registry/storagePrefix.js
📝 Walkthrough

Walkthrough

Temporary registry storage is assigned to global state during setup. Jest teardown now awaits server shutdown, removes the recorded storage directory recursively, handles shutdown and removal errors, and skips cleanup when no path exists. Tests and Jest package configuration cover this behavior.

Changes

Registry storage cleanup

Layer / File(s) Summary
Storage handoff and teardown cleanup
pnpm11/__utils__/jest-config/with-registry/globalSetup.js, pnpm11/__utils__/jest-config/with-registry/globalTeardown.js
Setup records the temporary registry storage path. Teardown awaits server shutdown, recursively removes the path, preserves shutdown errors, and combines shutdown and removal failures.
Teardown behavior coverage
pnpm11/__utils__/jest-config/test/globalTeardown.test.js
Tests cover recursive removal, cleanup after shutdown failure, absent storage paths, and test-state isolation.
Jest test wiring
pnpm11/__utils__/jest-config/package.json
Adds Jest dependencies, an ESM-compatible test script, and the pnpm Jest preset.

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

Suggested labels: product: pnpm@11

Suggested reviewers: copilot

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-jest-registry-storage-leak

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 Jest with-registry teardown to delete temporary Verdaccio storage

🐞 Bug fix 🕐 10-20 Minutes

Grey Divider

AI Description

• Persist per-run registry mock storage path from globalSetup to globalTeardown.
• Kill the mock registry server, then recursively remove the temp storage directory.
• Warn (don�t fail) if cleanup cannot remove the directory to avoid test flakiness.
Diagram

graph TD
  T["Jest test run"] --> S["globalSetup.js"] --> D[("Temp storage dir")] --> R["Registry mock server"] --> G["globalTeardown.js"] --> F["rm -r storage"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Return teardown context via Jest setup result (instead of global)
  • ➕ Avoids implicit shared global state between setup/teardown.
  • ➕ More explicit contract for what teardown should clean up.
  • ➖ Jest�s globalSetup/globalTeardown APIs don�t provide a clean typed channel in plain JS; often still ends up using globals/env.
  • ➖ Would require more structural changes across the preset for marginal gain.
2. Best-effort sweep of all pnpm-registry-mock-storage-* on teardown/start
  • ➕ Cleans up historical leftovers without manual intervention.
  • ➖ Races with concurrently running test suites (could delete active storage).
  • ➖ Requires extra locking/uniqueness mechanisms to be safe.

Recommendation: The PR�s approach (store only the per-run mkdtemp path on global and remove it after killing the server) is the safest minimal change: it avoids deleting externally-supplied paths and avoids races by ensuring server shutdown precedes deletion. The warning-on-failure behavior is appropriate to prevent turning cleanup issues into new test flakiness while still surfacing leaks.

Files changed (2) +23 / -2

Bug fix (2) +23 / -2
globalSetup.jsPersist per-run mock storage path for teardown cleanup +5/-0

Persist per-run mock storage path for teardown cleanup

• Stores the mkdtemp-created registry mock storage directory path on global so globalTeardown can delete only the directory created for that run. Adds explanatory comments documenting the ENOSPC/leak failure mode.

pnpm11/utils/jest-config/with-registry/globalSetup.js

globalTeardown.jsDelete registry mock storage after stopping the server +18/-2

Delete registry mock storage after stopping the server

• Converts teardown to async, stops the mock server first, then recursively removes the per-run storage directory via fs/promises rm. Cleanup failures are surfaced as warnings instead of failing the test run.

pnpm11/utils/jest-config/with-registry/globalTeardown.js

@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: 3

🤖 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 `@pnpm11/__utils__/jest-config/with-registry/globalTeardown.js`:
- Around line 7-12: Update the teardown flow around global.killServer and
registryMockStorage so rm always runs even when server shutdown rejects or times
out. Place storage cleanup in a finally block, while preserving and propagating
the original shutdown error after cleanup completes.
- Around line 3-18: Add a checked-in regression test for the global teardown
function in globalTeardown.js that exercises setup and teardown, then asserts
the registry mock storage directory no longer exists afterward. Use the existing
global.killServer and global.registryMockStorage integration points, and keep
the test targeted to cleanup of leftover registry storage directories.
- Around line 11-18: Update the cleanup try/catch around rm in globalTeardown so
only expected missing-path failures such as ENOENT are ignored; rethrow
permission, I/O, and other unexpected failures instead of downgrading them to
warnings. Inspect the caught error using its native error code/property rather
than instanceof Error, while preserving the existing warning for handled cleanup
failures.
🪄 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: 6a3752f6-fddd-4f04-890d-f940b0cd7521

📥 Commits

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

📒 Files selected for processing (2)
  • pnpm11/__utils__/jest-config/with-registry/globalSetup.js
  • pnpm11/__utils__/jest-config/with-registry/globalTeardown.js

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Remediation recommended

1. Nonstandard Jest test script ✓ Resolved 🐞 Bug ☼ Reliability ⭐ New
Description
pnpm11/__utils__/jest-config adds only a "test" script and sets a fixed NODE_OPTIONS value, which
can both drop caller/CI-provided NODE_OPTIONS flags and fail to integrate with the repo’s standard
recursive .test runner. This can lead to environment-specific test flakiness and/or the new tests
not being executed in the main workspace test flow.
Code

pnpm11/utils/jest-config/package.json[R28-33]

+  "scripts": {
+    "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
+  },
+  "jest": {
+    "preset": "@pnpm/jest-config"
+  }
Relevance

⭐⭐ Medium

Repo has rejected some test-script convention tweaks; no clear precedent on requiring .test or
preserving NODE_OPTIONS.

PR-#13064

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new package script overwrites NODE_OPTIONS and only defines test, while the root workspace
runner uses recursive .test and other packages define .test using an append-to-$NODE_OPTIONS
pattern.

pnpm11/utils/jest-config/package.json[28-33]
package.json[12-16]
pnpm11/utils/scripts/package.json[6-9]
pnpm11/utils/get-release-text/package.json[6-12]

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

### Issue description
`pnpm11/__utils__/jest-config/package.json` defines a `test` script that overwrites `NODE_OPTIONS` and does not define the workspace-standard `.test` script used by recursive test runs.

### Issue Context
The repo’s root scripts invoke `-r .test`, and other workspace packages implement `.test` to run jest while *appending* to existing `NODE_OPTIONS`.

### Fix Focus Areas
- pnpm11/__utils__/jest-config/package.json[28-33]
- package.json[12-16]
- pnpm11/__utils__/scripts/package.json[6-9]

### Suggested change
- Add a `.test` script that runs jest.
- Make `test` call `pn .test` (optional, but aligns with other packages).
- Preserve existing env flags by appending to `$NODE_OPTIONS` (and consider matching the repo’s usual warning-suppression flags).

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


2. came back historical comments ✓ Resolved 📘 Rule violation ⚙ Maintainability ⭐ New
Description
New comments use historical phrasing (came back / come back) instead of describing the current
behavior and rationale. This conflicts with the rule to keep source comments focused on present-day
contracts, and makes comments go stale as implementations evolve.
Code

pnpm11/utils/jest-config/test/globalTeardown.test.js[R30-31]

+// The leak this teardown exists to prevent came back if a rejecting
+// `killServer` skipped the removal.
Relevance

⭐⭐ Medium

Mixed history: some temporal/historical comment rewrites accepted, but multiple similar requests
were rejected as stylistic.

PR-#13125
PR-#12964
PR-#12954

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The checklist forbids comments that reference past behavior using historical/temporal phrasing. The
added comment in the new test file says the leak "came back", and the JSDoc in globalTeardown.js
says the leak could "come back", both of which are explicitly the kind of historical phrasing the
rule disallows.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm11/utils/jest-config/test/globalTeardown.test.js[30-31]
pnpm11/utils/jest-config/with-registry/globalTeardown.js[35-40]

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

## Issue description
Comments added in this PR use historical phrasing (e.g., `came back` / `come back`) rather than describing current behavior and rationale.

## Issue Context
Per the compliance checklist, comments should describe current behavior/contracts and avoid historical narration.

## Fix Focus Areas
- pnpm11/__utils__/jest-config/test/globalTeardown.test.js[30-31]
- pnpm11/__utils__/jest-config/with-registry/globalTeardown.js[35-40]

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


3. Missing rm retry options ✓ Resolved 🐞 Bug ☼ Reliability
Description
globalTeardown removes a multi-GB temp directory with rm(recursive, force) but without
maxRetries/retryDelay, so transient EBUSY/EPERM failures will warn and still leak the storage this
PR is trying to eliminate. The repo already uses rm retries elsewhere to handle Windows/handle
contention cleanup reliably.
Code

pnpm11/utils/jest-config/with-registry/globalTeardown.js[R11-13]

+  try {
+    await rm(storage, { recursive: true, force: true })
+  } catch (err) {
Relevance

⭐⭐⭐ High

They already added rm(maxRetries,retryDelay) for Windows EBUSY cleanup; same reliability pattern
fits teardown deletion.

PR-#12575

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The teardown currently performs best-effort deletion without retries, which can leave large
directories behind when rm fails; the codebase already demonstrates a pattern of adding rm retries
to avoid such leaks on Windows.

pnpm11/utils/jest-config/with-registry/globalTeardown.js[9-18]
pnpm11/exec/commands/src/dlx.ts[215-230]

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

### Issue description
`globalTeardown` deletes the registry mock storage via `rm(storage, { recursive: true, force: true })` but does not use `maxRetries`/`retryDelay`. On platforms/filesystems where recently-written files can be briefly locked (notably Windows, AV scanners, etc.), the removal can fail transiently; because the code catches and only warns, the temp directory remains and can accumulate until `/tmp` (or the temp volume) fills.

### Issue Context
There is existing precedent in the repo for using bounded retries for best-effort cleanup so transient handle-holding does not defeat cleanup.

### Fix Focus Areas
- pnpm11/__utils__/jest-config/with-registry/globalTeardown.js[9-18]

### Suggested change
Use something like:
- `await rm(storage, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })`

Keep the existing try/catch + warn as the final fallback after retries are exhausted.

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



Informational

4. Temp dir cleanup not guaranteed ✓ Resolved 🐞 Bug ☼ Reliability ⭐ New
Description
The new globalTeardown tests create real temp directories with mkdtempSync, but only clean them up
via the code under test; if a test fails before calling globalTeardown (or throws during setup), the
directory can be left behind. This can reintroduce /tmp pollution during failing runs and make
subsequent runs flaky on tmpfs systems.
Code

pnpm11/utils/jest-config/test/globalTeardown.test.js[R9-18]

+afterEach(() => {
+  delete global.killServer
+  delete global.registryMockStorage
+})
+
+function createStorage () {
+  const storage = mkdtempSync(path.join(tmpdir(), 'pnpm-registry-mock-storage-test-'))
+  // Non-empty, so a recursive removal is actually exercised.
+  writeFileSync(path.join(storage, 'packument.json'), '{}')
+  return storage
Relevance

⭐⭐⭐ High

Team previously accepted preventing test artifacts from leaking by ensuring cleanup runs even on
failures.

PR-#11363

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test suite creates a real temp directory and only clears globals in afterEach; there is no
fallback filesystem removal if execution fails before calling the teardown function.

pnpm11/utils/jest-config/test/globalTeardown.test.js[9-18]
PR-#11363

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

### Issue description
Tests create temp dirs but don’t have a guaranteed cleanup path if the test fails before invoking `globalTeardown()`.

### Issue Context
`afterEach()` currently only deletes global references; it does not remove any filesystem artifacts created by `createStorage()`.

### Fix Focus Areas
- pnpm11/__utils__/jest-config/test/globalTeardown.test.js[9-18]

### Suggested change
Track created storage paths and remove them in `afterEach` (best-effort, `rmSync(..., { recursive: true, force: true })`) or wrap each test body in `try/finally` to ensure cleanup even on assertion/setup failures.

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


5. Unvalidated recursive delete target 🐞 Bug ⛨ Security
Description
globalTeardown recursively deletes the path stored in global.registryMockStorage without validating
it matches the expected mkdtemp-created directory under os.tmpdir(). This is low-likelihood in
normal runs, but it increases the blast radius of accidental/mis-set globals because rm(recursive,
force) can remove an unintended directory tree.
Code

pnpm11/utils/jest-config/with-registry/globalTeardown.js[R9-12]

+  const storage = global.registryMockStorage
+  if (storage == null) return
+  try {
+    await rm(storage, { recursive: true, force: true })
Relevance

⭐⭐⭐ High

Repo often hardens file/path side effects; validating rm target under tmpdir matches prior
security-style fixes.

PR-#12669
PR-#13075

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Setup stores the mkdtemp path in a mutable global, while teardown deletes that global path
recursively with force and no invariant checks.

pnpm11/utils/jest-config/with-registry/globalSetup.js[23-35]
pnpm11/utils/jest-config/with-registry/globalTeardown.js[3-18]

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

### Issue description
`globalTeardown` uses `rm(storage, { recursive: true, force: true })` on `global.registryMockStorage` without verifying the path is the specific temp directory created by this preset (expected prefix + under `os.tmpdir()`). This is primarily defense-in-depth: if the global is ever accidentally overwritten, teardown could delete an unintended path.

### Issue Context
`globalSetup` creates the storage with `mkdtempSync(path.join(tmpdir(), 'pnpm-registry-mock-storage-'))` and stores it in `global.registryMockStorage`. Teardown should only remove directories that match that invariant.

### Fix Focus Areas
- pnpm11/__utils__/jest-config/with-registry/globalSetup.js[23-35]
- pnpm11/__utils__/jest-config/with-registry/globalTeardown.js[9-18]

### Suggested change
Before calling `rm`, validate:
- `resolvedStorage` is inside `tmpdir()` (use `path.resolve` + `path.relative` or a proper path containment check)
- basename starts with `pnpm-registry-mock-storage-`
- `resolvedStorage` is not equal to `tmpdir()` / `/`

If validation fails, `console.warn` and skip deletion (or throw if you prefer to fail fast in CI).

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


Grey Divider

Previous review results

Review updated until commit cee6559

Results up to commit b562326 ⚖️ Balanced


🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Missing rm retry options ✓ Resolved 🐞 Bug ☼ Reliability
Description
globalTeardown removes a multi-GB temp directory with rm(recursive, force) but without
maxRetries/retryDelay, so transient EBUSY/EPERM failures will warn and still leak the storage this
PR is trying to eliminate. The repo already uses rm retries elsewhere to handle Windows/handle
contention cleanup reliably.
Code

pnpm11/utils/jest-config/with-registry/globalTeardown.js[R11-13]

+  try {
+    await rm(storage, { recursive: true, force: true })
+  } catch (err) {
Relevance

⭐⭐⭐ High

They already added rm(maxRetries,retryDelay) for Windows EBUSY cleanup; same reliability pattern
fits teardown deletion.

PR-#12575

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The teardown currently performs best-effort deletion without retries, which can leave large
directories behind when rm fails; the codebase already demonstrates a pattern of adding rm retries
to avoid such leaks on Windows.

pnpm11/utils/jest-config/with-registry/globalTeardown.js[9-18]
pnpm11/exec/commands/src/dlx.ts[215-230]

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

### Issue description
`globalTeardown` deletes the registry mock storage via `rm(storage, { recursive: true, force: true })` but does not use `maxRetries`/`retryDelay`. On platforms/filesystems where recently-written files can be briefly locked (notably Windows, AV scanners, etc.), the removal can fail transiently; because the code catches and only warns, the temp directory remains and can accumulate until `/tmp` (or the temp volume) fills.

### Issue Context
There is existing precedent in the repo for using bounded retries for best-effort cleanup so transient handle-holding does not defeat cleanup.

### Fix Focus Areas
- pnpm11/__utils__/jest-config/with-registry/globalTeardown.js[9-18]

### Suggested change
Use something like:
- `await rm(storage, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })`

Keep the existing try/catch + warn as the final fallback after retries are exhausted.

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



Informational
2. Unvalidated recursive delete target 🐞 Bug ⛨ Security
Description
globalTeardown recursively deletes the path stored in global.registryMockStorage without validating
it matches the expected mkdtemp-created directory under os.tmpdir(). This is low-likelihood in
normal runs, but it increases the blast radius of accidental/mis-set globals because rm(recursive,
force) can remove an unintended directory tree.
Code

pnpm11/utils/jest-config/with-registry/globalTeardown.js[R9-12]

+  const storage = global.registryMockStorage
+  if (storage == null) return
+  try {
+    await rm(storage, { recursive: true, force: true })
Relevance

⭐⭐⭐ High

Repo often hardens file/path side effects; validating rm target under tmpdir matches prior
security-style fixes.

PR-#12669
PR-#13075

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Setup stores the mkdtemp path in a mutable global, while teardown deletes that global path
recursively with force and no invariant checks.

pnpm11/utils/jest-config/with-registry/globalSetup.js[23-35]
pnpm11/utils/jest-config/with-registry/globalTeardown.js[3-18]

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

### Issue description
`globalTeardown` uses `rm(storage, { recursive: true, force: true })` on `global.registryMockStorage` without verifying the path is the specific temp directory created by this preset (expected prefix + under `os.tmpdir()`). This is primarily defense-in-depth: if the global is ever accidentally overwritten, teardown could delete an unintended path.

### Issue Context
`globalSetup` creates the storage with `mkdtempSync(path.join(tmpdir(), 'pnpm-registry-mock-storage-'))` and stores it in `global.registryMockStorage`. Teardown should only remove directories that match that invariant.

### Fix Focus Areas
- pnpm11/__utils__/jest-config/with-registry/globalSetup.js[23-35]
- pnpm11/__utils__/jest-config/with-registry/globalTeardown.js[9-18]

### Suggested change
Before calling `rm`, validate:
- `resolvedStorage` is inside `tmpdir()` (use `path.resolve` + `path.relative` or a proper path containment check)
- basename starts with `pnpm-registry-mock-storage-`
- `resolvedStorage` is not equal to `tmpdir()` / `/`

If validation fails, `console.warn` and skip deletion (or throw if you prefer to fail fast in CI).

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


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.

@greptile-apps

greptile-apps Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5

The PR is not yet safe to merge because a failed or timed-out shutdown can trigger deletion while the registry process remains alive.

The shutdown helper can reject before process closure is confirmed, while teardown catches that rejection and unconditionally removes the server’s storage, preserving the previously reported live-writer deletion race.

Files Needing Attention: pnpm11/utils/jest-config/with-registry/globalSetup.js, pnpm11/utils/jest-config/with-registry/globalTeardown.js, pnpm11/utils/jest-config/test/globalTeardown.test.js

Reviews (3): Last reviewed commit: "fix(jest-config): run the new tests in C..." | Re-trigger Greptile

…test it

Follow-up to the review of #13340.

`killServer` can reject — it throws on a `treeKill` failure and after a
10-second wait for pnpr to exit — and awaiting it before the removal
meant a failed shutdown skipped cleanup entirely, leaving behind the
directory this teardown exists to remove. The shutdown error is now
captured, cleanup runs regardless, and the error is rethrown afterwards.
When both fail they are reported together as an `AggregateError`, since
a server still holding the directory is the likeliest reason a removal
fails and letting the second error hide the first would be misleading.

A failed removal now propagates instead of warning. `force` already
ignores a directory that isn't there, so anything left is unexpected,
and downgrading it to a warning is how a leak comes back unnoticed —
the repo convention is to catch the specific expected condition rather
than swallow everything. `maxRetries` covers the transient case where
the just-killed server has not released its handles yet, which Windows
is prone to.

The package had no test setup, so this adds one: a jest preset
reference, a `test` script, and three cases covering removal, removal
after a rejected shutdown, and a run that never recorded a path. The
second was confirmed to fail against the previous `await
global.killServer?.()` ordering.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 25, 2026 12:44

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.

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 091cae4

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

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

🧹 Nitpick comments (1)
pnpm11/__utils__/jest-config/test/globalTeardown.test.js (1)

21-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for cleanup failures and AggregateError.

The implementation adds two observable branches that are currently untested: unexpected removal failures must propagate, and simultaneous shutdown/removal failures must produce an AggregateError containing both errors. Add focused tests for these cases; the current suite only covers successful removal, shutdown-only failure, and a missing path.

As per path instructions, changed Jest infrastructure should include targeted regression cases that fail without the fix and verify the real behavior.

🤖 Prompt for 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.

In `@pnpm11/__utils__/jest-config/test/globalTeardown.test.js` around lines 21 -
45, Extend the globalTeardown tests with focused cases where storage removal
fails unexpectedly and where both killServer and storage removal fail together.
Assert that removal-only failures propagate, and simultaneous failures reject
with an AggregateError containing both original errors, using the existing
globalTeardown, killServer, and storage setup patterns.

Source: Path instructions

🤖 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.

Nitpick comments:
In `@pnpm11/__utils__/jest-config/test/globalTeardown.test.js`:
- Around line 21-45: Extend the globalTeardown tests with focused cases where
storage removal fails unexpectedly and where both killServer and storage removal
fail together. Assert that removal-only failures propagate, and simultaneous
failures reject with an AggregateError containing both original errors, using
the existing globalTeardown, killServer, and storage setup patterns.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 75645336-64fb-4018-b004-901f0dde5140

📥 Commits

Reviewing files that changed from the base of the PR and between b562326 and 091cae4.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (3)
  • pnpm11/__utils__/jest-config/package.json
  • pnpm11/__utils__/jest-config/test/globalTeardown.test.js
  • pnpm11/__utils__/jest-config/with-registry/globalTeardown.js

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 25, 2026
…lete

Follow-up to the review of #13340.

The test script was the important one: CI runs `pn --filter=... --if-present
.test`, and the package only declared `test`, so the regression tests
added in the previous commit would never have run there. A test that
does not run is not a regression test. The package now follows the
convention the other ~120 packages use — a hidden `.test` carrying the
jest invocation, with `test` delegating to it — which also stops the
script from clobbering a caller's `NODE_OPTIONS` instead of extending
it.

`removeStorage` refuses a path whose basename is not shaped like the one
`globalSetup` creates. It is a recursive force-delete driven by a
mutable global, so it should not act on a value that did not come from
that setup; the prefix now lives in one module both sides import.

The tests no longer leak the directories they create. They exist because
of a directory leak, so leaving one behind when an assertion fails ahead
of the removal would be its own small version of the bug.

Comments reworded to state the current contract rather than narrate what
used to happen, per the comment conventions in AGENTS.md.

Verified: `pnpm test` in the package runs all four cases, a real
registry suite still leaves nothing behind in /tmp, and `pnpm run lint`
passes including `meta-updater --test`. (`pnpm .test` cannot be invoked
directly — hidden scripts are callable only from other scripts — and the
locally pinned pnpm v12 alpha rejects the recursive form too, for
existing `.test` packages as well as this one.)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 25, 2026 12:57

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

All four addressed in cee6559630 — thanks, the test-script one was the most important finding on this PR.

Nonstandard jest test script — you were right, and the consequence was worse than style. CI runs pn --filter=... --if-present .test, and I had declared only test, so the regression tests added in the previous commit would never have run in CI. A test that does not run is not a regression test. The package now follows the convention the other ~120 packages use — a hidden .test holding the jest invocation, test delegating to it — which also fixes the NODE_OPTIONS clobbering you flagged, since that form extends "$NODE_OPTIONS ..." instead of replacing it.

Temp dir cleanup not guaranteed (in the tests) — correct, and a bit pointed given what the tests are about. They now track what they create and remove it in afterEach, so an assertion failing before the code under test runs cannot leave a directory behind.

Unvalidated recursive delete target — accepted. removeStorage now refuses a path whose basename is not shaped like the one globalSetup creates, with the prefix in one module both sides import. It is a recursive force-delete driven by a mutable global, so the blast radius is worth three lines. Covered by a new test asserting an unrelated directory is refused and left on disk.

Historical phrasing in comments — fixed; they state the current contract rather than narrate what used to happen, per the comment conventions in AGENTS.md.

Verification: pnpm test runs all four cases, a real registry suite still leaves nothing in /tmp, and pnpm run lint passes including meta-updater --test with the new wiring.

One note on .test: it cannot be invoked directly (ERR_PNPM_HIDDEN_SCRIPT — hidden scripts are callable only from other scripts), and the locally pinned pnpm v12 alpha rejects the recursive form too. I confirmed that is not specific to this package by running the same command against @pnpm/scripts, which has always had a .test; it fails identically. So the wiring matches the repo convention and the local rejection is a quirk of the pinned alpha.


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 cee6559

@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 992933a into main Jul 25, 2026
33 checks passed
@zkochan
zkochan deleted the fix-jest-registry-storage-leak branch July 25, 2026 13:04
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…m#13340)

The `with-registry` jest preset built its verdaccio-shaped storage into
a fresh mkdtemp directory on every run, but globalTeardown only killed
the server — the directory was never removed, so every run of every
registry-backed suite leaked one permanently (~2 MB for a small suite,
up to ~2 GB for suites that proxy real packages).

On a tmpfs /tmp they accumulate until it fills, and the suite then fails
with ENOSPC in whichever test happens to write next — which reads as
flakiness, since a different test fails each run and each passes in
isolation.

globalSetup now hands the path it created to globalTeardown through
`global`, the same way it already hands over killServer, so teardown
removes only that run's directory. Removal happens after the server is
killed, since pnpr writes proxy-cache entries into the storage while
serving. A failed removal warns rather than throwing.

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

Labels

product: pnpm@11 reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants