Skip to content

fix(resolver): condense retained registry metadata to keep large installs in memory - #13133

Merged
zkochan merged 7 commits into
mainfrom
fix-8441
Jul 19, 2026
Merged

zkochan merged 7 commits into
mainfrom
fix-8441

Conversation

@zkochan

@zkochan zkochan commented Jul 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #8441.

pnpm install ran out of memory on large dependency graphs because full registry documents were retained in memory unstripped for the whole resolution phase. On a plain install, full packuments (per-version readmes, scripts, descriptions, exports maps, maintainer info) reach the in-memory caches through three routes:

  1. Optional dependencies — always fetched as full documents to get libc (pnpm install fetch all binaries ignoring os / arch #9950) and cached whole.
  2. minimumReleaseAge upgrades — recently-modified packages are re-fetched as full documents for per-version time and cached whole; the full body was also written into the abbreviated disk mirror, so warm installs re-inflated from disk too.
  3. Disk mirrors holding full bodies, promoted into memory unstripped.

Each document was pinned twice — in the resolver's metaCache and in memoizeFetchMetadata's settled-entry memo. Heap snapshots from the reproduction (haines/pnpm-memory, 1464 packages, minimumReleaseAge active) showed ~645 MB of full-document strings plus ~340 MB of parsed objects at the 1 GB heap limit.

With this change, every packument retained in memory is condensed to the abbreviated field set (everything installation reads: dependency maps, dist, libc/os/cpu, time, _npmUser, hasInstallScript, …). Measured on the reproduction:

  • Before: OOM (Ineffective mark-compacts near heap limit) at ~1176 of 1464 packages with --max-old-space-size=1024.
  • After: the same cold-cache scenario completes within 1 GB; the --heapsnapshot-near-heap-limit handler never fires.
  • Warm cache: a second install resolves all 1459 packages in ~4 s from the condensed mirrors and produces a byte-identical lockfile to the cold run.

Two CI regression guards ride along, both verified to fail against a build of the pre-fix source:

  • Resolver-level (resolving/npm-resolver/test/memoryBounded.test.ts): a subprocess capped at --max-old-space-size=100 resolves 30 optional dependencies whose documents each carry 4 MB of install-irrelevant bulk from a local server. Pre-fix: exit 134 (V8 heap-limit abort); post-fix: passes with ~3× headroom.
  • Whole-CLI level (pnpm/test/install/memoryBounded.ts): the bundled pnpm install --lockfile-only resolves 40 optional dependencies with 6 MB of bulk each (240 MB total) from a local registry stub under a 256 MB cap, with network-concurrency=4 so the cap measures retention rather than in-flight transients. Pre-fix: heap-limit abort; post-fix: passes even a 192 MB cap. This one catches a future retention route anywhere in the install pipeline, not just in the resolver package.

Squash Commit Body

Full packuments reached the resolver's in-memory caches unstripped on plain
installs through three routes: optional dependencies (fetched full for libc),
minimumReleaseAge time upgrades, and disk mirrors holding full bodies. Each
document was pinned twice for the whole resolution phase (metaCache and the
settled-fetch memo in memoizeFetchMetadata), so per-version readmes, scripts,
and descriptions accumulated to multi-GB heaps and OOM'd large workspaces
(Fixes pnpm/pnpm#8441).

clearMeta is now identity-memoized (WeakMap) and etag-preserving, and every
layer that retains a packument condenses it through clearMeta: pickPackage's
cache writes and disk-mirror loads, and memoizeFetchMetadata's settled-entry
swap (via the new condenseSettledMeta option). The memoization is what keeps
the layers sharing one condensed copy instead of pinning one each. Resolvers
created with fullMetadata and no filterMetadata (pnpm outdated --long) retain
full documents, gated by the new retainsFullMeta predicate.

Two deliberate on-disk changes ride along: the release-age upgrade path now
mirrors the condensed document (which keeps time, the only thing the next
install needs from that slot) instead of writing the multi-MB full body into
the abbreviated mirror, and prepareJsonForDisk drops etag from a serialized
body — the condensed object is shared and gets its etag assigned after a
fetch, and the etag's home is the mirror's headers line.

The common abbreviated path still mirrors the raw response body verbatim, so
cold installs pay no extra serialization; condensing an already-abbreviated
document costs one shallow copy per package, which also protects against
mirrors polluted by earlier releases and registries that ignore the
abbreviated Accept header on disk-loaded documents.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.

Pacquet porting note

Pacquet retains full documents through the same three routes (pick_package.rs:437-438 ties stripping to the install-wide filter_metadata, cache insert at pick_package.rs:724, upgrade path at pick_package.rs:1214-1248, unstripped disk promotes at pick_package.rs:529/611/642), but the impact is materially smaller: versions are kept as lazy Arc<RawValue> byte fragments rather than fully-parsed object graphs, so the retained bulk is roughly the raw document size. A follow-up should apply clear_meta (mirror.rs:323) at those sites behind the same "retains full meta" gate as this PR.


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

Summary by CodeRabbit

  • Bug Fixes
    • Reduced peak memory during pnpm install by condensing cached npm packument metadata to install-relevant fields.
    • Improved consistency of condensed vs full metadata across online, offline, and mirror promotion flows.
    • Prevented duplicate etag content when persisting cached metadata.
  • Tests
    • Added/expanded regression coverage for metadata condensation, cached settlement behavior, optional-dependency handling, and memory-bounded resolver/install scenarios.
  • Chores
    • Documented the dependency-resolver update via a changeset.

zkochan added 2 commits July 18, 2026 23:40
…alls in memory

Full packuments reached the resolver's in-memory caches unstripped on plain
installs through three routes: optional dependencies (fetched full for libc),
minimumReleaseAge time upgrades, and disk mirrors holding full bodies. Each
document was pinned twice for the whole resolution phase (metaCache and the
settled-fetch memo), so per-version readmes, scripts, and descriptions
accumulated to multi-GB heaps and OOM'd large workspaces
(#8441).

Every retained packument is now condensed to the abbreviated field set via a
WeakMap-memoized clearMeta, so all layers share one condensed copy. Resolvers
created with fullMetadata and no filterMetadata (pnpm outdated --long) keep
full documents. The release-age upgrade path now mirrors the condensed form
instead of writing full bodies into the abbreviated mirror.
Copilot AI review requested due to automatic review settings July 18, 2026 21:46

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 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 25859fde-619b-4961-bf8f-e7ad60522f3a

📥 Commits

Reviewing files that changed from the base of the PR and between 32a2b43 and ba8844d.

📒 Files selected for processing (9)
  • pnpm11/pnpm/test/install/memoryBounded.ts
  • pnpm11/resolving/npm-resolver/src/clearMeta.ts
  • pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts
  • pnpm11/resolving/npm-resolver/src/pickPackage.ts
  • pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs
  • pnpm11/resolving/npm-resolver/test/memoizeFetchMetadata.test.ts
  • pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts
  • pnpm11/resolving/npm-resolver/test/metaCache.test.ts
  • pnpm11/resolving/npm-resolver/test/optionalDependencies.test.ts
💤 Files with no reviewable changes (2)
  • pnpm11/resolving/npm-resolver/test/memoizeFetchMetadata.test.ts
  • pnpm11/resolving/npm-resolver/test/metaCache.test.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs
  • pnpm11/pnpm/test/install/memoryBounded.ts
  • pnpm11/resolving/npm-resolver/src/clearMeta.ts
  • pnpm11/resolving/npm-resolver/test/optionalDependencies.test.ts
  • pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts
  • pnpm11/resolving/npm-resolver/src/pickPackage.ts

📝 Walkthrough

Walkthrough

The npm resolver now retains condensed package metadata in memory, memoizes condensed objects, preserves full metadata when configured, and applies the policy across fetch, cache, upgrade, and disk persistence paths. Tests cover metadata fields, cache behavior, memoization, optional dependencies, and bounded-memory resolution.

Changes

Metadata retention and caching

Layer / File(s) Summary
Metadata condensation and memoization
pnpm11/resolving/npm-resolver/src/clearMeta.ts, pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts, pnpm11/resolving/npm-resolver/src/index.ts
Adds identity-based condensation memoization, the retainsFullMeta policy, and optional condensation for settled metadata cache entries.
Cache loading and persistence policy
pnpm11/resolving/npm-resolver/src/pickPackage.ts
Applies condensed metadata handling across mirror loading, upgrades, revalidation, fallback paths, persistence, and disk serialization while keeping etag in headers only.
Behavior coverage and release declaration
pnpm11/resolving/npm-resolver/test/*, pnpm11/pnpm/test/install/memoryBounded.ts, .changeset/condense-retained-packuments.md
Adds coverage for condensation, memoization, cache promotion, mirror contents, optional dependencies, bounded-memory resolution, and the patch release declaration.

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

Sequence Diagram(s)

sequenceDiagram
  participant Resolver
  participant MetadataMemoizer
  participant MetadataCache
  participant Mirror
  Resolver->>MetadataMemoizer: Fetch registry metadata
  MetadataMemoizer->>MetadataCache: Retain condensed settled metadata
  MetadataCache->>Mirror: Persist selected metadata representation
  Mirror-->>Resolver: Load metadata for package selection
  Resolver-->>Resolver: Keep full metadata only when configured
Loading

Assessment against linked issues

Objective Addressed Explanation
Reduce pnpm install heap usage when resolving large dependency graphs [#8441] ✅

Possibly related PRs

  • pnpm/pnpm#13014: Both changes modify npm-resolver cache and 304 Not Modified handling.
  • pnpm/pnpm#13079: Both changes modify memoized metadata settlement behavior.

Suggested labels: product: pnpm@11

Suggested reviewers: copilot

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

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

Condense cached registry metadata to prevent OOM on large installs

🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Condense packuments before caching to prevent resolver OOM on large dependency graphs.
• Apply condensation consistently across fetch memo, metaCache, and disk-mirror upgrade paths.
• Add regression tests plus a changeset documenting the memory reduction.
Diagram

graph TD
A["createNpmResolver"] --> B["memoizeFetchMetadata"] --> C["Registry fetch"]
B --> D["clearMeta() (WeakMap)"]
E["pickPackage"] --> F["loadMeta()/fetch"] --> D --> G["metaCache (memory)"]
F --> H[("Disk mirror")]
D --> H
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Lazy/partial parsing of packuments
  • ➕ Could avoid allocating full parsed objects for unused fields entirely
  • ➕ Potentially reduces both parse time and peak heap further
  • ➖ Significantly more invasive; requires a new representation across resolver code
  • ➖ Harder to maintain correctness across the many fields consumers may read
2. Aggressively avoid retaining full-meta fetch results (no metaCache pinning)
  • ➕ Minimizes long-lived heap pressure without needing object rewriting
  • ➖ Risks re-fetches/re-reads and performance regressions across large graphs
  • ➖ Still needs careful handling of disk-mirror promotion and request deduping

Recommendation: The PR’s approach is the best tradeoff: it reuses an explicit field whitelist (clearMeta), applies it at every retention layer, and identity-memoizes the condensed object so layers share a single copy. The retainsFullMeta gate preserves full documents only for known full-metadata consumers, keeping the behavioral surface area small while addressing the OOM root cause.

Files changed (9) +314 / -59

Bug fix (4) +159 / -49
clearMeta.tsMemoize clearMeta output and add retainsFullMeta gating predicate +52/-5

Memoize clearMeta output and add retainsFullMeta gating predicate

• Adds WeakMap identity memoization so multiple condensation sites share one condensed packument object. Preserves etag when present, and introduces retainsFullMeta() to keep full packuments only for full-metadata consumers without filterMetadata.

pnpm11/resolving/npm-resolver/src/clearMeta.ts

index.tsWire settled-fetch condensation into resolver construction +4/-1

Wire settled-fetch condensation into resolver construction

• Passes condenseSettledMeta into memoizeFetchMetadata so the retained memo entry is condensed for install-style resolvers. Uses retainsFullMeta() to skip condensation for full-metadata resolvers (e.g. long outdated output).

pnpm11/resolving/npm-resolver/src/index.ts

memoizeFetchMetadata.tsSupport condenseSettledMeta to shrink retained fetch results +23/-3

Support condenseSettledMeta to shrink retained fetch results

• Extends memoizeFetchMetadata with options allowing post-settlement swapping of retained meta to a condensed object while leaving the initiating caller’s result untouched. Keeps jsonText dropping behavior and clarifies docs around retention and disk serialization.

pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts

pickPackage.tsCondense all packuments promoted into metaCache and adjust mirror writes +80/-40

Condense all packuments promoted into metaCache and adjust mirror writes

• Ensures disk-loaded and fetched packuments are condensed before being stored in metaCache unless retainsFullMeta() applies. Refactors release-age upgrade persistence so condensed meta is retained and, when appropriate, mirrored (preserving time without writing multi-MB full bodies). Also drops etag from serialized bodies in prepareJsonForDisk.

pnpm11/resolving/npm-resolver/src/pickPackage.ts

Tests (4) +149 / -10
clearMeta.test.tsAdd unit tests for clearMeta memoization, etag carry-over, and gating +62/-0

Add unit tests for clearMeta memoization, etag carry-over, and gating

• Tests that clearMeta preserves install-relevant fields while dropping bulk fields, is identity-memoized (including idempotence on already-condensed objects), carries etag through condensation, and validates retainsFullMeta behavior.

pnpm11/resolving/npm-resolver/test/clearMeta.test.ts

memoizeFetchMetadata.test.tsTest condenseSettledMeta swaps retained meta but not the initiating caller result +20/-0

Test condenseSettledMeta swaps retained meta but not the initiating caller result

• Adds coverage ensuring the memo retains the condensed meta on cache hits while the initial fetch caller receives the original meta object. Confirms the swap happens only for the retained entry after settlement.

pnpm11/resolving/npm-resolver/test/memoizeFetchMetadata.test.ts

metaCache.test.tsAdd integration tests for condensing optional/full mirrors and disk promotion +58/-1

Add integration tests for condensing optional/full mirrors and disk promotion

• Adds tests asserting that optional-dependency full documents are condensed in memory while mirrors keep the raw registry body, and that full-body mirrors are condensed when loaded into the in-memory cache during offline resolution.

pnpm11/resolving/npm-resolver/test/metaCache.test.ts

optionalDependencies.test.tsAdjust optional dependency caching test to assert libc visibility under condensation +9/-9

Adjust optional dependency caching test to assert libc visibility under condensation

• Updates the test expectations to use libc (present only in full metadata) as the observable difference between regular and optional resolution cache slots, since scripts are now dropped by in-memory condensation.

pnpm11/resolving/npm-resolver/test/optionalDependencies.test.ts

Documentation (1) +6 / -0
condense-retained-packuments.mdAdd changeset describing resolver memory fix for large graphs +6/-0

Add changeset describing resolver memory fix for large graphs

• Introduces a patch changeset for @pnpm/resolving.npm-resolver and pnpm. Documents that full registry documents were retained and are now condensed to install-relevant fields to prevent OOM on large installs.

.changeset/condense-retained-packuments.md

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
pnpm11/resolving/npm-resolver/src/pickPackage.ts (1)

650-655: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Log the best-effort mirror-write failure.

This catch silently discards saveMeta failures. Keep the write non-fatal, but log the error with pkgMirror context before proceeding.

As per coding guidelines, never swallow errors and include the offending path. Based on learnings, mirror-write failures must be logged while the install continues. <coding_guidelines> <retrieved_learnings>

🤖 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/resolving/npm-resolver/src/pickPackage.ts` around lines 650 - 655,
Update the catch block around saveMeta in the runLimited mirror-write flow to
log the failure with the pkgMirror path and caught error, while preserving the
non-fatal behavior so installation continues after the log.

Sources: Coding guidelines, Learnings

pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts (1)

64-78: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Handle failures from condenseSettledMeta.

If condense(result.meta) throws, the ignored then promise rejects without a handler, potentially terminating the process while leaving the full resolved pending entry cached. Observe that rejection, evict the entry, and report the error with package context.

As per path instructions, registry metadata must be treated as attacker-controlled. <path_instructions>

🤖 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/resolving/npm-resolver/src/memoizeFetchMetadata.ts` around lines 64 -
78, Update the ignored promise chain in memoizeFetchMetadata so errors thrown
while condensing result.meta are handled. Evict the cache entry when it still
references pending, and report the error using the existing error-reporting
mechanism with the package context available to this function. Preserve the
successful metadata caching behavior and ensure the rejection is not left
unhandled.

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.

Outside diff comments:
In `@pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts`:
- Around line 64-78: Update the ignored promise chain in memoizeFetchMetadata so
errors thrown while condensing result.meta are handled. Evict the cache entry
when it still references pending, and report the error using the existing
error-reporting mechanism with the package context available to this function.
Preserve the successful metadata caching behavior and ensure the rejection is
not left unhandled.

In `@pnpm11/resolving/npm-resolver/src/pickPackage.ts`:
- Around line 650-655: Update the catch block around saveMeta in the runLimited
mirror-write flow to log the failure with the pkgMirror path and caught error,
while preserving the non-fatal behavior so installation continues after the log.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a055c856-abff-431a-90a1-904201242f4e

📥 Commits

Reviewing files that changed from the base of the PR and between 0dbf7e6 and d827e18.

📒 Files selected for processing (9)
  • .changeset/condense-retained-packuments.md
  • pnpm11/resolving/npm-resolver/src/clearMeta.ts
  • pnpm11/resolving/npm-resolver/src/index.ts
  • pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts
  • pnpm11/resolving/npm-resolver/src/pickPackage.ts
  • pnpm11/resolving/npm-resolver/test/clearMeta.test.ts
  • pnpm11/resolving/npm-resolver/test/memoizeFetchMetadata.test.ts
  • pnpm11/resolving/npm-resolver/test/metaCache.test.ts
  • pnpm11/resolving/npm-resolver/test/optionalDependencies.test.ts

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 18, 2026
@greptile-apps

greptile-apps Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge; the fix is well-contained to the resolver's in-memory and on-disk caching layers with no changes to the lockfile format, CLI surface, or wire protocol.

The core condensation logic, WeakMap memoization, and writeCondensed flag are all correct across every fetch path. Two deterministic regression guards fail on pre-fix code. The only uncovered path is the disk-write side of the release-age upgrade inside persistFreshMeta, which is a test gap rather than a code defect.

The release-age upgrade branch of persistFreshMeta in pickPackage.ts (writeCondensed = true where resultToSave !== fetched && meta !== resultToSave.meta) has no dedicated test — metaCache.test.ts would benefit from a warm-cache scenario with minimumReleaseAge active.

Reviews (5): Last reviewed commit: "docs(resolver): trim comments to the sel..." | Re-trigger Greptile

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (3) 📎 Requirement gaps (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Action required

1. Missing trailing commas in params ✗ Dismissed 📘 Rule violation ⚙ Maintainability
Description
Several newly-added multi-line TypeScript parameter lists omit trailing commas on the last
parameter. This violates the trailing-comma requirement for multi-line constructs.
Code

pnpm11/resolving/npm-resolver/src/pickPackage.ts[R231-234]

+function condenseMetaForCache (
+  ctx: { fullMetadata?: boolean, filterMetadata?: boolean },
+  meta: PackageMeta
+): PackageMeta {
Evidence
The checklist requires trailing commas in multi-line parameter lists. The function signatures for
condenseMetaForCache, upgradeMetaForCache, and persistUpgradedMeta are multi-line and the last
parameter line lacks a trailing comma.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/resolving/npm-resolver/src/pickPackage.ts[231-236]
pnpm11/resolving/npm-resolver/src/pickPackage.ts[625-634]
pnpm11/resolving/npm-resolver/src/pickPackage.ts[641-645]

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

## Issue description
Multi-line function parameter lists are missing trailing commas on their last parameter.

## Issue Context
The rule applies to multi-line parameter lists in `.ts` files.

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/src/pickPackage.ts[231-236]
- pnpm11/resolving/npm-resolver/src/pickPackage.ts[625-634]
- pnpm11/resolving/npm-resolver/src/pickPackage.ts[641-645]

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


2. upgradeMetaForCache has four parameters ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
upgradeMetaForCache is introduced with 4 positional parameters, exceeding the 3-parameter limit.
This makes call sites harder to read and maintain versus passing an options object.
Code

pnpm11/resolving/npm-resolver/src/pickPackage.ts[R625-633]

+function upgradeMetaForCache (
+  ctx: { fullMetadata?: boolean, filterMetadata?: boolean },
+  pkgMirror: string,
+  dryRun: boolean,
+  upgrade: { meta: PackageMeta, upgradedFrom?: FetchMetadataResult }
+): PackageMeta {
+  if (upgrade.upgradedFrom == null) return upgrade.meta
+  if (dryRun) return condenseMetaForCache(ctx, upgrade.meta)
+  return persistUpgradedMeta(ctx, pkgMirror, upgrade.upgradedFrom)
Evidence
The checklist restricts TypeScript function signatures to three parameters or fewer unless using a
single options object. The new upgradeMetaForCache signature has 4 parameters (ctx, pkgMirror,
dryRun, upgrade).

Rule 713433: Limit TypeScript functions to three parameters or fewer
pnpm11/resolving/npm-resolver/src/pickPackage.ts[625-634]

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

## Issue description
`upgradeMetaForCache` takes 4 positional parameters, violating the max-3-parameters rule.

## Issue Context
The rule allows using a single options/config object parameter instead of many positional parameters.

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/src/pickPackage.ts[625-634]

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


3. fullMeta declared before usage ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
In clearMeta.test.ts, function fullMeta() is declared before any call site in the file. This
violates the requirement that TypeScript function declarations appear only after their first usage.
Code

pnpm11/resolving/npm-resolver/test/clearMeta.test.ts[R6-27]

+function fullMeta (): PackageMeta {
+  return {
+    name: 'foo',
+    'dist-tags': { latest: '1.0.0' },
+    versions: {
+      '1.0.0': {
+        name: 'foo',
+        version: '1.0.0',
+        libc: ['glibc'],
+        scripts: { postinstall: 'node scripts/build.js' },
+        description: 'dropped',
+        dist: {
+          tarball: 'https://registry.npmjs.org/foo/-/foo-1.0.0.tgz',
+          integrity: 'sha512-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==',
+        },
+      },
+    },
+    time: { '1.0.0': '2020-01-01T00:00:00.000Z' },
+    modified: '2020-01-01T00:00:00.000Z',
+    readme: '# dropped',
+  } as unknown as PackageMeta
+}
Evidence
The checklist requires function declarations to appear only after at least one usage in the same
file. fullMeta() is declared at lines 6-27, and the first usage (clearMeta(fullMeta())) occurs
later at line 30.

Rule 713432: Declare TypeScript functions only after their first usage
pnpm11/resolving/npm-resolver/test/clearMeta.test.ts[6-30]

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

## Issue description
`fullMeta()` is declared before its first usage, violating the local ordering rule for TypeScript function declarations.

## Issue Context
Rule scope applies to top-level `function foo() {}` declarations in `.ts` files.

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/test/clearMeta.test.ts[6-30]

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



Remediation recommended

4. condenseMetaForCache JSDoc lacks contract 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new JSDoc explains rationale and sources of full metadata, but does not document the function’s
contract (inputs assumed valid, whether meta is mutated, and what invariants the returned
PackageMeta guarantees). This increases maintenance risk because callers can’t rely on a clearly
stated pre/postcondition for what is retained in memory.
Code

pnpm11/resolving/npm-resolver/src/pickPackage.ts[R221-224]

+ * The form in which a packument is retained in memory (see {@link clearMeta}
+ * for why). Full documents reach even a plain install via optional
+ * dependencies (fetched full for `libc`), release-age `time` upgrades, and
+ * mirror files that hold a full body.
Evidence
PR Compliance ID 713430 requires that new/modified function JSDoc describe the function contract
(preconditions, postconditions, edge cases) rather than mainly re-describing behavior/context. The
JSDoc added above condenseMetaForCache provides rationale and examples of how full documents are
reached, but does not specify the contract of the helper (e.g., whether it mutates meta, exact
guarantees about what fields are present/absent in the returned object).

Rule 713430: JSDoc must document function contracts, not re-describe implementation
pnpm11/resolving/npm-resolver/src/pickPackage.ts[221-224]

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

## Issue description
`condenseMetaForCache` has new JSDoc, but it focuses on rationale/background and does not clearly state the function contract (preconditions/postconditions, mutation/ownership expectations, and what fields are guaranteed on the returned `PackageMeta`).

## Issue Context
Compliance requires that JSDoc documents the function contract rather than primarily describing implementation context.

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/src/pickPackage.ts[221-224]

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


5. upgradeMetaForCache JSDoc lacks contract 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new JSDoc describes why the helper exists but does not clearly document its contract
(inputs/edge cases, side effects like mirror writes vs dry-run behavior, and return-value
guarantees). This makes it harder to safely reuse or change the function without introducing subtle
cache/mirror regressions.
Code

pnpm11/resolving/npm-resolver/src/pickPackage.ts[R593-596]

+ * The meta to retain after a release-age upgrade check, persisted to the
+ * mirror (unless dry-run) because the mirror otherwise still holds the
+ * pre-upgrade abbreviated form without `time`, and every future install
+ * would re-trigger the upgrade fetch.
Evidence
PR Compliance ID 713430 requires contract-focused JSDoc for new/modified functions. The added JSDoc
for upgradeMetaForCache explains persistence motivation but does not specify the contract (e.g.,
what is guaranteed when upgrade.upgradedFrom is absent/present, what happens under dryRun, and
what side effects occur).

Rule 713430: JSDoc must document function contracts, not re-describe implementation
pnpm11/resolving/npm-resolver/src/pickPackage.ts[593-596]

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

## Issue description
`upgradeMetaForCache` has new JSDoc, but it does not sufficiently document the function’s contract (especially side effects and edge cases).

## Issue Context
Compliance expects JSDoc on new/modified functions to describe contracts (preconditions, postconditions, edge-case behavior), not mainly narrative about why the function exists.

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/src/pickPackage.ts[593-596]

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


6. Fixture cleanup not guaranteed 🐞 Bug ☼ Reliability
Description
The resolve-bloated-metadata.mjs fixture only closes the HTTP server and removes the temp cache
directory on the success path; if resolution throws, cleanup is skipped, which can keep the child
process alive and/or leak temp dirs until the parent test’s timeout.
Code

pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs[R53-73]

+const cacheDir = mkdtempSync(path.join(os.tmpdir(), 'pnpm-memory-bounded-'))
+const { resolveFromNpm } = createNpmResolver(createFetchFromRegistry({}), () => undefined, {
+  cacheDir,
+  registries: { default: registry },
+})
+
+// Sequential on purpose: transient memory (response body + freshly parsed
+// document) then stays around one document, so the heap cap measures what is
+// RETAINED across resolutions, not the fetch concurrency.
+for (let i = 0; i < PACKAGE_COUNT; i++) {
+  const result = await resolveFromNpm(
+    { alias: `bloated-pkg-${i}`, bareSpecifier: '1.0.0', optional: true },
+    {}
+  )
+  if (result?.manifest?.version !== '1.0.0' || result.manifest.libc?.[0] !== 'glibc') {
+    throw new Error(`bloated-pkg-${i} resolved incorrectly: ${JSON.stringify(result?.manifest)}`)
+  }
+}
+
+server.close()
+rmSync(cacheDir, { recursive: true, force: true })
Evidence
The fixture’s cleanup runs only after the loop and is not protected by a finally block, so any
thrown error before the end skips cleanup. The parent test executes it synchronously with a timeout,
so leaked handles can manifest as timeouts/flakiness rather than crisp failures.

pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs[53-73]
pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts[21-37]

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 child-process fixture performs cleanup (`server.close()`, `rmSync(cacheDir, ...)`) only after the resolution loop. If the loop throws (resolver error or assertion failure), the server handle and temp directory may leak, and the child can hang until killed by the parent timeout.

### Issue Context
`memoryBounded.test.ts` runs this fixture under `execFileSync` with a timeout; leaked handles can convert a meaningful failure into a slow timeout and leave residue in OS temp.

### Fix Focus Areas
- pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs[53-73]
- pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts[21-37]

### Suggested fix
Refactor the fixture to:
- Create `cacheDir` and start the server.
- `try { ...resolution loop... } finally { ...close server... rmSync(cacheDir)... }`
Optionally make server shutdown awaitable (wrap `server.close` in a Promise) so the child deterministically exits after failures.

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


View more (5)
7. Silent condense fallback 🐞 Bug ◔ Observability
Description
In memoizeFetchMetadata(), condenseSettledMeta exceptions are swallowed with an empty catch, so a
condenser failure will quietly retain the full (potentially huge) meta in the settled cache entry
and can reintroduce high retained-heap behavior with no diagnostic signal.
Code

pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts[R90-95]

+    if (condense != null) {
+      try {
+        meta = condense(result.meta)
+      } catch {}
+    }
+    return { ...result, jsonText: undefined, meta }
Evidence
The new settledEntry() path explicitly swallows all condenser exceptions and still stores the
result back into the long-lived resolution-phase cache, meaning a failure to condense will
persistently keep the original meta with no log/metric indicating condensation was skipped.

pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts[80-96]

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

### Issue description
`memoizeFetchMetadata()` intentionally catches condenser errors to avoid unhandled rejections, but the empty `catch {}` makes failures invisible. When condensing fails, the settled entry retains the uncondensed packument, which can defeat the PR’s memory objective without any signal to debug why.

### Issue Context
The condenser runs in a fire-and-forget `then` handler; it must not throw. However, silently skipping condensation makes memory regressions hard to diagnose.

### Fix Focus Areas
- pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts[90-95]

### Suggested fix
In the `catch`, emit a *low-volume* debug log (or counter/metric if available) indicating condensation failed for the cache key/package, without logging the full metadata object (to avoid large logs / sensitive data). Keep behavior as fallback-to-uncondensed, but make it observable.

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


8. Historical phrasing in regression comment ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
A new test comment describes past behavior (as the resolver did before condensing) rather than the
current contract, which can become misleading as the implementation evolves. Comments should be
phrased in terms of present behavior and invariants.
Code

pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts[R13-15]

+ * install-irrelevant bulk — 120 MB total. Retaining the parsed documents,
+ * as the resolver did before condensing, overflows the 100 MB cap after a
+ * dozen packages; the condensed working set is a few KB per package, which
Evidence
The comment in memoryBounded.test.ts explicitly references prior behavior (before condensing),
which the checklist forbids in inline comments; it should instead describe the current
requirement/invariant the test enforces.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts[13-15]

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 comment uses historical phrasing (`before condensing`), which violates the rule that comments must describe current behavior.

## Issue Context
This is a regression-guard test; the intent can be preserved while phrasing it as a current invariant (e.g., “Retaining full parsed documents would overflow…”).

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts[13-15]

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


9. Non-deterministic fixture cleanup 🐞 Bug ☼ Reliability
Description
The child fixture calls server.close() without awaiting completion and never tears down undici
dispatchers created via createFetchFromRegistry, so the child process may linger on keep-alive
sockets (or behave differently on Windows where pnpm explicitly destroys dispatchers on exit),
making memoryBounded.test.ts slower or flaky.
Code

pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs[R43-71]

+const server = http.createServer((req, res) => {
+  const name = decodeURIComponent(req.url.slice(1))
+  res.setHeader('content-type', 'application/json')
+  res.end(packumentFor(name))
+})
+await new Promise((resolve) => {
+  server.listen(0, '127.0.0.1', resolve)
+})
+const registry = `http://127.0.0.1:${server.address().port}/`
+
+const { resolveFromNpm } = createNpmResolver(createFetchFromRegistry({}), () => undefined, {
+  cacheDir: mkdtempSync(path.join(os.tmpdir(), 'pnpm-memory-bounded-')),
+  registries: { default: registry },
+})
+
+// Sequential on purpose: transient memory (response body + freshly parsed
+// document) then stays around one document, so the heap cap measures what is
+// RETAINED across resolutions, not the fetch concurrency.
+for (let i = 0; i < PACKAGE_COUNT; i++) {
+  const result = await resolveFromNpm(
+    { alias: `bloated-pkg-${i}`, bareSpecifier: '1.0.0', optional: true },
+    {}
+  )
+  if (result?.manifest?.version !== '1.0.0' || result.manifest.libc?.[0] !== 'glibc') {
+    throw new Error(`bloated-pkg-${i} resolved incorrectly: ${JSON.stringify(result?.manifest)}`)
+  }
+}
+
+server.close()
Evidence
The fixture creates an HTTP server and a registry fetcher but only calls server.close() at the end
without awaiting, and provides no cleanup for undici dispatchers. The repo’s fetch layer uses undici
Agents with keep-alive, and pnpm’s own exit path destroys dispatchers on Windows specifically to
avoid exiting with open sockets—so lack of deterministic teardown in a standalone child process can
translate into hangs/slowness or platform-specific flakiness.

pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs[43-71]
pnpm11/network/fetch/src/dispatcher.ts[12-33]
pnpm11/network/fetch/src/dispatcher.ts[103-119]
pnpm11/pnpm/src/exit.ts[1-11]
pnpm11/pnpm/test/errorHandler.test.ts[56-88]

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 child-process fixture starts an HTTP server and uses `createFetchFromRegistry()` (undici keep-alive). It ends with a bare `server.close()` (not awaited) and no dispatcher teardown, which can leave open handles/sockets and delay or prevent process exit; it also creates a temp cacheDir that is never removed.

## Issue Context
- `@pnpm/network.fetch` configures an undici `Agent` with keep-alive timeouts and `pnpm` itself works around a Windows crash by calling `destroyDispatchers()` on exit.
- This fixture is executed via `execFileSync` in `memoryBounded.test.ts`, so any child lingering translates into test slowness/timeouts.

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs[43-71]

### Suggested implementation sketch
- Import `destroyDispatchers` alongside `createFetchFromRegistry`.
- Capture `cacheDir` in a variable.
- Wrap the main logic in `try { ... } finally { ... }`.
- In `finally`:
 - `await new Promise((resolve, reject) => server.close(err => err ? reject(err) : resolve()))`
 - `await destroyDispatchers()` (safe here because the script is ending)
 - `rmSync(cacheDir, { recursive: true, force: true })` (optional but keeps temp clean).

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


10. Condense error pins jsonText ✓ Resolved 🐞 Bug ☼ Reliability
Description
In memoizeFetchMetadata(), condenseSettledMeta is executed inline while constructing the settled
cache entry that is supposed to drop jsonText. If the condense callback throws, the cache swap is
skipped and the Map continues to retain the original settled promise/result (including potentially
multi‑MB jsonText) for the whole resolution phase.
Code

pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts[R67-73]

          cache.set(
            key,
            Promise.resolve(
-              result.notModified ? result : { ...result, jsonText: undefined }
+              result.notModified
+                ? result
+                : { ...result, jsonText: undefined, meta: condense ? condense(result.meta) : result.meta }
            )
Evidence
The memoization layer depends on swapping in a body-less clone after settlement to avoid retaining
large jsonText strings; the new condensing hook is evaluated inside the construction of that
replacement object. A thrown exception prevents reaching the cache.set() call that installs the
replacement, so the cache can keep the original entry with jsonText retained.

pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts[29-74]
pnpm11/resolving/npm-resolver/src/index.ts[215-223]

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

### Issue description
`memoizeFetchMetadata()` relies on a post-settlement swap to replace the cached entry with a clone that drops `jsonText` (large raw registry bodies). The new `condenseSettledMeta` hook is invoked inline during that swap; if it throws, the swap doesn’t happen and the cache may retain the original result (including `jsonText`) for the rest of the resolution phase.

### Issue Context
- The comments explicitly state that retaining `jsonText` past settlement would pin hundreds of MB on large graphs.
- `createNpmResolver()` wires `condenseSettledMeta` to `clearMeta` for most resolver instances.

### Fix Focus Areas
- pnpm11/resolving/npm-resolver/src/memoizeFetchMetadata.ts[54-79]

### Suggested fix
- Ensure the “drop `jsonText`” swap happens even if condensing fails:
 - Compute `nextMeta` in a `try/catch`:
   - On success: use condensed meta.
   - On failure: fall back to the original `result.meta` (still drop `jsonText`) **or** evict the cache entry so a subsequent call refetches.
 - Then `cache.set(key, Promise.resolve({...result, jsonText: undefined, meta: nextMeta}))`.
- Optionally log (debug-level) when condensing fails, since this reintroduces memory pressure and may indicate malformed metadata.

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


11. clearMeta comment duplicates JSDoc 📘 Rule violation ⚙ Maintainability
Description
A call-site comment in clearMeta.test.ts restates the same memoization rationale already
documented in clearMeta/related JSDoc. This creates duplicated documentation that can drift over
time.
Code

pnpm11/resolving/npm-resolver/test/clearMeta.test.ts[R41-43]

+  // Several layers condense the same parsed document (the settled-fetch memo
+  // and the resolver cache); identity-memoization is what makes them share
+  // one condensed copy instead of pinning one each.
Evidence
The checklist prohibits call-site comments that substantially restate the function's existing JSDoc.
The comment above clearMeta(meta) repeats the memoization rationale already documented for the
condensing behavior.

Rule 713431: Avoid duplicating JSDoc content in call-site comments
pnpm11/resolving/npm-resolver/test/clearMeta.test.ts[40-48]

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

## Issue description
A call-site comment repeats content already covered by the callee's JSDoc, increasing duplication and drift risk.

## Issue Context
Prefer keeping purpose/behavior documentation in the function's JSDoc and leaving call sites with only contextual rationale.

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/test/clearMeta.test.ts[40-48]

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


Grey Divider

Qodo Logo

Resolves 30 optional dependencies whose full documents each carry 4 MB of
install-irrelevant bulk under a 100 MB --max-old-space-size cap. Retaining
the parsed documents, as before the condensing fix for
#8441, aborts the child with a V8
heap-limit error (verified: exit 134 against the pre-fix resolver); the
condensed working set leaves roughly a 3x headroom, so the guard is
deterministic rather than timing-sensitive.
Copilot AI review requested due to automatic review settings July 18, 2026 21: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.

@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to ba8844d

Warning

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

CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve lifecycle script detection

Derive and set the hasInstallScript flag before dropping the scripts object when
condensing full metadata. This ensures packages with lifecycle scripts do not
incorrectly skip their build steps.

pnpm11/resolving/npm-resolver/src/clearMeta.ts [54-56]

 for (const [version, info] of Object.entries(pkg.versions ?? {})) {
-  versions[version] = pick(ABBREVIATED_VERSION_FIELDS, info)
+  const condensedInfo = pick(ABBREVIATED_VERSION_FIELDS, info)
+  if (
+    condensedInfo.hasInstallScript == null &&
+    (info.scripts?.preinstall != null ||
+      info.scripts?.install != null ||
+      info.scripts?.postinstall != null)
+  ) {
+    condensedInfo.hasInstallScript = true
+  }
+  versions[version] = condensedInfo
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 10

__

Why: The suggestion identifies a critical bug where condensing full metadata drops the scripts object without preserving the hasInstallScript flag, which would cause pnpm to silently skip lifecycle scripts for packages fetched with full metadata (such as optional dependencies).

High
  • More

Previous suggestions

Suggestions
CategorySuggestion                                                                                                                                    Impact
Possible issue
Isolate condensed metadata cache entries

Differentiate cache keys for condensed metadata and full metadata to prevent
cache poisoning when metaCache is shared between different resolver instances.
Modify getPkgMetaCacheKey to append a specific suffix like :condensed when
appropriate.

pnpm11/resolving/npm-resolver/src/pickPackage.ts [231-236]

+function getMetaCacheKey (
+  ctx: { fullMetadata?: boolean, filterMetadata?: boolean },
+  registry: string,
+  pkgName: string,
+  fullMetadata: boolean
+): string {
+  const key = getPkgMetaCacheKey(registry, pkgName, fullMetadata, ctx.filterMetadata === true)
+  return fullMetadata && !retainsFullMeta(ctx) ? `${key}:condensed` : key
+}
+
 function condenseMetaForCache (
   ctx: { fullMetadata?: boolean, filterMetadata?: boolean },
   meta: PackageMeta
 ): PackageMeta {
   return retainsFullMeta(ctx) ? meta : clearMeta(meta)
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion identifies a critical cache-poisoning bug where sharing metaCache across resolver instances could lead to full-metadata consumers receiving condensed documents and missing required fields.

High

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 9ee3975

@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

CategorySuggestion                                                                                                                                    Impact
Possible issue
Isolate condensed metadata cache entries

Differentiate cache keys for condensed metadata and full metadata to prevent
cache poisoning when metaCache is shared between different resolver instances.
Modify getPkgMetaCacheKey to append a specific suffix like :condensed when
appropriate.

pnpm11/resolving/npm-resolver/src/pickPackage.ts [231-236]

+function getMetaCacheKey (
+  ctx: { fullMetadata?: boolean, filterMetadata?: boolean },
+  registry: string,
+  pkgName: string,
+  fullMetadata: boolean
+): string {
+  const key = getPkgMetaCacheKey(registry, pkgName, fullMetadata, ctx.filterMetadata === true)
+  return fullMetadata && !retainsFullMeta(ctx) ? `${key}:condensed` : key
+}
+
 function condenseMetaForCache (
   ctx: { fullMetadata?: boolean, filterMetadata?: boolean },
   meta: PackageMeta
 ): PackageMeta {
   return retainsFullMeta(ctx) ? meta : clearMeta(meta)
 }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion identifies a critical cache-poisoning bug where sharing metaCache across resolver instances could lead to full-metadata consumers receiving condensed documents and missing required fields.

High
  • More

@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 (3)
pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs (2)

6-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Sort standard library imports alphabetically.

As per coding guidelines, standard library imports should be ordered alphabetically.

♻️ Proposed fix
-import http from 'node:http'
-import { mkdtempSync } from 'node:fs'
+import { mkdtempSync } from 'node:fs'
+import http from 'node:http'
 import os from 'node:os'
 import path from 'node:path'
🤖 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/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs`
around lines 6 - 9, Reorder the standard-library imports in the fixture so the
imported module specifiers are alphabetized, keeping the existing imports and
behavior unchanged.

Source: Coding guidelines


53-56: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Clean up the temporary cache directory after successful execution.

To avoid leaving residual directories in the system's temporary folder across local test runs, consider extracting the cacheDir path and removing it at the end of the script.

♻️ Proposed fix to prevent temp dir leakage

First, update the node:fs import to include rmSync:

-import { mkdtempSync } from 'node:fs'
+import { mkdtempSync, rmSync } from 'node:fs'

Next, extract the variable here:

+const cacheDir = mkdtempSync(path.join(os.tmpdir(), 'pnpm-memory-bounded-'))
 const { resolveFromNpm } = createNpmResolver(createFetchFromRegistry({}), () => undefined, {
-  cacheDir: mkdtempSync(path.join(os.tmpdir(), 'pnpm-memory-bounded-')),
+  cacheDir,
   registries: { default: registry },
 })

Finally, add the cleanup below server.close() at the bottom of the file (Line 71):

 server.close()
+rmSync(cacheDir, { recursive: true, force: true })
🤖 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/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs`
around lines 53 - 56, Update the fixture setup around createNpmResolver to store
the mkdtempSync result in a cacheDir variable and import rmSync from node:fs.
After the successful execution and server.close() at the script’s end, remove
that temporary cache directory with rmSync using recursive cleanup.
pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts (1)

25-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Expose the child process stderr for accurate diagnosis.

Wrapping execFileSync in expect().not.toThrow() causes Jest to swallow the custom stderr buffer attached to the error object. This defeats the intent of the comment stating "with the child's stderr attached for diagnosis". Instead, catch the error, append the stderr to the error message, and rethrow it so Jest can display the full diagnostic context. As per coding guidelines, do not swallow errors and ensure contextual information is included in error messages.

♻️ Proposed fix
-  expect(() => {
-    execFileSync(process.execPath, ['--max-old-space-size=100', fixture], {
-      stdio: ['ignore', 'ignore', 'pipe'],
-      timeout: 100_000,
-    })
-  }).not.toThrow()
+  try {
+    execFileSync(process.execPath, ['--max-old-space-size=100', fixture], {
+      stdio: ['ignore', 'ignore', 'pipe'],
+      timeout: 100_000,
+    })
+  } catch (err: any) {
+    if (err.stderr != null) {
+      err.message += `\n\nChild stderr:\n${err.stderr.toString()}`
+    }
+    throw err
+  }
🤖 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/resolving/npm-resolver/test/memoryBounded.test.ts` around lines 25 -
30, Update the execFileSync assertion in memoryBounded.test.ts to catch failures
explicitly, append the child process stderr to the thrown error message, and
rethrow the enriched error so Jest displays the diagnostic context. Preserve the
existing command options and successful execution behavior.

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.

Nitpick comments:
In `@pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs`:
- Around line 6-9: Reorder the standard-library imports in the fixture so the
imported module specifiers are alphabetized, keeping the existing imports and
behavior unchanged.
- Around line 53-56: Update the fixture setup around createNpmResolver to store
the mkdtempSync result in a cacheDir variable and import rmSync from node:fs.
After the successful execution and server.close() at the script’s end, remove
that temporary cache directory with rmSync using recursive cleanup.

In `@pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts`:
- Around line 25-30: Update the execFileSync assertion in memoryBounded.test.ts
to catch failures explicitly, append the child process stderr to the thrown
error message, and rethrow the enriched error so Jest displays the diagnostic
context. Preserve the existing command options and successful execution
behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3ebd7e80-c603-45ee-a86f-dc2858e991b6

📥 Commits

Reviewing files that changed from the base of the PR and between d827e18 and 9ee3975.

📒 Files selected for processing (2)
  • pnpm11/resolving/npm-resolver/test/fixtures/resolve-bloated-metadata.mjs
  • pnpm11/resolving/npm-resolver/test/memoryBounded.test.ts

zkochan added 2 commits July 19, 2026 00:11
Deduplicate the three best-effort mirror-write blocks into
saveMetaBestEffort, which debug-logs a write failure with the mirror path
instead of discarding it. Guard the settled-fetch swap in
memoizeFetchMetadata against a throwing condenser: the swap runs in a
fire-and-forget then-callback where a throw would become an unhandled
rejection, so a condense failure now falls back to retaining the
uncondensed meta. Give upgradeMetaForCache an options object instead of a
fourth positional parameter, surface the memory-guard child's stderr in
the jest failure message, and clean up the fixture's temp cache dir.
Copilot AI review requested due to automatic review settings July 18, 2026 22:12

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 18, 2026

Copy link
Copy Markdown
Member Author

Addressed the CodeRabbit review findings in 1487e0d:

  • Unhandled rejection if condenseSettledMeta throws (memoizeFetchMetadata.ts): the settlement swap now runs the condenser inside a guard — a failure falls back to retaining the uncondensed meta (correct, just bigger), so the fire-and-forget then-callback can no longer produce an unhandled rejection. Surfacing a genuinely malformed document stays with the resolution path, which condenses the same document with proper error propagation. Pinned by a new test (a throwing condenseSettledMeta falls back to retaining the uncondensed meta).
  • Silent saveMeta catch (pickPackage.ts): the three copy-pasted best-effort mirror-write blocks are deduplicated into saveMetaBestEffort, which debug-logs the failure with the mirror path while keeping the write non-fatal. Debug level rather than warn on purpose: a read-only cache dir would otherwise emit one warning per package.
  • Nitpicks: fixture imports alphabetized, the fixture's temp cache dir is removed on success, and the memory-guard test now folds the child's stderr into the thrown error message instead of hiding it behind expect(...).not.toThrow().

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

@qodo-code-review

Copy link
Copy Markdown

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

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

CategorySuggestion                                                                                                                                    Impact
Possible issue
Isolate condensed metadata cache entries

Differentiate cache keys for condensed metadata and full metadata to prevent
cache poisoning when metaCache is shared between different resolver instances.
Modify getPkgMetaCacheKey to append a specific suffix like :condensed when
appropriate.

pnpm11/resolving/npm-resolver/src/pickPackage.ts [231-236]

+function getMetaCacheKey (
+  ctx: { fullMetadata?: boolean, filterMetadata?: boolean },
+  registry: string,
+  pkgName: string,
+  fullMetadata: boolean
+): string {
+  const key = getPkgMetaCacheKey(registry, pkgName, fullMetadata, ctx.filterMetadata === true)
+  return fullMetadata && !retainsFullMeta(ctx) ? `${key}:condensed` : key
+}
+
 function condenseMetaForCache (
   ctx: { fullMetadata?: boolean, filterMetadata?: boolean },
   meta: PackageMeta
 ): PackageMeta {
   return retainsFullMeta(ctx) ? meta : clearMeta(meta)
 }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion identifies a critical cache-poisoning bug where sharing metaCache across resolver instances could lead to full-metadata consumers receiving condensed documents and missing required fields.

High
  • More

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.

pnpm install suddenly reaches heap limit every time.

2 participants