Skip to content

fix(package-manager): derive global-virtual-store slots deterministically - #13368

Merged
zkochan merged 4 commits into
mainfrom
fix-13316
Jul 25, 2026
Merged

zkochan merged 4 commits into
mainfrom
fix-13316

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #13316 — pnpm 12 re-imported a varying subset of packages on every repeat frozen install of an unchanged project (reported on mui/material-ui, where eslint, vitest, @vitest/*, @mui/internal-* came back run after run).

Root cause. calc_dep_graph_hash breaks dependency cycles by hashing a node that re-enters through one of its own ancestors with its children truncated, and it memoizes that truncated digest until the outermost visit overwrites it. So the digest a cycle member ends up with depends on which node the walk entered the cycle from. pnpm's TypeScript CLI is deterministic here only because JS objects iterate in insertion order; pacquet drove the same walk from HashMaps — the lockfile's snapshots map and each node's children map — whose iteration order changes on every process. Every install therefore re-derived a different global-virtual-store hash, and thus a different slot path, for whichever packages happened to sit in a cycle. CreateVirtualStore's current-lockfile skip gate then found no directory at the new path, emitted pnpm:_broken_node_modules, and re-imported them.

Only the packages caught in a cycle moved, and which ones moved changed per run — matching the issue's "varying subset" exactly.

Fix. Pin both iteration orders to the ones upstream's objects carry:

  • DepsGraphNode::children becomes an IndexMap, and the single shared builder inserts dependencies before optionalDependencies, each in lockfile key order — upstream's {...dependencies, ...optionalDependencies} spread. virtual_store_layout's private duplicate of that builder is gone.
  • VirtualStoreLayout::new walks snapshots in lockfile key order instead of HashMap order, so the per-install memo is filled from the same entry points upstream uses.
  • BuildModules shares one DepsStateCache across concurrently dispatched chunk members, which has the same entry-point sensitivity, so it now primes that cache in lockfile key order before the chunks run. Otherwise the side-effects-cache key of a builder inside a cycle moved between runs and its build re-ran on every install.

Cross-stack parity. The unit test pins the eight digests of a two-cycle fixture against the values pnpm's own @pnpm/deps.graph-hasher produces for the same graph (obtained by running the compiled TS package). The two CLIs share one global virtual store, so a cyclic package has to land on the same slot whichever of them installed it; the fixture is built so that both a plain alphabetical children merge and an optionalDependencies-first merge produce different digests, and either mistake fails the test.

TypeScript side. No change needed: the TS CLI's iteration orders are already fixed by insertion order. Worth noting as a follow-up (not fixed here, and not a regression): building/after-install computes side-effects-cache keys from a shared depsStateCache inside its concurrent chunk loop, so the key of a cyclic builder there is scheduling-dependent in the same way pacquet's was.

Drive-by. needs_build_marker_triggers_reimport_on_next_install corrupted a slot file with fs::write. When the store and the slot share a filesystem the importer hardlinks, so that rewrote the store's content-addressed file too and no re-import could restore the original bytes — the test failed locally on the very assertion it exists to make (it passes on CI, where the two land on different filesystems). It now unlinks before writing. Kept as its own commit.

Squash Commit Body

A frozen install of an unchanged project re-imported a varying subset of
its packages on every repeat run, instead of reusing the slots the
previous install materialized.

`calc_dep_graph_hash` breaks dependency cycles by hashing a node that
re-enters through one of its own ancestors with its children truncated —
and it memoizes that truncated digest until the outermost visit
overwrites it. The digest a cycle member ends up with therefore depends
on which node the walk entered the cycle from. Upstream is deterministic
because JS objects iterate in insertion order; pacquet drove the same
walk from `HashMap`s, whose iteration order differs per process, so every
install re-derived a different global-virtual-store hash — and a
different slot path — for the packages caught in a cycle. The
current-lockfile skip gate then found no directory at the new path and
re-imported them.

Both iteration orders are now pinned to the ones upstream's objects
carry:

- `DepsGraphNode::children` becomes an `IndexMap`, and the one shared
  builder inserts `dependencies` before `optionalDependencies`, each in
  lockfile key order — upstream's
  `{...dependencies, ...optionalDependencies}` spread.
  `virtual_store_layout`'s private copy of that builder is gone.
- `VirtualStoreLayout::new` walks the snapshots in lockfile key order
  rather than `HashMap` order, so the per-install memo is filled from the
  same entry points upstream uses.

`BuildModules` shares one `DepsStateCache` across concurrently dispatched
chunk members, which has the same entry-point sensitivity, so it primes
that cache in lockfile key order before the chunks run — otherwise the
side-effects-cache key of a cyclic builder moved between runs and the
build re-ran on every install.

The unit test pins the digests against the ones pnpm's own
`@pnpm/deps.graph-hasher` produces for the same graph: the two CLIs share
one global virtual store, so a cyclic package has to land on the same
slot whichever of them installed it.

Closes pnpm/pnpm#13316

Checklist

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

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


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed repeated --frozen-lockfile installs re-importing an inconsistent subset of packages by making global virtual store slot assignment deterministic for dependency cycles.
  • Reliability

    • Improved determinism in dependency graph hashing and virtual store layout generation, ensuring stable results across repeated runs and concurrent installation work.
  • Tests

    • Added and strengthened regression tests to verify consistent frozen-install outcomes for cyclic dependency scenarios and to confirm stability regardless of query/evaluation order.

zkochan added 2 commits July 25, 2026 17:45
`needs_build_marker_triggers_reimport_on_next_install` overwrites a file
in a global-virtual-store slot to prove the retry re-imports pristine
content. When the store and the slot share a filesystem the importer
hardlinks, so writing through the slot's copy rewrote the store's
content-addressed file too — after which no re-import could restore the
original bytes, and the test failed on the very assertion it exists to
make. Unlink the slot's entry first so only the slot's copy is replaced.
…ally

A frozen install of an unchanged project re-imported a varying subset of
its packages on every repeat run (#13316), instead of reusing the
slots the previous install materialized.

`calc_dep_graph_hash` breaks dependency cycles by hashing a node that
re-enters through one of its own ancestors with its children truncated —
and it memoizes that truncated digest until the outermost visit overwrites
it. The digest a cycle member ends up with therefore depends on which node
the walk entered the cycle from. Upstream is deterministic because JS
objects iterate in insertion order; pacquet drove the same walk from
`HashMap`s, whose iteration order differs per process, so every install
re-derived a different global-virtual-store hash — and a different slot
path — for the packages caught in a cycle. The current-lockfile skip gate
then found no directory at the new path and re-imported them.

Both iteration orders are now pinned to the ones upstream's objects carry:

- `DepsGraphNode::children` becomes an `IndexMap`, and the one shared
  builder inserts `dependencies` before `optionalDependencies`, each in
  lockfile key order — upstream's `{...dependencies, ...optionalDependencies}`
  spread. `virtual_store_layout`'s private copy of that builder is gone.
- `VirtualStoreLayout::new` walks the snapshots in lockfile key order
  rather than `HashMap` order, so the per-install memo is filled from the
  same entry points upstream uses.

`BuildModules` shares one `DepsStateCache` across concurrently dispatched
chunk members, which has the same entry-point sensitivity, so it primes
that cache in lockfile key order before the chunks run — otherwise the
side-effects-cache key of a cyclic builder moved between runs and the
build re-ran on every install.

The unit test pins the digests against the ones pnpm's own
`@pnpm/deps.graph-hasher` produces for the same graph: the two CLIs share
one global virtual store, so a cyclic package has to land on the same slot
whichever of them installed it.

Closes #13316
Copilot AI review requested due to automatic review settings July 25, 2026 15:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: c510a663-a859-46d1-8369-3f111cd25425

📥 Commits

Reviewing files that changed from the base of the PR and between 5a1b25b and f78dadc.

📒 Files selected for processing (2)
  • pnpm/crates/graph-hasher/src/dep_state.rs
  • pnpm/crates/graph-hasher/src/dep_state/tests.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm/crates/graph-hasher/src/dep_state.rs
  • pnpm/crates/graph-hasher/src/dep_state/tests.rs

📝 Walkthrough

Walkthrough

The PR makes dependency graph traversal and cache initialization deterministic, updates global virtual store hashing for cyclic dependencies, adds graph and install regression tests, and records a pacquet patch release.

Changes

Deterministic cyclic GVS hashing

Layer / File(s) Summary
Ordered graph hashing
pnpm/crates/graph-hasher/...
DepsGraphNode children use IndexMap, cache warming is publicly exported, and tests cover query-order-sensitive cyclic hashes.
Deterministic layout integration
pnpm/crates/package-manager/src/deps_graph.rs, pnpm/crates/package-manager/src/virtual_store_layout.rs, pnpm/crates/package-manager/src/build_modules.rs, pnpm/crates/package-manager/src/virtual_store_layout/tests.rs
Dependency edges and snapshot traversal follow lockfile order, cache warming occurs before workers run, and cyclic GVS suffixes are checked against expected and repeated results.
Install regression coverage
pnpm/crates/cli/tests/global_virtual_store.rs, .changeset/deterministic-gvs-hashes-for-cycles.md
Repeated frozen-lockfile installs verify stable circular-dependency slots, and a patch changeset documents the behavior.

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

Possibly related PRs

  • pnpm/pnpm#13156: Both changes modify the global virtual store build pipeline and its slot/cache behavior.

Suggested labels: product: pacquet

Suggested reviewers: copilot

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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix deterministic global-virtual-store slot hashing for cyclic dependencies

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Make dependency-graph hashing deterministic for cycles by ordering snapshot and child iteration.
• Align pacquet’s graph hash contract with pnpm’s {...dependencies, ...optionalDependencies}
 semantics.
• Add regression tests ensuring repeat frozen installs reuse existing GVS slots and digests.
Diagram

graph TD
  L["Lockfile snapshots"] --> DG["Deps graph builder"] --> H["Graph hasher"] --> V["VirtualStoreLayout"] --> S[("Global virtual store")]
  DG --> B["BuildModules"] --> H
  V --> I["Installer / importer"] --> S
  subgraph Legend
    direction LR
    _in["Input"] ~~~ _svc(["Module"]) ~~~ _db[("Store")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Sort children keys during hashing (no IndexMap)
  • ➕ Avoids introducing/propagating insertion-ordered maps through the graph model
  • ➕ Keeps graph structure using standard HashMap
  • ➖ Requires allocating/sorting at each node visit; higher CPU overhead
  • ➖ Harder to exactly match pnpm’s insertion semantics when aliases overlap between deps/optionalDeps
2. Canonicalize cyclic SCCs before hashing
  • ➕ Makes cycle handling explicitly order-independent
  • ➕ Potentially more principled for future hash-contract changes
  • ➖ Significantly more complex (SCC detection + canonical traversal)
  • ➖ Higher risk/maintenance; deviates from upstream’s current algorithm
3. Use BTreeMap for children
  • ➕ Deterministic iteration without extra sorting step
  • ➕ Simpler mental model than insertion order
  • ➖ Does not match pnpm’s {...deps, ...optionalDeps} insertion contract when duplicates exist
  • ➖ Would change hashes vs upstream for some graphs

Recommendation: Keep the PR’s approach: it reproduces pnpm’s effective ordering contract (deps then optionalDeps in key order) and addresses both single-thread and concurrent entry-point sensitivity by pre-warming caches. This is the lowest-risk path to cross-CLI parity and stable GVS slot reuse.

Files changed (12) +447 / -80

Enhancement (1) +3 / -1
lib.rsExport cache-warming API from graph-hasher +3/-1

Export cache-warming API from graph-hasher

• Re-exports 'warm_deps_state_cache' to make deterministic cache priming available to other crates.

pnpm/crates/graph-hasher/src/lib.rs

Bug fix (4) +123 / -47
dep_state.rsMake dep-graph hashing order-deterministic and cache-warmable +53/-2

Make dep-graph hashing order-deterministic and cache-warmable

• Switches 'DepsGraphNode::children' to 'IndexMap' and documents why visit order affects hashes in cycles. Adds 'warm_deps_state_cache' to deterministically prime the install-scoped cache to stabilize results across unordered/concurrent entry points.

pnpm/crates/graph-hasher/src/dep_state.rs

build_modules.rsPrime deps-state cache deterministically before parallel build chunks +15/-0

Prime deps-state cache deterministically before parallel build chunks

• Shares a single deps-state cache across concurrently processed build chunks and warms it in lockfile key order to prevent cycle-dependent side-effects-cache keys from fluctuating between runs.

pnpm/crates/package-manager/src/build_modules.rs

deps_graph.rsBuild ordered children maps and provide lockfile-key-ordered snapshot iteration +47/-14

Build ordered children maps and provide lockfile-key-ordered snapshot iteration

• Replaces HashMap-based child-edge building with 'IndexMap' that mimics pnpm’s deps-then-optionalDeps merge in key order (including duplicate alias semantics). Adds 'in_lockfile_order' helper to provide deterministic snapshot iteration order from parsed HashMaps.

pnpm/crates/package-manager/src/deps_graph.rs

virtual_store_layout.rsUse lockfile key order and shared children builder for stable slot suffixes +8/-31

Use lockfile key order and shared children builder for stable slot suffixes

• Iterates snapshots via 'in_lockfile_order' when filling hash caches, avoiding HashMap iteration nondeterminism. Removes a private duplicate of children merging logic in favor of the shared ordered builder.

pnpm/crates/package-manager/src/virtual_store_layout.rs

Tests (4) +314 / -32
global_virtual_store.rsHarden GVS re-import test and add regression for cyclic slot stability +54/-1

Harden GVS re-import test and add regression for cyclic slot stability

• Fixes a test that corrupted a hardlinked store file by unlinking before writing. Adds an e2e-style test asserting repeat '--frozen-lockfile' installs reuse existing slots for circular dependencies across fresh processes.

pnpm/crates/cli/tests/global_virtual_store.rs

tests.rsExpand dep_state tests for cycle order sensitivity and cache warming +87/-20

Expand dep_state tests for cycle order sensitivity and cache warming

• Migrates fixtures to 'IndexMap' and adds tests proving query order affects cyclic hashes without warming, then verifying warming removes that sensitivity.

pnpm/crates/graph-hasher/src/dep_state/tests.rs

tests.rsUpdate GVS path hasher tests for IndexMap children +12/-11

Update GVS path hasher tests for IndexMap children

• Adapts existing global virtual store hashing tests to use insertion-ordered children maps to reflect the updated hashing contract.

pnpm/crates/graph-hasher/src/global_virtual_store_path/tests.rs

tests.rsAdd pnpm-parity fixtures for cyclic slot digests and stability +161/-0

Add pnpm-parity fixtures for cyclic slot digests and stability

• Adds a cycle-heavy fixture with pinned expected digests taken from pnpm’s own hasher, ensuring cross-CLI parity. Adds a stress test asserting repeated runs produce identical slot suffixes despite HashMap nondeterminism.

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

Documentation (1) +5 / -0
deterministic-gvs-hashes-for-cycles.mdAdd changeset documenting deterministic GVS slot hashing fix +5/-0

Add changeset documenting deterministic GVS slot hashing fix

• Introduces a patch changeset for pacquet describing the repeat frozen-install re-import bug and the new deterministic, pnpm-matching slot derivation for cyclic dependencies.

.changeset/deterministic-gvs-hashes-for-cycles.md

Other (2) +2 / -0
Cargo.lockLockfile update for new IndexMap dependency +1/-0

Lockfile update for new IndexMap dependency

• Adds the 'indexmap' crate to the resolved dependency graph (via pacquet-graph-hasher).

Cargo.lock

Cargo.tomlAdd IndexMap dependency to graph-hasher +1/-0

Add IndexMap dependency to graph-hasher

• Declares 'indexmap' as a workspace dependency to support insertion-ordered child maps used by hashing.

pnpm/crates/graph-hasher/Cargo.toml

@greptile-apps

greptile-apps Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (3): Last reviewed commit: "perf(graph-hasher): skip already-memoize..." | Re-trigger Greptile

@github-actions

github-actions Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.06     11.6±0.06ms    32.2 MB/sec    1.00     11.0±0.04ms    34.0 MB/sec
packument/parse                1.00     36.4±0.15µs  1824.6 MB/sec    1.06     38.4±0.06µs  1726.8 MB/sec
tarball/download_dependency    1.00      2.4±0.09ms  1827.3 KB/sec    1.00      2.4±0.08ms  1828.8 KB/sec

`slot_dir` builds its tail from native path components, so the Windows
run of the new parity test compared `@\a\1.0.0\<digest>` against the
`/`-separated form the global-virtual-store path is canonically written
in. Only the separators differed — the digests already matched.
@codecov-commenter

codecov-commenter commented Jul 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.21%. Comparing base (a1e3225) to head (f78dadc).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13368   +/-   ##
=======================================
  Coverage   87.21%   87.21%           
=======================================
  Files         536      536           
  Lines       92034    92049   +15     
=======================================
+ Hits        80269    80283   +14     
- Misses      11765    11766    +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.

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. Warm cache alloc overhead ✓ Resolved 🐞 Bug ➹ Performance
Description
warm_deps_state_cache allocates a fresh HashSet and calls calc_dep_graph_hash for every key even
when that key’s digest is already cached, adding O(|nodes|) avoidable allocations/calls during cache
priming. This is exercised in BuildModules when priming the shared deps_state_cache in lockfile
order before chunks run.
Code

pnpm/crates/graph-hasher/src/dep_state.rs[R159-168]

+pub fn warm_deps_state_cache<'a, Key>(
+    graph: &HashMap<Key, DepsGraphNode<Key>>,
+    cache: &mut DepsStateCache<Key>,
+    keys: impl IntoIterator<Item = &'a Key>,
+) where
+    Key: 'a + Clone + Eq + std::hash::Hash,
+{
+    for key in keys {
+        calc_dep_graph_hash(graph, cache, &mut HashSet::new(), key);
+    }
Relevance

⭐⭐⭐ High

Team often accepts straightforward early-guard/short-circuit changes to cut repeated work in hot
loops.

PR-#13172
PR-#13161

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The warm-up loop always constructs a new HashSet and invokes the hasher per key, while the hasher
itself returns immediately when the key is already in the cache; BuildModules calls warm-up across
all graph keys, so many iterations will become pure overhead after earlier walks populate the cache.

pnpm/crates/graph-hasher/src/dep_state.rs[159-169]
pnpm/crates/graph-hasher/src/dep_state.rs[121-123]
pnpm/crates/package-manager/src/build_modules.rs[685-701]

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

### Issue description
`warm_deps_state_cache()` currently calls `calc_dep_graph_hash()` with `&mut HashSet::new()` for *every* key, even when the hash is already present in `cache`. Since `calc_dep_graph_hash()` immediately returns on a cache hit, most of these calls become “allocate HashSet + call + HashMap lookup”, which is avoidable overhead when warming many keys.

### Issue Context
This warm-up is invoked from `BuildModules` to prime a shared `deps_state_cache` before parallel chunk execution, and it iterates all graph keys in lockfile order.

### Fix Focus Areas
- pnpm/crates/graph-hasher/src/dep_state.rs[159-169]

### Suggested fix
- In `warm_deps_state_cache`, add an early guard:
 - `if cache.contains_key(key) { continue; }`
- Also consider reusing a single `parents: HashSet<String>` across iterations:
 - `let mut parents = HashSet::new();`
 - For each uncached key: `parents.clear(); calc_dep_graph_hash(..., &mut parents, key);`
This preserves behavior while eliminating per-key allocation on cache hits.

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



Informational

2. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset front-matter lists only pacquet and does not declare a bump for pnpm as
required. This can cause the release tooling to miss or misclassify the required pnpm version bump
for this change.
Code

.changeset/deterministic-gvs-hashes-for-cycles.md[R1-3]

+---
+"pacquet": patch
+---
Relevance

⭐ Low

Analogous “add pnpm entry” changeset-compliance suggestions were repeatedly rejected for
pacquet-only changesets.

PR-#13349
PR-#12981
PR-#13329

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each new/modified changeset to explicitly include a pnpm package
entry with an appropriate bump type. The added changeset front-matter only specifies pacquet,
omitting pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/deterministic-gvs-hashes-for-cycles.md[1-3]

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

## Issue description
The changeset front-matter is missing a `pnpm` entry (with a valid bump type), which violates the changeset requirements.

## Issue Context
This PR adds a new changeset file but its front-matter only declares a `pacquet` bump.

## Fix Focus Areas
- .changeset/deterministic-gvs-hashes-for-cycles.md[1-3]

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


3. Ordering sort allocates strings 🐞 Bug ➹ Performance
Description
in_lockfile_order() sorts by materializing key.to_string() for every entry, which adds temporary
allocations proportional to the number/size of snapshot keys. This is now used in
VirtualStoreLayout::new (all snapshots) and for BuildModules cache priming, so very large lockfiles
can see extra time/memory overhead.
Code

pnpm/crates/package-manager/src/deps_graph.rs[R163-169]

+pub(crate) fn in_lockfile_order<Value>(
+    snapshots: &HashMap<PackageKey, Value>,
+) -> Vec<(&PackageKey, &Value)> {
+    let mut entries: Vec<(String, &PackageKey, &Value)> =
+        snapshots.iter().map(|(key, value)| (key.to_string(), key, value)).collect();
+    entries.sort_unstable_by(|(left, ..), (right, ..)| left.cmp(right));
+    entries.into_iter().map(|(_, key, value)| (key, value)).collect()
Relevance

⭐ Low

Repo has rejected similar micro-optimizations focused on avoiding temporary String/Vec allocations
without clear measured impact.

PR-#13191
PR-#13149

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The implementation explicitly builds a temporary Vec containing owned rendered keys for sorting. The
new GVS layout and build-cache priming paths both rely on this function, so the allocation happens
during installs; the lockfile serializer’s lexicographic key ordering shows why ordering by rendered
string is the correct comparator baseline.

pnpm/crates/package-manager/src/deps_graph.rs[163-170]
pnpm/crates/package-manager/src/virtual_store_layout.rs[203-215]
pnpm/crates/package-manager/src/build_modules.rs[687-700]
pnpm/crates/lockfile/src/yaml_emit.rs[86-107]
pnpm/crates/lockfile/src/yaml_emit.rs[123-126]

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

### Issue description
`in_lockfile_order()` allocates a `String` for every `PackageKey` (`key.to_string()`) to sort entries deterministically. This is correct for matching pnpm’s lexicographic lockfile key order, but it can add noticeable temporary allocation overhead on very large lockfiles.

### Issue Context
- `VirtualStoreLayout::new()` uses `in_lockfile_order(snapshots)` when computing GVS suffixes.
- `BuildModules` uses `in_lockfile_order(graph)` to derive the warm-up key order.
- The lockfile emitter sorts map keys lexicographically by their string form, so any optimization must preserve that exact order.

### Fix Focus Areas
- pnpm/crates/package-manager/src/deps_graph.rs[163-170]

### Possible fixes
Pick one that preserves *exact* rendered-key lexicographic ordering:
1) Introduce an allocation-free comparator:
  - Implement `Ord` (or a dedicated `cmp_lockfile_key(&self, &Self)`) for `PkgNameVerPeer`/`PackageKey` that matches the same ordering as `to_string().cmp(...)`.
  - Then sort `Vec<(&PackageKey, &Value)>` with that comparator without allocating rendered strings.
2) Cache rendered keys once at a higher layer:
  - If a caller already has a stable rendered-key representation (e.g., during lockfile parsing/loading), pass that through so sorting doesn’t re-render.

Keep the current implementation if profiling shows negligible impact; this is a micro-optimization opportunity, not a functional bug.

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


Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

Copilot AI review requested due to automatic review settings July 25, 2026 15:58

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
pnpm/crates/cli/tests/global_virtual_store.rs (1)

750-754: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Second corruption step still writes over package_manifest without unlinking first.

corrupt_pristine_file was introduced (and used at line 737) precisely to avoid truncating a hardlinked slot file in place, since that would corrupt the shared content-addressed store copy and make it impossible to recover the pristine bytes. The second corruption at line 753 (fs::write(&package_manifest, "{}")) still does the unguarded in-place write, right after a reimport at line 740 that (under the default hardlink import method) would have re-hardlinked this file to the store. This risks corrupting the store's copy and making the later pristine_manifest comparisons (761-765) unreliable/flaky.

🛠️ Proposed fix
     fs::write(&marker, "").expect("write the second incomplete-build marker");
     fs::remove_file(&postinstall_artifact).expect("remove the rebuilt artifact");
-    fs::write(&package_manifest, "{}").expect("corrupt the pristine file again");
+    corrupt_pristine_file(&package_manifest);
     pacquet(&workspace).with_arg("install").assert().success();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/cli/tests/global_virtual_store.rs` around lines 750 - 754,
Replace the second direct fs::write(&package_manifest, "{}") in the
repeat-install scenario with the existing corrupt_pristine_file helper,
preserving the same corruption behavior while unlinking the hardlinked slot file
before rewriting it. Keep the surrounding marker, artifact removal, install, and
pristine-manifest assertions unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@pnpm/crates/cli/tests/global_virtual_store.rs`:
- Around line 750-754: Replace the second direct fs::write(&package_manifest,
"{}") in the repeat-install scenario with the existing corrupt_pristine_file
helper, preserving the same corruption behavior while unlinking the hardlinked
slot file before rewriting it. Keep the surrounding marker, artifact removal,
install, and pristine-manifest assertions unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a0afb7f8-1438-4feb-b2e6-c967ae7837fc

📥 Commits

Reviewing files that changed from the base of the PR and between d01230b and fbbad30.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (11)
  • .changeset/deterministic-gvs-hashes-for-cycles.md
  • pnpm/crates/cli/tests/global_virtual_store.rs
  • pnpm/crates/graph-hasher/Cargo.toml
  • pnpm/crates/graph-hasher/src/dep_state.rs
  • pnpm/crates/graph-hasher/src/dep_state/tests.rs
  • pnpm/crates/graph-hasher/src/global_virtual_store_path/tests.rs
  • pnpm/crates/graph-hasher/src/lib.rs
  • pnpm/crates/package-manager/src/build_modules.rs
  • pnpm/crates/package-manager/src/deps_graph.rs
  • pnpm/crates/package-manager/src/virtual_store_layout.rs
  • pnpm/crates/package-manager/src/virtual_store_layout/tests.rs

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5a1b25b

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

The warm-up walked every key with a freshly allocated `parents` set, even
though the walker returns immediately once a key is memoized — so priming
a graph whose earlier walks already covered most of it paid an allocation
and a call per node for nothing. Guard on the cache and thread one set
through instead; each walk restores it to empty, which the test now pins
against per-key walks from fresh sets.
Copilot AI review requested due to automatic review settings July 25, 2026 16:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zkochan

zkochan commented Jul 25, 2026

Copy link
Copy Markdown
Member Author

Thanks — went through all three findings.

1. Warm cache alloc overhead — fixed in f78dadc. warm_deps_state_cache now skips keys that are already memoized and threads one parents set through the whole warm-up instead of allocating per key. Each walk restores that set to empty (every insert is paired with a guarded remove), and the test now pins that invariant by comparing the warmed cache against per-key walks that each start from a fresh set — a leak would change the digests and fail there.

2. Changeset missing pnpm entry — not applicable. This is a Rust-only change, and in this repo pnpm in a changeset means the TypeScript CLI package specifically. pnpm/AGENTS.md requires a Rust-only changeset to target pacquet and to omit "pnpm"; adding it would cut a TypeScript release for a change that touches no TypeScript code. (The finding's own relevance note records that the same suggestion was rejected on #13349, #12981 and #13329.)

3. in_lockfile_order allocates a String per key — keeping as is. This is a deliberate decorate-sort: one String per snapshot, allocated once, so the comparisons themselves are plain str compares. The alternative — a comparator that walks PackageKey's fields without allocating — would have to re-derive the exact byte order of its Display impl ({name}@{suffix}, where the suffix itself renders version plus peer context). Getting that subtly wrong wouldn't fail loudly; it would silently move the global-virtual-store hash of cyclic packages away from what pnpm computes, which is precisely the bug this PR fixes. For a 1.3k-snapshot lockfile the transform is ~80 KB of short-lived strings against an install that spends its time on I/O, so the safety is worth more than the allocation. Sorting in place with sort_unstable_by_key would be strictly worse — it re-renders each key on every comparison.


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 f78dadc

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@github-actions

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: f78dadcda6ce

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.571 ± 0.184 2.365 2.794 1.72 ± 0.18
pacquet@main 2.591 ± 0.113 2.367 2.745 1.73 ± 0.15
pnpr@HEAD 1.590 ± 0.135 1.402 1.802 1.06 ± 0.12
pnpr@main 1.497 ± 0.113 1.358 1.654 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.5710746369599997,
      "stddev": 0.1840941601682281,
      "median": 2.54891354206,
      "user": 1.56451922,
      "system": 1.2826190199999998,
      "min": 2.36487973806,
      "max": 2.79409548706,
      "times": [
        2.3906514090599997,
        2.73817264706,
        2.79409548706,
        2.36487973806,
        2.7642516760599998,
        2.39967841006,
        2.38283812206,
        2.60465377306,
        2.49317331106,
        2.77835179606
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.5907083303600005,
      "stddev": 0.1131200706121093,
      "median": 2.61357777006,
      "user": 1.50337682,
      "system": 1.3416448200000002,
      "min": 2.36690659406,
      "max": 2.74506128806,
      "times": [
        2.66090835306,
        2.5652479330599998,
        2.62566313106,
        2.60149240906,
        2.64035238706,
        2.44831474306,
        2.69374918206,
        2.36690659406,
        2.55938728306,
        2.74506128806
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.59025028596,
      "stddev": 0.13470064135678284,
      "median": 1.5468901370600001,
      "user": 1.0789652200000002,
      "system": 1.13037812,
      "min": 1.4022696700600001,
      "max": 1.80208994206,
      "times": [
        1.80208994206,
        1.54928949606,
        1.53731778306,
        1.4022696700600001,
        1.64311125806,
        1.7771964570600003,
        1.5444907780600001,
        1.51510338006,
        1.6921655090600003,
        1.43946858606
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.49672958366,
      "stddev": 0.1131463787275212,
      "median": 1.5080918440600002,
      "user": 1.06336822,
      "system": 1.12465612,
      "min": 1.35759713006,
      "max": 1.6541971510600002,
      "times": [
        1.5836084420600003,
        1.40571329806,
        1.5306058770600002,
        1.3739222960600002,
        1.4855778110600002,
        1.35759713006,
        1.5841778960600001,
        1.3709857170600002,
        1.6541971510600002,
        1.6209102180600001
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 255.6 ± 5.3 246.1 264.1 1.02 ± 0.03
pacquet@main 250.0 ± 6.5 242.2 262.4 1.00
pnpr@HEAD 270.6 ± 8.8 258.0 290.3 1.08 ± 0.05
pnpr@main 275.1 ± 3.7 268.9 282.0 1.10 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.25559146336,
      "stddev": 0.005342097847691387,
      "median": 0.25554190676,
      "user": 0.21341278,
      "system": 0.52485116,
      "min": 0.24608385026000001,
      "max": 0.26411087626,
      "times": [
        0.25884927526,
        0.25370171726,
        0.24608385026000001,
        0.25699039826,
        0.25409341526,
        0.24967298826000003,
        0.26411087626,
        0.26045042326,
        0.25885662826,
        0.25310506126
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.25004286366,
      "stddev": 0.006528431851242669,
      "median": 0.24784394526000003,
      "user": 0.20602218,
      "system": 0.51483016,
      "min": 0.24222602526,
      "max": 0.26238603426,
      "times": [
        0.24888728826,
        0.25278690226,
        0.25689956726,
        0.24222602526,
        0.24358481726000003,
        0.24660265926000002,
        0.24511839926,
        0.25513634126,
        0.26238603426,
        0.24680060226000003
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.27059496466,
      "stddev": 0.008773548120581806,
      "median": 0.26938733175999996,
      "user": 0.20480197999999997,
      "system": 0.5301293599999999,
      "min": 0.25802328726,
      "max": 0.29026062126,
      "times": [
        0.25802328726,
        0.26092453826,
        0.26836727326,
        0.27608048926,
        0.27184974026,
        0.27354927626,
        0.26919415226,
        0.26958051126,
        0.26811975726,
        0.29026062126
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.27509394796,
      "stddev": 0.0037472575770994944,
      "median": 0.27515386726,
      "user": 0.23302757999999996,
      "system": 0.5247284600000001,
      "min": 0.26893411225999997,
      "max": 0.28202676326,
      "times": [
        0.26893411225999997,
        0.27159385726,
        0.28202676326,
        0.27861663226,
        0.27595465126,
        0.27730524825999997,
        0.27412377026,
        0.27503724226,
        0.27527049226,
        0.27207671025999997
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.794 ± 0.027 2.741 2.847 1.80 ± 0.10
pacquet@main 2.791 ± 0.016 2.769 2.811 1.79 ± 0.10
pnpr@HEAD 1.581 ± 0.136 1.434 1.830 1.02 ± 0.11
pnpr@main 1.555 ± 0.089 1.425 1.685 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.7935676746399993,
      "stddev": 0.027407137764178774,
      "median": 2.7965593437400003,
      "user": 1.71762172,
      "system": 1.3253944599999998,
      "min": 2.74104499124,
      "max": 2.84668640924,
      "times": [
        2.80383395724,
        2.77051300224,
        2.74104499124,
        2.84668640924,
        2.79632251724,
        2.79041439924,
        2.79679617024,
        2.81007269824,
        2.80042063224,
        2.77957196924
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.7913133385399993,
      "stddev": 0.015926430584589917,
      "median": 2.79545670374,
      "user": 1.71584652,
      "system": 1.31051046,
      "min": 2.76923507324,
      "max": 2.81120649624,
      "times": [
        2.79981933924,
        2.80754638624,
        2.80346866824,
        2.76923507324,
        2.77834707124,
        2.81120649624,
        2.80338864224,
        2.77017651024,
        2.79109406824,
        2.77885113024
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.58142764074,
      "stddev": 0.1362722292313111,
      "median": 1.54382240774,
      "user": 1.0137647200000002,
      "system": 1.1904341599999997,
      "min": 1.43369076324,
      "max": 1.82980210324,
      "times": [
        1.70024703224,
        1.76342054824,
        1.43369076324,
        1.82980210324,
        1.46964792924,
        1.54872351124,
        1.51830425224,
        1.55852596724,
        1.53892130424,
        1.45299299624
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.55524630974,
      "stddev": 0.08851296943303374,
      "median": 1.55307172674,
      "user": 1.01946652,
      "system": 1.1666681599999997,
      "min": 1.42513346324,
      "max": 1.68544571224,
      "times": [
        1.63321240524,
        1.68544571224,
        1.55792221924,
        1.5106894092399998,
        1.51301001324,
        1.44496507424,
        1.42513346324,
        1.67594134724,
        1.55730725024,
        1.54883620324
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 587.5 ± 7.7 574.5 598.2 1.92 ± 0.04
pacquet@main 587.3 ± 10.4 571.6 605.0 1.92 ± 0.05
pnpr@HEAD 305.5 ± 5.6 298.6 313.9 1.00
pnpr@main 306.5 ± 6.8 296.0 319.5 1.00 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.5874565833600002,
      "stddev": 0.007742150362112578,
      "median": 0.5885067935600001,
      "user": 0.6928834199999999,
      "system": 0.7007068799999999,
      "min": 0.5744941690600001,
      "max": 0.5982339010600001,
      "times": [
        0.5744941690600001,
        0.5824885870600001,
        0.5912930890600001,
        0.59061468106,
        0.5781485970600001,
        0.59631726906,
        0.5839141130600001,
        0.5982339010600001,
        0.5926625210600001,
        0.5863989060600001
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.5872891274600001,
      "stddev": 0.010417519343374005,
      "median": 0.5868297530600001,
      "user": 0.7010605199999999,
      "system": 0.69376488,
      "min": 0.5716013670600001,
      "max": 0.60496749106,
      "times": [
        0.5834330660600001,
        0.5812094550600001,
        0.58785330706,
        0.5754125600600001,
        0.5858061990600001,
        0.6008017200600001,
        0.5882592820600001,
        0.60496749106,
        0.5935468270600001,
        0.5716013670600001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.30545663276,
      "stddev": 0.0055854560915820795,
      "median": 0.30417086856,
      "user": 0.21020832,
      "system": 0.5269856799999999,
      "min": 0.29862142006000003,
      "max": 0.31391339006,
      "times": [
        0.30439988006,
        0.30819344006,
        0.31246323606,
        0.30063912206,
        0.30394185706,
        0.30234980606,
        0.31090879706,
        0.31391339006,
        0.29913537906,
        0.29862142006000003
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.30652028216000005,
      "stddev": 0.006810996027967106,
      "median": 0.30556922856,
      "user": 0.19022441999999998,
      "system": 0.56494848,
      "min": 0.29604045506,
      "max": 0.31948119306,
      "times": [
        0.30246244806,
        0.30919916506,
        0.31290076206,
        0.30022050406,
        0.29604045506,
        0.30304910406,
        0.30411374006,
        0.30702471706,
        0.31948119306,
        0.31071073306
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.918 ± 0.009 1.904 1.936 6.27 ± 0.16
pacquet@main 1.917 ± 0.013 1.899 1.943 6.26 ± 0.16
pnpr@HEAD 0.306 ± 0.008 0.292 0.319 1.00
pnpr@main 0.309 ± 0.007 0.302 0.324 1.01 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.9184411981,
      "stddev": 0.0090007182868924,
      "median": 1.9189533299000001,
      "user": 0.9488908,
      "system": 0.7751988599999999,
      "min": 1.9037261129,
      "max": 1.9357408779,
      "times": [
        1.9250087819000001,
        1.9357408779,
        1.9183212589,
        1.9195854009000002,
        1.9156468789,
        1.9068726319,
        1.9206895159000001,
        1.9037261129,
        1.9225941209000001,
        1.9162264009
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.9167477697,
      "stddev": 0.012614905301016244,
      "median": 1.9141454294,
      "user": 0.9831888000000001,
      "system": 0.7433483599999999,
      "min": 1.8989128229,
      "max": 1.9432834919000002,
      "times": [
        1.9138853689000002,
        1.9432834919000002,
        1.9322172559000002,
        1.9144054899,
        1.9179475448999999,
        1.8989128229,
        1.9054373699,
        1.9135140098999999,
        1.9147700259,
        1.9131043169
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.3060954783,
      "stddev": 0.007736663857170112,
      "median": 0.3056316334,
      "user": 0.18950379999999997,
      "system": 0.55369646,
      "min": 0.2918119309,
      "max": 0.31886914190000004,
      "times": [
        0.31886914190000004,
        0.30884807690000005,
        0.3062625829,
        0.30193574790000005,
        0.3050006839,
        0.31385379890000004,
        0.2918119309,
        0.30086356890000004,
        0.3120921099,
        0.30141714090000005
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.3087175940000001,
      "stddev": 0.007017885808663972,
      "median": 0.30581355740000005,
      "user": 0.19938399999999998,
      "system": 0.5392269599999999,
      "min": 0.3020328319,
      "max": 0.3240758629,
      "times": [
        0.3060217699,
        0.3056053449,
        0.30334045690000006,
        0.30330020990000006,
        0.3037537449,
        0.3240758629,
        0.3020328319,
        0.31518878590000005,
        0.31151417090000005,
        0.31234276190000004
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 364.1 ± 26.0 344.0 418.6 4.22 ± 0.32
pacquet@main 358.4 ± 6.9 351.2 373.7 4.15 ± 0.12
pnpr@HEAD 86.5 ± 2.1 81.5 90.1 1.00 ± 0.03
pnpr@main 86.4 ± 2.0 82.4 90.4 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.36414927818000004,
      "stddev": 0.025977482555368702,
      "median": 0.35377120338,
      "user": 0.35389446,
      "system": 0.058750219999999985,
      "min": 0.34402455038,
      "max": 0.41859955038,
      "times": [
        0.40521024738,
        0.35036756438,
        0.34943571738,
        0.34402455038,
        0.34705870838,
        0.41859955038,
        0.34851226838,
        0.35717484238,
        0.36079237938000003,
        0.36031695338
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.35844965008,
      "stddev": 0.006908845045490837,
      "median": 0.35672921288000004,
      "user": 0.35511016000000006,
      "system": 0.05378172,
      "min": 0.35123956838000003,
      "max": 0.37373756638,
      "times": [
        0.36275523038,
        0.36327464738000004,
        0.35360094638,
        0.35338991938000003,
        0.35449133538,
        0.35123956838000003,
        0.36036534438,
        0.37373756638,
        0.35896709038,
        0.35267485238
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.08648620495575757,
      "stddev": 0.0021272880211936074,
      "median": 0.08678488538,
      "user": 0.020535902424242417,
      "system": 0.008593841818181817,
      "min": 0.08150033638,
      "max": 0.09010467238,
      "times": [
        0.08683170438,
        0.08678159838,
        0.08780028938,
        0.08705138738,
        0.08731109738,
        0.08678488538,
        0.08884672237999999,
        0.08766815938,
        0.08930120838,
        0.08411772938,
        0.08869801138,
        0.08646126638,
        0.08703600838,
        0.09010467238,
        0.08790005638,
        0.08507611638,
        0.08599114838,
        0.08265192738,
        0.08372303438,
        0.08654558438,
        0.08959074438,
        0.08536120238,
        0.08773623938,
        0.08765967338,
        0.08753085238,
        0.08150033638,
        0.08549963438,
        0.08523592638,
        0.08919164238,
        0.08575473538,
        0.08173048938,
        0.08589331638,
        0.08467736338
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.08635507771333334,
      "stddev": 0.0019804464141062942,
      "median": 0.08642989638,
      "user": 0.01921835696969697,
      "system": 0.009721431515151514,
      "min": 0.08240958038,
      "max": 0.09036028338,
      "times": [
        0.08737805238,
        0.08766547638,
        0.08760274738,
        0.08559746938,
        0.08740348138,
        0.08345561138,
        0.08870803038,
        0.08796973838,
        0.08532320138,
        0.09036028338,
        0.08434192238,
        0.08929639838,
        0.08515764038,
        0.08240958038,
        0.08432338738,
        0.08535152438,
        0.08246300038,
        0.08276707438,
        0.08574867238,
        0.08515864138,
        0.08729816238,
        0.08763411638,
        0.08903757138,
        0.08842772238,
        0.08508897038,
        0.08656886838,
        0.08636426338,
        0.08580517938,
        0.08683552138,
        0.08811916938,
        0.08595815838,
        0.08642989638,
        0.08766803138
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.648 ± 0.186 4.441 4.896 1.33 ± 0.06
pacquet@main 4.539 ± 0.091 4.446 4.725 1.29 ± 0.03
pnpr@HEAD 3.522 ± 0.059 3.437 3.634 1.00 ± 0.02
pnpr@main 3.505 ± 0.060 3.439 3.624 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.64753136826,
      "stddev": 0.18592770181400822,
      "median": 4.59481113906,
      "user": 1.7399543199999996,
      "system": 1.37422162,
      "min": 4.44112306956,
      "max": 4.89617243956,
      "times": [
        4.881168983559999,
        4.44112306956,
        4.4467582195599995,
        4.47414289756,
        4.54310032156,
        4.52908736456,
        4.89617243956,
        4.64652195656,
        4.75911751256,
        4.85812091756
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.53870282826,
      "stddev": 0.0914705989132989,
      "median": 4.5125059280599995,
      "user": 1.7211192199999998,
      "system": 1.4087267200000002,
      "min": 4.44626520656,
      "max": 4.72526719356,
      "times": [
        4.72526719356,
        4.482314071559999,
        4.57839561756,
        4.54269778456,
        4.468834762559999,
        4.650887668559999,
        4.46905819356,
        4.47042866456,
        4.44626520656,
        4.55287911956
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.5220704522600004,
      "stddev": 0.0590827880636769,
      "median": 3.50826130156,
      "user": 1.1974666199999997,
      "system": 1.2191200199999996,
      "min": 3.4366467595600003,
      "max": 3.63443288956,
      "times": [
        3.5681019585600002,
        3.51517580456,
        3.45695605656,
        3.5609393815600003,
        3.4366467595600003,
        3.63443288956,
        3.4963855285600003,
        3.49024186356,
        3.50134679856,
        3.56047748156
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.5047916097600003,
      "stddev": 0.05964424839568193,
      "median": 3.4839919320600004,
      "user": 1.1636166199999998,
      "system": 1.2335154200000003,
      "min": 3.43863473556,
      "max": 3.62404798956,
      "times": [
        3.47689962456,
        3.49108423956,
        3.4520899865600003,
        3.43863473556,
        3.46988964856,
        3.52864314456,
        3.62404798956,
        3.4540445115600003,
        3.5542801495600003,
        3.55830206756
      ]
    }
  ]
}

@github-actions

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13368
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,741.04 ms
(+0.19%)Baseline: 2,735.71 ms
3,282.85 ms
(83.50%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
1,903.73 ms
(+0.69%)Baseline: 1,890.64 ms
2,268.76 ms
(83.91%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
574.49 ms
(+0.11%)Baseline: 573.85 ms
688.62 ms
(83.43%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
344.02 ms
(-0.42%)Baseline: 345.49 ms
414.59 ms
(82.98%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,364.88 ms
(+0.08%)Baseline: 2,363.05 ms
2,835.66 ms
(83.40%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,441.12 ms
(+0.25%)Baseline: 4,429.91 ms
5,315.89 ms
(83.54%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
246.08 ms
(-0.26%)Baseline: 246.72 ms
296.07 ms
(83.12%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13368
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,433.69 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
291.81 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
298.62 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
81.50 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,402.27 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
3,436.65 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
258.02 ms
🐰 View full continuous benchmarking report in Bencher

@zkochan
zkochan merged commit 0754566 into main Jul 25, 2026
33 checks passed
@zkochan
zkochan deleted the fix-13316 branch July 25, 2026 16:29
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…ally (pnpm#13368)

A frozen install of an unchanged project re-imported a varying subset of
its packages on every repeat run, instead of reusing the slots the
previous install materialized.

`calc_dep_graph_hash` breaks dependency cycles by hashing a node that
re-enters through one of its own ancestors with its children truncated —
and it memoizes that truncated digest until the outermost visit
overwrites it. The digest a cycle member ends up with therefore depends
on which node the walk entered the cycle from. Upstream is deterministic
because JS objects iterate in insertion order; pacquet drove the same
walk from `HashMap`s, whose iteration order differs per process, so every
install re-derived a different global-virtual-store hash — and a
different slot path — for the packages caught in a cycle. The
current-lockfile skip gate then found no directory at the new path and
re-imported them.

Both iteration orders are now pinned to the ones upstream's objects
carry:

- `DepsGraphNode::children` becomes an `IndexMap`, and the one shared
  builder inserts `dependencies` before `optionalDependencies`, each in
  lockfile key order — upstream's
  `{...dependencies, ...optionalDependencies}` spread.
  `virtual_store_layout`'s private copy of that builder is gone.
- `VirtualStoreLayout::new` walks the snapshots in lockfile key order
  rather than `HashMap` order, so the per-install memo is filled from the
  same entry points upstream uses.

`BuildModules` shares one `DepsStateCache` across concurrently dispatched
chunk members, which has the same entry-point sensitivity, so it primes
that cache in lockfile key order before the chunks run — otherwise the
side-effects-cache key of a cyclic builder moved between runs and the
build re-ran on every install.

The unit test pins the digests against the ones pnpm's own
`@pnpm/deps.graph-hasher` produces for the same graph: the two CLIs share
one global virtual store, so a cyclic package has to land on the same
slot whichever of them installed it.

Closes pnpm#13316
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.

pnpm 12 repeatedly re-imports dependencies on frozen MUI repeat installs

3 participants