Skip to content

perf(resolver): avoid repeated packument filtering and semver parsing during version picking - #13504

Merged
zkochan merged 4 commits into
pnpm:mainfrom
charpeni:perf/resolver-avoid-repeated-packument-filtering
Aug 1, 2026
Merged

zkochan merged 4 commits into
pnpm:mainfrom
charpeni:perf/resolver-avoid-repeated-packument-filtering

Conversation

@charpeni

@charpeni charpeni commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Dependency resolution spends a large share of its CPU time redoing identical work: with minimumReleaseAge on by default, filterPkgMetadataByPublishDate re-filters the same packument once per dependency edge instead of once per packument, and the version pickers re-parse the same semver strings and ranges thousands of times per install. CPU profiles of a full resolution of the pnpm11/benchmarks fixture (1246 packages, hot cache) attributed ~25% of the run to pickPackageFromMeta, dominated by these two costs.

This PR removes the recomputation without changing any observable behavior:

  • Memoize filterPkgMetadataByPublishDate per packument object (WeakMap), keyed by cutoff date + trusted versions so a shared meta cache serving installs with different policies can't cross-contaminate. This is the dominant win (−11% alone).
  • Cache parsed SemVer and Range instances in pickPackageFromMeta, and replace semver.maxSatisfying/minSatisfying (which re-parse the range and every version on every call) with cache-reusing equivalents (−4% alone).
  • Dedupe offline mirror loads: concurrent offline picks of the same package queued behind the per-package limiter each re-read and re-parsed the mirror file (176 of 1311 loads in the fixture were duplicates); the limiter now re-checks the in-memory cache.
  • Condense packuments with a direct field loop in clearMeta instead of ramda's curried pick (~2M field checks per install on the fixture).

Benchmarks (hyperfine, offline so runs are deterministic, fixture from pnpm11/benchmarks):

Scenario Before After Change
Full resolution (install --offline --lockfile-only, hot cache) 4.27s ± 0.20 3.73s ± 0.07 1.14× ± 0.06 (−12.5%)
Fresh install, offline, hot store (resolve + link)¹ 5.88s ± 0.21 5.07s ± 0.07 1.16× ± 0.04 (−13.7%)
Frozen-lockfile restore (does not resolve) 1.97s 2.01s 1.00× (no change)

¹ measured on the pre-rebase base; the resolution-only row is measured on current main.

Correctness evidence: the optimized build produces a byte-identical pnpm-lock.yaml to main on the fixture; all existing @pnpm/resolving.npm-resolver (287) and @pnpm/resolving.registry.pkg-metadata-filter tests pass, including the test added in #13044 for the latest-fallback bound, which exercises the memoized path.

pacquet

The same three costs were checked against the Rust resolver. Two were already
paid off there: cached_range memoizes parsed ranges and max_satisfying /
min_satisfying are loops that reuse it, and pick_package already re-checks
the in-memory cache after acquiring the per-mirror permit and promotes the
mirror before releasing it, so concurrent offline picks already read the mirror
once.

The filter memoization was missing, so this PR adds it: the derived packument is
memoized on the document it derives from (DerivedPackuments, hung on
Package, so the derived copies die with it), keyed by cutoff plus trusted
versions, and capped at four policies so a long-lived host (the napi bindings, a
daemon) holding one shared meta cache can't retain a derived copy per install.
Offline resolution of the same fixture:

Scenario Before After Change
Full resolution (install --offline --lockfile-only, hot cache) 167.6ms ± 5.0 161.9ms ± 4.9 1.04× ± 0.04
— CPU time 166.6ms 152.0ms −8.8%

(hyperfine, 50 runs, lockfile removed before each run; the resulting
pnpm-lock.yaml is byte-identical between the two binaries.) The win is
proportional to how many packuments carry per-version time: 22 of 1126 on this
fresh cache, and every packument under resolutionMode=time-based or
trustPolicy=no-downgrade, which force full metadata.

Not mirrored: the version-instance cache. Rust's Version::parse is cheap
enough that a process-global map keyed by version string is not obviously a win,
and the expensive half of that optimization — the range parse — is already
cached in pacquet. clearMeta has no pacquet counterpart: version manifests
stay as unhydrated JSON fragments there, so nothing is condensed per field.

Prototype pollution in the filtered maps

versionsWithinDate and distTagsWithinDate were plain objects populated with
registry-controlled keys, so a version or dist-tag named __proto__ reassigned
the map's prototype instead of becoming an own key — which also let the
malicious manifest's own fields read back as versions within date. Both are now
null-prototype, matching clearMeta. Reported by Copilot on this PR; covered by
a test that fails on the plain-object form.

Squash Commit Body

Resolution re-derived the same data once per dependency edge instead of
once per packument:

- filterPkgMetadataByPublishDate ran on every pick (every edge) with
  minimumReleaseAge active — the default since it is 1440 min — parsing
  a Date per version and rebuilding the versions map each time. It is
  now memoized per packument object in a WeakMap, keyed by cutoff and
  trusted versions so one packument served under different policies
  still filters per policy. Sharing the returned object is safe: callers
  already shared the inner version manifests, and the packument objects
  the resolver passes in are themselves cached and treated as read-only.

- pickPackageFromMeta re-parsed version strings and ranges on every
  satisfies/maxSatisfying call. Parsed SemVer and Range instances are
  now cached in capped Maps (cleared at 50k entries so long-lived
  processes cannot grow them without bound), and maxSatisfying/
  minSatisfying are replaced with loops that reuse the caches. The
  dist-tag repopulation loop in the publish-date filter likewise
  compares already-parsed instances instead of calling semver.gt on
  strings.

- Concurrent offline picks of one package all miss the pre-queue
  in-memory cache check, then each re-read and re-parsed the mirror
  behind the per-package limiter (176 of 1311 loads on the benchmark
  fixture were duplicates). The limiter callback now re-checks the
  cache; offline entries are always disk-sourced, so this is equivalent
  to arriving after the first caller cached it.

- clearMeta condensed every version object through ramda's curried
  pick; a direct field loop does the same with no per-field dispatch.
  The presence check via undefined-comparison matches the previous
  behavior because version objects come from JSON, which cannot encode
  undefined.

Resolution of the 1246-package benchmark fixture is 12.5% faster on
top of current main (4.27s -> 3.73s, hyperfine, offline hot cache);
the resulting lockfile is byte-identical. Attribution: filter
memoization -11%, semver caches -4%, the rest ~-1%.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting. (The filter
    memoization is now in both stacks; the other items were already in pacquet or
    don't apply there — see the pacquet section.)
  • 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. (A regression test for simultaneous offline picks
    — one mirror read for N concurrent picks, fails on the pre-fix code — and a
    test of the filter memoization contract incl. bounded per-packument policy
    cache.)

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

Summary by CodeRabbit

  • Performance
    • Improved dependency resolution with minimum release age by filtering package metadata once per packument.
    • Reduced repeated semantic version parsing and comparisons through bounded caching.
    • Improved dist-tag best-version selection by reusing parsed versions.
  • Bug Fixes
    • Prevented a race during offline or preferred-offline resolution, ensuring metadata is cached consistently.
  • Tests
    • Added coverage for offline concurrency, version selection, and publish-date filtering memoization.

@coderabbitai

coderabbitai Bot commented Jul 30, 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: 0eefbf9b-f631-467e-b53c-e350a444350a

📥 Commits

Reviewing files that changed from the base of the PR and between 0818cb1 and e12b141.

📒 Files selected for processing (3)
  • pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs
  • pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta/tests.rs
  • pnpm11/resolving/npm-resolver/test/pickVersionByVersionRange.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta/tests.rs
  • pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs

📝 Walkthrough

Walkthrough

Resolver metadata filtering, disk loading, and version selection now reuse bounded caches. Condensed metadata copying no longer uses Ramda. Concurrent offline reads populate the cache within the limiter. Rust package metadata adds shared derived-packument caching. A changeset records patch releases.

Changes

Resolver cache optimizations

Layer / File(s) Summary
Derived packument memo implementation
pnpm/crates/registry/src/package.rs, pnpm/crates/registry/src/lib.rs, pnpm/crates/registry/src/package/tests.rs
Package now stores a bounded, mutex-protected DerivedPackuments memo for policy-derived metadata.
Rust publish-date filtering integration
pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs, pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta/tests.rs, pnpm/crates/resolving-npm-resolver/src/mirror.rs, pnpm/crates/resolving-npm-resolver/src/create_npm_resolution_verifier.rs, pnpm/crates/resolving-resolver-base/src/errors/tests.rs
Rust filtering reuses derived packages by cutoff and trusted-version policy. Package construction paths initialize the memo. Tests cover reuse, policy separation, cutoff precision, and eviction.
Metadata condensation and offline cache reuse
pnpm11/resolving/npm-resolver/src/clearMeta.ts, pnpm11/resolving/npm-resolver/src/pickPackage.ts, pnpm11/resolving/npm-resolver/test/metaCache.test.ts
Condensed fields are copied locally. Offline loads populate ctx.metaCache inside the limiter. Tests verify one mirror read for concurrent picks.
Cached semver selection and packument filtering
pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts, pnpm11/resolving/npm-resolver/test/pickVersionByVersionRange.test.ts, pnpm11/resolving/registry/pkg-metadata-filter/src/index.ts, pnpm11/resolving/registry/pkg-metadata-filter/test/index.ts, .changeset/perf-resolver-caches.md
Parsed semver ranges and versions use capped caches. Publish-date filtering is memoized per packument and policy. Dist-tag comparisons use parsed versions. Tests cover selection, memoization, eviction, and prototype-safe metadata keys. Patch releases are recorded.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • pnpm/pnpm#12458: Both modify disk-loaded metadata promotion into ctx.metaCache.
  • pnpm/pnpm#13133: Both modify condensed metadata and resolver cache behavior.
  • pnpm/pnpm#13512: Both modify resolver caching, metadata filtering, and semver selection paths.

Suggested labels: product: pnpm@11, product: pacquet

Suggested reviewers: zkochan, copilot

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

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

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


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.

@charpeni
charpeni marked this pull request as ready for review July 30, 2026 14:45
@charpeni
charpeni requested a review from zkochan as a code owner July 30, 2026 14:45
Copilot AI review requested due to automatic review settings July 30, 2026 14:45
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (5): Last reviewed commit: "fix(resolver): key the pacquet filter me..." | Re-trigger Greptile

@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 (2)
pnpm11/resolving/npm-resolver/src/clearMeta.ts (1)

72-76: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Keep only the non-obvious invariant in this comment.

“Equivalent to ramda” and the per-call implementation narrative describe removed/internal implementation. Retain the JSON/undefined contract only.

As per coding guidelines, TypeScript comments must not “describe removed implementation history” or “narrate the function body.”

🤖 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/clearMeta.ts` around lines 72 - 76, Update
the comment near the abbreviated version field selection to remove the Ramda
comparison and implementation-performance narrative, retaining only the
invariant that JSON-derived version objects cannot contain undefined, so the !==
undefined presence check is safe.

Source: Coding guidelines

.changeset/perf-resolver-caches.md (1)

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

Describe the observable improvement rather than cache internals.

~13% is benchmark-specific, and the filtering/parsing details are implementation rationale. Use a concise outcome such as “Improve dependency-resolution performance, including when minimumReleaseAge is enabled.”

As per path instructions, changeset descriptions should be concise and accurate, with implementation rationale kept in commit messages. Based on learnings, Changesets should describe user-visible behavior rather than internal resolver mechanics.

🤖 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 @.changeset/perf-resolver-caches.md at line 7, Update the changeset
description to concisely state the observable improvement: dependency-resolution
performance is improved, including when minimumReleaseAge is enabled. Remove the
benchmark-specific percentage and internal filtering, parsing, and caching
implementation details.

Sources: Path instructions, Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pnpm11/resolving/npm-resolver/src/pickPackage.ts`:
- Around line 304-315: Update the limited callback around loadMetaCondensed so
every non-null disk metadata result is immediately promoted via
cacheDiskLoadedMeta before the limiter releases, while preserving the cached
fast path. Add a regression test covering simultaneous offline picks and verify
only one mirror read/parse occurs.

---

Nitpick comments:
In @.changeset/perf-resolver-caches.md:
- Line 7: Update the changeset description to concisely state the observable
improvement: dependency-resolution performance is improved, including when
minimumReleaseAge is enabled. Remove the benchmark-specific percentage and
internal filtering, parsing, and caching implementation details.

In `@pnpm11/resolving/npm-resolver/src/clearMeta.ts`:
- Around line 72-76: Update the comment near the abbreviated version field
selection to remove the Ramda comparison and implementation-performance
narrative, retaining only the invariant that JSON-derived version objects cannot
contain undefined, so the !== undefined presence check is safe.
🪄 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: 3db53056-df46-4502-b9a2-5e75f9b7d965

📥 Commits

Reviewing files that changed from the base of the PR and between 18e5e4c and 2271385.

📒 Files selected for processing (5)
  • .changeset/perf-resolver-caches.md
  • pnpm11/resolving/npm-resolver/src/clearMeta.ts
  • pnpm11/resolving/npm-resolver/src/pickPackage.ts
  • pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts
  • pnpm11/resolving/registry/pkg-metadata-filter/src/index.ts

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.

Pull request overview

Optimizes dependency resolution CPU hotspots by memoizing packument publish-date filtering and reusing parsed semver/range objects during version selection, reducing repeated work across dependency edges and concurrent offline picks.

Changes:

  • Memoizes filterPkgMetadataByPublishDate per packument (WeakMap) keyed by cutoff + trusted versions.
  • Adds capped caches for parsed semver.Range/semver.SemVer and replaces semver.maxSatisfying/minSatisfying with cache-reusing loops.
  • Avoids duplicate offline mirror loads behind the per-package limiter; replaces Ramda pick in clearMeta with a direct field-copy loop.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pnpm11/resolving/registry/pkg-metadata-filter/src/index.ts Adds per-packument memoization for publish-date filtering and reuses parsed semver instances for dist-tag repopulation.
pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts Introduces capped semver/range parse caches and cache-reusing satisfying pickers to reduce repeated parsing.
pnpm11/resolving/npm-resolver/src/pickPackage.ts Re-checks in-memory meta cache inside the limiter to dedupe concurrent offline mirror reads/parses.
pnpm11/resolving/npm-resolver/src/clearMeta.ts Replaces Ramda pick with a tight loop to build abbreviated version objects.
.changeset/perf-resolver-caches.md Adds a changeset documenting the resolver performance improvements.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copilot AI review requested due to automatic review settings July 30, 2026 15:05

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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
pnpm11/resolving/registry/pkg-metadata-filter/test/index.ts (1)

108-141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover trusted-version slotting and verify the exact eviction bound.

This test only varies cutoff dates, so a cache that ignored trustedVersions would still pass. It also creates six unique policies before checking eviction; a five-entry cache would therefore pass too. Add a post-cutoff version, call the function with and without that version in trustedVersions, and assert eviction after the fifth unique policy.

Based on path instructions, REVIEW_GUIDE.md requires regression coverage for correct cache-slotting and bounded eviction.

🤖 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/registry/pkg-metadata-filter/test/index.ts` around lines 108
- 141, Extend the test around filterPkgMetadataByPublishDate to include a
post-cutoff version and invoke it with policies both containing and omitting
that version, asserting distinct cache results for the trustedVersions variants.
Adjust the unique-policy sequence so the eviction assertion occurs after exactly
five distinct policies, then verify the original cutoff result is recomputed
rather than relying on a sixth policy.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pnpm11/resolving/registry/pkg-metadata-filter/test/index.ts`:
- Around line 108-141: Extend the test around filterPkgMetadataByPublishDate to
include a post-cutoff version and invoke it with policies both containing and
omitting that version, asserting distinct cache results for the trustedVersions
variants. Adjust the unique-policy sequence so the eviction assertion occurs
after exactly five distinct policies, then verify the original cutoff result is
recomputed rather than relying on a sixth policy.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4ffd0eea-5873-4c01-8a74-952072f2b6b0

📥 Commits

Reviewing files that changed from the base of the PR and between 2271385 and 6bbffa6.

📒 Files selected for processing (4)
  • pnpm11/resolving/npm-resolver/src/pickPackage.ts
  • pnpm11/resolving/npm-resolver/test/metaCache.test.ts
  • pnpm11/resolving/registry/pkg-metadata-filter/src/index.ts
  • pnpm11/resolving/registry/pkg-metadata-filter/test/index.ts

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

github-actions Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark Results

# Scenario main HEAD
1 Isolated linker: fresh restore, hot cache + hot store 1.184s ± 0.135s 1.455s ± 0.25s
2 Isolated linker: fresh add new dep, hot cache + hot store 2.757s ± 0.354s 2.463s ± 0.084s
3 Isolated linker: fresh install, hot cache + hot store 4.22s ± 0.654s 3.929s ± 0.463s
4 Isolated linker: fresh restore, cold cache + cold store 3.827s ± 0.54s 4.024s ± 0.418s
5 Isolated linker: fresh install, cold cache + cold store 6.858s ± 0.696s 6.516s ± 0.903s
6 Isolated linker: fresh resolve, hot cache, offline 1.882s ± 0.08s 1.611s ± 0.043s
7 GVS linker: fresh restore, hot cache + hot store 0.674s ± 0.06s 0.557s ± 0.026s

Run 30640509226 · 10 runs per scenario · triggered by @zkochan

Copilot AI review requested due to automatic review settings July 31, 2026 14:21
@charpeni
charpeni force-pushed the perf/resolver-avoid-repeated-packument-filtering branch from 6bbffa6 to 8cefbb5 Compare July 31, 2026 14:21

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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

charpeni and others added 3 commits July 31, 2026 16:49
… during version picking

Resolution re-derived the same data once per dependency edge instead of
once per packument:

- filterPkgMetadataByPublishDate ran on every pick (every edge) with
  minimumReleaseAge active — the default since it is 1440 min — parsing
  a Date per version and rebuilding the versions map each time. It is
  now memoized per packument object in a WeakMap, keyed by cutoff and
  trusted versions so one packument served under different policies
  still filters per policy. Sharing the returned object is safe: callers
  already shared the inner version manifests, and the packument objects
  the resolver passes in are themselves cached and treated as read-only.

- pickPackageFromMeta re-parsed version strings and ranges on every
  satisfies/maxSatisfying call. Parsed SemVer and Range instances are
  now cached in capped Maps (cleared at 50k entries so long-lived
  processes cannot grow them without bound), and maxSatisfying/
  minSatisfying are replaced with loops that reuse the caches. The
  dist-tag repopulation loop in the publish-date filter likewise
  compares already-parsed instances instead of calling semver.gt on
  strings.

- Concurrent offline picks of one package all miss the pre-queue
  in-memory cache check, then each re-read and re-parsed the mirror
  behind the per-package limiter (176 of 1311 loads on the benchmark
  fixture were duplicates). The limiter callback now re-checks the
  cache; offline entries are always disk-sourced, so this is equivalent
  to arriving after the first caller cached it.

- clearMeta condensed every version object through ramda's curried
  pick; a direct field loop does the same with no per-field dispatch.
  The presence check via undefined-comparison matches the previous
  behavior because version objects come from JSON, which cannot encode
  undefined.

Resolution of the 1246-package benchmark fixture is 12.5% faster on
top of current main (4.27s -> 3.73s, hyperfine, offline hot cache);
the resulting lockfile is byte-identical. Attribution: filter
memoization -11%, semver caches -4%, the rest ~-1%.
…inside the limiter

Two review hardenings of the resolver perf work:

- filterPkgMetadataByPublishDate's per-packument policy map could grow
  without bound in a long-lived process (store server, daemon): each
  install computes a fresh minimumReleaseAge cutoff while a shared meta
  cache keeps the packument object alive, so every install would add
  and retain one filtered copy. The map is now capped at 4 policies per
  packument, evicting the oldest; a single install uses one cutoff, so
  the cap never evicts within an install.

- The offline mirror-load dedupe promoted the parsed packument into the
  in-memory cache only after `await limit()` returned, which races with
  the next dequeued task's cache check (p-limit starts it as soon as
  the previous callback resolves, possibly before the caller's
  continuation runs). The promotion now happens inside the limited
  callback, before the limiter releases. The new regression test fails
  on the previous code (2 mirror reads for 10 simultaneous picks) and
  passes now (1 read).

Both packages' suites pass (288 + 3); the benchmark fixture still
resolves to a byte-identical lockfile at the same speedup (1.16x vs
main on the offline resolution scenario).
…arden the filtered maps

The publish-date filter runs once per dependency edge in both stacks and
rebuilds the same document each time, so pacquet gets the memoization
the TypeScript resolver got here: the derived packument is cached on the
document it derives from, keyed by cutoff plus trusted versions, and the
memo is capped at four policies so a long-lived host (napi, a daemon)
holding one shared meta cache can't retain a derived copy per install.
Offline resolution of the 1246-package benchmark fixture drops from
167.6ms to 161.9ms (hyperfine, 50 runs, hot cache) with a byte-identical
lockfile; CPU time drops 166.6ms to 152.0ms. The other two wins are
already in pacquet: the range-parse cache with cache-reusing
max/min-satisfying loops, and the post-permit cache re-check that keeps
concurrent offline picks to one mirror read.

The filtered versions and dist-tags maps are now null-prototype in the
TypeScript filter, matching clearMeta: a registry-controlled version key
named `__proto__` was reassigning the map's prototype instead of
becoming an own key, which also let the malicious manifest's fields read
back as versions within date. Registry metadata is attacker-controlled,
so the maps that index it get the same treatment as every other one.

The dist-tag repopulation loop carries its parsed best version instead
of re-reading it from the parse cache behind an unreachable null check.
Copilot AI review requested due to automatic review settings July 31, 2026 15:36
@zkochan
zkochan force-pushed the perf/resolver-avoid-repeated-packument-filtering branch from 8cefbb5 to 0818cb1 Compare July 31, 2026 15:36

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. metaWithoutLatest declared too early 📘 Rule violation ⚙ Maintainability ⭐ New
Description
In pickVersionByVersionRange.test.ts, the function metaWithoutLatest() is declared before any
usage in the file. This violates the requirement to place TypeScript function declarations after
their first usage to keep file flow top-down.
Code

pnpm11/resolving/npm-resolver/test/pickVersionByVersionRange.test.ts[R43-57]

+function metaWithoutLatest (versions: string[]): PackageMeta {
+  const meta: PackageMeta = {
+    name: 'pick-version',
+    'dist-tags': {},
+    versions: {},
+  }
+  for (const version of versions) {
+    meta.versions[version] = {
+      name: 'pick-version',
+      version,
+      dist: { tarball: `https://registry.npmjs.org/pick-version/-/pick-version-${version}.tgz`, shasum: '' },
+    }
+  }
+  return meta
+}
Relevance

●●● Strong

Same ordering rule fix was accepted recently; moving helper below first use is low-risk.

PR-#13133

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713432 requires TypeScript function declarations to appear only after their first
usage in the same file. metaWithoutLatest() is declared at lines 43-57, but its first usage occurs
later at lines 60-61.

Rule 713432: Declare TypeScript functions only after their first usage
pnpm11/resolving/npm-resolver/test/pickVersionByVersionRange.test.ts[43-57]
pnpm11/resolving/npm-resolver/test/pickVersionByVersionRange.test.ts[59-62]

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

## Issue description
`metaWithoutLatest()` is a TypeScript function declaration that appears before its first call site in the same file.

## Issue Context
Compliance requires top-level TypeScript function declarations to be placed after their first usage (function expressions/arrow functions are exempt).

## Fix Focus Areas
- pnpm11/resolving/npm-resolver/test/pickVersionByVersionRange.test.ts[43-69]

## Suggested approach
- Either move the `function metaWithoutLatest(...)` block below its first usage, **or** convert it to a `const metaWithoutLatest = (...) => { ... }` function expression so the rule no longer applies.

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


2. Cutoff key loses precision ✓ Resolved 🐞 Bug ≡ Correctness
Description
In Rust publish-date filtering memoization, the policy key uses cutoff.timestamp_millis(), so
distinct cutoffs within the same millisecond can collide and reuse a derived packument computed for
a different cutoff. Since cutoffs are computed from Utc::now() with sub-millisecond precision and
registry timestamps may include fractional seconds, this can incorrectly include/exclude boundary
versions under minimumReleaseAge.
Code

pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs[R407-412]

+    let mut key = cutoff.timestamp_millis().to_string();
+    for trusted in trusted_versions.unwrap_or_default() {
+        key.push('\0');
+        key.push_str(trusted);
+    }
+    key
Relevance

●●● Strong

Team has accepted prior fixes for timestamp-resolution edge cases; precision-safe policy keys fit
that pattern.

PR-#12981
PR-#13375

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The memoization key truncates cutoff precision to milliseconds, but both the cutoff source and the
timestamp parser preserve sub-millisecond precision, and the filter compares against the
full-precision cutoff; therefore two different cutoffs can map to the same cache entry while
producing different filtering results.

pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs[389-413]
pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs[425-436]
pnpm/crates/cli/src/config_deps.rs[113-124]
pnpm/crates/resolving-resolver-base/src/publish_time.rs[15-18]

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

### Issue description
`filter_pkg_metadata_by_publish_date()` memoizes derived packuments on `Package.derived` using a `policy_key`. The key currently encodes the cutoff as `timestamp_millis()`, but the filter compares publish timestamps against the full-precision `DateTime<Utc>` cutoff. This can cause collisions when two different cutoffs fall in the same millisecond, returning a derived packument filtered using the wrong cutoff.

### Issue Context
- `published_by` is derived from `chrono::Utc::now()` (sub-ms precision).
- Packument timestamps are parsed from RFC3339 and can include fractional seconds.
- Memoization is intended to be safe across installs/policies in long-lived processes.

### Fix Focus Areas
- pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs[403-413]

### Suggested fix
- Change `publish_date_policy_key()` to encode the cutoff at full precision, e.g.:
 - Prefer `cutoff.timestamp_nanos_opt()` (or `cutoff.timestamp()` + `cutoff.timestamp_subsec_nanos()`) rather than `timestamp_millis()`.
 - Keep the trusted-versions portion unchanged.
- Add a targeted unit test that constructs two cutoffs within the same millisecond and a version whose publish timestamp falls between them, and asserts the derived packuments are not shared for those two policies.

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


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Previous review results

Review updated until commit e12b141

Results up to commit 0818cb1 ⚖️ Balanced


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


Remediation recommended
1. Cutoff key loses precision ✓ Resolved 🐞 Bug ≡ Correctness
Description
In Rust publish-date filtering memoization, the policy key uses cutoff.timestamp_millis(), so
distinct cutoffs within the same millisecond can collide and reuse a derived packument computed for
a different cutoff. Since cutoffs are computed from Utc::now() with sub-millisecond precision and
registry timestamps may include fractional seconds, this can incorrectly include/exclude boundary
versions under minimumReleaseAge.
Code

pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs[R407-412]

+    let mut key = cutoff.timestamp_millis().to_string();
+    for trusted in trusted_versions.unwrap_or_default() {
+        key.push('\0');
+        key.push_str(trusted);
+    }
+    key
Relevance

●●● Strong

Team has accepted prior fixes for timestamp-resolution edge cases; precision-safe policy keys fit
that pattern.

PR-#12981
PR-#13375

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The memoization key truncates cutoff precision to milliseconds, but both the cutoff source and the
timestamp parser preserve sub-millisecond precision, and the filter compares against the
full-precision cutoff; therefore two different cutoffs can map to the same cache entry while
producing different filtering results.

pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs[389-413]
pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs[425-436]
pnpm/crates/cli/src/config_deps.rs[113-124]
pnpm/crates/resolving-resolver-base/src/publish_time.rs[15-18]

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

### Issue description
`filter_pkg_metadata_by_publish_date()` memoizes derived packuments on `Package.derived` using a `policy_key`. The key currently encodes the cutoff as `timestamp_millis()`, but the filter compares publish timestamps against the full-precision `DateTime<Utc>` cutoff. This can cause collisions when two different cutoffs fall in the same millisecond, returning a derived packument filtered using the wrong cutoff.

### Issue Context
- `published_by` is derived from `chrono::Utc::now()` (sub-ms precision).
- Packument timestamps are parsed from RFC3339 and can include fractional seconds.
- Memoization is intended to be safe across installs/policies in long-lived processes.

### Fix Focus Areas
- pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs[403-413]

### Suggested fix
- Change `publish_date_policy_key()` to encode the cutoff at full precision, e.g.:
 - Prefer `cutoff.timestamp_nanos_opt()` (or `cutoff.timestamp()` + `cutoff.timestamp_subsec_nanos()`) rather than `timestamp_millis()`.
 - Keep the trusted-versions portion unchanged.
- Add a targeted unit test that constructs two cutoffs within the same millisecond and a version whose publish timestamp falls between them, and asserts the derived packuments are not shared for those two policies.

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

@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)
pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts (1)

290-326: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider a proper LRU cache instead of full-clear-at-cap.

parseRangeLoose and parseSemverLoose clear the entire Map once it reaches SEMVER_CACHE_MAX_SIZE. This causes a cache-thrashing cliff: every frequently used range/version parsed just before the clear is evicted at once, even if used a moment later. lru-cache is already a transitive dependency of semver itself (node-semver's own Range class uses it internally for parse memoization), so it does not add a new dependency to the tree and gives bounded, least-recently-used eviction instead of periodic full resets.

Do you want me to generate a diff that replaces the two Map caches with lru-cache instances?

♻️ Proposed refactor sketch
-const SEMVER_CACHE_MAX_SIZE = 50_000
-const semverRangeCache = new Map<string, semver.Range | null>()
-const semverInstanceCache = new Map<string, semver.SemVer | null>()
+import LRUCache from 'lru-cache'
+
+const SEMVER_CACHE_MAX_SIZE = 50_000
+const semverRangeCache = new LRUCache<string, semver.Range | null>({ max: SEMVER_CACHE_MAX_SIZE })
+const semverInstanceCache = new LRUCache<string, semver.SemVer | null>({ max: SEMVER_CACHE_MAX_SIZE })

LRUCache#set evicts the least-recently-used entry automatically once max is reached, so the explicit if (cache.size >= SEMVER_CACHE_MAX_SIZE) cache.clear() checks in parseRangeLoose/parseSemverLoose can be removed.

As per path instructions, "Before writing non-trivial code, search for existing functionality and reuse or extract shared utilities; prefer established open-source packages over custom implementations."

🤖 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/pickPackageFromMeta.ts` around lines 290 -
326, Replace the Map-based semverRangeCache and semverInstanceCache with
lru-cache instances configured with SEMVER_CACHE_MAX_SIZE as their maximum size.
Update parseRangeLoose and parseSemverLoose to use the LRU caches’ get/set
operations and remove the manual size checks and full clears, while preserving
cached null results and existing parsing behavior.

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.

Inline comments:
In `@pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts`:
- Around line 251-326: Add regression tests covering maxSatisfyingLoose,
minSatisfyingLoose, parseRangeLoose, and parseSemverLoose against semver’s
native results for normal, prerelease, and malformed inputs. Verify repeated
valid and invalid range/version lookups reuse cached values, cache eviction at
SEMVER_CACHE_MAX_SIZE preserves correctness, and cache keys remain
prototype-safe; instrument or spy on parsing as needed to prove malformed inputs
are not reparsed.

---

Nitpick comments:
In `@pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts`:
- Around line 290-326: Replace the Map-based semverRangeCache and
semverInstanceCache with lru-cache instances configured with
SEMVER_CACHE_MAX_SIZE as their maximum size. Update parseRangeLoose and
parseSemverLoose to use the LRU caches’ get/set operations and remove the manual
size checks and full clears, while preserving cached null results and existing
parsing behavior.
🪄 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: 710a597b-79c6-45a3-85ec-c03f8269b60d

📥 Commits

Reviewing files that changed from the base of the PR and between 8cefbb5 and 0818cb1.

📒 Files selected for processing (15)
  • .changeset/perf-resolver-caches.md
  • pnpm/crates/registry/src/lib.rs
  • pnpm/crates/registry/src/package.rs
  • pnpm/crates/registry/src/package/tests.rs
  • pnpm/crates/resolving-npm-resolver/src/create_npm_resolution_verifier.rs
  • pnpm/crates/resolving-npm-resolver/src/mirror.rs
  • pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta.rs
  • pnpm/crates/resolving-npm-resolver/src/pick_package_from_meta/tests.rs
  • pnpm/crates/resolving-resolver-base/src/errors/tests.rs
  • pnpm11/resolving/npm-resolver/src/clearMeta.ts
  • pnpm11/resolving/npm-resolver/src/pickPackage.ts
  • pnpm11/resolving/npm-resolver/src/pickPackageFromMeta.ts
  • pnpm11/resolving/npm-resolver/test/metaCache.test.ts
  • pnpm11/resolving/registry/pkg-metadata-filter/src/index.ts
  • pnpm11/resolving/registry/pkg-metadata-filter/test/index.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • pnpm11/resolving/npm-resolver/test/metaCache.test.ts
  • .changeset/perf-resolver-caches.md
  • pnpm11/resolving/registry/pkg-metadata-filter/test/index.ts
  • pnpm11/resolving/npm-resolver/src/clearMeta.ts
  • pnpm11/resolving/registry/pkg-metadata-filter/src/index.ts
  • pnpm11/resolving/npm-resolver/src/pickPackage.ts

@codecov-commenter

codecov-commenter commented Jul 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.14815% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 87.92%. Comparing base (c2b7cfb) to head (e12b141).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pnpm/crates/registry/src/package.rs 96.42% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13504   +/-   ##
=======================================
  Coverage   87.92%   87.92%           
=======================================
  Files         550      550           
  Lines       96449    96502   +53     
=======================================
+ Hits        84800    84854   +54     
+ Misses      11649    11648    -1     

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

@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: e12b141a20d9

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

The tables below show mean ± σ; Bencher thresholds on the minimum latency, which is far less perturbed by shared-runner contention (noise only adds time).

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.695 ± 0.165 2.459 3.011 1.68 ± 0.18
pacquet@main 2.747 ± 0.213 2.483 3.029 1.71 ± 0.20
pnpr@HEAD 1.636 ± 0.177 1.430 1.897 1.02 ± 0.14
pnpr@main 1.607 ± 0.140 1.433 1.798 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.6945785802200004,
      "stddev": 0.16460470669134028,
      "median": 2.67181152772,
      "user": 2.1785791999999997,
      "system": 1.7113448000000002,
      "min": 2.45874371272,
      "max": 3.01057312872,
      "times": [
        2.61124212672,
        2.45874371272,
        2.8869041447200003,
        2.7003487767200003,
        2.5925638387200003,
        2.7224257037200004,
        2.7785738617200004,
        2.54113622972,
        2.6432742787200003,
        3.01057312872
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.74685105552,
      "stddev": 0.2129755915966358,
      "median": 2.73623349922,
      "user": 2.1421336,
      "system": 1.6392528,
      "min": 2.48275872072,
      "max": 3.02944507072,
      "times": [
        3.00489899972,
        3.02944507072,
        2.95669104672,
        2.84213515372,
        2.58601470472,
        2.5109036967200002,
        2.63033184472,
        2.8566607367200003,
        2.48275872072,
        2.56867058072
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.63639588112,
      "stddev": 0.17686368160836693,
      "median": 1.5941153587199999,
      "user": 1.4539688,
      "system": 1.5188837999999998,
      "min": 1.43022647872,
      "max": 1.89672039872,
      "times": [
        1.44710094972,
        1.43022647872,
        1.86885128372,
        1.6206313347199999,
        1.47298236772,
        1.83170800872,
        1.89672039872,
        1.6867152247200001,
        1.5675993827199999,
        1.5414233817199998
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.60729170232,
      "stddev": 0.13984524104404844,
      "median": 1.59101400522,
      "user": 1.5195151999999998,
      "system": 1.6584701,
      "min": 1.43250906772,
      "max": 1.79847561072,
      "times": [
        1.78499587072,
        1.46635437272,
        1.6150315397200001,
        1.52346990472,
        1.69600219572,
        1.73695491172,
        1.43250906772,
        1.45212707872,
        1.56699647072,
        1.79847561072
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 353.9 ± 35.0 311.6 424.8 1.14 ± 0.13
pacquet@main 365.8 ± 41.3 315.2 433.1 1.18 ± 0.15
pnpr@HEAD 339.9 ± 37.8 299.8 428.4 1.10 ± 0.14
pnpr@main 309.1 ± 19.8 284.4 335.8 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.35394327420000005,
      "stddev": 0.03502982276863085,
      "median": 0.3454405195,
      "user": 0.29276469999999993,
      "system": 0.6921752999999999,
      "min": 0.3116116695,
      "max": 0.4247757305,
      "times": [
        0.35701054050000003,
        0.3561935465,
        0.3428187535,
        0.3116116695,
        0.3392567175,
        0.4032772095,
        0.4247757305,
        0.3215734675,
        0.3480622855,
        0.3348528215
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.36580023500000003,
      "stddev": 0.04134942458886441,
      "median": 0.355680229,
      "user": 0.30666389999999993,
      "system": 0.6873941999999997,
      "min": 0.3152094725,
      "max": 0.4330864495,
      "times": [
        0.3442968975,
        0.41485459950000003,
        0.3345573265,
        0.3711102845,
        0.3531741505,
        0.3208895345,
        0.4330864495,
        0.4126373275,
        0.3581863075,
        0.3152094725
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.3398764996,
      "stddev": 0.03776440822712198,
      "median": 0.32561108149999995,
      "user": 0.285806,
      "system": 0.6309472999999999,
      "min": 0.2998258575,
      "max": 0.4284498695,
      "times": [
        0.3330188785,
        0.3779235425,
        0.4284498695,
        0.3515526695,
        0.3293966965,
        0.3191432425,
        0.3177275675,
        0.3199012055,
        0.3218254665,
        0.2998258575
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.3091419516,
      "stddev": 0.01975317914315074,
      "median": 0.3058112965,
      "user": 0.26351839999999993,
      "system": 0.5716441999999999,
      "min": 0.2843533695,
      "max": 0.3357817395,
      "times": [
        0.3082370245,
        0.3033855685,
        0.2887766015,
        0.2843533695,
        0.3350439465,
        0.3357817395,
        0.3343588995,
        0.2986293125,
        0.3114878245,
        0.2913652295
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.755 ± 0.085 2.607 2.922 1.57 ± 0.11
pacquet@main 2.720 ± 0.041 2.638 2.778 1.55 ± 0.10
pnpr@HEAD 1.763 ± 0.112 1.607 1.964 1.00 ± 0.09
pnpr@main 1.756 ± 0.111 1.586 1.948 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.75515499718,
      "stddev": 0.08452445543880703,
      "median": 2.75779580658,
      "user": 1.97003412,
      "system": 1.5910735399999998,
      "min": 2.6071788490800003,
      "max": 2.92161396008,
      "times": [
        2.92161396008,
        2.80257541908,
        2.6878467660800003,
        2.81389979308,
        2.75151586008,
        2.72194707508,
        2.77810268808,
        2.70279380808,
        2.76407575308,
        2.6071788490800003
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.71975582678,
      "stddev": 0.04146118796104248,
      "median": 2.72117264708,
      "user": 1.9021178199999997,
      "system": 1.52194594,
      "min": 2.63822281108,
      "max": 2.7781691630800003,
      "times": [
        2.7017476850800004,
        2.68048400808,
        2.63822281108,
        2.72483511608,
        2.7385287750800003,
        2.7781691630800003,
        2.76582328208,
        2.70422678808,
        2.71751017808,
        2.7480104610800002
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.7633618925800003,
      "stddev": 0.11241009661602094,
      "median": 1.7470216900800002,
      "user": 1.39068022,
      "system": 1.4782988400000001,
      "min": 1.6070057130800002,
      "max": 1.96385754308,
      "times": [
        1.79433673608,
        1.64488072708,
        1.86655904308,
        1.7383603500800002,
        1.66474075108,
        1.7267532450800003,
        1.8714417870800002,
        1.7556830300800002,
        1.6070057130800002,
        1.96385754308
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.7563306359800002,
      "stddev": 0.11102816734415309,
      "median": 1.76174172508,
      "user": 1.3282276199999998,
      "system": 1.46217014,
      "min": 1.58563945608,
      "max": 1.94828046208,
      "times": [
        1.73935000608,
        1.81527383408,
        1.7275104850800003,
        1.78413344408,
        1.6204849720800003,
        1.58563945608,
        1.8544849110800001,
        1.94828046208,
        1.81894125708,
        1.6692075320800002
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 502.9 ± 16.0 481.9 524.5 1.32 ± 0.12
pacquet@main 529.9 ± 44.7 467.6 583.0 1.39 ± 0.17
pnpr@HEAD 386.9 ± 24.6 358.1 422.6 1.01 ± 0.11
pnpr@main 381.6 ± 32.9 345.9 451.4 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.5029416867600001,
      "stddev": 0.01600407621456474,
      "median": 0.5038657659600001,
      "user": 0.66732288,
      "system": 0.8340651799999999,
      "min": 0.48190998596,
      "max": 0.52448282396,
      "times": [
        0.48190998596,
        0.48441456696,
        0.51960496796,
        0.52448282396,
        0.49711026696000005,
        0.5191408669600001,
        0.49432834496000005,
        0.48633849896000003,
        0.51062126496,
        0.51146527996
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.5298572082599999,
      "stddev": 0.044676199257090946,
      "median": 0.52639634546,
      "user": 0.72262608,
      "system": 0.80127998,
      "min": 0.46755018296000006,
      "max": 0.58304363096,
      "times": [
        0.46755018296000006,
        0.58010501396,
        0.58304363096,
        0.50298692696,
        0.48914055796000006,
        0.5657729139600001,
        0.48629114896000003,
        0.50045615596,
        0.54980576396,
        0.5734197869600001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.38689192126000005,
      "stddev": 0.024604382297360887,
      "median": 0.38990445496000004,
      "user": 0.28896178,
      "system": 0.66440678,
      "min": 0.35807722596,
      "max": 0.42263306496,
      "times": [
        0.41221364896,
        0.39775641196000006,
        0.42263306496,
        0.41093726296000005,
        0.38246486096000004,
        0.35807722596,
        0.35841069196,
        0.39734404896000003,
        0.37020250496,
        0.35887949096000005
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.38158008716,
      "stddev": 0.032878075060492194,
      "median": 0.37753237746,
      "user": 0.27638888,
      "system": 0.64771328,
      "min": 0.34591742296,
      "max": 0.45136929296000006,
      "times": [
        0.34591742296,
        0.35616146096,
        0.36531656396,
        0.34879578496,
        0.37937931896000004,
        0.38250794096,
        0.39063686996,
        0.42003077996000004,
        0.45136929296000006,
        0.37568543596000004
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.896 ± 0.059 1.824 1.982 5.05 ± 0.36
pacquet@main 1.935 ± 0.062 1.868 2.040 5.16 ± 0.37
pnpr@HEAD 0.393 ± 0.058 0.347 0.498 1.05 ± 0.17
pnpr@main 0.375 ± 0.024 0.349 0.427 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.89574939154,
      "stddev": 0.05910200280341122,
      "median": 1.9034686976400002,
      "user": 0.98691032,
      "system": 0.9931594399999998,
      "min": 1.8242686321400001,
      "max": 1.9824034051400001,
      "times": [
        1.98200840414,
        1.84599551214,
        1.9043718331400001,
        1.9025655621400002,
        1.91006213314,
        1.84633703314,
        1.93276493514,
        1.8242686321400001,
        1.8267164651399999,
        1.9824034051400001
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.9354691795400005,
      "stddev": 0.06206823668680429,
      "median": 1.92709216764,
      "user": 1.1148080200000001,
      "system": 0.95576234,
      "min": 1.86845056914,
      "max": 2.04024125414,
      "times": [
        1.91229846114,
        2.04024125414,
        1.86845056914,
        1.9291871701399999,
        1.86901026014,
        1.92499716514,
        1.96147101514,
        2.0363408021400002,
        1.93421686014,
        1.87847823814
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.39343641284,
      "stddev": 0.05787455203492208,
      "median": 0.36665611614000004,
      "user": 0.28125501999999997,
      "system": 0.62712024,
      "min": 0.34699688714000004,
      "max": 0.49829631914000005,
      "times": [
        0.38978464714000005,
        0.36022947314000003,
        0.37308275914000005,
        0.35805801814000005,
        0.35731353014000006,
        0.34839991114,
        0.40512640414000006,
        0.34699688714000004,
        0.49707617914,
        0.49829631914000005
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.37538100454,
      "stddev": 0.02404646708867171,
      "median": 0.36934278864000003,
      "user": 0.27127122,
      "system": 0.63250204,
      "min": 0.34889187314000003,
      "max": 0.42691999914000006,
      "times": [
        0.40236691414000003,
        0.42691999914000006,
        0.38363139814,
        0.36872051014,
        0.35191464714000004,
        0.34889187314000003,
        0.35957524514000005,
        0.36267460414,
        0.37914978714,
        0.36996506714000005
      ]
    }
  ]
}

Scenario: Isolated linker: fresh resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 204.3 ± 18.7 176.4 251.7 2.17 ± 0.23
pacquet@main 222.6 ± 17.5 199.7 250.4 2.37 ± 0.23
pnpr@HEAD 94.0 ± 5.1 87.2 107.1 1.00
pnpr@main 94.8 ± 5.2 86.1 114.7 1.01 ± 0.08
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.20433457157714288,
      "stddev": 0.01870179384321068,
      "median": 0.20130032322000002,
      "user": 0.19966366285714288,
      "system": 0.06964315142857143,
      "min": 0.17641795472,
      "max": 0.25174621272000003,
      "times": [
        0.20254090572,
        0.18766988472,
        0.22639813572,
        0.20250504872,
        0.20175673472,
        0.19290874672,
        0.20084391172000002,
        0.19597780772,
        0.22330901672,
        0.25174621272000003,
        0.19417145772,
        0.19687680472,
        0.20756137972,
        0.17641795472
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.2225670695381818,
      "stddev": 0.017511962063129848,
      "median": 0.21593928372,
      "user": 0.22051865636363635,
      "system": 0.06668930727272727,
      "min": 0.19970488272,
      "max": 0.25042253872000003,
      "times": [
        0.25042253872000003,
        0.21354932872000001,
        0.20129456672,
        0.21065046772,
        0.19970488272,
        0.21093122372,
        0.24098690672,
        0.21593928372,
        0.24368338772,
        0.22995928872000002,
        0.23111588972
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.0939713004296774,
      "stddev": 0.005067148368581111,
      "median": 0.09290855072,
      "user": 0.02505376193548386,
      "system": 0.011115754838709678,
      "min": 0.08717642272,
      "max": 0.10709839472,
      "times": [
        0.08989865172,
        0.09233196872,
        0.09108173272,
        0.09155651372,
        0.09324157572,
        0.10042519972,
        0.10673771772,
        0.09305833172,
        0.09014930272,
        0.09626156472,
        0.09155786672,
        0.09434248372,
        0.10104352972,
        0.09302005972,
        0.09475627972,
        0.08902000272,
        0.09393063972,
        0.08907415471999999,
        0.09158671972,
        0.08717642272,
        0.08740136372,
        0.09238113172,
        0.09290855072,
        0.08970863472,
        0.08842208972,
        0.10709839472,
        0.09264852272,
        0.10093847272,
        0.09894567372,
        0.09627252472,
        0.09613423572
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.09479010932,
      "stddev": 0.005176593275693499,
      "median": 0.09441739772,
      "user": 0.026515619999999993,
      "system": 0.010785293999999999,
      "min": 0.08613606972,
      "max": 0.11465377572,
      "times": [
        0.09441531872,
        0.09748758672,
        0.09441947672,
        0.09826501572,
        0.09546897772,
        0.09781670372,
        0.09454830972,
        0.09196089272,
        0.09397878072,
        0.09547183272,
        0.09881736172,
        0.09906903472,
        0.09634373872,
        0.09452595672,
        0.10014475372,
        0.11465377572,
        0.10072997172,
        0.09373919972,
        0.09455548272,
        0.09024923972,
        0.08994182272,
        0.09357031372,
        0.09013927372,
        0.09274483372,
        0.09301996072,
        0.08936825672,
        0.08613606972,
        0.08775515872,
        0.09201410272,
        0.09235207672
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, cold cache + cold store + cold pnpr

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.636 ± 0.199 4.460 5.119 1.29 ± 0.07
pacquet@main 4.686 ± 0.178 4.509 5.070 1.31 ± 0.07
pnpr@HEAD 3.619 ± 0.152 3.484 3.906 1.01 ± 0.06
pnpr@main 3.586 ± 0.128 3.476 3.909 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.63582340666,
      "stddev": 0.19912046028962468,
      "median": 4.57117091806,
      "user": 2.2292447199999996,
      "system": 1.7445540999999998,
      "min": 4.45970227106,
      "max": 5.11879542806,
      "times": [
        4.57029678306,
        4.57204505306,
        4.65977144106,
        4.57833543106,
        4.51457626706,
        4.48530363406,
        4.45970227106,
        5.11879542806,
        4.83161615806,
        4.56779160006
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.6856101484599995,
      "stddev": 0.17812620828183284,
      "median": 4.665968572560001,
      "user": 2.3301597199999997,
      "system": 1.7483376,
      "min": 4.50860981006,
      "max": 5.06972037506,
      "times": [
        4.50860981006,
        4.51443099506,
        4.67062049206,
        5.06972037506,
        4.86475875406,
        4.78191412706,
        4.66556092206,
        4.52566831606,
        4.66637622306,
        4.58844147006
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.61871703586,
      "stddev": 0.15249046877178069,
      "median": 3.5499310895600003,
      "user": 1.43749852,
      "system": 1.4071308,
      "min": 3.48379134606,
      "max": 3.90592330306,
      "times": [
        3.49174313106,
        3.74612374006,
        3.50243863706,
        3.48379134606,
        3.48943370606,
        3.66333780306,
        3.90592330306,
        3.55328879206,
        3.8045165130600003,
        3.54657338706
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.5864266475599997,
      "stddev": 0.12757010784140285,
      "median": 3.5443010260600003,
      "user": 1.42751662,
      "system": 1.4539544,
      "min": 3.47606597606,
      "max": 3.90885200406,
      "times": [
        3.69164430306,
        3.51901199506,
        3.53747432006,
        3.58402265906,
        3.49626576006,
        3.54945410406,
        3.47606597606,
        3.90885200406,
        3.53914794806,
        3.56232740606
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13504
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
2,607.18 ms
(-3.81%)Baseline: 2,710.46 ms
3,252.55 ms
(80.16%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
1,824.27 ms
(-1.52%)Baseline: 1,852.38 ms
2,222.85 ms
(82.07%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
481.91 ms
(-4.69%)Baseline: 505.64 ms
606.76 ms
(79.42%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
176.42 ms
(-26.93%)Baseline: 241.45 ms
289.74 ms
(60.89%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,458.74 ms
(+0.72%)Baseline: 2,441.14 ms
2,929.36 ms
(83.93%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,459.70 ms
(-1.68%)Baseline: 4,535.80 ms
5,442.96 ms
(81.94%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
311.61 ms
(+7.08%)Baseline: 291.00 ms
349.20 ms
(89.24%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13504
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,607.01 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
347.00 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
358.08 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
87.18 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,430.23 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
3,483.79 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
299.83 ms
🐰 View full continuous benchmarking report in Bencher

…es at

The memo key rounded the cutoff to the millisecond while the filter
compares publish timestamps against the full-precision cutoff, so two
installs whose cutoffs fall in the same millisecond shared one derived
packument even when they keep different versions. Both ends of that
comparison carry sub-millisecond precision: the cutoff comes from
Utc::now() and RFC3339 packument timestamps parse with nanoseconds. The
key now carries seconds plus subsecond nanos. The TypeScript filter is
unaffected: a JS Date is millisecond-resolution on both sides of the
comparison.

Also covers the loose min/max-satisfying pickers with an equivalence
test against semver's own minSatisfying/maxSatisfying across
prereleases, build metadata, unparseable versions and ranges, and the
equal-version tie-break, since they select the version that ends up in
the lockfile.
Copilot AI review requested due to automatic review settings July 31, 2026 21:04

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

Copy link
Copy Markdown
Member

Valid, fixed in e12b141. The key now carries cutoff.timestamp() plus cutoff.timestamp_subsec_nanos(), so it is as precise as the comparison it stands for — Utc::now() and parse_packument_timestamp both keep sub-millisecond precision, so a millisecond-rounded key really could hand one install a packument filtered at a cutoff up to 1ms away.

Added filter_memo_separates_cutoffs_inside_one_millisecond: a version published at .000400Z with cutoffs at .000300Z and .000500Z. It fails on the timestamp_millis() key (the second call gets the first call's derived packument, so the version is missing) and passes now.

The TypeScript side doesn't have this problem: publishedBy.getTime() is milliseconds, but so is every Date it is compared against, so the key is exact there.


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

@qodo-code-review

Copy link
Copy Markdown

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

@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 0b4ebcf into pnpm:main Aug 1, 2026
39 checks passed
@welcome

welcome Bot commented Aug 1, 2026

Copy link
Copy Markdown

Congrats on merging your first pull request! 🎉🎉🎉

zkochan pushed a commit to charpeni/pnpm that referenced this pull request Aug 1, 2026
…lazy version hydration

The metadata mirror stored one JSON document per package, so every
resolution parsed every version manifest of every packument it touched:
178MB of JSON for the 1246-package benchmark fixture, of which ~1% (the
picked versions) was ever read. loadMeta was 23% of resolution CPU after
pnpm#13504.

The Rust CLI already ships an indexed mirror layout (pacquet-meta-v1:
headers record, index record with per-version byte spans, concatenated
raw version fragments) and reads the NDJSON layout as a fallback; until
now the TypeScript CLI treated Rust-written mirrors as cache misses, so
the two stacks thrashed a shared cache. The TypeScript resolver now
reads and writes the same layout.

Loading an indexed mirror parses only the two leading records and
builds versions as enumerable parse-once getters over byte spans. The
getters hydrate through a per-document cache, so a manifest keeps one
identity even when the publish-date filter copies its property
descriptor onto a filtered view (the filter now copies descriptors, not
values, precisely so filtering does not hydrate every in-date version).
When the resolver condenses documents, condensation happens inside the
getter and the document is marked already-condensed, so clearMeta
returns it unchanged instead of materializing every version.

Write policy matches the Rust CLI: indexed everywhere except
filterMetadata documents, which keep NDJSON. Fragments are serialized
per version, which adds write-side CPU on cold installs compared with
mirroring the raw response body; reads won by laziness dominate over
the mirror's lifetime. Truncated or corrupt indexed files, and spans
falling outside the file, read as cache misses. loadMetaHeaders
understands both layouts so conditional requests keep working.

Resolution of the 1246-package fixture is 16% faster on top of
pnpm#13504 (3.82s -> 3.21s, interleaved paired runs, offline warm
mirror); the resulting lockfile is byte-identical in old-format,
new-format, and mixed-format configurations.
zkochan added a commit that referenced this pull request Aug 1, 2026
The peer-heavy scenario asserted that pacquet resolves the fixture at least
10x faster than the TypeScript CLI. That headroom was measured against a base
that still re-filtered the packument and re-parsed semver ranges once per
dependency edge on the offline hot-cache path. #13504 removed that
per-edge work, so the same 401-package DAG now resolves in ~2.9s instead of
~34.4s and the ratio fell to ~1.7x, failing the benchmark on main.

Tie the floor to what the assertion is actually for: a peer-resolution blowup
of the kind #13540 tracked runs slower than the TypeScript CLI (7.0s
versus 2.9s, ~0.4x), so 1.25x clears the run-to-run noise while still catching
it, and no longer breaks whenever the TypeScript resolver gets faster.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
zkochan pushed a commit to charpeni/pnpm that referenced this pull request Aug 16, 2026
…lazy version hydration

The metadata mirror stored one JSON document per package, so every
resolution parsed every version manifest of every packument it touched:
178MB of JSON for the 1246-package benchmark fixture, of which ~1% (the
picked versions) was ever read. loadMeta was 23% of resolution CPU after
pnpm#13504.

The Rust CLI already ships an indexed mirror layout (pacquet-meta-v1:
headers record, index record with per-version byte spans, concatenated
raw version fragments) and reads the NDJSON layout as a fallback; until
now the TypeScript CLI treated Rust-written mirrors as cache misses, so
the two stacks thrashed a shared cache. The TypeScript resolver now
reads and writes the same layout.

Loading an indexed mirror parses only the two leading records and
builds versions as enumerable parse-once getters over byte spans. The
getters hydrate through a per-document cache, so a manifest keeps one
identity even when the publish-date filter copies its property
descriptor onto a filtered view (the filter now copies descriptors, not
values, precisely so filtering does not hydrate every in-date version).
When the resolver condenses documents, condensation happens inside the
getter and the document is marked already-condensed, so clearMeta
returns it unchanged instead of materializing every version.

Write policy matches the Rust CLI: indexed everywhere except
filterMetadata documents, which keep NDJSON. Fragments are serialized
per version, which adds write-side CPU on cold installs compared with
mirroring the raw response body; reads won by laziness dominate over
the mirror's lifetime. Truncated or corrupt indexed files, and spans
falling outside the file, read as cache misses. loadMetaHeaders
understands both layouts so conditional requests keep working.

Resolution of the 1246-package fixture is 16% faster on top of
pnpm#13504 (3.82s -> 3.21s, interleaved paired runs, offline warm
mirror); the resulting lockfile is byte-identical in old-format,
new-format, and mixed-format configurations.
charpeni added a commit to charpeni/pnpm that referenced this pull request Aug 20, 2026
…lazy version hydration

The metadata mirror stored one JSON document per package, so every
resolution parsed every version manifest of every packument it touched:
178MB of JSON for the 1246-package benchmark fixture, of which ~1% (the
picked versions) was ever read. loadMeta was 23% of resolution CPU after
pnpm#13504.

The Rust CLI already ships an indexed mirror layout (pacquet-meta-v1:
headers record, index record with per-version byte spans, concatenated
raw version fragments) and reads the NDJSON layout as a fallback; until
now the TypeScript CLI treated Rust-written mirrors as cache misses, so
the two stacks thrashed a shared cache. The TypeScript resolver now
reads and writes the same layout.

Loading an indexed mirror parses only the two leading records and
builds versions as enumerable parse-once getters over byte spans. The
getters hydrate through a per-document cache, so a manifest keeps one
identity even when the publish-date filter copies its property
descriptor onto a filtered view (the filter now copies descriptors, not
values, precisely so filtering does not hydrate every in-date version).
When the resolver condenses documents, condensation happens inside the
getter and the document is marked already-condensed, so clearMeta
returns it unchanged instead of materializing every version.

Write policy matches the Rust CLI: indexed everywhere except
filterMetadata documents, which keep NDJSON. Fragments are serialized
per version, which adds write-side CPU on cold installs compared with
mirroring the raw response body; reads won by laziness dominate over
the mirror's lifetime. Truncated or corrupt indexed files, and spans
falling outside the file, read as cache misses. loadMetaHeaders
understands both layouts so conditional requests keep working.

Resolution of the 1246-package fixture is 16% faster on top of
pnpm#13504 (3.82s -> 3.21s, interleaved paired runs, offline warm
mirror); the resulting lockfile is byte-identical in old-format,
new-format, and mixed-format configurations.
jdalton pushed a commit to charpeni/pnpm that referenced this pull request Aug 21, 2026
…h lazy version hydration

The metadata mirror stored one JSON document per package, so every
resolution parsed every version manifest of every packument it touched:
178MB of JSON for the 1246-package benchmark fixture, of which ~1% (the
picked versions) was ever read. loadMeta was 23% of resolution CPU after
pnpm#13504.

The Rust CLI already shipped an indexed mirror layout (headers record,
index record with per-version byte spans, concatenated raw version
fragments); the TypeScript CLI treated those mirrors as cache misses,
so the two stacks thrashed a shared cache. Both CLIs now read and write
the same layout under the format id pnpm-meta-v1, and the metadata
cache directories move from v11 to v12 so a pnpm version that predates
the layout never opens the files at all. NDJSON remains the layout for
filterMetadata documents and is still read as a fallback.

Loading an indexed mirror parses only the two leading records and
builds versions as enumerable parse-once getters over byte spans, so a
manifest keeps one identity across filtered views and hook mutations.
Corruption is treated like an unreadable mirror in both stacks: a
fragment that does not parse throws a typed error, offline resolution
fails with NO_OFFLINE_META, the disk fast paths fall through to the
network (only for errors attributable to the disk copy), and a 304 over
a damaged file escalates to a cache-bypassing refetch that rewrites the
mirror — otherwise the intact etag would keep 304-validating a poisoned
file forever. The declared headers length is bounded, the encoded
mirror form is memoized per fetch result so workspace projects sharing
one in-flight fetch do not each serialize a copy, and cache view reads
through the shared loader in both CLIs.

Resolution of the 1246-package fixture is 16% faster on a warm mirror
(3.82s -> 3.21s, interleaved paired runs, offline); the resulting
lockfile is byte-identical across old-format, new-format, and
mixed-format configurations.
zkochan pushed a commit to charpeni/pnpm that referenced this pull request Sep 26, 2026
…azy version hydration

The metadata mirror stored one JSON document per package, so every
resolution parsed every version manifest of every packument it touched:
178MB of JSON for the 1246-package benchmark fixture, of which ~1% (the
picked versions) was ever read. loadMeta was 23% of resolution CPU after
pnpm#13504.

The Rust CLI already shipped an indexed mirror layout (headers record,
index record with per-version byte spans, concatenated raw version
fragments); the TypeScript CLI treated those mirrors as cache misses,
so the two stacks thrashed a shared cache. Both CLIs now read and write
the same layout under the format id pnpm-meta-v1, and the metadata
cache directories move from v11 to v12 so a pnpm version that predates
the layout never opens the files at all. NDJSON remains the layout for
filterMetadata documents and is still read as a fallback.

Loading an indexed mirror parses only the two leading records and
builds versions as enumerable parse-once getters over byte spans, so a
manifest keeps one identity across filtered views and hook mutations.
Corruption is treated like an unreadable mirror in both stacks: a
fragment that does not parse throws a typed error, offline resolution
fails with NO_OFFLINE_META, the disk fast paths fall through to the
network (only for errors attributable to the disk copy), and a 304 over
a damaged file escalates to a cache-bypassing refetch that rewrites the
mirror — otherwise the intact etag would keep 304-validating a poisoned
file forever. The declared headers length is bounded, the encoded
mirror form is memoized per fetch result so workspace projects sharing
one in-flight fetch do not each serialize a copy, and cache view reads
through the shared loader in both CLIs.

Resolution of the 1246-package fixture is 16% faster on a warm mirror
(3.82s -> 3.21s, interleaved paired runs, offline); the resulting
lockfile is byte-identical across old-format, new-format, and
mixed-format configurations.
zkochan pushed a commit to charpeni/pnpm that referenced this pull request Sep 26, 2026
…azy version hydration

The metadata mirror stored one JSON document per package, so every
resolution parsed every version manifest of every packument it touched:
178MB of JSON for the 1246-package benchmark fixture, of which ~1% (the
picked versions) was ever read. loadMeta was 23% of resolution CPU after
pnpm#13504.

The Rust CLI already shipped an indexed mirror layout (headers record,
index record with per-version byte spans, concatenated raw version
fragments); the TypeScript CLI treated those mirrors as cache misses,
so the two stacks thrashed a shared cache. Both CLIs now read and write
the same layout under the format id pnpm-meta-v1, and the metadata
cache directories move from v11 to v12 so a pnpm version that predates
the layout never opens the files at all. NDJSON remains the layout for
filterMetadata documents and is still read as a fallback.

Loading an indexed mirror parses only the two leading records and
builds versions as enumerable parse-once getters over byte spans, so a
manifest keeps one identity across filtered views and hook mutations.
Corruption is treated like an unreadable mirror in both stacks: a
fragment that does not parse throws a typed error, offline resolution
fails with NO_OFFLINE_META, the disk fast paths fall through to the
network (only for errors attributable to the disk copy), and a 304 over
a damaged file escalates to a cache-bypassing refetch that rewrites the
mirror — otherwise the intact etag would keep 304-validating a poisoned
file forever. The declared headers length is bounded, the encoded
mirror form is memoized per fetch result so workspace projects sharing
one in-flight fetch do not each serialize a copy, and cache view reads
through the shared loader in both CLIs.

Resolution of the 1246-package fixture is 16% faster on a warm mirror
(3.82s -> 3.21s, interleaved paired runs, offline); the resulting
lockfile is byte-identical across old-format, new-format, and
mixed-format configurations.
zkochan pushed a commit to charpeni/pnpm that referenced this pull request Oct 5, 2026
…azy version hydration

The metadata mirror stored one JSON document per package, so every
resolution parsed every version manifest of every packument it touched:
178MB of JSON for the 1246-package benchmark fixture, of which ~1% (the
picked versions) was ever read. loadMeta was 23% of resolution CPU after
pnpm#13504.

The Rust CLI already shipped an indexed mirror layout (headers record,
index record with per-version byte spans, concatenated raw version
fragments); the TypeScript CLI treated those mirrors as cache misses,
so the two stacks thrashed a shared cache. Both CLIs now read and write
the same layout under the format id pnpm-meta-v1, and the metadata
cache directories move from v11 to v12 so a pnpm version that predates
the layout never opens the files at all. NDJSON remains the layout for
filterMetadata documents and is still read as a fallback.

Loading an indexed mirror parses only the two leading records and
builds versions as enumerable parse-once getters over byte spans, so a
manifest keeps one identity across filtered views and hook mutations.
Corruption is treated like an unreadable mirror in both stacks: a
fragment that does not parse throws a typed error, offline resolution
fails with NO_OFFLINE_META, the disk fast paths fall through to the
network (only for errors attributable to the disk copy), and a 304 over
a damaged file escalates to a cache-bypassing refetch that rewrites the
mirror — otherwise the intact etag would keep 304-validating a poisoned
file forever. The declared headers length is bounded, the encoded
mirror form is memoized per fetch result so workspace projects sharing
one in-flight fetch do not each serialize a copy, and cache view reads
through the shared loader in both CLIs.

Resolution of the 1246-package fixture is 16% faster on a warm mirror
(3.82s -> 3.21s, interleaved paired runs, offline); the resulting
lockfile is byte-identical across old-format, new-format, and
mixed-format configurations.
zkochan added a commit that referenced this pull request Oct 5, 2026
…azy version hydration (#13512)

The metadata mirror stored one JSON document per package, so every
resolution parsed every version manifest of every packument it touched:
178MB of JSON for the 1246-package benchmark fixture, of which ~1% (the
picked versions) was ever read. loadMeta was 23% of resolution CPU after
#13504.

The Rust CLI already shipped an indexed mirror layout (headers record,
index record with per-version byte spans, concatenated raw version
fragments); the TypeScript CLI treated those mirrors as cache misses,
so the two stacks thrashed a shared cache. Both CLIs now read and write
the same layout under the format id pnpm-meta-v1, and the metadata
cache directories move from v11 to v12 so a pnpm version that predates
the layout never opens the files at all. The offline legacy-mirror hint
now looks under v11, and pnpm cache prune removes the v11 roots. NDJSON
remains the layout for filterMetadata documents and is still read as a
fallback.

Loading an indexed mirror parses only the two leading records and
builds versions as enumerable parse-once getters over byte spans, so a
manifest keeps one identity across filtered views and hook mutations.
Corruption is treated like an unreadable mirror in both stacks: a
fragment that does not parse throws a typed error, offline resolution
fails with NO_OFFLINE_META, the disk fast paths fall through to the
network (only for errors attributable to the disk copy), and a 304 over
a damaged file escalates to a cache-bypassing refetch that rewrites the
mirror — otherwise the intact etag would keep 304-validating a poisoned
file forever. The declared headers length is bounded, the encoded
mirror form is memoized per fetch result so workspace projects sharing
one in-flight fetch do not each serialize a copy, and cache view reads
through the shared loader in both CLIs.

Resolution of the 1246-package fixture is 16% faster on a warm mirror
(3.82s -> 3.21s, interleaved paired runs, offline); the resulting
lockfile is byte-identical across old-format, new-format, and
mixed-format configurations.

---------

Co-authored-by: Zoltan Kochan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants