Skip to content

perf: absorb a new workspace project into the fast lockfile update - #13803

Merged
zkochan merged 5 commits into
mainfrom
fix-13800
Aug 11, 2026
Merged

zkochan merged 5 commits into
mainfrom
fix-13800

Conversation

@zkochan

@zkochan zkochan commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #13800, item 3 of #13696.

Adding a package to a workspace always paid a full resolution, even when every dependency it declared was already locked for a sibling — the normal case for a package scaffolded from a template. The importers fast update now writes such a project's whole entry from the versions the lockfile already holds.

The gate the issue named was not the blocker. contextProjects.every((project) => ctx.wantedLockfile.importers[project.id] != null) is always true: readLockfiles seeds an empty { specifiers: {} } entry for every project the lockfile has no entry for, before any handler runs. What actually fired was tryFastUpdateImporters' own fallback, on the first declared alias with no recorded reference. So a new project reaches the handler as an importer that records nothing, and that — not a missing key — is what the new branch keys on. The dead gate is removed. pacquet does not seed, so its handler takes both shapes.

Which version the new edge gets is the rule #13779 established and measured: the already-locked version resolution would dedupe onto, because preferredVersions biases resolution toward what the graph already holds. Four things keep the resolver:

  • a dependency that resolves to a directory — workspace:, link:, file:, and a plain range on a workspace project's name, which linkWorkspacePackages may turn into a link. Only the resolver decides that, and linkedPackagesAreUpToDate would not catch a wrong guess: it looks a workspace package up by the recorded version, so a registry version recorded where a link belonged reads as up to date. Break-tested in both stacks.
  • a specifier that is not a semver range (aliases, tags, git, tarballs, catalog:).
  • a range no locked version satisfies — only the resolver can fetch.
  • a range several locked versions satisfy under resolutionMode: time-based or lowest-direct. Those modes resolve a direct dependency to the lowest satisfying version, so "the highest locked version" is the wrong end of the range — but only for a run that leaves the manifest alone, so which end applies is not a property of the lockfile. Rather than model that, the reuse declines when the candidates are ambiguous; with one candidate the two ends coincide, so an exact specifier keeps its fast path. Caught by Qodo in review, break-tested in both stacks, and it fixes the same latent gap in the existing changed-range reuse from fix: reuse the version resolution would dedupe onto for a changed range #13779. The overrides handler keeps taking the highest: resolutionMode moves only direct dependencies, and an override names a package at any depth.

A new importer is the one edit that adds reachability, so the shared epilogue has to recompute the optional flags rather than assume them: a package that until now only optional dependencies reached can stop being optional. GraphEdits.movedAcrossOptional is renamed optionalFlagsAreStale since it now covers both causes.

isDirectoryDependency already existed in the settings handler and is reused rather than restated; the same in pacquet, along with workspace_package_names.

Confirmed rather than assumed, as every item of #13696 asks: two byte-identity tests run the same addition through the fast path and through forceFullResolution and compare the written lockfile. The second is on a resolutionMode: time-based lockfile, where the new project's dependency was transitive-only before and so carries no publish date of its own — the files still match, so no time bail is needed.

Not covered, unchanged from before: a new project declaring peerDependencies that autoInstallPeers folds into its dependencies. The candidate fails satisfiesPackageManifest and the run falls back to the resolver, exactly as today. The same gap already applies to existing importers with auto-installed peers, so it belongs in its own change.

Squash Commit Body

Adding a package to a workspace always paid a full resolution, even
when every dependency it declared was already locked for a sibling —
the normal case for a package scaffolded from a template. The importers
handler now writes such a project's whole entry from the versions the
lockfile already holds, by the rule pnpm/pnpm#13779 established for a
single changed range: the already-locked version resolution would
dedupe onto.

The project arrives as an importer with nothing recorded rather than a
missing one, because reading the lockfile seeds an empty entry for
every project that has none. The gate that asked whether every project
had an importer was therefore always satisfied; the fallback that
actually fired was the handler's, on the first alias with no recorded
reference. pacquet does not seed, so its handler takes both shapes.

A dependency that resolves to a directory keeps the resolver, since
only it decides whether a plain range on a workspace project's name
becomes a link. So do a non-semver specifier and a range no locked
version satisfies.

So does a range several locked versions satisfy under `resolutionMode:
time-based` or `lowest-direct`. Those modes resolve a direct dependency
to the lowest satisfying version, and they apply only to a run that
leaves the manifest alone, so which end of the range wins is not a
property of the lockfile. With one candidate the two ends coincide, so
an exact specifier keeps its fast path. This closes the same gap in the
changed-range reuse. The overrides handler keeps taking the highest:
`resolutionMode` moves only direct dependencies, and an override names
a package at any depth.

A new importer is the one edit that adds reachability, so the shared
epilogue has to recompute the `optional` flags rather than leave them:
a package only optional dependencies reached can stop being optional.
`GraphEdits.movedAcrossOptional` becomes `optionalFlagsAreStale` to
cover both causes.

Both stacks. A byte-identity test runs the same addition through the
fast path and through a forced resolution, including on a time-based
lockfile, where the new direct dependency was transitive-only before
and so carries no publish date of its own.

Item 3 of pnpm/pnpm#13696, closes pnpm/pnpm#13800.

Checklist

  • I checked the referenced issue and verified that none of the PRs
    already linked to it solves it.
  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.

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

Summary by CodeRabbit

  • New Features

    • Added faster lockfile updates when adding workspace packages.
    • Reuses compatible locked dependency versions without full dependency resolution.
    • Initializes new workspace projects from available lockfile data while preserving dependency settings.
  • Bug Fixes

    • Falls back to resolution when suitable locked versions are unavailable.
    • Respects resolution mode when selecting reusable versions.
    • Improves handling of directory, invalid-range, workspace-related, and ambiguous dependencies.
    • Refreshes optional dependency metadata when necessary.

Adding a package to a workspace always paid a full resolution, even
when every dependency it declared was already locked for a sibling —
the normal case for a package scaffolded from a template. The importers
handler now writes such a project's whole entry from the versions the
lockfile already holds, by the rule #13779 established for a
single changed range: the highest locked version satisfying each
declared range, which is what resolution would settle on.

The project arrives as an importer with nothing recorded rather than a
missing one, because reading the lockfile seeds an empty entry for
every project that has none. The gate that asked whether every project
had an importer was therefore always satisfied; the fallback that
actually fired was the handler's, on the first alias with no recorded
reference.

A dependency that resolves to a directory keeps the resolver, since
only it decides whether a plain range on a workspace project's name
becomes a link. So do a non-semver specifier and a range no locked
version satisfies.

A new importer is the one edit that adds reachability, so the shared
epilogue has to recompute the `optional` flags rather than leave them:
a package only optional dependencies reached can stop being optional.
`GraphEdits.movedAcrossOptional` becomes `optionalFlagsAreStale` to
cover both causes.

Both stacks. A byte-identity test runs the same addition through the
fast path and through a forced resolution, including on a time-based
lockfile, where the new direct dependency was transitive-only before
and so carries no publish date of its own.

Item 3 of #13696, closes #13800.
Copilot AI lite review requested due to automatic review settings August 11, 2026 02:08

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 11, 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: d26abd51-13d0-4434-9d75-079e5686540f

📥 Commits

Reviewing files that changed from the base of the PR and between 2911ca8 and ecc7948.

📒 Files selected for processing (1)
  • pnpm/crates/package-manager/src/fast_update_importers.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • pnpm/crates/package-manager/src/fast_update_importers.rs

📝 Walkthrough

Walkthrough

The fast lockfile-update path now creates missing workspace importers from compatible locked versions. It preserves manifest metadata, applies resolution-mode-aware selection, and recomputes optional reachability. Unsupported or unavailable dependencies fall back to resolution.

Changes

New workspace importer fast update

Layer / File(s) Summary
Rust importer planning and workspace metadata
pnpm/crates/package-manager/src/fast_update_importers.rs, pnpm/crates/package-manager/src/fast_update_compose.rs, pnpm/crates/package-manager/src/fast_update_settings.rs
Importer plans retain manifests and workspace package names. Drift detection receives project manifests and resolution-mode information.
Rust importer reconstruction and version selection
pnpm/crates/package-manager/src/fast_update_importers.rs, pnpm/crates/package-manager/src/fast_update_overrides.rs
Missing or empty importers are rebuilt from suitable locked versions. Selection respects resolution mode and rejects unsupported or ambiguous matches.
Optional state and fast-update wiring
pnpm/crates/package-manager/src/fast_update_lockfile.rs, pnpm11/installing/deps-installer/src/install/index.ts, pnpm11/installing/deps-installer/src/install/tryComposeFastUpdates.ts, pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts, pnpm11/installing/deps-installer/src/install/tryFastUpdateSettings.ts
Fast-update options include workspace package metadata. Optional flags are recomputed when graph state becomes stale.
Fast-update validation and release support
pnpm/crates/package-manager/src/fast_update_importers/tests.rs, pnpm11/installing/deps-installer/test/install/*, .changeset/new-importer-fast-update.md
Tests cover locked-version reuse, resolver fallback, workspace dependencies, optional flags, and resolution modes. Existing callers provide the new option. The changeset documents the behavior.

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

Sequence Diagram(s)

sequenceDiagram
  participant Workspace as Workspace installation
  participant Composer as tryComposeFastUpdates
  participant ImporterUpdater as tryFastUpdateImporters
  participant Lockfile as Lockfile graph
  Workspace->>Composer: Provide project manifests and workspacePackages
  Composer->>ImporterUpdater: Plan importer updates
  ImporterUpdater->>Lockfile: Find compatible locked versions
  alt All dependencies are compatible
    ImporterUpdater->>Lockfile: Insert reconstructed importer
    Lockfile->>Lockfile: Recompute optional flags
  else Dependency requires resolution
    ImporterUpdater-->>Composer: Return false
    Composer-->>Workspace: Fall back to resolver
  end
Loading

Possibly related issues

  • pnpm/pnpm#13800 — Directly tracks fast lockfile updates for new workspace importers.
  • pnpm/pnpm#13798 — Covers reuse of satisfying locked versions with resolver fallback.
  • pnpm/pnpm#13696 — Covers broader fast lockfile updates, including new importer handling.

Possibly related PRs

  • pnpm/pnpm#13779 — Modifies fast importer updates to reuse compatible locked versions.
  • pnpm/pnpm#13784 — Modifies fast lockfile importer update logic for adding importers.
  • pnpm/pnpm#13790 — Modifies importer drift detection and composition for workspace changes.

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

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-13800

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: Fast-update lockfile when adding a new workspace importer

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Populate a new workspace project’s importer from already-locked versions to avoid full resolution.
• Fall back to the resolver for directory deps, non-semver specifiers, or unsatisfied ranges.
• Recompute optional reachability flags when new importer edges are introduced; add parity tests.
Diagram

graph TD
  A["mutateModules (install)"] --> B["tryComposeFastUpdates"] --> C["tryFastUpdateImporters"] --> D[("pnpm-lock.yaml")]
  B --> E["Workspace packages"] --> C
  C --> F["locked-version importer fill"] --> D
  C --> G{{"Resolver (full)"}} --> D
  F --> H["finishGraphEdits: recompute optional flags"] --> D

  subgraph Legend
    direction LR
    _m["Module"] ~~~ _db[("Lockfile")] ~~~ _ext{{"Fallback resolver"}}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Always full-resolve on new importer
  • ➕ Simplest correctness story; resolver decides links/tags/unsatisfied ranges
  • ➖ Regresses performance for common “template-scaffolded” workspace additions where everything is already locked
2. Invoke resolver in a lockfile-only / no-fetch mode for new importers
  • ➕ Centralizes version/link decisions in resolver code paths
  • ➕ Could reduce bespoke logic around highest-locked-version selection
  • ➖ Requires (or expands) resolver APIs/flags; risk of subtle behavioral drift
  • ➖ Might still be more expensive than direct lockfile reuse and still needs workspace-link handling
3. Compute importer entry by reusing dependency graph snapshots (instead of package list scan)
  • ➕ Potentially more direct mapping from reachable graph to importer entry
  • ➖ Adds complexity in deriving “direct” deps vs transitive snapshots
  • ➖ Still needs special-casing for directory-like dependencies and non-semver specifiers

Recommendation: The PR’s approach (synthesize a new importer from existing locked versions, with explicit and conservative fallbacks) is the best tradeoff: it captures the common fast path while preserving correctness by delegating ambiguous cases (directory/linkable deps, non-semver specifiers, and unsatisfied ranges) to the resolver. The added lockfile parity tests meaningfully reduce risk and make this preferable to introducing new resolver modes or more graph-based derivations.

Files changed (17) +522 / -30

Enhancement (4) +158 / -15
fast_update_compose.rsPass project manifests into importer drift detection +1/-0

Pass project manifests into importer drift detection

• Extends the Rust fast-update composition to provide project manifest metadata to importer drift detection, enabling workspace-aware decisions for new importers.

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

fast_update_importers.rsSynthesize new importer from locked versions; fix drift detection for missing importer +93/-10

Synthesize new importer from locked versions; fix drift detection for missing importer

• Enhances the Rust importer fast-update handler to detect “new” importers that record no dependencies and populate their entries from already-locked versions. Adds conservative resolver fallbacks (directory deps, non-semver, unsatisfied ranges), reuses shared settings helpers, and treats a missing importer with non-empty manifest deps as drift.

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

index.tsRemove dead “missing importer” gate; pass workspace packages into fast update +1/-2

Remove dead “missing importer” gate; pass workspace packages into fast update

• Removes an always-true precondition for fast updates (importer entry existence) and threads workspacePackages into tryComposeFastUpdates so the importer handler can detect linkable workspace deps.

pnpm11/installing/deps-installer/src/install/index.ts

tryFastUpdateImporters.tsFast-update new importer from locked versions with conservative fallbacks +63/-3

Fast-update new importer from locked versions with conservative fallbacks

• Detects a seeded-but-empty importer as a new project and writes its full importer entry from highest locked versions satisfying manifest ranges. Falls back to resolver on directory/linkable deps, non-semver specifiers, or missing satisfying locked versions; marks optional flags stale when reachability increases.

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts

Refactor (4) +29 / -12
fast_update_lockfile.rsRename and broaden optional-flag staleness tracking +5/-4

Rename and broaden optional-flag staleness tracking

• Renames GraphEdits.moved_across_optional to optional_flags_are_stale and updates the finalization condition so optional flags are recomputed when edges are added or moved across optionalDependencies.

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

fast_update_settings.rsExport directory-dependency and workspace-name helpers +10/-2

Export directory-dependency and workspace-name helpers

• Makes is_directory_dependency and workspace_package_names public within the crate and documents their semantics so importer fast-update can reuse consistent workspace-link detection.

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

tryComposeFastUpdates.tsThread workspacePackages and rename optional staleness flag +8/-5

Thread workspacePackages and rename optional staleness flag

• Extends composed fast-update options to include workspacePackages, and renames movedAcrossOptional to optionalFlagsAreStale to reflect both moves and additions affecting optional reachability.

pnpm11/installing/deps-installer/src/install/tryComposeFastUpdates.ts

tryFastUpdateSettings.tsExport isDirectoryDependency for reuse by importer handler +6/-1

Export isDirectoryDependency for reuse by importer handler

• Exports the directory-dependency predicate (including workspace-sibling range handling) so importer fast-update can share the exact same decision logic as settings fast-update.

pnpm11/installing/deps-installer/src/install/tryFastUpdateSettings.ts

Tests (8) +328 / -3
tests.rsAdd Rust unit tests for new importer behavior and optional recomputation +88/-0

Add Rust unit tests for new importer behavior and optional recomputation

• Introduces tests covering writing a new importer from locked versions, rejecting missing locked deps, rejecting workspace-sibling dependencies, and ensuring optional flags are recomputed when reachability changes.

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

catalogFastUpdate.tsUpdate composed fast-update tests to provide workspacePackages +1/-1

Update composed fast-update tests to provide workspacePackages

• Adjusts test helper calls to tryComposeFastUpdates to include workspacePackages, matching the new required options signature.

pnpm11/installing/deps-installer/test/install/catalogFastUpdate.ts

composedFastUpdate.tsPlumb workspacePackages through composed fast-update test cases +6/-0

Plumb workspacePackages through composed fast-update test cases

• Updates composed fast-update tests to pass workspacePackages (empty map in these scenarios) after the API change.

pnpm11/installing/deps-installer/test/install/composedFastUpdate.ts

ignoredOptionalDependencies.tsUpdate ignored-optional fast-update tests for new options +1/-0

Update ignored-optional fast-update tests for new options

• Adds workspacePackages to the tryComposeFastUpdates invocation in ignoredOptionalDependencies tests to satisfy the updated API.

pnpm11/installing/deps-installer/test/install/ignoredOptionalDependencies.ts

importerGroupMoveFastUpdate.tsUpdate importer-group-move tests for new options +1/-1

Update importer-group-move tests for new options

• Updates helper wrapper around tryComposeFastUpdates to pass workspacePackages after the signature change.

pnpm11/installing/deps-installer/test/install/importerGroupMoveFastUpdate.ts

importerRemovalFastUpdate.tsUpdate importer-removal tests for new options +1/-1

Update importer-removal tests for new options

• Updates helper wrapper around tryComposeFastUpdates to pass workspacePackages after the signature change.

pnpm11/installing/deps-installer/test/install/importerRemovalFastUpdate.ts

lockedVersionReuse.tsUpdate locked-version reuse tests for new options +4/-0

Update locked-version reuse tests for new options

• Adds workspacePackages to composed fast-update invocations in lockedVersionReuse tests.

pnpm11/installing/deps-installer/test/install/lockedVersionReuse.ts

newImporterFastUpdate.tsAdd integration tests ensuring new-importer fast path matches full resolution +226/-0

Add integration tests ensuring new-importer fast path matches full resolution

• Adds new Jest tests validating that adding a workspace project reuses locked versions without resolver requests, selects the highest satisfying locked version, falls back when necessary, recomputes optional flags, and produces byte-identical lockfiles to full resolution (including time-based lockfiles).

pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts

Documentation (1) +7 / -0
new-importer-fast-update.mdAdd changeset for new-importer fast-update behavior +7/-0

Add changeset for new-importer fast-update behavior

• Adds a patch changeset for pnpm, pacquet, and deps-installer describing the new fast path when adding a workspace project whose dependencies are already locked.

.changeset/new-importer-fast-update.md

@greptile-apps

greptile-apps Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (3): Last reviewed commit: "perf(pacquet): keep the locked-version p..." | Re-trigger Greptile

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

Inline comments:
In `@pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts`:
- Around line 73-83: Update the TypeScript fast-update flow around the importer
lookup in tryFastUpdateImporters to reconstruct a missing
lockfile.importers[project.id] from locked versions, matching
writeImporterFromLockedVersions behavior in the Rust path, instead of
immediately returning false. Preserve the existing dependency-change handling
and optionalFlagsAreStale updates, and add coverage for both a sole missing
importer and a missing importer combined with another importer change.

In `@pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts`:
- Around line 134-149: Extend the fast-update regression coverage in
pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts around
tryComposeFastUpdates with equivalent workspace: and link: dependency cases,
covering both excludeLinksFromLockfile settings and the expected resolver
fallback. Add matching Rust cases in
pnpm/crates/package-manager/src/fast_update_importers/tests.rs around the
existing tests, using the corresponding configuration so TypeScript and Rust
behavior remain identical.
- Around line 35-52: Expand the regression coverage in
pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts:35-52 and
pnpm/crates/package-manager/src/fast_update_importers/tests.rs:773-796 by
seeding at least two locked versions of `@pnpm.e2e/foo` that satisfy the requested
range, then assert the reconstructed new importer records the highest compatible
version; keep both TypeScript and Rust tests behaviorally equivalent.
🪄 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: 08ce3644-8c40-4e6a-b928-bbc5f37789a6

📥 Commits

Reviewing files that changed from the base of the PR and between ac97bc1 and 2b67d7e.

📒 Files selected for processing (17)
  • .changeset/new-importer-fast-update.md
  • pnpm/crates/package-manager/src/fast_update_compose.rs
  • pnpm/crates/package-manager/src/fast_update_importers.rs
  • pnpm/crates/package-manager/src/fast_update_importers/tests.rs
  • pnpm/crates/package-manager/src/fast_update_lockfile.rs
  • pnpm/crates/package-manager/src/fast_update_settings.rs
  • pnpm11/installing/deps-installer/src/install/index.ts
  • pnpm11/installing/deps-installer/src/install/tryComposeFastUpdates.ts
  • pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts
  • pnpm11/installing/deps-installer/src/install/tryFastUpdateSettings.ts
  • pnpm11/installing/deps-installer/test/install/catalogFastUpdate.ts
  • pnpm11/installing/deps-installer/test/install/composedFastUpdate.ts
  • pnpm11/installing/deps-installer/test/install/ignoredOptionalDependencies.ts
  • pnpm11/installing/deps-installer/test/install/importerGroupMoveFastUpdate.ts
  • pnpm11/installing/deps-installer/test/install/importerRemovalFastUpdate.ts
  • pnpm11/installing/deps-installer/test/install/lockedVersionReuse.ts
  • pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                                            main                                   pr
-----                                            ----                                   --
lockfile/parse_pnpm_lock                         1.04     12.7±0.18ms    29.5 MB/sec    1.00     12.2±0.06ms    30.7 MB/sec
packument/parse                                  1.03     42.9±0.35µs  1547.4 MB/sec    1.00     41.5±0.08µs  1597.3 MB/sec
tarball/download_dependency                      1.01      2.5±0.10ms  1767.5 KB/sec    1.00      2.4±0.10ms  1777.3 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.08    195.1±9.30ms 82.0 KElem/sec    1.00    181.4±2.99ms 88.2 KElem/sec
workspace_resolution/hoist_heavy                 1.12    276.2±2.92ms        ? ?/sec    1.00    246.0±1.20ms        ? ?/sec

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Wrong version in lowest-direct ✓ Resolved 🐞 Bug ≡ Correctness
Description
The new new-importer fast-update path always picks the highest locked version satisfying a semver
range, but the resolver explicitly picks the lowest satisfying version for direct deps under
resolutionMode: lowest-direct (and uses a dedicated “pick lowest” mode for time-based). This can
make the fast-updated lockfile disagree with a full resolution, changing installed versions and
causing avoidable lockfile churn under those modes.
Code

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[R164-167]

+    if (isDirectoryDependency(alias, specifier, workspacePackages)) return false
+    if (semver.validRange(specifier) == null) return false
+    const version = highestLockedVersionSatisfying(lockfile, alias, specifier)
+    if (version == null) return false
Relevance

●● Moderate

No close precedent; team recently codified “highest locked satisfying”, but lowest-direct/time-based
might require divergence.

PR-#13779

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed code path chooses the highest already-locked satisfying version when writing a new
importer entry, while the resolver codebase explicitly enables a “pick lowest” policy for
time-based/lowest-direct when resolving direct dependencies, so the fast path can produce
different results than full resolution under those modes.

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-179]
pnpm11/installing/deps-resolver/src/resolveDependencies.ts[638-663]
pnpm11/installing/deps-resolver/src/resolveDependencies.ts[756-799]
pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[118-123]
pnpm/crates/package-manager/src/fast_update_importers.rs[197-235]

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 new-project fast path (`writeImporterFromLockedVersions` in TS and `importer_from_locked_versions` in Rust) always selects the highest locked semver version satisfying a range. This is incompatible with resolver behavior under `resolutionMode: lowest-direct` (and potentially `time-based`), where the resolver’s selection policy for direct dependencies differs.

## Issue Context
- TS resolver sets `pickLowestVersion` when `ctx.resolutionMode` is `time-based` or `lowest-direct`, meaning the fast path cannot assume “highest locked” matches full resolution.
- Rust resolver has an explicit `pick_lowest_direct` option for `time-based`/`lowest-direct`.

## Fix Focus Areas
- pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-180]
- pnpm/crates/package-manager/src/fast_update_importers.rs[120-139]
- pnpm/crates/package-manager/src/fast_update_importers.rs[203-235]

## Suggested fix
1. Read the effective resolution mode (prefer `lockfile.settings?.resolutionMode`, falling back to default `highest`).
2. If the mode is `lowest-direct` (and, conservatively, `time-based` unless proven equivalent), **disable the new-importer fast path** by returning `false`/`None` so the resolver runs.
  - This is the safe fix because the resolver may legitimately choose a version that is not present in the lockfile (especially in `lowest-direct`), which the fast path cannot discover without querying the registry.
3. Add a regression test that:
  - Uses `resolutionMode: lowest-direct`.
  - Has a lockfile with two satisfying locked versions for a dependency (e.g. `[email protected]` and `[email protected]`, range `^1.0.0`).
  - Asserts fast-update falls back (or exactly matches full resolution if you implement lowest-direct selection precisely).

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



Remediation recommended

2. Collects all satisfying versions ✓ Resolved 🐞 Bug ➹ Performance
Description
locked_version_resolution_would_pick() clones every satisfying Version into a Vec, adding allocation
and extra copying in a function invoked inside per-importer/per-dependency loops. This increases
CPU/memory overhead for fast updates when many locked versions satisfy a range (wide ranges or large
lockfiles).
Code

pnpm/crates/package-manager/src/fast_update_importers.rs[R327-330]

+        if version.satisfies(range) {
+            satisfying.push(version.clone());
        }
    }
-    highest
Relevance

●●● Strong

Team recently accepted allocation-reduction optimizations in this fast-update codepath; this is a
similar low-risk perf improvement.

PR-#13762

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The function explicitly clones each satisfying version into a Vec and then computes max, which is
additional work beyond the unavoidable scan of the package-key set. It is called from the
per-importer/per-alias update loop, so the extra allocation/cloning cost can repeat many times in a
single fast-update run.

pnpm/crates/package-manager/src/fast_update_importers.rs[312-335]
pnpm/crates/package-manager/src/fast_update_importers.rs[125-169]

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_version_resolution_would_pick()` collects all satisfying versions into a `Vec<Version>` and clones each element, then calls `.max()`. This adds avoidable allocation and cloning overhead in a helper that is called repeatedly during fast importer updates.

### Issue Context
The helper runs inside the importer-update loop (and also when synthesizing a new importer), so the overhead is multiplied by the number of manifest dependencies processed.

### Fix Focus Areas
- pnpm/crates/package-manager/src/fast_update_importers.rs[318-335]

### Suggested fix
- Replace the `Vec<Version>` with a one-pass approach:
 - Track the current `best: Option<Version>` for the highest-pick case.
 - If `resolution_picks_lowest` is true, return `None` as soon as a *second* satisfying version is found (no need to collect them).
 - Avoid cloning when possible by moving `version` into `best` (depending on the return type of `version_semver()`).

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


3. Missing trailing comma in install helper 📘 Rule violation ⚙ Maintainability
Description
New multi-line TypeScript function parameter lists in the install test helper and
writeImporterFromLockedVersions omit a trailing comma on the last parameter. This violates the
repository’s trailing-comma requirement, reducing formatter consistency and increasing diff noise on
future edits.
Code

pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts[R195-198]

+  const install = async (
+    projects: WorkspaceProject[],
+    extraOptions?: { forceFullResolution: boolean }
+  ): Promise<string[]> => {
Relevance

●● Moderate

Trailing-comma fixes are inconsistently treated (some accepted, many rejected as style-only).

PR-#13779
PR-#13792

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript constructs; in the newly
added test file, the install helper’s parameter list spans multiple lines and its last parameter
extraOptions?: { forceFullResolution: boolean } does not end with a comma, and in
writeImporterFromLockedVersions the multi-line parameter list similarly ends with
workspacePackages: WorkspacePackages without a trailing comma, demonstrating non-compliance in
both locations.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts[195-198]
pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-161]

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

## Issue description
Multi-line TypeScript function parameter lists are missing a trailing comma on the last parameter, violating the repo’s formatting/compliance rule and increasing diff noise in future edits.

## Issue Context
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript constructs to keep diffs stable and formatting consistent. The newly added/modified functions have multi-line parameter lists where the final parameter currently does not end with a comma.

## Fix Focus Areas
- pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts[195-198]
- pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-161]

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



Informational

4. No early ambiguity exit 🐞 Bug ➹ Performance ⭐ New
Description
locked_version_resolution_would_pick() only checks satisfying > 1 && resolution_picks_lowest after
finishing the full scan of packages, even though once the second satisfying version is found the
result is guaranteed to be None. This can add avoidable work in the fast-update hot path when
resolution_picks_lowest is enabled and a range matches multiple locked versions.
Code

pnpm/crates/package-manager/src/fast_update_importers.rs[R335-337]

+    if satisfying > 1 && resolution_picks_lowest {
+        return None;
+    }
Relevance

● Weak

Similar fast_update_importers scan-optimization was rejected previously; team seems to decline micro
perf tweaks here.

PR-#13790

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The function increments a satisfying counter for every matching version and only after the loop
returns None when satisfying > 1 && resolution_picks_lowest, which means it will scan all
package keys even though the outcome is already determined as soon as the second match is found. The
same file shows this function is invoked inside loops over manifest dependencies, so the extra
scanning can repeat many times during a fast update.

pnpm/crates/package-manager/src/fast_update_importers.rs[312-339]
pnpm/crates/package-manager/src/fast_update_importers.rs[125-189]

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_version_resolution_would_pick()` defers the ambiguity decision (`satisfying > 1 && resolution_picks_lowest`) until after iterating all package keys. When `resolution_picks_lowest` is true, the function can return `None` immediately upon encountering the second satisfying locked version.

### Issue Context
This function is called in per-importer/per-dependency loops (both for updating existing importers and for building a new importer from locked versions), so avoiding unnecessary full-map scans matters most on large lockfiles.

### Fix Focus Areas
- pnpm/crates/package-manager/src/fast_update_importers.rs[319-337]

### Suggested change
Inside the `if version.satisfies(range)` block, after incrementing `satisfying`, add:
- if `resolution_picks_lowest && satisfying > 1 { return None; }`

Optionally, only maintain `satisfying` when `resolution_picks_lowest` is true.

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


5. Repeated full lockfile scans 🐞 Bug ➹ Performance
Description
Building a new importer calls highestLockedVersionSatisfying/highest_locked_version_satisfying
once per declared dependency, and each call scans the entire lockfile.packages set. For large
lockfiles and template-generated projects with many dependencies, this makes the fast path do
O(packages×deps) work and can noticeably reduce the intended performance win.
Code

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[R163-166]

+  for (const [alias, specifier] of Object.entries(getManifestSpecifiers(project.manifest))) {
+    if (isDirectoryDependency(alias, specifier, workspacePackages)) return false
+    if (semver.validRange(specifier) == null) return false
+    const version = highestLockedVersionSatisfying(lockfile, alias, specifier)
Relevance

● Weak

Similar perf requests to avoid repeated lockfile scans in fast-update were previously rejected.

PR-#13600
PR-#13779

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The PR adds a loop that calls the existing “scan all packages and select best version” helper for
every manifest dependency of a new project. The helper itself iterates all package entries, so the
new path multiplies that scan cost by the number of dependencies.

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-171]
pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[196-213]
pnpm/crates/package-manager/src/fast_update_importers.rs[203-225]
pnpm/crates/package-manager/src/fast_update_importers.rs[292-311]

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 new importer-writing fast path (`writeImporterFromLockedVersions` in TS and `importer_from_locked_versions` in Rust) calls the “pick highest locked satisfying version” helper for every dependency, and the helper scans *all* lockfile package entries each time. This creates O(packages×deps) behavior for new projects.

## Issue Context
This work happens on a hot path (install / lockfile fast-update). Although it may still beat a full resolution, it is avoidable CPU work that scales poorly with lockfile size.

## Fix Focus Areas
- pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-213]
- pnpm/crates/package-manager/src/fast_update_importers.rs[203-311]

## Suggested fix
### TypeScript
1. In `writeImporterFromLockedVersions`, do a single pass over `lockfile.packages` to build an index:
  - `Map<string, string[]>` of `alias -> semverVersions[]` (excluding non-semver, peer-suffixed, registry-qualified like current helper does).
2. For each dependency in the new importer, choose the best version by filtering that alias’s version list by `semver.satisfies(version, specifier)` and taking `rcompare` max (or min if you later support lowest-direct/time-based semantics).

### Rust
1. Similarly, build `HashMap<PkgName, Vec<Version>>` once from `packages.keys()` (excluding peer-suffix / registry-qualified keys).
2. For each dependency, choose max satisfying from the per-alias list.

### Validation
Add a microbenchmark or targeted perf test (large `packages` + many deps) to confirm reduced CPU time versus repeated full scans.

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


Grey Divider

Context used
✅ Compliance rules (platform): 26 rules

Grey Divider

Tip of the day
💡 Did you know, you can group findings by type and pick your Finding display, from Minimal to Full

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous review results

Review updated until commit ecc7948

Results up to commit 2b67d7e ⚖️ Balanced


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


Action required
1. Wrong version in lowest-direct ✓ Resolved 🐞 Bug ≡ Correctness
Description
The new new-importer fast-update path always picks the highest locked version satisfying a semver
range, but the resolver explicitly picks the lowest satisfying version for direct deps under
resolutionMode: lowest-direct (and uses a dedicated “pick lowest” mode for time-based). This can
make the fast-updated lockfile disagree with a full resolution, changing installed versions and
causing avoidable lockfile churn under those modes.
Code

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[R164-167]

+    if (isDirectoryDependency(alias, specifier, workspacePackages)) return false
+    if (semver.validRange(specifier) == null) return false
+    const version = highestLockedVersionSatisfying(lockfile, alias, specifier)
+    if (version == null) return false
Relevance

●● Moderate

No close precedent; team recently codified “highest locked satisfying”, but lowest-direct/time-based
might require divergence.

PR-#13779

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed code path chooses the highest already-locked satisfying version when writing a new
importer entry, while the resolver codebase explicitly enables a “pick lowest” policy for
time-based/lowest-direct when resolving direct dependencies, so the fast path can produce
different results than full resolution under those modes.

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-179]
pnpm11/installing/deps-resolver/src/resolveDependencies.ts[638-663]
pnpm11/installing/deps-resolver/src/resolveDependencies.ts[756-799]
pnpm/crates/resolving-deps-resolver/src/resolve_importer.rs[118-123]
pnpm/crates/package-manager/src/fast_update_importers.rs[197-235]

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 new-project fast path (`writeImporterFromLockedVersions` in TS and `importer_from_locked_versions` in Rust) always selects the highest locked semver version satisfying a range. This is incompatible with resolver behavior under `resolutionMode: lowest-direct` (and potentially `time-based`), where the resolver’s selection policy for direct dependencies differs.

## Issue Context
- TS resolver sets `pickLowestVersion` when `ctx.resolutionMode` is `time-based` or `lowest-direct`, meaning the fast path cannot assume “highest locked” matches full resolution.
- Rust resolver has an explicit `pick_lowest_direct` option for `time-based`/`lowest-direct`.

## Fix Focus Areas
- pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-180]
- pnpm/crates/package-manager/src/fast_update_importers.rs[120-139]
- pnpm/crates/package-manager/src/fast_update_importers.rs[203-235]

## Suggested fix
1. Read the effective resolution mode (prefer `lockfile.settings?.resolutionMode`, falling back to default `highest`).
2. If the mode is `lowest-direct` (and, conservatively, `time-based` unless proven equivalent), **disable the new-importer fast path** by returning `false`/`None` so the resolver runs.
  - This is the safe fix because the resolver may legitimately choose a version that is not present in the lockfile (especially in `lowest-direct`), which the fast path cannot discover without querying the registry.
3. Add a regression test that:
  - Uses `resolutionMode: lowest-direct`.
  - Has a lockfile with two satisfying locked versions for a dependency (e.g. `[email protected]` and `[email protected]`, range `^1.0.0`).
  - Asserts fast-update falls back (or exactly matches full resolution if you implement lowest-direct selection precisely).

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



Remediation recommended
2. Missing trailing comma in install helper 📘 Rule violation ⚙ Maintainability
Description
New multi-line TypeScript function parameter lists in the install test helper and
writeImporterFromLockedVersions omit a trailing comma on the last parameter. This violates the
repository’s trailing-comma requirement, reducing formatter consistency and increasing diff noise on
future edits.
Code

pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts[R195-198]

+  const install = async (
+    projects: WorkspaceProject[],
+    extraOptions?: { forceFullResolution: boolean }
+  ): Promise<string[]> => {
Relevance

●● Moderate

Trailing-comma fixes are inconsistently treated (some accepted, many rejected as style-only).

PR-#13779
PR-#13792

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript constructs; in the newly
added test file, the install helper’s parameter list spans multiple lines and its last parameter
extraOptions?: { forceFullResolution: boolean } does not end with a comma, and in
writeImporterFromLockedVersions the multi-line parameter list similarly ends with
workspacePackages: WorkspacePackages without a trailing comma, demonstrating non-compliance in
both locations.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts[195-198]
pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-161]

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

## Issue description
Multi-line TypeScript function parameter lists are missing a trailing comma on the last parameter, violating the repo’s formatting/compliance rule and increasing diff noise in future edits.

## Issue Context
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript constructs to keep diffs stable and formatting consistent. The newly added/modified functions have multi-line parameter lists where the final parameter currently does not end with a comma.

## Fix Focus Areas
- pnpm11/installing/deps-installer/test/install/newImporterFastUpdate.ts[195-198]
- pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-161]

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



Informational
3. Repeated full lockfile scans 🐞 Bug ➹ Performance
Description
Building a new importer calls highestLockedVersionSatisfying/highest_locked_version_satisfying
once per declared dependency, and each call scans the entire lockfile.packages set. For large
lockfiles and template-generated projects with many dependencies, this makes the fast path do
O(packages×deps) work and can noticeably reduce the intended performance win.
Code

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[R163-166]

+  for (const [alias, specifier] of Object.entries(getManifestSpecifiers(project.manifest))) {
+    if (isDirectoryDependency(alias, specifier, workspacePackages)) return false
+    if (semver.validRange(specifier) == null) return false
+    const version = highestLockedVersionSatisfying(lockfile, alias, specifier)
Relevance

● Weak

Similar perf requests to avoid repeated lockfile scans in fast-update were previously rejected.

PR-#13600
PR-#13779

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The PR adds a loop that calls the existing “scan all packages and select best version” helper for
every manifest dependency of a new project. The helper itself iterates all package entries, so the
new path multiplies that scan cost by the number of dependencies.

pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-171]
pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[196-213]
pnpm/crates/package-manager/src/fast_update_importers.rs[203-225]
pnpm/crates/package-manager/src/fast_update_importers.rs[292-311]

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 new importer-writing fast path (`writeImporterFromLockedVersions` in TS and `importer_from_locked_versions` in Rust) calls the “pick highest locked satisfying version” helper for every dependency, and the helper scans *all* lockfile package entries each time. This creates O(packages×deps) behavior for new projects.

## Issue Context
This work happens on a hot path (install / lockfile fast-update). Although it may still beat a full resolution, it is avoidable CPU work that scales poorly with lockfile size.

## Fix Focus Areas
- pnpm11/installing/deps-installer/src/install/tryFastUpdateImporters.ts[157-213]
- pnpm/crates/package-manager/src/fast_update_importers.rs[203-311]

## Suggested fix
### TypeScript
1. In `writeImporterFromLockedVersions`, do a single pass over `lockfile.packages` to build an index:
  - `Map<string, string[]>` of `alias -> semverVersions[]` (excluding non-semver, peer-suffixed, registry-qualified like current helper does).
2. For each dependency in the new importer, choose the best version by filtering that alias’s version list by `semver.satisfies(version, specifier)` and taking `rcompare` max (or min if you later support lowest-direct/time-based semantics).

### Rust
1. Similarly, build `HashMap<PkgName, Vec<Version>>` once from `packages.keys()` (excluding peer-suffix / registry-qualified keys).
2. For each dependency, choose max satisfying from the per-alias list.

### Validation
Add a microbenchmark or targeted perf test (large `packages` + many deps) to confirm reduced CPU time versus repeated full scans.

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


Results up to commit 2911ca8 ⚖️ Balanced


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


Remediation recommended
1. Collects all satisfying versions ✓ Resolved 🐞 Bug ➹ Performance
Description
locked_version_resolution_would_pick() clones every satisfying Version into a Vec, adding allocation
and extra copying in a function invoked inside per-importer/per-dependency loops. This increases
CPU/memory overhead for fast updates when many locked versions satisfy a range (wide ranges or large
lockfiles).
Code

pnpm/crates/package-manager/src/fast_update_importers.rs[R327-330]

+        if version.satisfies(range) {
+            satisfying.push(version.clone());
        }
    }
-    highest
Relevance

●●● Strong

Team recently accepted allocation-reduction optimizations in this fast-update codepath; this is a
similar low-risk perf improvement.

PR-#13762

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The function explicitly clones each satisfying version into a Vec and then computes max, which is
additional work beyond the unavoidable scan of the package-key set. It is called from the
per-importer/per-alias update loop, so the extra allocation/cloning cost can repeat many times in a
single fast-update run.

pnpm/crates/package-manager/src/fast_update_importers.rs[312-335]
pnpm/crates/package-manager/src/fast_update_importers.rs[125-169]

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_version_resolution_would_pick()` collects all satisfying versions into a `Vec<Version>` and clones each element, then calls `.max()`. This adds avoidable allocation and cloning overhead in a helper that is called repeatedly during fast importer updates.

### Issue Context
The helper runs inside the importer-update loop (and also when synthesizing a new importer), so the overhead is multiplied by the number of manifest dependencies processed.

### Fix Focus Areas
- pnpm/crates/package-manager/src/fast_update_importers.rs[318-335]

### Suggested fix
- Replace the `Vec<Version>` with a one-pass approach:
 - Track the current `best: Option<Version>` for the highest-pick case.
 - If `resolution_picks_lowest` is true, return `None` as soon as a *second* satisfying version is found (no need to collect them).
 - Avoid cloning when possible by moving `version` into `best` (depending on the return type of `version_semver()`).

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

@blacksmith-sh

This comment has been minimized.

@codecov-commenter

codecov-commenter commented Aug 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.25%. Comparing base (ac97bc1) to head (ecc7948).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13803   +/-   ##
=======================================
  Coverage   88.24%   88.25%           
=======================================
  Files         624      624           
  Lines      101807   101887   +80     
=======================================
+ Hits        89837    89917   +80     
  Misses      11970    11970           

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

`resolutionMode: time-based` and `lowest-direct` resolve a direct
dependency to the *lowest* version satisfying its range, so reusing the
highest locked one recorded a version a full resolution would not. The
reuse now declines whenever those modes are on and more than one locked
version satisfies: the modes only apply to a run that leaves the
manifest alone, so which end of the range wins is not a property of the
lockfile. With exactly one locked candidate the two ends coincide and
the reuse still applies, which is why an exact specifier keeps its fast
path. This covers the changed-range reuse as much as the new importer.

The overrides handler keeps taking the highest: `resolutionMode` moves
only direct dependencies, and an override names a package at any depth.

Also from review:

- Detect and rebuild an importer the lockfile omits entirely, not only
  one it records as empty. Reading the lockfile seeds an empty entry so
  only the empty shape reaches production, but the two stacks disagreed
  on the absent one, and pacquet does not seed.
- The reuse tests locked a single satisfying version, so they could not
  tell the highest from the first. Both stacks now lock two.
- Cover the `workspace:` and `link:` protocols explicitly rather than
  only a plain range on a workspace project's name.
- Drop the narration from the test fixture helper; its name carries it.

The time-based test pinned the transitive version it promoted to a
direct dependency, which time-based resolution is free to choose
differently — it did on CI. It now reads back whatever the initial
install locked.
Copilot AI review requested due to automatic review settings August 11, 2026 02:28

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.

greptile-apps[bot]
greptile-apps Bot previously approved these changes Aug 11, 2026
@zkochan

zkochan commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

CI note: Rust CI / Test / macos failed on attempt 1 in import_indexed_dir::tests::concurrent_importers_of_one_shared_slot_both_succeed, with RemoveExisting { … DirectoryNotEmpty }.

That is not this PR — it is in pnpm/crates/deps-restorer, which the diff does not touch, and it passed on every other target in the same matrix. It is a real race in the product path rather than a test-only artifact, so rather than re-run it away silently I filed #13806 for it and re-ran the job.


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

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 2911ca8

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

Collecting the satisfying versions to take their max allocated a Vec and
cloned every candidate, where a running maximum clones only the winner.
The ambiguity guard the pick-lowest resolution modes need is a count,
not the collection.
Copilot AI review requested due to automatic review settings August 11, 2026 02:40
zkochan added a commit that referenced this pull request Aug 11, 2026
pnpm remove already skips resolution when the lockfile proves the
outcome; its twin did not. `pnpm add <pkg>@<version>` re-resolved the
whole graph even when the requested version was one the lockfile
already held — promoting a transitive dependency to a direct one, or
adding to a second workspace package what a first one already depends
on.

The rule is the one #13779 established: resolution reuses the
already-locked version it would dedupe onto rather than fetching a
higher one, because preferredVersions biases it toward what the graph
already holds. The importers handler now records a brand-new importer
edge at that version, under the group the manifest declares, alongside
the whole-new-project entry #13803 added. It reuses that
change's guards: a range several locked versions satisfy under
`resolutionMode: time-based` or `lowest-direct` keeps the resolver,
since those pick the low end and only for a run that leaves the
manifest alone, and so does a plain range on a workspace project's
name, which may resolve to a link instead. A lockfile carrying `time`
keeps it too: `time` records a publish date per direct dependency and
is only pruned on save, never extended, so a package promoted into
that position would be missing the one a resolution records.

`installSome` cannot edit the manifests in place the way
`uninstallSome` does — the resolution path reads them to tell a new
dependency from a re-added one, and reads them again to pick the range
style it saves — so the edit is staged on copies, handed to the fast
update and its freshness gates, and the context takes it only once the
rewrite commits. The range a selector saves is computed with the
resolver's own rule, extracted as `calcVersionRange` in
`@pnpm/pkg-manifest.utils` alongside the `inferRangeSpecStyle` it needs.

pacquet needed only the gate: `add` already pins the manifest before
the install runs, so `may_fast_update_lockfile` admits `InstallSome`
and `add` stops forcing `preferFrozenLockfile` off. `update` is also
`InstallSome` and keeps its explicit opt-out, so it is unaffected. Its
manifest pin still consults the registry packument; only the
install-side resolution is skipped.

The narrow cut is a plain registry specifier. A dist tag, an alias, a
`workspace:`/`catalog:`/git/tarball specifier, `--save-peer`, a
`catalogMode` other than `manual`, an overridden package, and a version
nothing locked satisfies all keep the resolver.

Closes #13798.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zkochan added a commit that referenced this pull request Aug 11, 2026
pnpm remove already skips resolution when the lockfile proves the
outcome; its twin did not. `pnpm add <pkg>@<version>` re-resolved the
whole graph even when the requested version was one the lockfile
already held — promoting a transitive dependency to a direct one, or
adding to a second workspace package what a first one already depends
on.

The rule is the one #13779 established: resolution reuses the
already-locked version it would dedupe onto rather than fetching a
higher one, because preferredVersions biases it toward what the graph
already holds. The importers handler now records a brand-new importer
edge at that version, under the group the manifest declares, alongside
the whole-new-project entry #13803 added. It reuses that
change's guards: a range several locked versions satisfy under
`resolutionMode: time-based` or `lowest-direct` keeps the resolver,
since those pick the low end and only for a run that leaves the
manifest alone, and so does a plain range on a workspace project's
name, which may resolve to a link instead. A lockfile carrying `time`
keeps it too: `time` records a publish date per direct dependency and
is only pruned on save, never extended, so a package promoted into
that position would be missing the one a resolution records.

`installSome` cannot edit the manifests in place the way
`uninstallSome` does — the resolution path reads them to tell a new
dependency from a re-added one, and reads them again to pick the range
style it saves — so the edit is staged on copies, handed to the fast
update and its freshness gates, and the context takes it only once the
rewrite commits. The range a selector saves is computed with the
resolver's own rule, extracted as `calcVersionRange` in
`@pnpm/pkg-manifest.utils` alongside the `inferRangeSpecStyle` it needs.

pacquet needed only the gate: `add` already pins the manifest before
the install runs, so `may_fast_update_lockfile` admits `InstallSome`
and `add` stops forcing `preferFrozenLockfile` off. `update` is also
`InstallSome` and keeps its explicit opt-out, so it is unaffected. Its
manifest pin still consults the registry packument; only the
install-side resolution is skipped.

The narrow cut is a plain registry specifier. A dist tag, an alias, a
`workspace:`/`catalog:`/git/tarball specifier, `--save-peer`, a
`catalogMode` other than `manual`, an overridden package, and a version
nothing locked satisfies all keep the resolver.

Closes #13798.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zkochan added a commit that referenced this pull request Aug 11, 2026
)

pnpm remove already skips resolution when the lockfile proves the
outcome; its twin did not. `pnpm add <pkg>@<version>` re-resolved the
whole graph even when the requested version was one the lockfile
already held — promoting a transitive dependency to a direct one, or
adding to a second workspace package what a first one already depends
on.

The rule is the one #13779 established: resolution reuses the
already-locked version it would dedupe onto rather than fetching a
higher one, because preferredVersions biases it toward what the graph
already holds. The importers handler now records a brand-new importer
edge at that version, under the group the manifest declares, alongside
the whole-new-project entry #13803 added. It reuses that
change's guards: a range several locked versions satisfy under
`resolutionMode: time-based` or `lowest-direct` keeps the resolver,
since those pick the low end and only for a run that leaves the
manifest alone, and so does a plain range on a workspace project's
name, which may resolve to a link instead. A lockfile carrying `time`
keeps it too: `time` records a publish date per direct dependency and
is only pruned on save, never extended, so a package promoted into
that position would be missing the one a resolution records.

`installSome` cannot edit the manifests in place the way
`uninstallSome` does — the resolution path reads them to tell a new
dependency from a re-added one, and reads them again to pick the range
style it saves — so the edit is staged on copies, handed to the fast
update and its freshness gates, and the context takes it only once the
rewrite commits. The range a selector saves is computed with the
resolver's own rule, extracted as `calcVersionRange` in
`@pnpm/pkg-manifest.utils` alongside the `inferRangeSpecStyle` it needs.

pacquet needed only the gate: `add` already pins the manifest before
the install runs, so `may_fast_update_lockfile` admits `InstallSome`
and `add` stops forcing `preferFrozenLockfile` off. `update` is also
`InstallSome` and keeps its explicit opt-out, so it is unaffected. Its
manifest pin still consults the registry packument; only the
install-side resolution is skipped.

The narrow cut is a plain registry specifier. A dist tag, an alias, a
`workspace:`/`catalog:`/git/tarball specifier, `--save-peer`, a
`catalogMode` other than `manual`, an overridden package, and a version
nothing locked satisfies all keep the resolver.

Closes #13798.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet product: pnpm@11 reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fast lockfile update for a new workspace project whose dependencies are already locked

3 participants