Skip to content

fix(pacquet): preserve locked peers during dedupe - #13459

Merged
zkochan merged 5 commits into
mainfrom
fix/pacquet-dedupe-peer-parity
Jul 28, 2026
Merged

zkochan merged 5 commits into
mainfrom
fix/pacquet-dedupe-peer-parity

Conversation

@zkochan

@zkochan zkochan commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Summary

During pnpm dedupe --check on the n8n workspace, pacquet suppressed importer-local optional peer hoisting when another importer had already traversed the same package. That removed optional peer providers already represented in the wanted lockfile's peer suffixes, producing many bufferutil and utf-8-validate peer-context differences from the TypeScript CLI.

Keep preferred versions that occur in wanted-lockfile peer suffixes eligible for importer-local hoisting. This brings the affected jsdom and vitest peer contexts in n8n in line with the TypeScript CLI.

The n8n comparison still exposes two independent parity gaps outside this fix: applying the @browserbasehq/stagehand override during dedupe, and adding integrity for the git-hosted wa-sqlite tarball.

Related to #13305.

Squash Commit Body

Pacquet's cross-importer missing-peer suppression treated all preferred
versions alike. During lockfile re-resolution, this could suppress optional
peer providers that were already encoded in peer suffixes in the wanted
lockfile.

Derive the names of locked peer providers from wanted-lockfile snapshot
suffixes and exempt those names from cross-importer suppression. This keeps
importer-local peer contexts stable during dedupe and aligns the affected n8n
jsdom and vitest variants with the TypeScript CLI.

Related to pnpm/pnpm#13305.

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 (Codex, GPT-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
    • Preserved optional peer providers from “peer suffix” lockfile entries when rebuilding a workspace lockfile via deduplication.
    • Prevented locked peers from being incorrectly suppressed during required-peer hoisting by honoring lockfile-derived locked peer names.
  • Tests
    • Added unit tests covering locked peer name derivation, including missing and hashed peer-suffix scenarios.
    • Updated workspace hoisting coverage so optional peer providers remain eligible when an existing lockfile entry is present.
  • Chores
    • Added release metadata for a pacquet patch update.

Copilot AI review requested due to automatic review settings July 28, 2026 07:48

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

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The resolver derives peer providers from workspace lockfile peer suffixes, threads them through required-peer hoisting, and prevents matching missing-peer scopes from being suppressed. Tests cover plain, hashed, and workspace-hoisting cases, and a patch changeset documents the behavior.

Changes

Locked peer provider handling

Layer / File(s) Summary
Hoist suppression contract
pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs
HoistMissingScope records locked peer names and bypasses suppression for matching peer names.
Importer integration
pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs
The importer extracts peer names from lockfile suffixes and package metadata, then supplies them during importer and required-peer hoisting.
Validation and release metadata
pnpm/crates/resolving-deps-resolver/src/resolve_importer/tests.rs, pnpm/crates/resolving-deps-resolver/src/resolve_workspace/tests.rs, .changeset/pacquet-dedupe-locked-peers.md
Tests cover plain and hashed suffixes plus workspace hoisting, and the Changesets entry documents the patch release.

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

Sequence Diagram(s)

sequenceDiagram
  participant WorkspaceWantedLockfile
  participant ImporterHoistState
  participant HoistMissingScope
  WorkspaceWantedLockfile->>ImporterHoistState: provide snapshot suffixes and package metadata
  ImporterHoistState->>ImporterHoistState: derive locked_peer_names
  ImporterHoistState->>HoistMissingScope: pass locked_peer_names during hoisting
  HoistMissingScope->>HoistMissingScope: bypass suppression for locked peers
Loading

Possibly related PRs

  • pnpm/pnpm#13432: Modifies the same required and optional peer-hoisting missing-scope machinery.
  • pnpm/pnpm#13381: Also changes the Rust dependency resolver’s peer-hoisting flow.

Suggested labels: product: pacquet

Suggested reviewers: copilot, yeshyungseok

✨ 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/pacquet-dedupe-peer-parity

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 pacquet dedupe to preserve lockfile-encoded optional peer providers

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Prevent cross-importer missing-peer suppression from dropping peers already encoded in
 wanted-lockfile peer suffixes.
• Derive “locked” peer provider names from lockfile snapshot peer suffixes and exempt them from
 suppression.
• Add unit coverage for peer-suffix-based locking behavior and ship a pacquet patch changeset.
Diagram

graph TD
  A(["ImporterHoistState"]) --> C(("locked_peer_names()")) --> D(["HoistMissingScope"]) --> E(["resolve_peers()"])
  B[("Wanted lockfile snapshots")] --> C
  E --> F{"suppress missing peer?"}

  subgraph Legend
    direction LR
    _state(["State/struct"]) ~~~ _fn(("Function")) ~~~ _db[("Lockfile data")] ~~~ _dec{"Decision"}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Parse peer suffixes structurally (no substring scan)
  • ➕ More robust than contains("({name}@") for edge cases and future lockfile encoding tweaks
  • ➕ Avoids any risk of accidental matches if the suffix format changes
  • ➖ Requires additional parsing utilities/APIs in pacquet_lockfile (or new code)
  • ➖ Higher implementation complexity for a narrow bug fix
2. Compute and cache locked_peer_names once per importer hoist state
  • ➕ Avoids recomputing the set each time HoistMissingScope is built (minor perf/clarity win)
  • ➕ Keeps the scope construction simpler in hot paths
  • ➖ Requires threading cached state through ImporterHoistState lifecycle
  • ➖ May be premature optimization if scope creation is infrequent

Recommendation: The PR’s approach is a good targeted fix: it uses the wanted lockfile as the source of truth for which peer contexts must remain stable during dedupe, and minimally changes suppression behavior. If this logic grows, consider a follow-up to parse peer suffixes into structured peer-provider lists and/or cache the derived set to reduce repeated work.

Files changed (4) +82 / -2

Bug fix (2) +35 / -0
resolve_importer.rsDerive locked peer providers from wanted lockfile peer suffixes +29/-0

Derive locked peer providers from wanted lockfile peer suffixes

• Threads a new 'locked_peer_names' set into 'HoistMissingScope' construction for importer peer resolution rounds. Introduces 'locked_peer_names()' which scans wanted-lockfile snapshot peer suffixes and intersects them with the preferred-versions keys to determine which peer names must remain eligible for importer-local hoisting.

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

resolve_peers.rsExempt lockfile-locked peers from cross-importer suppression +6/-0

Exempt lockfile-locked peers from cross-importer suppression

• Extends 'HoistMissingScope' with 'locked_peer_names' and updates 'suppresses()' to early-return false for those peers. This prevents dedupe re-resolution from suppressing optional peer providers that are already encoded in the wanted lockfile’s peer contexts.

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

Tests (1) +42 / -2
tests.rsUnit test for peer-suffix-based locked peer name detection +42/-2

Unit test for peer-suffix-based locked peer name detection

• Adds a focused test ensuring only peer provider names that appear in snapshot peer suffixes are treated as locked. Extends imports to use 'HashSet' and references the new helper.

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

Documentation (1) +5 / -0
pacquet-dedupe-locked-peers.mdAdd pacquet patch changeset for dedupe peer preservation +5/-0

Add pacquet patch changeset for dedupe peer preservation

• Adds a changeset documenting that 'pnpm dedupe' now preserves optional peer providers already recorded in peer suffixes. This serves as the user-facing release note for the pacquet patch.

.changeset/pacquet-dedupe-locked-peers.md

@greptile-apps

greptile-apps Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5

The PR is not yet safe to merge because the global name-only exemption can auto-hoist a genuinely missing peer into an unrelated importer.

A peer name locked by any snapshot is shared with every importer, and suppresses bypasses cross-importer suppression solely by that name, so an unrelated missing peer can be retained and hoisted into a lockfile context that was not previously present.

Files Needing Attention: pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs; pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs

Reviews (5): Last reviewed commit: "fix(pacquet): filter hashed peer provide..." | Re-trigger Greptile

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. Repeated lockfile scan 🐞 Bug ➹ Performance ⭐ New
Description
ImporterHoistState::init recomputes locked_peer_names() by scanning wanted-lockfile snapshots
for every importer, even though the result is workspace-global. On large workspaces/lockfiles this
adds avoidable O(importers × snapshots) overhead to resolve_workspace/dedupe runs.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[R424-425]

+        let locked_peer_names =
+            Arc::new(locked_peer_names(ctx.workspace().wanted_lockfile().map(AsRef::as_ref)));
Relevance

⭐⭐⭐ High

Team often accepts hot-path perf/caching fixes (e.g. avoid always computing O(n) data in #13172;
reduce repeated allocations in #13431).

PR-#13172
PR-#13431

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new code computes locked_peer_names during importer initialization and stores it on the
importer state, but resolve_workspace initializes one state per importer, so the lockfile snapshot
scan is repeated once per importer instead of being shared across the workspace.

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[417-470]
pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[792-825]
pnpm/crates/resolving-deps-resolver/src/resolve_workspace.rs[250-275]

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

## Issue description
`locked_peer_names(...)` is computed inside `ImporterHoistState::init`, which is invoked once per importer in `resolve_workspace`. The computation scans `wanted_lockfile.snapshots` (and does extra per-snapshot work for hashed peer suffixes), but the output depends only on the workspace wanted lockfile, so repeating it per importer is unnecessary overhead.

## Issue Context
- The computed set is already wrapped in `Arc<HashSet<...>>`, but it is not shared across importers because it is recomputed before being wrapped.
- This impacts the workspace hot path because `resolve_workspace` constructs an `ImporterHoistState` for each importer.

## Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[424-470]
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[792-825]
- pnpm/crates/resolving-deps-resolver/src/resolve_workspace.rs[250-275]

## Suggested fix
- Compute `Arc<HashSet<String>>` for locked peer names once per workspace (e.g., in `resolve_workspace` before the importer loop, or as a lazily initialized cache on `WorkspaceTreeCtx` using `OnceLock`/`OnceCell`).
- Thread that `Arc` into each `ImporterHoistState` (via a new parameter to `ImporterHoistState::init`, or via a `workspace.locked_peer_names()` accessor that memoizes the result).
- Keep `locked_peer_names()` as the pure helper (Option<&Lockfile> -> HashSet<String>), but ensure it’s only called once per workspace resolution run.

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


2. Misses packages-only lockfiles 🐞 Bug ≡ Correctness
Description
locked_peer_names() only scans wanted_lockfile.snapshots, so if a valid v9 lockfile omits
snapshots but includes peer-suffixed keys under packages, locked peer providers won’t be
detected and the new suppression exemption won’t apply.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[R798-804]

+    let peer_suffixes: Vec<&str> = wanted_lockfile
+        .and_then(|lockfile| lockfile.snapshots.as_ref())
+        .into_iter()
+        .flat_map(|snapshots| snapshots.keys())
+        .map(|key| key.suffix.peer())
+        .filter(|peer| !peer.is_empty())
+        .collect();
Relevance

⭐⭐ Medium

No historical evidence found about scanning packages vs snapshots for peer suffixes.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The lockfile type defines both packages and snapshots as optional maps keyed by PackageKey
(which includes peer suffixes), but the new code only reads snapshots, so it can miss peer
suffixes present only in packages.

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[794-804]
pnpm/crates/lockfile/src/lib.rs[166-177]
pnpm/crates/resolving-deps-resolver/src/resolve_importer/tests.rs[20-54]

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

### Issue description
`locked_peer_names()` derives locked peer providers exclusively from `lockfile.snapshots`. However, the v9 lockfile model also has `packages: Option<HashMap<PackageKey, ...>>`, where `PackageKey` includes peer suffixes. If `snapshots` is missing but `packages` is present, the function returns an empty set and the PR’s intended behavior won’t apply.

### Issue Context
The new behavior is meant to preserve locked peer providers encoded in peer suffixes in the wanted lockfile; those suffixes can be present on keys in both maps.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[794-813]
- pnpm/crates/lockfile/src/lib.rs[166-177]
- pnpm/crates/resolving-deps-resolver/src/resolve_importer/tests.rs[20-54]

### Suggested fix approach
1. Include `packages` keys in the scan:
  - Either scan `snapshots` keys **and** `packages` keys (union), or fall back to `packages` when `snapshots` is `None`.
2. Add a regression test alongside the existing one:
  - Construct a `Lockfile` with `packages: Some(HashMap::from([(PkgNameVerPeer::from_str("[email protected]([email protected])")?, ...)]))` and `snapshots: None`.
  - Assert `locked_peer_names(&preferred, Some(&lockfile))` contains `"peer"`.
3. Ensure any union logic dedupes keys and remains deterministic (order-independent).

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


3. Quadratic peer-suffix scan ✓ Resolved 🐞 Bug ➹ Performance
Description
locked_peer_names() builds a list of all peer suffix strings and then, for every preferred package
name, does a substring scan across all suffixes; this is called repeatedly during the required-round
loop, which can add significant overhead on large workspaces/lockfiles.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[R794-810]

+fn locked_peer_names(
+    preferred_versions: &PreferredVersions,
+    wanted_lockfile: Option<&pacquet_lockfile::Lockfile>,
+) -> HashSet<String> {
+    let peer_suffixes: Vec<&str> = wanted_lockfile
+        .and_then(|lockfile| lockfile.snapshots.as_ref())
+        .into_iter()
+        .flat_map(|snapshots| snapshots.keys())
+        .map(|key| key.suffix.peer())
+        .filter(|peer| !peer.is_empty())
+        .collect();
+    preferred_versions
+        .keys()
+        .filter(|name| {
+            let marker = format!("({name}@");
+            peer_suffixes.iter().any(|suffix| suffix.contains(&marker))
+        })
Relevance

⭐⭐ Medium

Perf feedback is mixed: some optimizations accepted, similar hot-path refactors rejected.

PR-#13431
PR-#13388
PR-#13391

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The required-round loop constructs HoistMissingScope with a fresh locked_peer_names(...) call,
and the implementation performs nested iteration with substring checks, which scales poorly with
lockfile size and preferred-versions size.

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[530-613]
pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[794-813]
REVIEW_GUIDE.md[30-35]
REVIEW_GUIDE.md[115-127]

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

### Issue description
`locked_peer_names()` currently does an avoidable O(P×S) scan (P = number of preferred package names, S = number of lockfile snapshot keys), and it’s recomputed inside the required-round loop. This is in a resolver hot path (dedupe / lockfile re-resolution) and can regress performance on large lockfiles.

### Issue Context
- Lockfiles are treated as attacker-controlled inputs in this repo’s review guide; avoid repeated full-map scans or repeated substring searches in resolver loops.
- The function is invoked when building `HoistMissingScope` during required-round processing.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[530-613]
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[794-813]

### Suggested fix approach
1. Compute the “locked peer provider names” set **once** per workspace resolve (or once per importer at most), and reuse it across rounds.
  - E.g. store it on `ImporterHoistState` or `WorkspaceTreeCtx` and pass an `Arc<HashSet<String>>` into `HoistMissingScope` rather than allocating a fresh set per call.
2. Avoid substring scanning across all suffixes for each preferred name:
  - Parse each peer suffix string once (it’s shaped like `(...)(...)`) and extract peer package names by splitting into segments and taking the portion before the **last** `@` in each segment (handles scoped names like `@types/node@...`).
  - Build a `HashSet<String>` of locked peer names from the lockfile keys, then intersect with `preferred_versions.keys()` if you still want to limit to preferred names.
3. (Optional) Add a micro-benchmark or regression test asserting the function is not called multiple times per round, if you introduce caching.

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



Informational

4. peer_suffix_names reimplements peer parsing 📘 Rule violation ⚙ Maintainability ⭐ New
Description
New peer-suffix parsing logic is implemented locally in peer_suffix_names() even though the crate
already has a peer-suffix segment parser (split_peer_suffix_segments/peer_segment_name).
Duplicating this parsing increases the risk of subtle format drift and inconsistent edge-case
handling across resolver paths.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[R828-834]

+fn peer_suffix_names(peer_suffix: &str) -> impl Iterator<Item = String> + '_ {
+    peer_suffix.match_indices('(').filter_map(|(start, _)| {
+        let segment = peer_suffix[start + 1..].split(['(', ')']).next()?;
+        let (name, _) = segment.rsplit_once('@')?;
+        (!name.is_empty()).then(|| name.to_string())
+    })
+}
Relevance

⭐ Low

Similar “don’t duplicate existing helper” refactors were previously rejected (e.g. reuse existing
intersection helper instead of new one in #13172).

PR-#13172

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new peer_suffix_names() function adds a standalone peer-suffix parser in
resolve_importer.rs, while resolve_peers.rs already contains dedicated helpers for splitting
peer-suffix segments and extracting peer package names. This matches the rule’s failure criteria
(duplicated, overlapping logic instead of reuse/extraction).

Rule 713439: Avoid reimplementing existing functionality; extract and reuse shared modules
pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[828-834]
pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs[2676-2713]

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

## Issue description
`peer_suffix_names()` introduces a second, custom peer-suffix parsing implementation. The crate already parses peer-suffix segments elsewhere, and duplicating parsing logic risks divergent behavior and future bugs.

## Issue Context
- New code: `peer_suffix_names()` extracts names by scanning for `(` and splitting substrings.
- Existing code in the same crate already parses peer-suffix segments robustly with explicit parenthesis depth tracking and scoped-name handling.

## Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[828-834]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs[2676-2713]

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


5. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset only bumps pacquet and does not declare a bump for the pnpm package. This
violates the requirement that every changeset explicitly includes a valid bump type for pnpm.
Code

.changeset/pacquet-dedupe-locked-peers.md[R1-3]

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

⭐ Low

Team repeatedly merged PRs rejecting “add pnpm entry” changeset compliance suggestions.

PR-#13455
PR-#13454
PR-#13417

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each changeset to contain an explicit pnpm entry with a valid
bump type. The added changeset front-matter includes only pacquet: patch and does not list pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/pacquet-dedupe-locked-peers.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 newly added changeset omits the required `pnpm` package entry in its front-matter.

## Issue Context
Compliance requires changeset front-matter to explicitly include `pnpm` with a valid bump type (`patch`/`minor`/`major`).

## Fix Focus Areas
- .changeset/pacquet-dedupe-locked-peers.md[1-3]

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


Grey Divider

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

Previous review results

Review updated until commit 50a8a89

Results up to commit 258cd40 ⚖️ Balanced


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


Remediation recommended
1. Misses packages-only lockfiles 🐞 Bug ≡ Correctness
Description
locked_peer_names() only scans wanted_lockfile.snapshots, so if a valid v9 lockfile omits
snapshots but includes peer-suffixed keys under packages, locked peer providers won’t be
detected and the new suppression exemption won’t apply.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[R798-804]

+    let peer_suffixes: Vec<&str> = wanted_lockfile
+        .and_then(|lockfile| lockfile.snapshots.as_ref())
+        .into_iter()
+        .flat_map(|snapshots| snapshots.keys())
+        .map(|key| key.suffix.peer())
+        .filter(|peer| !peer.is_empty())
+        .collect();
Relevance

⭐⭐ Medium

No historical evidence found about scanning packages vs snapshots for peer suffixes.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The lockfile type defines both packages and snapshots as optional maps keyed by PackageKey
(which includes peer suffixes), but the new code only reads snapshots, so it can miss peer
suffixes present only in packages.

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[794-804]
pnpm/crates/lockfile/src/lib.rs[166-177]
pnpm/crates/resolving-deps-resolver/src/resolve_importer/tests.rs[20-54]

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

### Issue description
`locked_peer_names()` derives locked peer providers exclusively from `lockfile.snapshots`. However, the v9 lockfile model also has `packages: Option<HashMap<PackageKey, ...>>`, where `PackageKey` includes peer suffixes. If `snapshots` is missing but `packages` is present, the function returns an empty set and the PR’s intended behavior won’t apply.

### Issue Context
The new behavior is meant to preserve locked peer providers encoded in peer suffixes in the wanted lockfile; those suffixes can be present on keys in both maps.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[794-813]
- pnpm/crates/lockfile/src/lib.rs[166-177]
- pnpm/crates/resolving-deps-resolver/src/resolve_importer/tests.rs[20-54]

### Suggested fix approach
1. Include `packages` keys in the scan:
  - Either scan `snapshots` keys **and** `packages` keys (union), or fall back to `packages` when `snapshots` is `None`.
2. Add a regression test alongside the existing one:
  - Construct a `Lockfile` with `packages: Some(HashMap::from([(PkgNameVerPeer::from_str("[email protected]([email protected])")?, ...)]))` and `snapshots: None`.
  - Assert `locked_peer_names(&preferred, Some(&lockfile))` contains `"peer"`.
3. Ensure any union logic dedupes keys and remains deterministic (order-independent).

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


2. Quadratic peer-suffix scan ✓ Resolved 🐞 Bug ➹ Performance
Description
locked_peer_names() builds a list of all peer suffix strings and then, for every preferred package
name, does a substring scan across all suffixes; this is called repeatedly during the required-round
loop, which can add significant overhead on large workspaces/lockfiles.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[R794-810]

+fn locked_peer_names(
+    preferred_versions: &PreferredVersions,
+    wanted_lockfile: Option<&pacquet_lockfile::Lockfile>,
+) -> HashSet<String> {
+    let peer_suffixes: Vec<&str> = wanted_lockfile
+        .and_then(|lockfile| lockfile.snapshots.as_ref())
+        .into_iter()
+        .flat_map(|snapshots| snapshots.keys())
+        .map(|key| key.suffix.peer())
+        .filter(|peer| !peer.is_empty())
+        .collect();
+    preferred_versions
+        .keys()
+        .filter(|name| {
+            let marker = format!("({name}@");
+            peer_suffixes.iter().any(|suffix| suffix.contains(&marker))
+        })
Relevance

⭐⭐ Medium

Perf feedback is mixed: some optimizations accepted, similar hot-path refactors rejected.

PR-#13431
PR-#13388
PR-#13391

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The required-round loop constructs HoistMissingScope with a fresh locked_peer_names(...) call,
and the implementation performs nested iteration with substring checks, which scales poorly with
lockfile size and preferred-versions size.

pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[530-613]
pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[794-813]
REVIEW_GUIDE.md[30-35]
REVIEW_GUIDE.md[115-127]

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

### Issue description
`locked_peer_names()` currently does an avoidable O(P×S) scan (P = number of preferred package names, S = number of lockfile snapshot keys), and it’s recomputed inside the required-round loop. This is in a resolver hot path (dedupe / lockfile re-resolution) and can regress performance on large lockfiles.

### Issue Context
- Lockfiles are treated as attacker-controlled inputs in this repo’s review guide; avoid repeated full-map scans or repeated substring searches in resolver loops.
- The function is invoked when building `HoistMissingScope` during required-round processing.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[530-613]
- pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[794-813]

### Suggested fix approach
1. Compute the “locked peer provider names” set **once** per workspace resolve (or once per importer at most), and reuse it across rounds.
  - E.g. store it on `ImporterHoistState` or `WorkspaceTreeCtx` and pass an `Arc<HashSet<String>>` into `HoistMissingScope` rather than allocating a fresh set per call.
2. Avoid substring scanning across all suffixes for each preferred name:
  - Parse each peer suffix string once (it’s shaped like `(...)(...)`) and extract peer package names by splitting into segments and taking the portion before the **last** `@` in each segment (handles scoped names like `@types/node@...`).
  - Build a `HashSet<String>` of locked peer names from the lockfile keys, then intersect with `preferred_versions.keys()` if you still want to limit to preferred names.
3. (Optional) Add a micro-benchmark or regression test asserting the function is not called multiple times per round, if you introduce caching.

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



Informational
3. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset only bumps pacquet and does not declare a bump for the pnpm package. This
violates the requirement that every changeset explicitly includes a valid bump type for pnpm.
Code

.changeset/pacquet-dedupe-locked-peers.md[R1-3]

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

⭐ Low

Team repeatedly merged PRs rejecting “add pnpm entry” changeset compliance suggestions.

PR-#13455
PR-#13454
PR-#13417

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each changeset to contain an explicit pnpm entry with a valid
bump type. The added changeset front-matter includes only pacquet: patch and does not list pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/pacquet-dedupe-locked-peers.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 newly added changeset omits the required `pnpm` package entry in its front-matter.

## Issue Context
Compliance requires changeset front-matter to explicitly include `pnpm` with a valid bump type (`patch`/`minor`/`major`).

## Fix Focus Areas
- .changeset/pacquet-dedupe-locked-peers.md[1-3]

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


Qodo Logo

@github-actions

github-actions Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                                            main                                   pr
-----                                            ----                                   --
lockfile/parse_pnpm_lock                         1.07     12.2±0.15ms    30.8 MB/sec    1.00     11.4±0.14ms    32.8 MB/sec
packument/parse                                  1.09     40.2±0.51µs  1649.3 MB/sec    1.00     37.1±0.37µs  1790.0 MB/sec
tarball/download_dependency                      1.01      2.4±0.07ms  1810.9 KB/sec    1.00      2.4±0.09ms  1825.8 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.05    190.2±6.13ms 84.1 KElem/sec    1.00    181.3±3.96ms 88.2 KElem/sec

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@pnpm/crates/resolving-deps-resolver/src/resolve_importer/tests.rs`:
- Around line 20-54: Add a resolver-level regression test, alongside
only_peer_suffix_versions_are_treated_as_locked_peer_providers, that reproduces
the cross-importer optional-peer scenario and exercises the resolver decision
path through HoistMissingScope::suppresses. Assert the optional peer remains
unsuppressed because it is present in locked_peer_names, so the test fails when
the production guard is removed rather than only validating locked-peer
extraction.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 50cb8297-35e9-4923-a86a-66470b577952

📥 Commits

Reviewing files that changed from the base of the PR and between 1c1442a and 258cd40.

📒 Files selected for processing (4)
  • .changeset/pacquet-dedupe-locked-peers.md
  • pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_importer/tests.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers.rs

Copilot AI review requested due to automatic review settings July 28, 2026 07:54

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.

Copilot AI review requested due to automatic review settings July 28, 2026 07:56

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.

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 28, 2026
Copilot AI review requested due to automatic review settings July 28, 2026 08:00

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

Copy link
Copy Markdown
Member Author

Addressed the performance finding in 78c69b6: peer names are now extracted from each suffix in one pass, including scoped and nested provider paths, cached once on ImporterHoistState, and shared across rounds through Arc.

The other two findings do not apply:

  • v9 packages metadata is peer-context-independent by contract; peer-suffixed variants live in snapshots. PackageMetadata is keyed by key.without_peer() throughout this implementation, so accepting peer-suffixed packages keys would preserve an invalid lockfile shape.
  • This is a Rust-only pacquet change. The repository instructions explicitly require Rust-only changesets to target pacquet and omit pnpm, which names the TypeScript CLI package.

Written by an agent (Codex, GPT-5).

@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 28, 2026 08:03

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.

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