Repository navigation
perf(npm-resolver): cache disk-loaded metadata in memory on offline resolution - #12760
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughResolvers now track whether cached packuments came from verified registry fetches or disk promotions, reuse unverified entries in memory, and fall back to revalidation when an unverified hit cannot satisfy a spec. Tests cover offline, prefer-offline, and stale-mirror flows, and a changeset records the release. ChangesOffline metadata caching
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested labels: Suggested reviewers: ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
PR Summary by QodoCache disk-loaded packument metadata in memory for offline npm resolution
AI Description
Diagram
High-Level Assessment
Files changed (3)
|
There was a problem hiding this comment.
Pull request overview
Improves offline (--offline) and prefer-offline (--prefer-offline) npm package resolution performance by ensuring packuments loaded from the on-disk metadata mirror are also promoted into the in-memory metaCache, avoiding repeated disk reads and JSON.parse for the same package within a command.
Changes:
- Promote disk-loaded packument metadata into
ctx.metaCacheon theofflinedisk-hit path. - Promote disk-loaded packument metadata into
ctx.metaCacheon thepreferOfflinedisk-hit path (when a package is successfully picked). - Add regression tests proving the second resolution succeeds even after the on-disk mirror is removed (verifying the in-memory cache is used).
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| pnpm11/resolving/npm-resolver/src/pickPackage.ts | Stores disk-loaded metadata in the in-memory cache for offline/prefer-offline flows to prevent repeated disk parsing. |
| pnpm11/resolving/npm-resolver/test/metaCache.test.ts | Adds regression tests covering offline and prefer-offline disk-hit promotion into metaCache. |
| .changeset/offline-metadata-in-memory-cache.md | Adds a patch changeset documenting the offline/prefer-offline performance improvement. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Code Review by Qodo
1. Partial move breaks build
|
|
Code review by qodo was updated up to the latest commit e8ab4e6 |
…esolution When resolving with --offline or --prefer-offline, pickPackage loaded a package's metadata from the on-disk cache mirror but never stored it in the in-memory metaCache. Every later resolution of the same package (once per dependent that references it) therefore re-read and re-parsed the packument from disk. On a large workspace this dominated wall time: a warm-cache `dedupe --offline` issued ~23,700 metadata loads for ~5,100 distinct packages (~4.6x redundancy), re-parsing ~67 GB of JSON. Store the parsed metadata in the in-memory cache after a successful disk load so each package is parsed once per command. maybeUpgradeAbbreviatedMetaForReleaseAge short-circuits when offline and re-runs identically for prefer-offline, so resolution output is unchanged. Cuts the above run from ~140s to ~75s.
e8ab4e6 to
b37f3f7
Compare
|
Code review by qodo was updated up to the latest commit b37f3f7 |
1 similar comment
|
Code review by qodo was updated up to the latest commit b37f3f7 |
…a cannot satisfy the spec Promoting disk-loaded packuments into the in-memory metaCache made the top-of-function cache-hit path terminal for them: when the promoted (possibly stale) packument could not satisfy a later request's range, pickPackage returned a null pick and the caller threw ERR_PNPM_NO_MATCHING_VERSION, where it previously fell through to a conditional registry request and succeeded. Track registry-unverified disk promotions in a WeakSet and let a cache hit on such an entry fall through to the regular network-validating flow when its pick fails and the resolver is not offline. Network-fetched and 304-revalidated packuments are never marked, so their cache hits behave as before. Also skip the redundant second metaCache.set on the prefer-offline path when the abbreviated-meta upgrade branch already cached the registry-validated document.
|
Code review by qodo was updated up to the latest commit 9279c8a |
1 similar comment
|
Code review by qodo was updated up to the latest commit 9279c8a |
…esolution in pacquet Promote packuments loaded from the on-disk mirror during offline and prefer-offline resolution into the install-scoped in-memory cache, so each package's metadata is parsed once per command instead of once per dependent that references it — the pacquet counterpart of the TypeScript-side change in this PR. Disk promotions are stored as registry-unverified via the new PackageMetaCache::set_unverified: the mirror may predate versions the registry has, so a cache hit on such an entry that cannot satisfy the requested spec falls through to the disk + network flow instead of returning a null pick, mirroring the TypeScript-side fall-through fix. This also repairs the pre-existing version-spec and publishedBy-mtime fast paths, whose disk promotions could previously turn a recoverable miss into a hard no-matching-version failure. The verified set() a fetch performs clears the marker, so each package revalidates at most once.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pacquet/crates/resolving-npm-resolver/src/pick_package.rs (1)
646-650: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winMark the publishedBy disk shortcut as unverified too.
This branch also promotes metadata loaded from the on-disk mirror, but
setmarks it registry-verified. A later request for a version absent from that mirror can then fail terminally instead of revalidating. Useset_unverifiedhere like the other disk-promotion paths.As per path instructions, “unverified disk-promotion” must not cause incorrect trust/selection, and pacquet must mirror pnpm resolver semantics.
Proposed fix
if !opts.dry_run { - ctx.meta_cache.set(cache_key.clone(), Arc::clone(meta)); + ctx.meta_cache.set_unverified(cache_key.clone(), Arc::clone(meta)); }🤖 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 `@pacquet/crates/resolving-npm-resolver/src/pick_package.rs` around lines 646 - 650, The publishedBy disk promotion path in pick_package::resolve_package is using meta_cache.set, which incorrectly marks on-disk mirror metadata as registry-verified. Update this branch to use meta_cache.set_unverified, matching the other disk-loaded promotion paths, so cached metadata from the mirror can be revalidated instead of causing terminal failures for missing versions.Source: Path instructions
🧹 Nitpick comments (1)
pacquet/crates/resolving-npm-resolver/src/pick_package/tests.rs (1)
55-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAvoid rustdoc comments for private test explanations.
These are not item contracts and mostly restate the test names/assertions. Prefer no comment, or a short
//only for non-obvious fixture intent.As per path instructions, pacquet’s Rust style says “Use doc comments for item contracts only” and not to duplicate test explanations.
Also applies to: 292-294, 336-339, 385-390
🤖 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 `@pacquet/crates/resolving-npm-resolver/src/pick_package/tests.rs` around lines 55 - 56, The test explanation currently uses rustdoc-style documentation for private test setup, which should be reserved for item contracts only. In the affected tests in pick_package/tests.rs, replace these `///` comments with either no comment or a brief `//` note only where fixture intent is not obvious, keeping the surrounding test names and assertions to explain 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 `@pacquet/crates/resolving-npm-resolver/src/pick_package.rs`:
- Around line 218-220: The set method in Package cache handling is clearing the
unverified marker before the verified metadata is fully stored, which can let
concurrent readers treat stale promoted data as verified. Update set so it
inserts the new Package into inner first, and only then removes the key from
unverified, keeping the cache state consistent for callers of set and the early
cache-check path.
---
Outside diff comments:
In `@pacquet/crates/resolving-npm-resolver/src/pick_package.rs`:
- Around line 646-650: The publishedBy disk promotion path in
pick_package::resolve_package is using meta_cache.set, which incorrectly marks
on-disk mirror metadata as registry-verified. Update this branch to use
meta_cache.set_unverified, matching the other disk-loaded promotion paths, so
cached metadata from the mirror can be revalidated instead of causing terminal
failures for missing versions.
---
Nitpick comments:
In `@pacquet/crates/resolving-npm-resolver/src/pick_package/tests.rs`:
- Around line 55-56: The test explanation currently uses rustdoc-style
documentation for private test setup, which should be reserved for item
contracts only. In the affected tests in pick_package/tests.rs, replace these
`///` comments with either no comment or a brief `//` note only where fixture
intent is not obvious, keeping the surrounding test names and assertions to
explain 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: a0ae24da-1164-4e90-b0f7-f9d4e0457447
📒 Files selected for processing (2)
pacquet/crates/resolving-npm-resolver/src/pick_package.rspacquet/crates/resolving-npm-resolver/src/pick_package/tests.rs
|
Code review by qodo was updated up to the latest commit e30f7cc |
|
Code review by qodo was updated up to the latest commit e30f7cc |
…e entry The registry-unverified marker lived in a DashSet beside the DashMap holding the packument, so the two were updated non-atomically: a concurrent reader could pair a stale disk-promoted packument with the cleared marker of a verified overwrite and treat a recoverable no-match cache hit as terminal. Fold the state into the cache value (CachedPackument) so a reader always observes the packument and its verification state as one unit — the same object-identity semantics the TypeScript side gets from its WeakSet — and drop the separate is_unverified lookup. Addresses the CodeRabbit and Qodo review comments on the marker/value race in InMemoryPackageMetaCache.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #12760 +/- ##
==========================================
- Coverage 85.62% 85.02% -0.60%
==========================================
Files 413 415 +2
Lines 64343 65418 +1075
==========================================
+ Hits 55093 55622 +529
- Misses 9250 9796 +546 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Code review by qodo was updated up to the latest commit 30d02b0 |
|
Code review by qodo was updated up to the latest commit 30d02b0 |
…asure real resolution
The pnpm benchmark pipeline had been silently dead since the
TypeScript CLI moved into pnpm11/: bench.sh resolved REPO_ROOT to
pnpm11/ (where no Cargo.toml exists, so the orchestrator build died
immediately), the orchestrator's pnpm run command probed the pre-move
pnpm/dist bundle path, and continue-on-error on the workflow's run
step swallowed the failure while every downstream step (Bencher
upload, PR comment) reported skipped on a green run. REPO_ROOT now
points at the git root, the bundle probe prefers the pnpm11 layout
with a fallback for revisions that predate the move, and the run step
fails loudly.
The offline fresh-resolve scenario also measured a no-op: node_modules
left behind by the pre-warm pass let both CLIs take the up-to-date
short-circuit ('Already up to date') instead of resolving. The
per-iteration cleanup now wipes node_modules alongside the lockfile,
and the same cleanup runs once before the pre-warm itself — a reused
work-env can carry a lockfile from a previous scenario, which would
turn the priming install into a locked install that fetches tarballs
without populating the metadata mirror.
With both fixed, the scenario shows the offline metadata promotion of
this PR directly: pnpm@HEAD resolves the fixture offline in 2.41s vs
3.17s for pnpm@main (1.31x), with mirror reads dropping from 2625 to
1297.
|
Code review by qodo was updated up to the latest commit 7ef9e7b |
1 similar comment
|
Code review by qodo was updated up to the latest commit 7ef9e7b |
…reads
The verifier's read_shared_meta queried the shared PackageMetaCache
with bare name / name:full keys, but the resolver stores entries under
registry-qualified keys ({registry}\x00{name} plus :full /
:full:filtered suffixes — see metadata_cache_key), so the shared-cache
fast path could never hit and the verifier always re-fetched or
re-read metadata the resolver already held. Build the key with
package_key and try full, filtered full, then abbreviated, mirroring
the TypeScript verifier's readSharedMeta. The trust-check site gains
the :full:filtered fallback too: clear_meta keeps time, per-version
_npmUser, and dist, which is everything fail_if_trust_downgraded
reads.
Found by review on pnpm#12760; the mismatch predates this PR but
sits on the exact reads it touched.
|
Disposition of the latest Qodo findings:
Findings 4–10 in the current numbering are the previously dispositioned items, unchanged. Written by an agent (Claude Code, claude-fable-5). |
|
Code review by qodo was updated up to the latest commit 0fb9bca |
1 similar comment
|
Code review by qodo was updated up to the latest commit 0fb9bca |
Benchmark Results
Run 28709506085 · 10 runs per scenario · triggered by @zkochan |
Summary
When resolving with
--offlineor--prefer-offline,pickPackageloaded a package's metadata from the on-disk cache mirror but never stored it in the in-memorymetaCache, so every subsequent resolution of the same package — once per dependent that references it — re-read and re-parsed the full packument from disk. On a large monorepo at Microsoft this meant 23,746 metadata loads for 5,124 distinct packages (66.8 GB of JSON parsed), andpnpm dedupe --offlinedropped from ~140 s to ~75 s (~1.9×) with a byte-identical lockfile once fixed. The pathological case is high fan-in to shared packages combined with very large packuments (30–42 MB abbreviated documents for internal packages with thousands of versions).This PR stores the parsed metadata in the in-memory cache on the offline and prefer-offline disk-return paths, so each package's metadata is parsed at most once per command. The cache is the existing bounded LRU (max 10,000 entries, 120 s TTL); the online and network paths are untouched.
Review of the change surfaced follow-up work that also landed here:
ERR_PNPM_NO_MATCHING_VERSION. Registry-unverified disk promotions are now tracked in aWeakSet, and a cache hit whose pick fails on such an entry falls through to the regular network-validating flow (unless offline). The pre-existing exact-version fast path had the same latent failure mode and is covered by the same marking. Each package revalidates at most once — a 304-revalidated or network-fetched packument is never marked.pacquet, with the verification state carried inside the cache value (CachedPackument { meta, registry_verified }) so a reader can never pair a packument with the verification state of a concurrent overwrite.PackageMetaCache::set_unverifiedis a required trait method so custom cache implementations can't silently inherit the terminal cache-hit behavior. Pacquet's version-spec and publishedBy-mtime fast paths — which already promoted disk metadata into the memory cache — gain the same recovery.read_shared_metaqueried barename/name:fullkeys while the resolver stores registry-qualified ones, so the verifier's shared-cache fast path could never hit; it now mirrors the TypeScriptreadSharedMeta(:full→:full:filtered→ abbreviated). Pre-existing, found by review of the touched reads.--offline/--prefer-offline. A newisolated-linker.fresh-resolve.hot-cache.offlinescenario measuresinstall --offline --lockfile-onlyagainst a warm mirror (with an untimed online pre-warm pass, since--offlinecan't prime a cold mirror), wired into the shared orchestrator,pnpm11/benchmarks/bench.sh, and the pacquet CI benchmark + Bencher uploads. Getting it to measure real work also revived the pnpm benchmark pipeline, silently dead since thepnpm11/move (REPO_ROOTmis-resolution, pre-move bundle path,continue-on-errormasking), and taught the scenario to wipenode_modulesso the up-to-date short-circuit can't skip the measured resolution. With that in place the scenario shows this PR directly:pnpm@HEAD2.41 s vspnpm@main3.17 s (1.31×), mirror reads 2,625 → 1,297. The pacquet arms tie by design — pacquet's deps-resolver memoizes per wanted dependency, so the redundant-parse amplification never occurs there.Verified end-to-end: byte-identical
pnpm-lock.yamlon the large monorepo, regression tests on both stacks that fail without their fixes, full dependent-package suites green (925 TS tests; 282 resolver + 677 verifier/package-manager Rust tests), and a live-registry benchmark run of the new scenario.Squash Commit Body
Checklist
pacquet/port, or the description notes what still needs porting.pnpm changeset) if this PR changes any publishedpackage. Keep it short and written for pnpm users — it becomes a release note.
Description restructured per the PR template by an agent (Claude Code, claude-fable-5); the Summary incorporates the original author's measurements and analysis.
Summary by CodeRabbit
Performance
--prefer-offlineworkflows in large workspaces by reusing cached package metadata within a single command, reducing repeated parsing.Bug Fixes
--prefer-offlineresolutions now properly promote disk-loaded package metadata into the in-memory cache, keeping it available for subsequent lookups.Tests