Skip to content

test: stop leaking temp dirs from three test fixtures - #13342

Merged
zkochan merged 2 commits into
mainfrom
fix-test-temp-leaks
Jul 25, 2026
Merged

zkochan merged 2 commits into
mainfrom
fix-test-temp-leaks

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

TempDir::keep() disables cleanup. Four test fixtures used it; three did not need to, because the 'static requirement was on the value being leaked (StoreDir, Config), never on the directory. Measured on a full cargo nextest run:

leaked dirs in the system temp dir
before ~45
after ~10

Small in bytes (~1 MB), but they accumulate across runs and never get collected.

The three fixes

  • overrides::tests::manifest_from_value (~25 callers) wrote a package.json only to read it straight back, for a path its own doc comment calls a stub. It now uses PackageManifest::from_value, which touches no filesystem at all — the helper drops to one line. The needless_pass_by_value expectation goes with it, since from_value consumes the value.
  • env_installer::tests::harness (~20 callers) leaked the store directory along with the &'static StoreDir pointing at it. The TempDir moves into Harness, which already exists to hold per-test handles. build_resolver in the same file already did exactly this.
  • install_package_from_registry::tests::create_config (5 callers) leaked a cache dir while every caller was separately creating one of its own and passing it to the resolver. It takes the caller's, so the config and resolver now share one cache the way they do in practice, and the caller's TempDir does the cleaning. Two callers that had no cache dir gained one.

The fourth stays

cli/tests/pnpr_install.rs keeps its keep(), with its existing justification: the detached server thread outlives both the function and the test, so there is no point at which the storage can be removed without giving that thread a shutdown handle. One directory per run.

just sweep-test-temp

A killed test process cannot run Drop at all, so a fail-fast or interrupted run always abandons whole fixture trees — and for the mocked-registry tests each tree contains a per-test store, which is how a machine accumulates hundreds of megabytes of pnpm-e2e-*. No amount of Drop correctness fixes that, so this sweeps them. It skips anything under an hour old, so it cannot disturb a concurrent run.

What I tried and rejected

Redirecting TMPDIR for the whole suite looked like the stronger fix — one per-run directory, wiped up front, bounding everything including killed-process leakage. It does not work:

  • Tests assert on stderr containing paths under the temp dir, so custom_resolvers::failing_should_refresh_resolution_aborts_the_install fails on the changed pnpmfile path.
  • A TMPDIR under target/ additionally breaks frozen_lockfile_applies_overrides_to_manifest_before_freshness_check, because the upward walk for pnpm-workspace.yaml then finds this repo's own.

Worth recording so the next person does not spend the same time on it.

Verification

Full workspace suite: 7063 tests pass, lint and dylint clean. Leak count measured before and after by counting /tmp/.tmp* across runs.

Tests and one justfile recipe only — no published behavior changes, so no changeset.

Related to pnpm/tasks#32.

Squash Commit Body

`TempDir::keep()` disables cleanup, and three of the four sites using it did
not need to: the `'static` requirement was on the value being leaked
(`StoreDir`, `Config`), never on the directory. A full run left ~45
directories in the system temp dir; it now leaves ~10.

- `overrides::tests::manifest_from_value` wrote a `package.json` only to read
  it straight back, for a path its own doc calls a stub. It builds the
  manifest with `PackageManifest::from_value` instead, which touches no
  filesystem at all — one leak per call across ~25 callers, gone, and the
  helper drops to one line.
- `env_installer::tests::harness` leaked the store directory alongside the
  `&'static StoreDir` pointing at it. The `TempDir` moves into `Harness`,
  which already exists to hold per-test handles.
- `install_package_from_registry::tests::create_config` leaked a cache dir
  while every caller was separately creating one of its own and passing it
  to the resolver. It takes the caller's, so the config and the resolver now
  share a cache the way they do in practice.

`cli/tests/pnpr_install.rs` keeps its `keep()`: the detached server thread
outlives both the function and the test.

Add `just sweep-test-temp` for the rest. A killed test process cannot run
`Drop`, so a fail-fast or interrupted run always abandons whole fixture
trees, including a per-test store for the mocked-registry tests. The sweep
skips anything under an hour old so it cannot disturb a concurrent run.

Redirecting `TMPDIR` at the whole suite does not work: tests assert on
stderr containing paths under the temp dir, and a `TMPDIR` under `target/`
makes the walk for `pnpm-workspace.yaml` find this repo's own.

Related to pnpm/tasks#32.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
    Rust test fixtures only; nothing user-visible to mirror.
  • 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.
    Not applicable: tests and a justfile recipe, no published behavior.
  • Added or updated tests.
    This is a change to test fixtures; the existing suites cover them.

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


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

  • Chores

    • Added a maintenance command to remove stale temporary files created by end-to-end tests.
    • Improved cleanup of temporary test directories and cached test data.
  • Tests

    • Simplified test setup and resource management.
    • Improved test isolation and reduced leftover temporary artifacts.

`TempDir::keep()` disables cleanup, and three of the four sites using it did
not need to: the `'static` requirement was on the value being leaked
(`StoreDir`, `Config`), never on the directory. A full run left ~45
directories in the system temp dir; it now leaves ~10.

- `overrides::tests::manifest_from_value` wrote a `package.json` only to read
  it straight back, for a path its own doc calls a stub. It builds the
  manifest with `PackageManifest::from_value` instead, which touches no
  filesystem at all — one leak per call across ~25 callers, gone, and the
  helper drops to one line. The `needless_pass_by_value` expectation goes
  with it: `from_value` consumes the value.
- `env_installer::tests::harness` leaked the store directory alongside the
  `&'static StoreDir` pointing at it. The `TempDir` moves into `Harness`,
  which already exists to hold per-test handles, so it drops with the
  harness. `build_resolver` in the same file already did it this way.
- `install_package_from_registry::tests::create_config` leaked a cache dir
  while every caller was separately creating one of its own and passing it
  to the resolver. It takes the caller's, so the config and the resolver now
  share a cache the way they do in practice, and the caller's `TempDir` does
  the cleaning. Two callers that had no cache dir gained one.

`cli/tests/pnpr_install.rs` keeps its `keep()`: the detached server thread
outlives both the function and the test, so there is no point at which the
storage can be removed without a shutdown handle for that thread.

Add `just sweep-test-temp` for the rest. A killed test process cannot run
`Drop`, so a fail-fast or interrupted run always abandons whole fixture
trees — for the mocked-registry tests that includes a per-test store, which
is how a machine ends up with hundreds of megabytes of them. The sweep skips
anything under an hour old so it cannot disturb a concurrent run.

Redirecting `TMPDIR` at the whole suite looked like the stronger fix and does
not work: tests assert on stderr containing paths under the temp dir, so
`custom_resolvers::failing_should_refresh_resolution_aborts_the_install`
fails, and a `TMPDIR` under `target/` additionally breaks
`frozen_lockfile_applies_overrides_to_manifest_before_freshness_check`,
because the walk for `pnpm-workspace.yaml` then finds this repo's own.

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

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: 13 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: c4ca9b56-7812-4e6c-8a20-f04e00f3bd71

📥 Commits

Reviewing files that changed from the base of the PR and between 2cef4fb and 08c4fe8.

📒 Files selected for processing (3)
  • justfile
  • pnpm/crates/cli/tests/deploy.rs
  • pnpm/crates/testing-utils/src/bin.rs
📝 Walkthrough

Walkthrough

The changes add stale test-artifact cleanup, make test temporary-directory ownership explicit, pass cache directories into registry-install test configuration, and construct override manifests directly from in-memory JSON.

Changes

Test temporary-resource cleanup

Layer / File(s) Summary
Explicit temporary directory ownership
pnpm/crates/env-installer/src/tests.rs, pnpm/crates/package-manager/src/install_package_from_registry/tests.rs
The harness retains its store-root TempDir; registry-install tests pass explicit cache directories into Config and clean them up with other temporary directories.
In-memory manifest construction
pnpm/crates/package-manager/src/overrides/tests.rs
Override tests build PackageManifest directly from JSON values instead of writing temporary manifest files.
Stale test artifact sweep
justfile
Adds sweep-test-temp to remove matching temporary artifacts older than one hour from ${TMPDIR:-/tmp}.

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

Possibly related PRs

  • pnpm/pnpm#13172: Both changes update the registry-install test create_config helper.

Suggested labels: product: pacquet

Suggested reviewers: copilot

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-test-temp-leaks

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

Tests: stop leaking temp dirs from three fixtures (and add temp sweep task)

🧪 Tests ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• Remove unnecessary TempDir::keep() usage in three test fixtures to restore cleanup.
• Refactor overrides tests to build manifests in-memory, avoiding filesystem tempdirs.
• Add a just sweep-test-temp task to prune abandoned test temp trees after interrupted runs.
Diagram

graph TD
  A["Test fixtures"] --> B["Own TempDir in harness/helpers"] --> C["Drop-based cleanup"] --> D[("System temp dir")]
  E["just sweep-test-temp"] --> D
  F["Overrides manifest_from_value"] --> B
  G["Registry install tests config"] --> B
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Suite-level per-run TMPDIR redirection
  • ➕ Bounds all temp artifacts to one directory per run (including killed-process leakage)
  • ➕ Simplifies cleanup (wipe once at start/end)
  • ➖ Breaks tests that assert on temp path contents in stderr/output
  • ➖ More invasive/global behavior change across the entire test suite
2. Rely solely on a sweep step (no fixture ownership fixes)
  • ➕ Very low code churn in fixtures
  • ➕ Handles killed-process leakage well
  • ➖ Still leaks during normal successful runs (unnecessary noise)
  • ➖ Encourages ignoring resource ownership correctness in test helpers
3. Introduce a shared test utility to manage leaked `'static` fixtures
  • ➕ Centralizes patterns for leaking &#x27;static values while preserving directory ownership
  • ➕ Reduces repeated helper patterns across test modules
  • ➖ More abstraction than needed for a small number of call sites
  • ➖ Requires additional API design and migration work

Recommendation: Current approach (fix ownership in the three fixtures and add an explicit sweep task) is the best balance: it restores correct cleanup for normal runs without destabilizing path-sensitive tests, while still addressing the unavoidable killed-process case via sweep-test-temp. The rejected TMPDIR redirection is attractive in theory but too risky given existing assertions on temp paths.

Files changed (4) +58 / -21

Bug fix (2) +48 / -10
tests.rsStop leaking store tempdir by owning it in the test harness +7/-1

Stop leaking store tempdir by owning it in the test harness

• Moves store temp directory ownership into the 'Harness' struct via a new '_store_root: TempDir' field. The leaked ''static StoreDir' now points at 'store_root.path()' while the directory itself is cleaned up when the harness drops.

pnpm/crates/env-installer/src/tests.rs

tests.rsPass cache dir into test config helper instead of creating/leaking one +41/-9

Pass cache dir into test config helper instead of creating/leaking one

• Extends 'create_config' to accept a 'cache_dir' argument and uses it rather than creating a new 'tempdir().keep()'. Updates callers to create and pass a cache tempdir, and ensures the cache dir is included in explicit drops where relevant.

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

Tests (1) +1 / -11
tests.rsBuild test manifests in-memory to avoid tempdir filesystem I/O +1/-11

Build test manifests in-memory to avoid tempdir filesystem I/O

• Replaces a tempdir + 'package.json' write/read roundtrip with 'PackageManifest::from_value(...)', eliminating filesystem usage and the prior 'keep()' call. Removes the now-unneeded Clippy expectation that justified pass-by-value for call-site ergonomics.

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

Other (1) +9 / -0
justfileAdd 'sweep-test-temp' task to prune abandoned temp trees +9/-0

Add 'sweep-test-temp' task to prune abandoned temp trees

• Introduces a Just target that removes old 'pnpm-e2e-*' and '.tmp*' directories from the system temp directory. It only deletes entries older than 60 minutes to avoid interfering with concurrent runs and tolerates missing permissions/errors.

justfile

@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

🧹 Nitpick comments (1)
pnpm/crates/env-installer/src/tests.rs (1)

81-84: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a regular comment for this private implementation detail.

_store_root is private, and this text explains ownership rationale rather than a public API contract. Per the Rust documentation guideline, use // instead of ///.

Proposed change
-    /// Owns the directory `store_dir` points at. Only the [`StoreDir`] value
-    /// has to be `'static`, so the directory itself is dropped with the
-    /// harness rather than left behind for the run's temp dir to accumulate.
+    // Owns the directory `store_dir` points at. Only the `StoreDir` value
+    // has to be `'static`, so the directory itself is dropped with the
+    // harness rather than left behind for the run's temp dir to accumulate.

As per coding guidelines, use rustdoc comments for public API contracts and regular comments for implementation rationale.

🤖 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 `@pnpm/crates/env-installer/src/tests.rs` around lines 81 - 84, Replace the
rustdoc comment above the private `_store_root` field with a regular `//`
comment, preserving the existing ownership rationale without documenting it as a
public API contract.

Source: Coding guidelines

🤖 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 `@justfile`:
- Around line 61-63: Harden the sweep-test-temp recipe by constraining and
validating the TMPDIR root before searching, adding -mindepth 1 so the root
itself cannot match, and narrowing both find patterns to test-owned prefixes or
markers. Ensure every rm -rf target is produced only from this constrained root
and ownership-specific matching, preserving the existing age threshold.

---

Nitpick comments:
In `@pnpm/crates/env-installer/src/tests.rs`:
- Around line 81-84: Replace the rustdoc comment above the private `_store_root`
field with a regular `//` comment, preserving the existing ownership rationale
without documenting it as a public API contract.
🪄 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: 8abee3bf-f38c-4cf4-8cdf-2b50c7553b7f

📥 Commits

Reviewing files that changed from the base of the PR and between f7e1fee and 2cef4fb.

📒 Files selected for processing (4)
  • justfile
  • pnpm/crates/env-installer/src/tests.rs
  • pnpm/crates/package-manager/src/install_package_from_registry/tests.rs
  • pnpm/crates/package-manager/src/overrides/tests.rs

Comment thread justfile Resolved
@github-actions

github-actions Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.02     10.7±0.33ms    35.1 MB/sec    1.00     10.5±0.17ms    35.8 MB/sec
packument/parse                1.00     36.3±0.49µs  1826.8 MB/sec    1.01     36.7±1.52µs  1808.3 MB/sec
tarball/download_dependency    1.01      2.8±0.14ms  1540.7 KB/sec    1.00      2.8±0.10ms  1551.0 KB/sec

@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. Silent sweep failures 🐞 Bug ◔ Observability ⭐ New
Description
The sweep-test-temp recipe redirects find/rm stderr to /dev/null and forces a zero exit (`||
true`), so permission/I/O errors and partial deletions become invisible and leaks can continue
accumulating without any signal.
Code

justfile[66]

+  find "${TMPDIR:-/tmp}" -mindepth 1 -maxdepth 1 -name 'pacquet-test-*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
Relevance

⭐⭐⭐ High

Repo accepted warning/handling for cleanup failures to avoid silent temp leaks; analogous to
registry mock teardown cleanup.

PR-#13340
PR-#12697

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The recipe explicitly discards all stderr output from find/rm and then masks any non-zero exit
code, so operators cannot tell when the sweep didn’t actually remove directories. This matches an
established repo pattern of warning (not silently ignoring) when temp cleanup fails.

justfile[56-66]
PR-#13340

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

## Issue description
`sweep-test-temp` currently suppresses diagnostics and always succeeds, even when `find` fails (e.g., unreadable TMPDIR) or `rm -rf` only partially removes a tree. This makes it hard to notice that the sweep did not actually clean up abandoned `pacquet-test-*` directories.

## Issue Context
This recipe is meant to keep `/tmp` (or `$TMPDIR`) from accumulating abandoned test fixture trees. Silent failure undermines that goal.

## Fix Focus Areas
- justfile[66-66]

## Suggested fix
Keep the recipe best-effort, but do not fully silence failures. For example:
- remove `2>/dev/null` and/or `|| true`, OR
- capture failures and emit a warning to stderr (while still exiting 0), e.g. by printing a summary of any paths that couldn’t be removed or by warning when `find`/`rm` exit non-zero.

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


2. Overbroad temp sweep rm ✓ Resolved 🐞 Bug ⛨ Security
Description
sweep-test-temp recursively deletes pnpm-e2e-* and especially .tmp* entries under
${TMPDIR:-/tmp} without validating the directory, so a mis-set/inherited TMPDIR (or broad
patterns) can delete unrelated user data outside the intended test-fixture leftovers.
Code

justfile[R61-63]

+sweep-test-temp:
+  find "${TMPDIR:-/tmp}" -maxdepth 1 -name 'pnpm-e2e-*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
+  find "${TMPDIR:-/tmp}" -maxdepth 1 -name '.tmp*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
Relevance

⭐⭐⭐ High

Team has accepted hardening destructive deletes by validating/canonicalizing paths to avoid deleting
outside intended roots.

PR-#12536

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The recipe’s deletion root is derived from TMPDIR and removes all .tmp* matches older than 60
minutes, which is not specific to pnpm fixtures; the repo’s security guide explicitly flags
env-var/path trust and arbitrary delete classes as high-priority review items.

justfile[56-63]
REVIEW_GUIDE.md[30-55]

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 `sweep-test-temp` recipe performs `rm -rf` over matches rooted at `${TMPDIR:-/tmp}` with a very broad `.tmp*` glob, which can remove unrelated directories/files if `TMPDIR` points somewhere unexpected or if other applications create `.tmp*` entries in the same temp root.

## Issue Context
REVIEW_GUIDE.md asks to treat env vars/paths as attacker-controlled and to watch for arbitrary file delete risks.

## Fix Focus Areas
- justfile[56-63]

## Suggested fix approach
- Introduce a local variable for the temp root and refuse clearly unsafe roots (e.g. empty string or `/`).
- Restrict deletions to directories only (`-type d`) and use `-mindepth 1`.
- Add `--` to `rm` (`rm -rf -- {}`) as defense-in-depth.
- Consider narrowing or removing the `.tmp*` sweep (or require a pnpm-specific marker/prefix) to avoid deleting other programs’ temp entries.

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



Informational

3. Unix-only recipe not scoped 🐞 Bug ☼ Reliability
Description
sweep-test-temp uses Unix utilities (find, rm, ${VAR:-default} expansion) but is not marked
[unix], so running it via just on standard Windows environments will fail unlike other OS-scoped
recipes in the same file.
Code

justfile[R60-63]

+# Remove what earlier test runs left behind in the system temp dir.
+sweep-test-temp:
+  find "${TMPDIR:-/tmp}" -maxdepth 1 -name 'pnpm-e2e-*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
+  find "${TMPDIR:-/tmp}" -maxdepth 1 -name '.tmp*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
Relevance

⭐⭐⭐ High

Repo often gates Unix-only behavior to avoid Windows failures; analogous POSIX-only tests were
required to be Unix-scoped.

PR-#12543

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new recipe is unscoped and uses Unix commands, while the same file demonstrates platform scoping
for other targets, indicating the intended pattern for OS-specific commands.

justfile[60-63]
justfile[73-81]

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

## Issue description
`sweep-test-temp` is a Unix-shell recipe but is defined without an OS selector, so it is exposed on Windows where it typically won’t run.

## Issue Context
The justfile already uses `[unix]`/`[windows]` selectors for other targets.

## Fix Focus Areas
- justfile[60-81]

## Suggested fix approach
- Add a `[unix]` selector for `sweep-test-temp`.
- Optionally add a `[windows]` variant that prints a short message (or a PowerShell equivalent cleanup) so the command is discoverable but not broken.

ⓘ 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 08c4fe8

Results up to commit 2cef4fb ⚖️ Balanced


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


Remediation recommended
1. Overbroad temp sweep rm ✓ Resolved 🐞 Bug ⛨ Security
Description
sweep-test-temp recursively deletes pnpm-e2e-* and especially .tmp* entries under
${TMPDIR:-/tmp} without validating the directory, so a mis-set/inherited TMPDIR (or broad
patterns) can delete unrelated user data outside the intended test-fixture leftovers.
Code

justfile[R61-63]

+sweep-test-temp:
+  find "${TMPDIR:-/tmp}" -maxdepth 1 -name 'pnpm-e2e-*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
+  find "${TMPDIR:-/tmp}" -maxdepth 1 -name '.tmp*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
Relevance

⭐⭐⭐ High

Team has accepted hardening destructive deletes by validating/canonicalizing paths to avoid deleting
outside intended roots.

PR-#12536

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The recipe’s deletion root is derived from TMPDIR and removes all .tmp* matches older than 60
minutes, which is not specific to pnpm fixtures; the repo’s security guide explicitly flags
env-var/path trust and arbitrary delete classes as high-priority review items.

justfile[56-63]
REVIEW_GUIDE.md[30-55]

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 `sweep-test-temp` recipe performs `rm -rf` over matches rooted at `${TMPDIR:-/tmp}` with a very broad `.tmp*` glob, which can remove unrelated directories/files if `TMPDIR` points somewhere unexpected or if other applications create `.tmp*` entries in the same temp root.

## Issue Context
REVIEW_GUIDE.md asks to treat env vars/paths as attacker-controlled and to watch for arbitrary file delete risks.

## Fix Focus Areas
- justfile[56-63]

## Suggested fix approach
- Introduce a local variable for the temp root and refuse clearly unsafe roots (e.g. empty string or `/`).
- Restrict deletions to directories only (`-type d`) and use `-mindepth 1`.
- Add `--` to `rm` (`rm -rf -- {}`) as defense-in-depth.
- Consider narrowing or removing the `.tmp*` sweep (or require a pnpm-specific marker/prefix) to avoid deleting other programs’ temp entries.

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



Informational
2. Unix-only recipe not scoped 🐞 Bug ☼ Reliability
Description
sweep-test-temp uses Unix utilities (find, rm, ${VAR:-default} expansion) but is not marked
[unix], so running it via just on standard Windows environments will fail unlike other OS-scoped
recipes in the same file.
Code

justfile[R60-63]

+# Remove what earlier test runs left behind in the system temp dir.
+sweep-test-temp:
+  find "${TMPDIR:-/tmp}" -maxdepth 1 -name 'pnpm-e2e-*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
+  find "${TMPDIR:-/tmp}" -maxdepth 1 -name '.tmp*' -mmin +60 -exec rm -rf {} + 2>/dev/null || true
Relevance

⭐⭐⭐ High

Repo often gates Unix-only behavior to avoid Windows failures; analogous POSIX-only tests were
required to be Unix-scoped.

PR-#12543

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new recipe is unscoped and uses Unix commands, while the same file demonstrates platform scoping
for other targets, indicating the intended pattern for OS-specific commands.

justfile[60-63]
justfile[73-81]

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

## Issue description
`sweep-test-temp` is a Unix-shell recipe but is defined without an OS selector, so it is exposed on Windows where it typically won’t run.

## Issue Context
The justfile already uses `[unix]`/`[windows]` selectors for other targets.

## Fix Focus Areas
- justfile[60-81]

## Suggested fix approach
- Add a `[unix]` selector for `sweep-test-temp`.
- Optionally add a `[windows]` variant that prints a short message (or a PowerShell equivalent cleanup) so the command is discoverable but not broken.

ⓘ 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: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (2): Last reviewed commit: "test: sweep only fixture trees this suit..." | Re-trigger Greptile

Comment thread justfile Resolved
@codecov-commenter

codecov-commenter commented Jul 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.04%. Comparing base (cf8fdc4) to head (08c4fe8).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   pnpm/pnpm#13342   +/-   ##
=======================================
  Coverage   87.04%   87.04%           
=======================================
  Files         534      535    +1     
  Lines       91806    91827   +21     
=======================================
+ Hits        79911    79934   +23     
+ Misses      11895    11893    -2     

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

The sweep matched `.tmp*`, which is `tempfile`'s default prefix and so
belongs to every crate that uses it — age is not ownership, and the recipe
would have deleted unrelated programs' temp data. It could also match its own
starting directory, making a `TMPDIR` named `.tmp*` or `pnpm-e2e-*` the
target of `rm -rf`.

Give `CommandTempCwd` a `pacquet-test-` prefix instead and sweep only that.
One site covers the trees that matter: they hold a per-test store for the
mocked-registry tests and are the bulk of what an interrupted run abandons.
`-mindepth 1` keeps the root out of the match. Verified both directions — a
stale `pacquet-test-*` is removed, an unrelated `.tmp*` of the same age is
left alone.

The longer prefix then exposed a test that was fragile to path length:
`deploy_all_files_rejects_symlink_escape` asserted on `"resolves outside"`,
which miette had been wrapping across a line break once the path grew. It
matches whitespace-collapsed output now, so where miette wraps no longer
decides whether it passes.

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

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

Both of you were right, and this was the dangerous kind of wrong — fixed in 08c4fe8.

Greptile: cleanup deletes unrelated temp data. .tmp* is tempfile's default prefix, so it belongs to every crate that uses it. Age is not ownership. A recipe that rm -rfs every hour-old /tmp/.tmp* would take other programs' data with it. I should not have shipped that, and I ran it on my own machine to test it before either of you flagged it — 3807 entries down to 537. Most were certainly this suite's, having just run it repeatedly, but I cannot prove none belonged to something else.

CodeRabbit: constrain the root and the targets. Also right, and the find-matches-its-own-start case is the worse half: a TMPDIR named .tmp* or pnpm-e2e-* would itself become the rm -rf target.

What it does now

Ownership is established rather than guessed. CommandTempCwd gets a pacquet-test- prefix, and the sweep matches only that:

find "${TMPDIR:-/tmp}" -mindepth 1 -maxdepth 1 -name 'pacquet-test-*' -mmin +60 -exec rm -rf {} +

One site covers what matters — those trees hold a per-test store for the mocked-registry tests and are the bulk of what an interrupted run abandons. -mindepth 1 keeps the root out of the match, per your note. The .tmp* pattern is gone entirely; ~10 tiny dirs per run are not worth a generic rm -rf.

Verified both directions:

sentinel:   /tmp/pacquet-test-SZfqJq   (aged 2h)  → removed
unrelated:  /tmp/.tmpOTHERtByI         (aged 2h)  → preserved

The prefix exposed a real test bug

deploy_all_files_rejects_symlink_escape asserted on "resolves outside", and the longer prefix pushed miette's line wrap into the middle of that phrase:

╰─▶ path /tmp/pacquet-test-ZsE2GH/.../outside resolves
    outside source directory /tmp/pacquet-test-ZsE2GH/...

So it was fragile to temp-path length all along and would break for anyone whose TMPDIR differed in width. It now matches whitespace-collapsed output, so where miette wraps no longer decides the outcome.

Full workspace suite: 7063 pass, lint and dylint clean.


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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 08c4fe8

@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 baf11ee into main Jul 25, 2026
33 checks passed
@zkochan
zkochan deleted the fix-test-temp-leaks branch July 25, 2026 13:31
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
`TempDir::keep()` disables cleanup, and three of the four sites using it did
not need to: the `'static` requirement was on the value being leaked
(`StoreDir`, `Config`), never on the directory. A full run left ~45
directories in the system temp dir; it now leaves ~10.

- `overrides::tests::manifest_from_value` wrote a `package.json` only to read
  it straight back, for a path its own doc calls a stub. It builds the
  manifest with `PackageManifest::from_value` instead, which touches no
  filesystem at all — one leak per call across ~25 callers, gone, and the
  helper drops to one line.
- `env_installer::tests::harness` leaked the store directory alongside the
  `&'static StoreDir` pointing at it. The `TempDir` moves into `Harness`,
  which already exists to hold per-test handles.
- `install_package_from_registry::tests::create_config` leaked a cache dir
  while every caller was separately creating one of its own and passing it
  to the resolver. It takes the caller's, so the config and the resolver now
  share a cache the way they do in practice.

`cli/tests/pnpr_install.rs` keeps its `keep()`: the detached server thread
outlives both the function and the test.

Add `just sweep-test-temp` for the rest. A killed test process cannot run
`Drop`, so a fail-fast or interrupted run always abandons whole fixture
trees, including a per-test store for the mocked-registry tests. The sweep
skips anything under an hour old so it cannot disturb a concurrent run.

Redirecting `TMPDIR` at the whole suite does not work: tests assert on
stderr containing paths under the temp dir, and a `TMPDIR` under `target/`
makes the walk for `pnpm-workspace.yaml` find this repo's own.

Related to pnpm/pnpm#12485.
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