Skip to content

fix: prune stale download and tarball spill directories - #16620

Merged
zkochan merged 3 commits into
mainfrom
fix-109
Oct 5, 2026
Merged

zkochan merged 3 commits into
mainfrom
fix-109

Conversation

@zkochan

@zkochan zkochan commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Summary

pnpm store prune removes abandoned download-* and tarball-* spill directories from the store root once both the directory and its files are more than 24 hours old. Recent entries, symlinks, and unrelated files or directories are preserved. Concurrent ENOENT cleanup races are tolerated; unexpected filesystem errors still propagate.

Closes pnpm/tasks#109.

This fixes the temporary spill paths introduced by #16613 in v11. The Rust CLI does not create these paths. No changeset is needed because the affected code has not shipped in a release. The existing store documentation sidebar entry already covers the updated page.

Validation: pnpm --filter @pnpm/store.controller test test/prune.ts test/projectRegistry.ts passed all 16 tests, including compilation and package lint. The cleanup regression test fails when the new prune call is removed. Reviewed the complete diff against the repository review guide.

Squash Commit Body

Clean up spill directories left after an interrupted download or archive extraction during store prune. Reuse the existing store-directory scan and removal helpers without adding install-time work.

Only remove matching directories when their own mtime and the mtimes of their immediate files are more than 24 hours old. Checking files preserves an old directory whose download is still writing. Stream file entries and check one directory and file at a time to bound pending filesystem work. Stop scanning a directory after its first recent file. Skip symlinks and tolerate ENOENT when another process finishes cleanup first.

Age is a conservative heuristic, not a process-liveness check: an install suspended for over 24 hours without filesystem activity can lose its spill directory.

Add regression coverage for stale, recent, empty, and unrelated entries, symlinks, missing stores, recent writes in old directories, and expected versus unexpected filesystem errors. Close SQLite fixture handles before removing test directories for Windows compatibility.

Closes pnpm/tasks#109.

Checklist

  • I checked the referenced issue and verified that none of the PRs already linked to it solves it.
  • New features are implemented only in the Rust pnpm v12 CLI. Bug fixes are implemented in every affected version.
  • Added or updated tests.
  • Updated the documentation if needed.

Written by an agent (Codex, GPT-6).

Summary by CodeRabbit

  • Improvements
    • pnpm store prune now removes temporary download and extraction directories left by interrupted installs when the directories and their contents have not been modified for more than 24 hours. Newer directories are kept.
  • Documentation
    • Updated the pnpm store prune guide to describe this cleanup behavior.

@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: pnpm/pnpm/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6ca7c426-a63b-4b61-8f1a-68971f147602
📥 Commits

Reviewing files that changed from the base of the PR and between e6f604a and d1827d1.

📒 Files selected for processing (3)
  • pnpm11/docs/cli/store.md
  • pnpm11/store/controller/src/storeController/prune.ts
  • pnpm11/store/controller/test/prune.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

pnpm store prune now removes top-level download- and tarball- directories when the directory and its immediate entries are older than 24 hours. Tests cover retained directories, filesystem errors, symlinks, and missing paths. The CLI documentation describes this cleanup.

Changes

Stale spill directory cleanup

Layer / File(s) Summary
Prune stale spill directories
pnpm11/store/controller/src/storeController/prune.ts, pnpm11/store/controller/test/prune.ts, pnpm11/docs/cli/store.md
prune removes eligible spill directories before content-addressable-store pruning. Tests cover age checks and filesystem cases. The CLI documentation describes the 24-hour threshold.

Priority: ⬇️ Low

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

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Prune as prune
  participant FS as Store filesystem
  participant CAS as Content-addressable store
  Prune->>FS: Inspect top-level download- and tarball- directories
  FS-->>Prune: Return directory and entry modification times
  Prune->>FS: Remove eligible directories older than 24 hours
  Prune->>CAS: Prune the content-addressable store
Loading

Assessment against linked issues

Objective Addressed Explanation
Clean up stale download-* and tarball-* spill directories without removing directories that may be in use [#109] ✅

Merge Risk: ⚪ Minimal · up to d1827

The cleanup appears ready to merge after normal checks; no actionable risk remains in the supplied evidence.

Security Architecture Review

Security architecture risk: 🔵 Low · up to d1827

Cleanup is limited to old temporary store directories and preserves recent entries and ordinary symlinks. However, age does not prove an installation has stopped: a long-paused installation sharing the store can lose its temporary data. Concurrent replacement and partial-removal behavior remain unverified.

Retained concerns

  • Low · reliability · inferred: Spill expiry is not coordinated with writer ownership. A download or extraction paused without filesystem activity for over 24 hours can qualify for removal while its process remains alive; activity resuming after the freshness scan does not cancel deletion. A prune operation can therefore disrupt another installation sharing the store. Recent-file checks substantially narrow this exposure, but they are not an atomic ownership guarantee.
Security review details

Security Blast Radius

  • inferred — The intended new deletion scope is matching stale temporary directories in the configured local store, under the calling process's filesystem authority. Installations sharing that store share the cleanup exposure. Out-of-store deletion through concurrent pathname replacement was not established or ruled out because recursive-removal race semantics remain unverified.

Trust Boundaries and Controls

  • observed — Ordinary top-level symlinks are excluded by directory enumeration and the subsequent lstat directory check. Regression coverage verifies that pre-existing links to an outside target and that target's contents remain intact. These controls verify the observed object, not its identity throughout the later check-to-delete interval.

Resilience and Maintainability Implications

  • observed — The inspected producer paths close resources and clean their own spills after failure or consumption. Download import and extraction errors propagate through existing cleanup paths, providing counterevidence against silently accepting missing spill data. These mechanisms do not coordinate ownership with independent pruning.

Hardening Proposals

  • proposed — For stronger writer-ownership guarantees, consider a producer/pruner coordination protocol rather than relying solely on age. Validate that protocol against resumed writers, pathname replacement, interruption, repeated pruning, and partial recursive-removal failure. Document the suspended-install limitation if age-based expiry remains intentional.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

pnpm11/store/controller/src/storeController/prune.ts

ESLint skipped: missing config or dependency (missing-dependency). The ESLint configuration references a package that is not available in the sandbox.

pnpm11/store/controller/test/prune.ts

ESLint skipped: the matched ESLint configuration already failed (missing-dependency).

🧰 Additional context used
📚 Code guidelines (2)
AGENTS.md — auto-discovered
DOCUMENTATION.md — auto-discovered

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.

@zkochan
zkochan marked this pull request as ready for review October 5, 2026 22:41
Copilot AI balanced review requested due to automatic review settings October 5, 2026 22:41

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

Your trial has ended. Reactivate Greptile to resume code reviews.

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

PR Summary by Qodo

Prune stale download and tarball spill directories

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Remove abandoned download and extraction directories during store pruning after 24 hours of
 inactivity.
• Preserve recent entries and symlinks while tolerating concurrent removal races.
• Add cleanup regression tests and document the retention rule.
Diagram

graph TD
  Prune["Store prune"] --> Scan["Scan store root"] --> Prefix{"Spill directory?"} -->|Yes| Age{"Inactive 24 hours?"} -->|Yes| Remove["Remove directory"]
  Prefix -->|No| Keep["Preserve entry"]
  Age -->|No| Keep
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Clean up during installation
  • ➕ Reclaims abandoned spill space without waiting for store prune.
  • ➖ Adds filesystem scans to installation and complicates coordination with active downloads.

Recommendation: Keep cleanup in the existing prune workflow: it avoids install-time overhead and uses the established store scan and removal helpers. The 24-hour inactivity check is a conservative safeguard, though it cannot establish whether a suspended install is still alive.

Files changed (3) +149 / -0

Bug fix (1) +26 / -0
prune.tsRemove stale spill directories during pruning +26/-0

Remove stale spill directories during pruning

• Scans store-root directories for download- and tarball-prefixed entries, removing them only when the directory and its immediate files predate the 24-hour cutoff. Uses directory-only scanning and lstat to avoid symlinks, tolerates ENOENT cleanup races, and propagates other errors.

pnpm11/store/controller/src/storeController/prune.ts

Tests (1) +119 / -0
prune.tsCover spill cleanup and preservation rules +119/-0

Cover spill cleanup and preservation rules

• Adds tests for stale, recent, empty, unrelated, and symlinked entries; recent writes in old directories; missing stores; and expected versus unexpected filesystem errors. Closes StoreIndex fixtures before removing temporary directories.

pnpm11/store/controller/test/prune.ts

Documentation (1) +4 / -0
store.mdDocument stale spill-directory cleanup +4/-0

Document stale spill-directory cleanup

• Explains that store prune removes temporary download and extraction directories after their directories and files have been inactive for more than 24 hours.

pnpm11/docs/cli/store.md

@qodo-code-review

qodo-code-review Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Three prune helpers precede first use 📘 Rule violation ⚙ Maintainability
Description
The new removeStaleSpillDirectories, removeSpillDirectoryIfStale, and spillFilesAreStale
declarations appear before their first in-file uses. The call chain reaches these declarations only
through hoisting, so later readers must scan below each use to find the implementation.
Code

pnpm11/store/controller/src/storeController/prune.ts[R49-54]

+async function removeStaleSpillDirectories (storeDir: string): Promise<void> {
+  const cutoff = Date.now() - 24 * 60 * 60_000
+  const directories = await getSubdirsSafely(storeDir)
+  await Promise.all(directories
+    .filter(directory => directory.startsWith('download-') || directory.startsWith('tarball-'))
+    .map(directory => removeSpillDirectoryIfStale(path.join(storeDir, directory), cutoff)))
Relevance

●●● Strong

Recent accepted precedents explicitly enforce usage-first TypeScript declarations.

PR-#16611
PR-#16607

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The checklist requires top-level TypeScript function declarations to appear after at least one usage
in the same file. The changed code calls removeStaleSpillDirectories at line 29 before its
declaration at line 49, and the helper declarations at lines 57 and 68 likewise precede their first
uses at lines 54 and 60.

Rule 713432: Declare TypeScript functions only after their first usage
pnpm11/store/controller/src/storeController/prune.ts[29-29]
pnpm11/store/controller/src/storeController/prune.ts[49-72]

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 new prune helper declarations appear before their first call sites, contrary to the project convention requiring TypeScript functions to be declared only after first usage.

## Fix Focus Areas
- pnpm11/store/controller/src/storeController/prune.ts[29-29]
- pnpm11/store/controller/src/storeController/prune.ts[49-72]

## Recommended Fix
Move `removeStaleSpillDirectories`, `removeSpillDirectoryIfStale`, and `spillFilesAreStale` below their respective first uses while preserving their behavior and keeping the existing helper call order intact.

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

Dismiss ↗ | View ↗


2. Large spills can overwhelm pruning ✓ Resolved
Description
removeStaleSpillDirectories starts work for every matching directory at once, and
spillFilesAreStale starts an lstat for every entry in each directory at once. A large
interrupted extraction can leave a tarball-* directory with one file per archive entry, causing
pnpm store prune to queue a large number of filesystem operations and promises before it can
remove that directory.
Code

pnpm11/store/controller/src/storeController/prune.ts[R68-70]

+async function spillFilesAreStale (directoryPath: string, cutoff: number): Promise<boolean> {
+  const files = await fs.readdir(directoryPath)
+  const stats = await Promise.all(files.map(file => fs.lstat(path.join(directoryPath, file))))
Relevance

●● Moderate

Concurrency findings are mixed: unbounded filesystem fan-out is sometimes accepted and sometimes
rejected.

PR-#14371
PR-#12777

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new cleanup fans out across all matching directories and then all entries within each directory.
The extraction writer creates a separate numbered temporary file for each archive entry, so an
interrupted extraction can supply a large entry count to this new scan.

pnpm11/store/controller/src/storeController/prune.ts[49-71]
pnpm11/store/cafs/src/createTarballFileWriter.ts[20-32]

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

## Issue description
Pruning starts unbounded work across matching spill directories and their entries, which can overwhelm filesystem resources for large interrupted extractions.
## Fix Focus Areas
- pnpm11/store/controller/src/storeController/prune.ts[52-54]
- pnpm11/store/controller/src/storeController/prune.ts[68-71]
## Recommended Fix
Limit concurrent directory checks and per-directory stat calls. Stop checking a directory as soon as a recent entry establishes that it must be kept.

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


Grey Divider

Context sources
✅ Compliance rules (platform): 55 rules
✅ Cross-repo context — repo relationships
  Explored: repo: pnpm/pnpm.io (sha: 84b885fd) — View relationship
Review mode: Auto: ⚖️ Balanced: Behavioral filesystem cleanup changes carry correctness and performance risk.

Grey Divider

Tip of the day
💡 Did you know, you can turn on the rule miner and Qodo learns your standards from review history

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit d1827d1

Results up to commit bcff615 ⚖️ Balanced


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


Remediation recommended
1. Three prune helpers precede first use 📘 Rule violation ⚙ Maintainability
Description
The new removeStaleSpillDirectories, removeSpillDirectoryIfStale, and spillFilesAreStale
declarations appear before their first in-file uses. The call chain reaches these declarations only
through hoisting, so later readers must scan below each use to find the implementation.
Code

pnpm11/store/controller/src/storeController/prune.ts[R49-54]

+async function removeStaleSpillDirectories (storeDir: string): Promise<void> {
+  const cutoff = Date.now() - 24 * 60 * 60_000
+  const directories = await getSubdirsSafely(storeDir)
+  await Promise.all(directories
+    .filter(directory => directory.startsWith('download-') || directory.startsWith('tarball-'))
+    .map(directory => removeSpillDirectoryIfStale(path.join(storeDir, directory), cutoff)))
Relevance

●●● Strong

Recent accepted precedents explicitly enforce usage-first TypeScript declarations.

PR-#16611
PR-#16607

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The checklist requires top-level TypeScript function declarations to appear after at least one usage
in the same file. The changed code calls removeStaleSpillDirectories at line 29 before its
declaration at line 49, and the helper declarations at lines 57 and 68 likewise precede their first
uses at lines 54 and 60.

Rule 713432: Declare TypeScript functions only after their first usage
pnpm11/store/controller/src/storeController/prune.ts[29-29]
pnpm11/store/controller/src/storeController/prune.ts[49-72]

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 new prune helper declarations appear before their first call sites, contrary to the project convention requiring TypeScript functions to be declared only after first usage.

## Fix Focus Areas
- pnpm11/store/controller/src/storeController/prune.ts[29-29]
- pnpm11/store/controller/src/storeController/prune.ts[49-72]

## Recommended Fix
Move `removeStaleSpillDirectories`, `removeSpillDirectoryIfStale`, and `spillFilesAreStale` below their respective first uses while preserving their behavior and keeping the existing helper call order intact.

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

Dismiss ↗ | View ↗


2. Large spills can overwhelm pruning ✓ Resolved
Description
removeStaleSpillDirectories starts work for every matching directory at once, and
spillFilesAreStale starts an lstat for every entry in each directory at once. A large
interrupted extraction can leave a tarball-* directory with one file per archive entry, causing
pnpm store prune to queue a large number of filesystem operations and promises before it can
remove that directory.
Code

pnpm11/store/controller/src/storeController/prune.ts[R68-70]

+async function spillFilesAreStale (directoryPath: string, cutoff: number): Promise<boolean> {
+  const files = await fs.readdir(directoryPath)
+  const stats = await Promise.all(files.map(file => fs.lstat(path.join(directoryPath, file))))
Relevance

●● Moderate

Concurrency findings are mixed: unbounded filesystem fan-out is sometimes accepted and sometimes
rejected.

PR-#14371
PR-#12777

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new cleanup fans out across all matching directories and then all entries within each directory.
The extraction writer creates a separate numbered temporary file for each archive entry, so an
interrupted extraction can supply a large entry count to this new scan.

pnpm11/store/controller/src/storeController/prune.ts[49-71]
pnpm11/store/cafs/src/createTarballFileWriter.ts[20-32]

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

## Issue description
Pruning starts unbounded work across matching spill directories and their entries, which can overwhelm filesystem resources for large interrupted extractions.
## Fix Focus Areas
- pnpm11/store/controller/src/storeController/prune.ts[52-54]
- pnpm11/store/controller/src/storeController/prune.ts[68-71]
## Recommended Fix
Limit concurrent directory checks and per-directory stat calls. Stop checking a directory as soon as a recent entry establishes that it must be kept.

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


Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

Copilot AI balanced review requested due to automatic review settings October 5, 2026 22:45

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.

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

Your trial has ended. Reactivate Greptile to resume code reviews.

@zkochan

zkochan commented Oct 5, 2026

Copy link
Copy Markdown
Member Author

Addressed the unbounded spill scan in d1827d1: directory checks are sequential, file entries are streamed with opendir, and the scan returns at the first recent file. A regression test verifies that it does not stat the remaining files. All 16 scoped tests and the repository pre-push checks pass.

The declaration-order finding is a false positive. removeStaleSpillDirectories is called at line 29 before its declaration. That function calls removeSpillDirectoryIfStale before its declaration, which in turn calls spillFilesAreStale before its declaration. This follows the repository's usage-first convention; no reordering is needed.


Written by an agent (Codex, GPT-6).

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit d1827d1

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

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Oct 5, 2026
@zkochan
zkochan merged commit daf8343 into main Oct 5, 2026
41 checks passed
@zkochan
zkochan deleted the fix-109 branch October 5, 2026 23:23
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.

v11: clean up stale download-* and tarball-* spill directories in the store

2 participants