Skip to content

perf(resolver): shrink the peer walk's per-occurrence state - #13844

Merged
zkochan merged 3 commits into
mainfrom
fix-13681-resolution-memory
Aug 12, 2026
Merged

zkochan merged 3 commits into
mainfrom
fix-13681-resolution-memory

Conversation

@zkochan

@zkochan zkochan commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Resolving peer dependencies realizes one tree node per distinct root-to-package path. In a workspace whose peer graph is highly cyclic that count is enormous: resolving the bit monorepo's env packages realizes 2,008,313 occurrences to produce a 6,133-node graph. Every byte held per occurrence, and every allocation made per visit, is therefore paid two million times.

This PR attacks the per-occurrence cost. It does not change what the walk resolves.

Changes

1. DependenciesTreeNode carried four wanted-lockfile fields inline. previous_dep_path, locked_peer_context, dependency_names_whose_current_provider_must_win and locked_peer_names are all None on a fresh resolution — which is every node the resolver produces today, as three of them are marked "the resolver does not capture this yet" — yet they cost ~88 bytes on every node. Moving them behind a boxed LockedResolution takes the node from 144 to 64 bytes, and the tree's hash table from 676 MB to 356 MB.

2. TreeChildren::Realized held its children map by value. realize_children therefore cloned the entire BTreeMap, every key String included, on each revisit of an already-realized node, and stored a second copy on the node itself. The map is immutable once built, so it is now shared through an Arc.

3. add_graph_child_or_pending buffered one pending edge per occurrence. A parent reached through many occurrences pushes the identical (parent_dep_path, alias, child_node_id) triple over and over, and replaying a duplicate is a no-op — it resolves the same DepPath and or_inserts the same slot. Dropping exact repeats takes the buffer from 2,224,865 entries to 114,778.

Result

Replaying the same install through @pnpm/napi (5 importers, 3,807 merged packages):

peak RSS
before 3638 / 3698 / 3633 MB
after 3250 / 3229 / 3225 MB

3656 → 3235 MB, -11.5%, n=3 each, non-overlapping ranges, no change in wall time. (Re-measured against main after rebasing; the earlier numbers were against the published 12.0.0-rc.1 and were materially the same.)

Byte attribution over the walker's fields, before → after:

before after
dependencies_tree (2.0M entries) 676 MB 356 MB
pending_peer_edges 224 MB (2,224,865) 7 MB (114,778)

Correctness

cargo test -p pacquet-resolving-deps-resolver: 324 passed. cargo check --workspace --all-targets, cargo clippy --all-targets and cargo fmt are clean.

Five of those tests are new, because none of these savings changes observable resolution — so without them nothing in the suite notices a regression. I checked each one actually fails when its fix is reverted: dropping the dedup guard turns repeated_pending_peer_edges_are_buffered_once into left: 3, right: 1, and inlining a field back onto the node trips the footprint assertion.

  • tree_node_keeps_its_per_occurrence_footprint_small — 56 bytes is the current layout, not a budget with room in it.
  • repeated_pending_peer_edges_are_buffered_once — pins both halves: repeats collapse, but two distinct triples sharing a (parent, alias) slot are both kept, since dropping the second would change which edge patch_pending_peer_edges lands on.
  • pending_peer_edges_replay_after_a_drain — the guard's lifetime is the buffer's.
  • realized_children_are_shared_across_visits — pointer equality, so map reuse is checked rather than assumed.
  • locked_resolution_is_unallocated_until_written — the accessors and their lazy allocation.

The lockfile stays within the engine's existing run-to-run variance. Worth flagging on its own: the engine is not deterministic across runs today. Two stock runs of the identical install differ from each other by 197 diff lines; stock vs. this branch differs by 173 and 88. All pairs churn the same packages (classnames, tippy.js, lodash, postcss), so this branch sits inside the existing envelope rather than adding to it — but the envelope should probably not exist. I can open a separate issue for that.

What this does not fix

The underlying expansion. Instrumenting the walk on this workload:

WALK_STATS full_walks=188707 ended_in_cycle=171508 ended_pure=6806 ended_cacheable=10393
HIT_STATS  find_hit_calls=188862 miss_no_bucket=51803 miss_context_mismatch=136904 hits=155

91% of full walks end in a cycle, and a cycle-resolved walk deliberately caches nothing (#5108 — its truncated subtree makes its peer sets non-authoritative). Only 10,393 walks ever store a PeersCacheItem, so find_hit hits 155 times in 188,862 lookups (0.08%) and nearly every occurrence re-walks its whole subtree.

That is the real driver of the 2M occurrences, and fixing it — caching cycle-resolved verdicts under a key that captures the truncation, so they are reused only where valid — would be worth far more than this PR. I did not attempt it here because getting it wrong produces wrong lockfiles rather than merely slow ones. Happy to take it on with guidance on the intended invariant.

Refs #13681


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

  • Performance

    • Reduced peak memory usage during dependency resolution, especially for large workspaces with deeply nested peer dependencies.
    • Improved sharing and reuse of dependency data to reduce memory duplication.
  • Bug Fixes

    • Prevented duplicate peer-dependency edges from being processed.
    • Improved handling of peer dependencies queued across multiple resolution passes.
    • Improved consistency when revisiting resolved dependency data.
  • Release

    • Included these improvements in a patch release.

Copilot AI lite review requested due to automatic review settings August 12, 2026 01:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Aug 12, 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: 395e824a-9911-4448-9405-46012afa7de8

📥 Commits

Reviewing files that changed from the base of the PR and between 994a009 and 38691ca.

📒 Files selected for processing (1)
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/tests.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/tests.rs

📝 Walkthrough

Walkthrough

The resolver lazily stores lockfile state, shares realized child maps through Arc, and deduplicates pending peer edges. Accessors replace direct locked-state access. Tests cover node size, map reuse, and edge replay.

Changes

Peer resolution memory optimization

Layer / File(s) Summary
Tree state representation
pnpm/crates/resolving-deps-resolver/src/resolved_tree.rs, pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/...
DependenciesTreeNode stores lockfile carry-over fields in optional LockedResolution state. Realized child maps use shared Arc storage. Constructors, workspace recording, and tests use the new representation.
Shared child-map cache flow
pnpm/crates/resolving-deps-resolver/src/resolve_peers/{cache.rs,walker.rs,test_support.rs,tests.rs}
Child realization returns and stores shared maps. Cache hits clone Arc references, and traversal iterates shared maps directly. Tests verify map reuse.
Peer-edge deduplication and accessor integration
pnpm/crates/resolving-deps-resolver/src/resolve_peers/{finalize.rs,walker.rs,tests.rs}, pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs, .changeset/peer-resolution-memory.md
Pending peer edges are deduplicated by parent dependency path, alias, and child node ID. The deduplication state clears after draining. Peer-resolution code uses locked-state accessors, and the changeset records the patch release.

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

Possibly related PRs

  • pnpm/pnpm#13473: Both modify locked peer-context handling in DependenciesTreeNode and peer resolution.
  • pnpm/pnpm#13545: Both modify peer-resolution tree and cache code to share resolver state.
  • pnpm/pnpm#13551: Both modify Walker, child realization, and peer-resolution tree behavior.

Suggested labels: product: pacquet

Suggested reviewers: greptile-apps

✨ 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-13681-resolution-memory

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

perf(resolver): reduce peer-walk memory per occurrence

✨ Enhancement 📝 Documentation 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Move wanted-lockfile carry-over fields behind a boxed LockedResolution to shrink each occurrence
 node.
• Share realized children maps via Arc to avoid cloning BTreeMap on revisits.
• Deduplicate buffered pending peer edges to prevent per-occurrence duplicate work and memory.
Diagram

graph TD
  A["Peer resolver walker"] --> B[("ResolvedTree")]
  B --> C[("DependenciesTreeNode")]
  C --> D[("LockedResolution (boxed)")]
  C --> E[("TreeChildren (Arc map)")]
  A --> F[("Pending peer edges (dedup set)")]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Intern child alias strings / DepPath components
  • ➕ Further reduces per-occurrence allocation and HashSet key sizes
  • ➕ Can improve cache locality in hot paths
  • ➖ Adds global interning lifetime/ownership complexity
  • ➖ Requires careful threading through existing APIs and tests
2. Index-based arena for occurrence nodes (IDs + side tables)
  • ➕ Maximizes memory density; avoids per-node heap allocations entirely
  • ➕ Can make sharing/deduplication more explicit and cheaper
  • ➖ Much larger refactor with higher regression risk
  • ➖ Would likely touch many more call sites and invariants (ordering/determinism)

Recommendation: The PR’s approach is a strong incremental win: it targets the dominant per-occurrence costs without changing resolution semantics. Consider string/DepPath interning only if profiling shows alias/DepPath storage still dominates after these structural reductions; an arena/index-based redesign is likely unjustified unless larger algorithmic changes are planned.

Files changed (11) +127 / -49

Enhancement (1) +19 / -5
finalize.rsDeduplicate buffered pending peer edges and clear dedupe keys on drain +19/-5

Deduplicate buffered pending peer edges and clear dedupe keys on drain

• Adds logic to skip buffering exact duplicate pending peer edges by tracking a 'HashSet<(parent_dep_path, alias, child_node_id)>'. Clears the key set whenever pending edges are drained to maintain correctness across graph mutations.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs

Refactor (6) +98 / -39
walk.rsInitialize realized children with Arc-wrapped map for linked nodes +1/-1

Initialize realized children with Arc-wrapped map for linked nodes

• Updates linked-node initialization to store an 'Arc<BTreeMap<...>>' in 'TreeChildren::Realized', matching the new shared-children representation.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs

workspace_ctx.rsWrite locked peer names via boxed locked state; Arc-wrap realized children +3/-3

Write locked peer names via boxed locked state; Arc-wrap realized children

• Routes 'locked_peer_names' writes through 'DependenciesTreeNode::locked_mut()' so the boxed carry-over is allocated only when needed. Also updates 'ChildrenRecording' to publish realized children as 'Arc<BTreeMap<...>>'.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs

resolve_peers.rsUse accessor for previous_dep_path when building reverse index +1/-1

Use accessor for previous_dep_path when building reverse index

• Switches 'build_node_ids_by_previous_dep_path' to call 'DependenciesTreeNode::previous_dep_path()' after moving lockfile carry-over behind 'LockedResolution'.

pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs

cache.rsShare realized children maps across revisits via Arc +10/-6

Share realized children maps across revisits via Arc

• Changes 'realize_children(_with)' to return 'Arc<BTreeMap<String, NodeId>>' and avoid cloning the realized map on revisits. Updates iteration sites to iterate over the shared map without taking ownership.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/cache.rs

walker.rsAdd pending edge dedupe set and switch to locked-state accessors +12/-7

Add pending edge dedupe set and switch to locked-state accessors

• Introduces 'pending_peer_edge_keys' to prevent buffering duplicate edges and initializes it in 'Walker::new'. Updates fast-cache gating and various code paths to use 'DependenciesTreeNode' accessor methods for locked fields (and a helper for the fast-cache precondition).

pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs

resolved_tree.rsBox rarely-used lockfile carry-over and Arc-share realized children +71/-21

Box rarely-used lockfile carry-over and Arc-share realized children

• Introduces 'LockedResolution' and stores it as 'DependenciesTreeNode.locked: Option<Box<...>>', with accessor methods and 'locked_mut()' to allocate on first write. Changes 'TreeChildren::Realized' to hold 'Arc<BTreeMap<String, NodeId>>' and updates helpers accordingly to avoid per-revisit cloning.

pnpm/crates/resolving-deps-resolver/src/resolved_tree.rs

Tests (3) +5 / -5
tests.rsAdjust workspace snapshot tests for Arc-backed realized children +1/-1

Adjust workspace snapshot tests for Arc-backed realized children

• Updates test fixtures to construct 'TreeChildren::Realized' from an 'Arc' (via '.into()'), aligning with the new shared map type.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs

test_support.rsUpdate peer-resolution test helpers for Arc-backed realized children +1/-1

Update peer-resolution test helpers for Arc-backed realized children

• Adjusts 'tree_node' helper to create 'TreeChildren::Realized(Arc::new(children))' so tests build trees using the new shared children representation.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/test_support.rs

tests.rsUpdate locked-provider preference tests for boxed locked state +3/-3

Update locked-provider preference tests for boxed locked state

• Moves test writes to 'previous_dep_path' and 'locked_peer_context' behind 'DependenciesTreeNode::locked_mut()' to reflect the new 'LockedResolution' layout.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/tests.rs

Documentation (1) +5 / -0
peer-resolution-memory.mdAdd changeset for reduced peer-resolution memory +5/-0

Add changeset for reduced peer-resolution memory

• Introduces a patch-level changeset describing reduced memory usage in peer dependency resolution for highly-cyclic peer graphs.

.changeset/peer-resolution-memory.md

@greptile-apps

greptile-apps Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (4): Last reviewed commit: "test(resolver): assert the pending-edge ..." | Re-trigger Greptile

Comment thread .changeset/peer-resolution-memory.md Resolved
@qodo-code-review

qodo-code-review Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. Key set retains allocation 🐞 Bug ➹ Performance
Description
patch_pending_peer_edges() calls pending_peer_edge_keys.clear(), which drops entries but retains
the hash table allocation; for large graphs this can keep a large bucket array resident after the
pending-edge drain and through the remainder of peer resolution/finalization, reducing the realized
memory savings.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[R223-226]

+        // Cleared with the buffer: a triple pushed after this drain must be
+        // applied again, since the graph it patches has moved on.
+        self.pending_peer_edge_keys.clear();
        for edge in std::mem::take(&mut self.pending_peer_edges) {
Relevance

●●● Strong

Memory/perf-focused PR; team often accepts small allocation-saving tweaks in resolve_peers (e.g.,
finalize.rs).

PR-#13589

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
patch_pending_peer_edges explicitly clears the key set, but only drains the edge vector with
std::mem::take, meaning the vector’s allocation can be released while the key set’s bucket
allocation is retained. In workspace resolution, the drain happens once after walking all importers,
so the retained allocation persists through finalization work.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[222-237]
pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs[381-451]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[64-78]

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

### Issue description
`pending_peer_edge_keys.clear()` does not free the set’s allocated capacity. After the pending-edge buffer is drained, a large `pending_peer_edge_keys` allocation can remain live until the `Walker` is dropped, reducing memory headroom during later phases (final depPath rebuild, final graph rebuild).

### Issue Context
In workspace mode, `walker.patch_pending_peer_edges()` is called once after all importers are walked, so `pending_peer_edge_keys` can grow large and then remain allocated for the rest of the function.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[222-237]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs[381-451]

### Suggested fix
- Replace `self.pending_peer_edge_keys.clear();` with a drop/take that releases capacity, e.g.:
 - `let _ = std::mem::take(&mut self.pending_peer_edge_keys);`
 - or `self.pending_peer_edge_keys = HashSet::default();`
- Keep the semantic intent (“a triple pushed after this drain must be applied again”) by ensuring the set is empty before processing/draining begins.

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


2. Pending-edge data duplicated 🐞 Bug ➹ Performance
Description
Each unique pending edge is stored twice: once as a full owned triple in pending_peer_edge_keys
and again as PendingPeerEdge in pending_peer_edges, duplicating DepPath and alias storage and
adding hashing overhead in the hot enqueue path. This reduces the net memory win of the new dedup
buffer on workloads with many *unique* pending edges (as opposed to mostly duplicates).
Code

pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[R721-724]

+            if self.pending_peer_edge_keys.insert((
+                parent_dep_path.clone(),
+                alias.clone(),
+                node_id.clone(),
Relevance

●● Moderate

Perf concern but needs structural redesign; no close precedent on removing Vec+HashSet duplication
for pending edges.

PR-#13589
PR-#13431

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The walker now holds both a vector of pending edges and a membership set keyed by the same triple,
and add_graph_child_or_pending clones values into the set while also storing the same values in
the pending-edge struct.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[66-78]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[700-731]

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

### Issue description
`Walker` now keeps both `pending_peer_edges: Vec<PendingPeerEdge>` and `pending_peer_edge_keys: HashSet<(DepPath, String, NodeId)>`. For each unique pending edge, the triple is retained in *both* structures, so the dedup guard duplicates payload memory and adds extra hashing/cloning overhead.

### Issue Context
This code runs in the peer-resolution hot path, where large cyclic graphs can enqueue many pending edges. The dedup set is valuable to eliminate repeats, but the current representation pays an extra copy per unique edge.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[72-78]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[700-731]

### Suggested fix directions
- Replace `Vec + HashSet` with a single insertion-ordered set (e.g., `indexmap::IndexSet<PendingPeerEdgeKey>`), so the triple is stored once while preserving deterministic drain order.
- If adding a new structure is undesirable, consider storing a more compact key in the guard (e.g., interned IDs for `DepPath` and alias, or a stable precomputed digest) while keeping the full payload only in the vector; ensure semantics remain “dedup by whole triple” and that the guard is cleared on drain.

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



Informational

3. FxHashSet collision DoS risk 🐞 Bug ⛨ Security
Description
The new pending_peer_edge_keys uses rustc_hash::FxHashSet keyed by (DepPath, String, NodeId)
where DepPath and alias strings come from dependency/lockfile-driven resolution; because FxHash is
deterministic (non-randomized), worst-case crafted inputs can trigger pathological hash collision
behavior and materially increase CPU in the hot pending-edge insertion path.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[R75-77]

+    /// Membership guard for [`Walker::pending_peer_edges`], keeping the
+    /// buffer free of exact duplicates. Cleared whenever the buffer drains.
+    pub(super) pending_peer_edge_keys: HashSet<(DepPath, String, NodeId)>,
Relevance

● Weak

Close precedent: team rejected switching away from FxHash* for HashDoS/attacker-controlled keys in
this resolver.

PR-#13506

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Walker aliases HashSet to rustc_hash::FxHashSet and the new pending_peer_edge_keys field
uses that alias. The set is populated by inserting a tuple containing parent_dep_path and alias
(both derived from resolution inputs) in add_graph_child_or_pending, which runs on the resolver
hot path when building graph children.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[28-35]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[64-78]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[700-732]

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

### Issue description
`pending_peer_edge_keys` is currently a `rustc_hash::FxHashSet` (via the `HashSet` alias), and its keys include attacker-influenced strings (`alias`, `DepPath`). FxHash is not collision-resistant, so the new membership guard introduces a potential algorithmic-complexity DoS surface on a hot path.

### Issue Context
This PR adds `pending_peer_edge_keys` to de-duplicate buffered pending peer edges and inserts into it for every buffered edge.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[72-77]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[716-731]

### Suggested fix
- Keep `FxHashSet` for internal-only sets if desired, but define `pending_peer_edge_keys` specifically as a randomized-hash set (e.g. `std::collections::HashSet<(DepPath, String, NodeId)>`) instead of the `rustc_hash` alias.
- Update `Walker::new` to initialize it with `std::collections::HashSet::new()`.
- Ensure all call sites continue to compile (they should; API is the same).

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


Grey Divider

Context
✅ Compliance rules (platform): 26 rules

Grey Divider

Tip of the day
💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous review results

Review updated until commit 38691ca ⚖️ Balanced

Results up to commit a452962 ⚖️ Balanced


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


Remediation recommended
1. Key set retains allocation 🐞 Bug ➹ Performance
Description
patch_pending_peer_edges() calls pending_peer_edge_keys.clear(), which drops entries but retains
the hash table allocation; for large graphs this can keep a large bucket array resident after the
pending-edge drain and through the remainder of peer resolution/finalization, reducing the realized
memory savings.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[R223-226]

+        // Cleared with the buffer: a triple pushed after this drain must be
+        // applied again, since the graph it patches has moved on.
+        self.pending_peer_edge_keys.clear();
        for edge in std::mem::take(&mut self.pending_peer_edges) {
Relevance

●●● Strong

Memory/perf-focused PR; team often accepts small allocation-saving tweaks in resolve_peers (e.g.,
finalize.rs).

PR-#13589

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
patch_pending_peer_edges explicitly clears the key set, but only drains the edge vector with
std::mem::take, meaning the vector’s allocation can be released while the key set’s bucket
allocation is retained. In workspace resolution, the drain happens once after walking all importers,
so the retained allocation persists through finalization work.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[222-237]
pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs[381-451]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[64-78]

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

### Issue description
`pending_peer_edge_keys.clear()` does not free the set’s allocated capacity. After the pending-edge buffer is drained, a large `pending_peer_edge_keys` allocation can remain live until the `Walker` is dropped, reducing memory headroom during later phases (final depPath rebuild, final graph rebuild).

### Issue Context
In workspace mode, `walker.patch_pending_peer_edges()` is called once after all importers are walked, so `pending_peer_edge_keys` can grow large and then remain allocated for the rest of the function.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[222-237]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs[381-451]

### Suggested fix
- Replace `self.pending_peer_edge_keys.clear();` with a drop/take that releases capacity, e.g.:
 - `let _ = std::mem::take(&mut self.pending_peer_edge_keys);`
 - or `self.pending_peer_edge_keys = HashSet::default();`
- Keep the semantic intent (“a triple pushed after this drain must be applied again”) by ensuring the set is empty before processing/draining begins.

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



Informational
2. FxHashSet collision DoS risk 🐞 Bug ⛨ Security
Description
The new pending_peer_edge_keys uses rustc_hash::FxHashSet keyed by (DepPath, String, NodeId)
where DepPath and alias strings come from dependency/lockfile-driven resolution; because FxHash is
deterministic (non-randomized), worst-case crafted inputs can trigger pathological hash collision
behavior and materially increase CPU in the hot pending-edge insertion path.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[R75-77]

+    /// Membership guard for [`Walker::pending_peer_edges`], keeping the
+    /// buffer free of exact duplicates. Cleared whenever the buffer drains.
+    pub(super) pending_peer_edge_keys: HashSet<(DepPath, String, NodeId)>,
Relevance

● Weak

Close precedent: team rejected switching away from FxHash* for HashDoS/attacker-controlled keys in
this resolver.

PR-#13506

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Walker aliases HashSet to rustc_hash::FxHashSet and the new pending_peer_edge_keys field
uses that alias. The set is populated by inserting a tuple containing parent_dep_path and alias
(both derived from resolution inputs) in add_graph_child_or_pending, which runs on the resolver
hot path when building graph children.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[28-35]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[64-78]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[700-732]

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

### Issue description
`pending_peer_edge_keys` is currently a `rustc_hash::FxHashSet` (via the `HashSet` alias), and its keys include attacker-influenced strings (`alias`, `DepPath`). FxHash is not collision-resistant, so the new membership guard introduces a potential algorithmic-complexity DoS surface on a hot path.

### Issue Context
This PR adds `pending_peer_edge_keys` to de-duplicate buffered pending peer edges and inserts into it for every buffered edge.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[72-77]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[716-731]

### Suggested fix
- Keep `FxHashSet` for internal-only sets if desired, but define `pending_peer_edge_keys` specifically as a randomized-hash set (e.g. `std::collections::HashSet<(DepPath, String, NodeId)>`) instead of the `rustc_hash` alias.
- Update `Walker::new` to initialize it with `std::collections::HashSet::new()`.
- Ensure all call sites continue to compile (they should; API is the same).

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


Results up to commit 994a009 ⚖️ Balanced


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


Remediation recommended
1. Pending-edge data duplicated 🐞 Bug ➹ Performance
Description
Each unique pending edge is stored twice: once as a full owned triple in pending_peer_edge_keys
and again as PendingPeerEdge in pending_peer_edges, duplicating DepPath and alias storage and
adding hashing overhead in the hot enqueue path. This reduces the net memory win of the new dedup
buffer on workloads with many *unique* pending edges (as opposed to mostly duplicates).
Code

pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[R721-724]

+            if self.pending_peer_edge_keys.insert((
+                parent_dep_path.clone(),
+                alias.clone(),
+                node_id.clone(),
Relevance

●● Moderate

Perf concern but needs structural redesign; no close precedent on removing Vec+HashSet duplication
for pending edges.

PR-#13589
PR-#13431

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The walker now holds both a vector of pending edges and a membership set keyed by the same triple,
and add_graph_child_or_pending clones values into the set while also storing the same values in
the pending-edge struct.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[66-78]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[700-731]

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

### Issue description
`Walker` now keeps both `pending_peer_edges: Vec<PendingPeerEdge>` and `pending_peer_edge_keys: HashSet<(DepPath, String, NodeId)>`. For each unique pending edge, the triple is retained in *both* structures, so the dedup guard duplicates payload memory and adds extra hashing/cloning overhead.

### Issue Context
This code runs in the peer-resolution hot path, where large cyclic graphs can enqueue many pending edges. The dedup set is valuable to eliminate repeats, but the current representation pays an extra copy per unique edge.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs[72-78]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs[700-731]

### Suggested fix directions
- Replace `Vec + HashSet` with a single insertion-ordered set (e.g., `indexmap::IndexSet<PendingPeerEdgeKey>`), so the triple is stored once while preserving deterministic drain order.
- If adding a new structure is undesirable, consider storing a more compact key in the guard (e.g., interned IDs for `DepPath` and alias, or a stable precomputed digest) while keeping the full payload only in the vector; ensure semantics remain “dedup by whole triple” and that the guard is cleared on drain.

ⓘ 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: 2

🤖 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 @.changeset/peer-resolution-memory.md:
- Around line 1-2: Update the changeset package key from "pnpm" to "pacquet" so
the Rust resolver change under pnpm/crates targets the required Rust wrapper
release.
- Line 5: Rewrite the changeset entry to describe the user-facing outcome:
reduced peak memory usage during peer dependency resolution. Remove references
to internal occurrence expansion, peer dependency graph cycles, and per-node
state while keeping the note concise.
🪄 Autofix

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: 39e46fdb-ea96-40a2-8691-45d719a6345a

📥 Commits

Reviewing files that changed from the base of the PR and between 676324f and a452962.

📒 Files selected for processing (11)
  • .changeset/peer-resolution-memory.md
  • pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/cache.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/finalize.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/test_support.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/tests.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/walker.rs
  • pnpm/crates/resolving-deps-resolver/src/resolved_tree.rs

Comment thread .changeset/peer-resolution-memory.md Resolved
Comment thread .changeset/peer-resolution-memory.md Resolved
@zkochan

zkochan commented Aug 12, 2026

Copy link
Copy Markdown
Member Author

Filed the lockfile nondeterminism noted in the Correctness section separately as #13846 — four consecutive stock runs of the same install produce four distinct lockfiles, with the resolved package set identical and the churn confined to snapshots: (dependency edges and peer suffixes swapping between entries).

That is what forced the pairwise-distance comparison in this PR instead of a straight lockfile diff.

Resolving peer dependencies realizes one tree node per distinct
root-to-package path. In a workspace whose peer graph is highly cyclic
that count is enormous — resolving the bit monorepo's env packages
realizes 2,008,313 occurrences to produce a 6,133-node graph — so every
byte held per occurrence, and every allocation made per visit, is paid
two million times.

Three changes, none of which alter what the walk resolves:

- `DependenciesTreeNode` kept four wanted-lockfile carry-over fields
  inline. All four are `None` on a fresh resolution, which is every node
  the resolver produces today, yet they cost ~88 bytes on each node.
  Moving them behind a boxed `LockedResolution` takes the node from 144
  to 64 bytes and the tree's table from 676 MB to 356 MB.

- `TreeChildren::Realized` held the children map by value, so
  `realize_children` cloned the whole `BTreeMap` — every key `String`
  included — on each revisit of an already-realized node, and stored a
  second copy on the node. It is immutable once built, so share it
  through an `Arc` instead.

- `add_graph_child_or_pending` buffered a pending edge per occurrence.
  A parent reached through many occurrences pushes the identical
  `(parent_dep_path, alias, child_node_id)` triple repeatedly, and
  replaying a duplicate is a no-op: it resolves the same `DepPath` and
  `or_insert`s the same slot. Dropping repeats takes the buffer from
  2,224,865 entries to 114,778.

Replaying the same install through @pnpm/napi, peak RSS drops from
3670 MB to 3224 MB (-12%, n=3 each, non-overlapping) with no change in
wall time. The resulting lockfile stays within the engine's existing
run-to-run variance: two stock runs differ from each other by 197 diff
lines, while stock and patched differ by 173 and 88, churning the same
packages either way.

This does not address the underlying expansion — 91% of full walks
(171,508 of 188,707) end in a cycle, and cycle-resolved walks are
deliberately never cached (#5108), so the peers cache hits 155 times in
188,862 lookups and nearly every occurrence re-walks its subtree.

Refs #13681
@zkochan
zkochan force-pushed the fix-13681-resolution-memory branch from a452962 to 3623678 Compare August 12, 2026 05:20
Copilot AI review requested due to automatic review settings August 12, 2026 05:20

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 Aug 12, 2026

Copy link
Copy Markdown
Member Author

Rebased onto main (the walk.rs conflict was upstream's refactor around my one-line TreeChildren::Realized change; took main's version and re-applied the Arc wrap) and addressed the review:

Changeset now targets pacquet. Correct catch — pnpm is the TypeScript CLI, and this is Rust-only. Also rewritten in terms of what a user sees rather than internal occurrence/cycle mechanics.

Added regression coverage for the dedup invariant (@greptile-apps' P2), plus four more. None of these three savings changes observable resolution, so nothing in the existing suite notices if they regress — which is exactly why they needed tests rather than a narrative comment. I verified each one fails when its fix is reverted: neutering the guard turns repeated_pending_peer_edges_are_buffered_once into left: 3, right: 1, and inlining a field back onto the node trips the footprint assertion at 56 bytes.

The dedup test pins both halves deliberately, since only one of them is the risky direction: repeats collapse, but two distinct triples sharing a (parent, alias) slot are both kept. Deduping by slot instead of by whole triple would change which edge patch_pending_peer_edges lands on, because it resolves first-resolvable-wins, not first-pushed.

Note the footprint assertion is a new convention here — there are no other size_of assertions in the repo. It is the only thing that actually guards the biggest of the three wins, but happy to drop it if you would rather not have layout pinned in a test.

Re-measured after the rebase, since main picked up 9 commits including the #13574 expansion work: 3656 -> 3235 MB (-11.5%, n=3 each, non-overlapping). Materially unchanged from the pre-rebase numbers.

324 tests pass; clippy --all-targets and fmt clean.

@greptile-apps

greptile-apps Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

The P2 has been addressed thoroughly. All three tests cover the right cases:

  • repeated_pending_peer_edges_are_buffered_once — pins both halves correctly: same triple collapses, but (parent, alias) pairs with different children are each kept. That's exactly the invariant that would break if someone switched from triple-keyed dedup to slot-keyed dedup.
  • pending_peer_edges_replay_after_a_drain — covers the subtler part: that pending_peer_edge_keys resets alongside the buffer so post-drain triples aren't silently suppressed.
  • realized_children_are_shared_across_visits — Arc::ptr_eq is the right check here; pointer equality is exactly what you want to prove, and it's cheaper than any content comparison.

On the footprint assertion — keep it. It's the only thing that actually guards the biggest saving, and the <= bound (rather than ==) gives future code room to add small fields while still catching anyone who inadvertently inlines a String or a Vec back onto the hot path. I'd add a #[cfg(target_pointer_width = "64")] guard around it so it doesn't spuriously fail on 32-bit targets, but otherwise the pattern is sound.

The new changeset is correctly targeting pacquet with a user-facing note. This is in good shape.

greptile-apps[bot]
greptile-apps Bot previously approved these changes Aug 12, 2026
Each of the three savings has an invariant that is easy to undo by
accident, and none of them changes observable resolution, so nothing in
the existing suite notices if they regress.

- `tree_node_keeps_its_per_occurrence_footprint_small` fails the moment
  a field is inlined back onto the node. 56 bytes is the current layout,
  not a budget with room in it.
- `repeated_pending_peer_edges_are_buffered_once` pins both halves of
  the dedup: repeats collapse, but two distinct triples sharing a
  `(parent, alias)` slot are both kept, since dropping the second would
  change which edge `patch_pending_peer_edges` lands on.
- `pending_peer_edges_replay_after_a_drain` pins the guard's lifetime to
  the buffer's.
- `realized_children_are_shared_across_visits` asserts pointer equality,
  so a revisit reusing the map rather than cloning it is checked rather
  than assumed.
- `locked_resolution_is_unallocated_until_written` covers the accessors
  and the lazy allocation behind them.

Also retargets the changeset at `pacquet` — `pnpm` is the TypeScript CLI
— and rewrites it in terms of what a user sees, per review feedback, and
satisfies the repo's dylint config: `LockedResolution`'s derives follow
the configured prefix order, and the multi-line assertions carry the
trailing comma the macro lint requires.
Copilot AI review requested due to automatic review settings August 12, 2026 05:26
@zkochan
zkochan force-pushed the fix-13681-resolution-memory branch from 3623678 to 994a009 Compare August 12, 2026 05:26
@greptile-apps
greptile-apps Bot dismissed their stale review August 12, 2026 05:26

Dismissed because a newer commit was pushed; Greptile will re-review the current head.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

greptile-apps[bot]
greptile-apps Bot previously approved these changes Aug 12, 2026
@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Aug 12, 2026
@github-actions

github-actions Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                                            main                                   pr
-----                                            ----                                   --
lockfile/parse_pnpm_lock                         1.14     13.8±1.16ms    27.2 MB/sec    1.00     12.1±0.27ms    31.0 MB/sec
packument/parse                                  1.14     45.7±6.23µs  1453.0 MB/sec    1.00     40.1±2.37µs  1652.7 MB/sec
tarball/download_dependency                      1.00      2.6±0.19ms  1643.4 KB/sec    1.03      2.7±0.44ms  1591.8 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.17   231.0±28.80ms 69.3 KElem/sec    1.00    197.8±3.64ms 80.9 KElem/sec
workspace_resolution/hoist_heavy                 1.05    271.8±5.68ms        ? ?/sec    1.00    258.6±2.66ms        ? ?/sec

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 994a009

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

@codecov-commenter

codecov-commenter commented Aug 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.30508% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 88.24%. Comparing base (cdc14c6) to head (38691ca).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...esolving-deps-resolver/src/resolve_peers/walker.rs 88.88% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13844   +/-   ##
=======================================
  Coverage   88.23%   88.24%           
=======================================
  Files         627      627           
  Lines      103279   103300   +21     
=======================================
+ Hits        91126    91153   +27     
+ Misses      12153    12147    -6     

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

…tches

The buffer-length assertions pinned an internal detail, not the thing
that matters: whether collapsing repeats can change the graph. They also
could not tell the two dedup strategies apart, because when both
candidate children resolve, first-wins holds either way.

Leaving the first triple unresolved separates them. `or_insert` fills
the slot from the first *resolvable* triple, so the edge must come from
the second — and deduplicating by `(parent, alias)` rather than by the
whole triple drops that triple and leaves the slot empty. Reverted
against a slot-keyed guard the assertion reports `None` where the edge
should be.

`the_first_resolvable_pending_edge_keeps_the_slot` covers the other
direction, so neither half of `or_insert` can drift unnoticed.
Copilot AI review requested due to automatic review settings August 12, 2026 05:36
@greptile-apps
greptile-apps Bot dismissed their stale review August 12, 2026 05:37

Dismissed because a newer commit was pushed; Greptile will re-review the current head.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 38691ca

@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: 38691ca4a7cf

Regular scenarios report direct and pnpr installs. The peer-heavy resolver scenario compares current Rust, main Rust, and TypeScript pnpm. 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.117 2.442 2.784 1.68 ± 0.19
pacquet@main 2.490 ± 0.127 2.372 2.745 1.63 ± 0.19
pnpr@HEAD 1.664 ± 0.107 1.546 1.789 1.09 ± 0.13
pnpr@main 1.531 ± 0.159 1.370 1.829 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.5709458213000005,
      "stddev": 0.1173376953389847,
      "median": 2.5338566305000003,
      "user": 1.96149834,
      "system": 1.5844570800000002,
      "min": 2.4424706695,
      "max": 2.7842322305000002,
      "times": [
        2.6017304675000004,
        2.7842322305000002,
        2.4994838575,
        2.4792912425000004,
        2.5176331705000004,
        2.4515363405,
        2.4424706695,
        2.6707842455,
        2.5500800905000003,
        2.7122158985
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.4895951974000003,
      "stddev": 0.1265404080373695,
      "median": 2.4541343490000003,
      "user": 1.8589337400000001,
      "system": 1.40934568,
      "min": 2.3722304135,
      "max": 2.7448606125,
      "times": [
        2.4173524435000004,
        2.4647833215,
        2.5003756975,
        2.3722304135,
        2.4657813775000004,
        2.7448606125,
        2.4176558735,
        2.4434853765,
        2.3809494935,
        2.6884773645
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.6643331737,
      "stddev": 0.10688969571096266,
      "median": 1.6552068895,
      "user": 1.10560634,
      "system": 1.15961318,
      "min": 1.5461372974999998,
      "max": 1.7885242504999999,
      "times": [
        1.7696176314999998,
        1.5697511995,
        1.7792846735,
        1.5461372974999998,
        1.5510101515,
        1.7885242504999999,
        1.6551517055,
        1.7808765345000002,
        1.5477162195,
        1.6552620735
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.5312805293999998,
      "stddev": 0.1590581286872212,
      "median": 1.4770682705,
      "user": 1.2298809400000001,
      "system": 1.30265648,
      "min": 1.3699502645,
      "max": 1.8291126695,
      "times": [
        1.8291126695,
        1.6878611435,
        1.4792424525,
        1.5294633475,
        1.7119445955,
        1.3833203775,
        1.3699502645,
        1.4748940885,
        1.3745474654999998,
        1.4724688895
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 307.9 ± 21.2 264.4 334.2 1.16 ± 0.09
pacquet@main 273.1 ± 14.6 252.8 296.0 1.02 ± 0.07
pnpr@HEAD 277.4 ± 5.6 270.9 286.4 1.04 ± 0.05
pnpr@main 266.5 ± 10.9 256.9 288.7 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.30789919556,
      "stddev": 0.021232284952859472,
      "median": 0.30425560716,
      "user": 0.25708855999999997,
      "system": 0.6075276599999999,
      "min": 0.26437648866,
      "max": 0.33420860866,
      "times": [
        0.32479166566,
        0.29293416066,
        0.30347810066,
        0.29716267866,
        0.30503311366,
        0.32567444566000003,
        0.32948517766,
        0.33420860866,
        0.26437648866,
        0.30184751566
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.27308300616000003,
      "stddev": 0.014595306917981932,
      "median": 0.27495514366000007,
      "user": 0.23001275999999998,
      "system": 0.5598438599999999,
      "min": 0.25282507266000004,
      "max": 0.29596298466000004,
      "times": [
        0.28700438266,
        0.25618514966,
        0.25809621166,
        0.28441915366000003,
        0.28082198166,
        0.27870017366000005,
        0.27121011366000003,
        0.29596298466000004,
        0.25282507266000004,
        0.26560483766000004
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.27742999536,
      "stddev": 0.00560588281978445,
      "median": 0.27754771166000003,
      "user": 0.23945735999999992,
      "system": 0.5338871599999999,
      "min": 0.27086182866,
      "max": 0.28642456366,
      "times": [
        0.27900259166,
        0.27228119666,
        0.28278574366000003,
        0.27783963566000003,
        0.27217650966,
        0.27086182866,
        0.27179469166000003,
        0.28387740466,
        0.27725578766000003,
        0.28642456366
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.26652235436000005,
      "stddev": 0.010922990757655076,
      "median": 0.26235636516000005,
      "user": 0.21006526,
      "system": 0.52254046,
      "min": 0.25690962166000003,
      "max": 0.28873237166000004,
      "times": [
        0.26193150066000004,
        0.26296628666000005,
        0.27077024666000005,
        0.28275986566,
        0.25847832966,
        0.26230020466000004,
        0.26241252566,
        0.25796259066000005,
        0.28873237166000004,
        0.25690962166000003
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.782 ± 0.049 2.720 2.871 1.68 ± 0.13
pacquet@main 2.798 ± 0.018 2.771 2.827 1.69 ± 0.13
pnpr@HEAD 1.802 ± 0.092 1.613 1.895 1.09 ± 0.10
pnpr@main 1.655 ± 0.127 1.476 1.853 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.7822375160999995,
      "stddev": 0.04903983391962854,
      "median": 2.7723022388,
      "user": 1.7052531599999998,
      "system": 1.44013532,
      "min": 2.7203708638,
      "max": 2.8711360318,
      "times": [
        2.7574691907999997,
        2.7760580038,
        2.7203708638,
        2.7700732938,
        2.7483669298,
        2.7354222068,
        2.8458441577999998,
        2.8231032988,
        2.8711360318,
        2.7745311837999997
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.7977229467999996,
      "stddev": 0.018235473826337795,
      "median": 2.7927490942999995,
      "user": 1.77364676,
      "system": 1.4938860200000001,
      "min": 2.7712698378,
      "max": 2.8268659858,
      "times": [
        2.7830305118,
        2.8127985958,
        2.7926909147999996,
        2.7928072738,
        2.7809902768,
        2.7712698378,
        2.8153078868,
        2.7876242778,
        2.8138439068,
        2.8268659858
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.8019253747999997,
      "stddev": 0.0918247385655768,
      "median": 1.8189332023000002,
      "user": 1.22143906,
      "system": 1.3287908199999998,
      "min": 1.6125932558,
      "max": 1.8947790188000002,
      "times": [
        1.8250672288,
        1.8113542708,
        1.7998851288,
        1.8742735548,
        1.6125932558,
        1.8253519528,
        1.8912550898000002,
        1.6718950718,
        1.8947790188000002,
        1.8127991758000002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.6547800295000001,
      "stddev": 0.12737832085191045,
      "median": 1.6564993638,
      "user": 1.16467736,
      "system": 1.32241012,
      "min": 1.4759505058,
      "max": 1.8534892138,
      "times": [
        1.6882508538,
        1.5509598278,
        1.8534892138,
        1.4929092788,
        1.8074460298000001,
        1.4759505058,
        1.6559227308000002,
        1.7589439788,
        1.6068518788000001,
        1.6570759968
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 475.5 ± 27.2 435.6 523.9 1.44 ± 0.12
pacquet@main 468.7 ± 33.7 428.6 525.6 1.42 ± 0.13
pnpr@HEAD 348.5 ± 36.3 311.5 440.2 1.06 ± 0.13
pnpr@main 329.7 ± 18.5 310.4 364.5 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.4755038540200001,
      "stddev": 0.027219365120774792,
      "median": 0.47075422002,
      "user": 0.58653986,
      "system": 0.7379799799999999,
      "min": 0.43555241952,
      "max": 0.52386140152,
      "times": [
        0.46965873252,
        0.46633480952,
        0.48129256352000005,
        0.46501897652,
        0.47651437852,
        0.52386140152,
        0.51683000452,
        0.47184970752000005,
        0.44812554652000003,
        0.43555241952
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.4687435142200001,
      "stddev": 0.03365229963299555,
      "median": 0.45926256552000005,
      "user": 0.6043740599999999,
      "system": 0.7293739799999999,
      "min": 0.42856426252,
      "max": 0.52558558052,
      "times": [
        0.43367217852,
        0.44387608352,
        0.42856426252,
        0.46990230052000004,
        0.45287166052000005,
        0.46547350152000005,
        0.52558558052,
        0.45305162952000005,
        0.50350370452,
        0.5109342405200001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.34849785542000006,
      "stddev": 0.036339633978452676,
      "median": 0.33451071052000003,
      "user": 0.26566506,
      "system": 0.5672457799999999,
      "min": 0.31145943352,
      "max": 0.44022333352000004,
      "times": [
        0.36221129152000003,
        0.44022333352000004,
        0.32667127552,
        0.36913899352,
        0.33591200252000003,
        0.31145943352,
        0.33138770552,
        0.33125389452000004,
        0.33310941852000003,
        0.34361120552
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.32966394422,
      "stddev": 0.018531696064904988,
      "median": 0.32818568102,
      "user": 0.24522506000000002,
      "system": 0.5310368799999999,
      "min": 0.31038273152,
      "max": 0.36451882652,
      "times": [
        0.33722457952,
        0.31382367452000004,
        0.31149630252000005,
        0.33890943252,
        0.31038273152,
        0.31914678252,
        0.31387832652000003,
        0.33971133852,
        0.36451882652,
        0.34754744752
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.955 ± 0.031 1.906 2.022 6.02 ± 0.20
pacquet@main 1.962 ± 0.044 1.904 2.065 6.04 ± 0.22
pnpr@HEAD 0.325 ± 0.009 0.315 0.348 1.00
pnpr@main 0.328 ± 0.009 0.314 0.340 1.01 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.9554782460600002,
      "stddev": 0.03053973954337285,
      "median": 1.94822242546,
      "user": 0.8869208400000002,
      "system": 0.8443067799999999,
      "min": 1.9056647739600001,
      "max": 2.02217961796,
      "times": [
        1.94088018496,
        1.94755003796,
        1.9056647739600001,
        2.02217961796,
        1.94301451396,
        1.95734242396,
        1.97612994496,
        1.93987987096,
        1.9488948129600001,
        1.97324627896
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.96224782026,
      "stddev": 0.043946329963963165,
      "median": 1.9523251944600002,
      "user": 0.9134117399999999,
      "system": 0.8805790800000001,
      "min": 1.9042078579600001,
      "max": 2.06510533896,
      "times": [
        1.94685276496,
        1.9234551909600002,
        1.9042078579600001,
        1.99743742396,
        1.95045150796,
        1.96504929296,
        1.9541988809600002,
        2.06510533896,
        1.9679281339599999,
        1.94779180996
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.32476567606,
      "stddev": 0.009493993125063752,
      "median": 0.32311683446,
      "user": 0.23869493999999997,
      "system": 0.53922128,
      "min": 0.31533262996,
      "max": 0.34797291396,
      "times": [
        0.31989742796,
        0.31926377796,
        0.32524263496,
        0.32716117996,
        0.32099103396,
        0.32598028096,
        0.34797291396,
        0.33001725696,
        0.31533262996,
        0.31579762396
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.32833921015999995,
      "stddev": 0.008594412274516777,
      "median": 0.33170739896,
      "user": 0.23212833999999996,
      "system": 0.5543141800000001,
      "min": 0.31398555896,
      "max": 0.33984944596,
      "times": [
        0.32763628396,
        0.33984944596,
        0.31495558096,
        0.31398555896,
        0.33083839096,
        0.33346576896,
        0.33432306996,
        0.33335522096,
        0.33257640696,
        0.32240637396
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 237.1 ± 17.8 206.2 263.4 2.56 ± 0.21
pacquet@main 282.7 ± 29.7 220.1 316.9 3.05 ± 0.34
pnpr@HEAD 93.6 ± 3.9 87.6 100.8 1.01 ± 0.05
pnpr@main 92.5 ± 3.1 86.0 99.0 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.23714888540181817,
      "stddev": 0.017751221202365237,
      "median": 0.23192421622000003,
      "user": 0.18903731818181815,
      "system": 0.06549597636363637,
      "min": 0.20624306022000002,
      "max": 0.26337343222000004,
      "times": [
        0.26337343222000004,
        0.23332757422000003,
        0.20624306022000002,
        0.23192421622000003,
        0.23138406022000002,
        0.22958571122000002,
        0.21960464422000003,
        0.25739711922,
        0.25908737622,
        0.24767803422000004,
        0.22903251122
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.28272593242,
      "stddev": 0.029657034382549276,
      "median": 0.29040777972,
      "user": 0.23935420000000002,
      "system": 0.08654474,
      "min": 0.22005246422000002,
      "max": 0.31689736422000003,
      "times": [
        0.28168474522000003,
        0.30870723222,
        0.30163803522000004,
        0.30110202922,
        0.28765499622,
        0.31689736422000003,
        0.29316056322,
        0.22005246422000002,
        0.25074265222000003,
        0.26561924222000005
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.09357935066827584,
      "stddev": 0.0038968256703343493,
      "median": 0.09313601822,
      "user": 0.022020982758620692,
      "system": 0.013345753793103448,
      "min": 0.08762900722,
      "max": 0.10084706922,
      "times": [
        0.09634095122,
        0.10084706922,
        0.10029400022,
        0.08947289422,
        0.09006572722,
        0.09667619122,
        0.09219532022,
        0.09086063122,
        0.09317708522,
        0.09187404722,
        0.09716780522,
        0.09448974222,
        0.08874104922,
        0.09036594222,
        0.09313601822,
        0.09346252122,
        0.09654304022,
        0.09034737622,
        0.09339872122000001,
        0.09731214622,
        0.09175937022,
        0.09764980022,
        0.09287969622,
        0.09935408422,
        0.09980216622,
        0.08909677722,
        0.08780731322,
        0.08762900722,
        0.09105467522
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.09254592361393939,
      "stddev": 0.003081567468482739,
      "median": 0.09285398722,
      "user": 0.024310015151515152,
      "system": 0.010898632727272727,
      "min": 0.08601870122000001,
      "max": 0.09898799622,
      "times": [
        0.08601870122000001,
        0.08628436022,
        0.08820916822,
        0.08727836022,
        0.08662788622,
        0.09898799622,
        0.09625897722,
        0.09347649822,
        0.08952638422,
        0.09282453222,
        0.09216367022000001,
        0.09302544922,
        0.09545148922,
        0.09371086822000001,
        0.09290795922,
        0.09285398722,
        0.09331152722,
        0.09712483422,
        0.09288679022,
        0.09253064022,
        0.09280508622,
        0.09648616422,
        0.09152983922,
        0.09292022222,
        0.09481064522,
        0.09141115622,
        0.09275500122000001,
        0.09129713222000001,
        0.09179940522,
        0.09198189822,
        0.09489573522,
        0.09543202222,
        0.09443109222
      ]
    }
  ]
}

Scenario: Isolated linker: peer-heavy resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 669.8 ± 72.9 554.0 771.1 1.04 ± 0.18
pacquet@main 644.3 ± 85.3 492.7 753.6 1.00
pnpm@HEAD 3124.1 ± 124.3 2882.7 3278.4 4.85 ± 0.67
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.6697992148555555,
      "stddev": 0.07293605792436787,
      "median": 0.6789624853,
      "user": 0.6661654155555554,
      "system": 0.12793461777777773,
      "min": 0.5539851623,
      "max": 0.7711014003,
      "times": [
        0.6789624853,
        0.6897907963,
        0.6957282753,
        0.7711014003,
        0.6408855833,
        0.7680569403,
        0.5539851623,
        0.6392851453,
        0.5903971453
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6443039886333333,
      "stddev": 0.08525281284203705,
      "median": 0.6616270353,
      "user": 0.6091350822222222,
      "system": 0.12313284,
      "min": 0.49267641130000006,
      "max": 0.7536393223,
      "times": [
        0.6616270353,
        0.7536393223,
        0.7094153783,
        0.6426639263,
        0.5197157173,
        0.6865872153,
        0.6801243593,
        0.6522865323,
        0.49267641130000006
      ]
    },
    {
      "command": "pnpm@HEAD",
      "mean": 3.1240896187444442,
      "stddev": 0.12432165252226833,
      "median": 3.1522124753,
      "user": 4.778671415555555,
      "system": 0.2866716177777778,
      "min": 2.8826945873,
      "max": 3.2783853923,
      "times": [
        3.2780472473,
        3.0195092013,
        3.1768251033,
        2.8826945873,
        3.0857487923,
        3.2783853923,
        3.1523087153,
        3.0910750543,
        3.1522124753
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.550 ± 0.118 4.456 4.867 1.26 ± 0.05
pacquet@main 4.591 ± 0.142 4.469 4.948 1.27 ± 0.05
pnpr@HEAD 3.602 ± 0.106 3.493 3.801 1.00
pnpr@main 3.747 ± 0.145 3.617 3.978 1.04 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.549861299940001,
      "stddev": 0.11750719371624571,
      "median": 4.51824477014,
      "user": 2.1091045799999995,
      "system": 1.4870235,
      "min": 4.455839070640001,
      "max": 4.8674406576400004,
      "times": [
        4.53007317164,
        4.5796886616400005,
        4.542393440640001,
        4.54782161564,
        4.50453518264,
        4.49045159764,
        4.50641636864,
        4.455839070640001,
        4.8674406576400004,
        4.47395323264
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.590633926440001,
      "stddev": 0.1419752618368678,
      "median": 4.55441885514,
      "user": 2.11717028,
      "system": 1.5785854000000001,
      "min": 4.46937636364,
      "max": 4.94845002764,
      "times": [
        4.58013770564,
        4.51867829964,
        4.5452696686400005,
        4.70104049664,
        4.46937636364,
        4.52229298464,
        4.5839108066400005,
        4.94845002764,
        4.47361486964,
        4.56356804164
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.6017872101400004,
      "stddev": 0.10647763085331845,
      "median": 3.5466401316400002,
      "user": 1.4458236799999997,
      "system": 1.4495283,
      "min": 3.49348087264,
      "max": 3.80111235864,
      "times": [
        3.5465320486400005,
        3.80111235864,
        3.49348087264,
        3.5315190236400005,
        3.54674821464,
        3.5374357086400003,
        3.4980724656400004,
        3.7047571616400004,
        3.6467100526400005,
        3.7115041946400003
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.7473027116400006,
      "stddev": 0.14475151332901967,
      "median": 3.67056418414,
      "user": 1.77256268,
      "system": 1.7259240999999999,
      "min": 3.61740096264,
      "max": 3.9784853686400004,
      "times": [
        3.9784853686400004,
        3.61740096264,
        3.64622506164,
        3.9394965506400004,
        3.69490330664,
        3.64387914064,
        3.8131915166400003,
        3.8953345556400003,
        3.6181026006400003,
        3.6260080526400005
      ]
    }
  ]
}

@github-actions

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13844
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,720.37 ms
(+0.40%)Baseline: 2,709.61 ms
3,251.54 ms
(83.66%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
1,905.66 ms
(+4.90%)Baseline: 1,816.67 ms
2,180.00 ms
(87.42%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
435.55 ms
(-4.36%)Baseline: 455.40 ms
546.48 ms
(79.70%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
206.24 ms
(-8.21%)Baseline: 224.69 ms
269.63 ms
(76.49%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,442.47 ms
(-1.44%)Baseline: 2,478.14 ms
2,973.76 ms
(82.13%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,455.84 ms
(-1.50%)Baseline: 4,523.47 ms
5,428.16 ms
(82.09%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
264.38 ms
(-11.15%)Baseline: 297.56 ms
357.08 ms
(74.04%)
isolated-linker.peer-heavy-resolve.hot-cache.offline📈 view plot
🚷 view threshold
553.99 ms
(-20.88%)Baseline: 700.17 ms
840.20 ms
(65.93%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13844
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,612.59 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
315.33 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
311.46 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
87.63 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,546.14 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
3,493.48 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
270.86 ms
🐰 View full continuous benchmarking report in Bencher

@zkochan
zkochan merged commit 46a9fe4 into main Aug 12, 2026
35 checks passed
@zkochan
zkochan deleted the fix-13681-resolution-memory branch August 12, 2026 06:51
zkochan added a commit that referenced this pull request Aug 12, 2026
…em (#13855)

Follow-up to #13844 on the same workload from #13681.

A workspace has a few thousand distinct `pkgIdWithPatchHash` values, but the peer walk realizes one occurrence node per distinct root-to-package path — **2,007,292 of them for a 6,133-node graph**. Every one of those nodes owned a fresh `String` copy of its package id, and every parent-context snapshot copied it again.

### Changes

- **`DependenciesTreeNode::resolved_package_id` and `ChildEdge::pkg_id` become `Arc<str>`.** `realize_children` now hands over a refcount instead of allocating, and the node shrinks from 56 to 48 bytes. The maps keyed by package id move to `Arc<str>` keys with it — `Arc<str>: Borrow<str>` keeps `&str` lookups working, and `Arc<str>` hashes as its `str`, so iteration order is unchanged.
- **`ParentPkgInfo::pkg_id` follows.** Those snapshots held **1,327,035 entries** across the walk, each with its own copy of an id that already existed on the tree node it was read from.
- **`DepPath` gains `From<Arc<str>>`.** It already wraps an `Arc<str>`, so these conversions stop round-tripping through `String` and reallocating.

### Result

| | peak RSS |
| --- | --- |
| `main` | 3306 / 3236 / 3250 MB |
| this branch | 3008 / 3086 / 3044 MB |

**3264 → 3046 MB, −6.7%**, alternating A/B to control for drift, non-overlapping, 3 of 3.

Cumulative with #13844 the same install has gone **3670 → 3046 MB (−17%)**.

(The first version of this PR measured −5%. Review caught that the conversion had left `Arc::from` calls on paths that previously did no allocation at all — comparisons in the cache-matching loop, a double allocation in `packages.insert`, a `&str → String → Arc<str>` round-trip. Removing them is what took it to −6.7%.)

### Correctness

The lockfile is **byte-identical** — `main` twice and this branch once all produced the same file, and the package sets match exactly. (Worth noting given #13846: on this run the engine happened to be deterministic, so the control was clean; that is not always true.)

326 tests pass, plus `cargo clippy --all-targets`, `cargo fmt` and `cargo dylint` clean across the workspace.

Two tests cover the change: the existing footprint assertion drops from 56 to 48 bytes, and `realizing_children_shares_the_edge_package_id` asserts pointer equality through `realize_children_with` — the path that creates the two million occurrences — so a future copy fails rather than silently costing memory. I verified it fails when that path is made to copy; the first version of it did not, because it only checked that the constructor kept its argument.
zkochan added a commit that referenced this pull request Aug 12, 2026
…truncation (#13859)

The third and largest piece of #13681, addressing what the first two PRs (#13844, #13855) deliberately left alone: the occurrence explosion itself.

### The problem

A walk that re-enters a package already on its ancestor chain resolves against a truncated subtree, so its verdict has never been cached — reusing it where the subtree is intact drops `transitivePeerDependencies` depending on traversal order (#5108). On a peer-cyclic graph this rule makes the peers cache inert. Resolving [bit](https://github.com/teambit/bit)'s env packages:

```
full walks:            188,707   (91% end in a cycle)
peers-cache hits:          155   of 188,862 lookups  (0.08%)
occurrence nodes:    2,008,130   for a 6,133-node graph
```

### The insight, measured before designed

The truncation is not arbitrary: `realize_children_with` drops exactly the edges `forms_cycle` finds in the occurrence's own ancestor ids. So a truncated verdict is a function of *(package, peer context, the chain entries the gate actually weighs)* — and everything else in the chain is noise. I instrumented the workload to check how much noise:

| candidate key | distinct keys / 171,508 cycle walks |
| --- | --- |
| full ancestor chain | 68,184 (2.5×) — and implemented honestly, memory got *worse* |
| chain ∩ reachable-set | 68,180 — useless, the cluster is one giant SCC |
| **chain ∩ consulted ids** | **~1,900 (91×)** |

### The mechanism

- Every full walk keeps a `ConsultedPkgs` frame — a bitset over interned package ids. Realization marks the package whose children are realized plus every child edge target (precisely the `forms_cycle` arguments); reusing an already-realized children map marks the same ids, since the map embodies the same answers. Finished walks fold their frame into their parent's; a cache hit folds the stored entry's set in. An outer frame therefore covers the dependence of everything under it.
- Cycle-resolved verdicts are now stored, tagged with a `CycleTruncationKey`: the consulted set plus the occurrence's ancestor ids restricted to it (base entries first — `forms_cycle` treats the halves differently, so the boundary is part of the key).
- `find_hit` hands a tagged verdict only to an occurrence whose ancestors, restricted to the entry's consulted set, are exactly the recorded chain. Equal restrictions ⇒ every gate answer equal ⇒ same realization, same truncation, same verdict, by induction on the walk. Non-matching occurrences — in particular ones whose ancestors don't truncate the subtree at all, the #5108 shape — re-walk exactly as before.

### Results

Same replayed install as the previous PRs (5 importers, 3,807 merged packages), alternating A/B:

| | peak RSS | wall time |
| --- | --- | --- |
| `main` | 3043 / 3056 / 3042 MB | 59 / 39 / 42 s |
| this branch | 1405 / 1416 / 1415 MB | 20 / 25 / 20 s |

**3047 → 1412 MB (−54%), roughly 2× faster.** Walk counts: full walks 188,707 → 33,648; cycle walks 171,508 → 16,563; the keyed entries hit 44,999 times. Cumulative across the three PRs the install has gone **3670 → 1412 MB (−62%)**.

### Correctness

This is the change #5108 exists to be afraid of, so I want to be explicit about the evidence and its limits.

- **328 tests pass**, including new ones that pin the key's semantics from both directions: unconsulted ancestors are noise (reuse happens), while order changes, extra occurrences, base/appended boundary moves, and — critically — *an occurrence whose ancestors don't truncate the subtree* all refuse reuse.
- **Repeat installs never churn.** Fixed-point checked both ways: the unmodified engine, handed this branch's lockfile as `wanted`, preserves it byte for byte; this branch preserves `main`'s lockfile byte for byte. Lockfile churn on repeat installs is the #5108 regression, and it cannot happen here.
- **Cold output is deterministic** — three cold runs, byte-identical.
- **Cold output differs from `main` in 13 snapshot entries** (52 diff lines of ~86k), all in the `@teambit/component → command-bar/pubsub/ui` cluster — the exact entries that already flip between *identical stock runs* (#13846, 96–197-line diffs). The branch picks a different valid peer variant there; the fixed-point check is what shows it is valid. I want to flag this honestly rather than bury it: if byte-identical cold output against current `main` is a hard requirement even inside the known-nondeterministic cluster, this needs a maintainer call.
- `cargo clippy --all-targets`, `cargo fmt`, and `cargo dylint` clean across the workspace.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants