Skip to content

fix(pacquet): honor --no-optional for transitive optional dependencies - #12965

Merged
zkochan merged 4 commits into
mainfrom
fix-no-optional
Jul 13, 2026
Merged

zkochan merged 4 commits into
mainfrom
fix-no-optional

Conversation

@zkochan

@zkochan zkochan commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

What

A fresh install with --no-optional (includeOptionalDeps: false) only dropped the root importer's own optionalDependencies. A transitive optional — an optionalDependencies entry of a resolved package — stayed in the graph and was materialized into node_modules. So install <pkg> --no-optional still linked <pkg>'s optional deps.

Why

The dependency_groups filter excludes the Optional group when building the root importer's direct-dep set, but extract_children in the deps resolver descends into every resolved package's optionalDependencies unconditionally. The frozen-lockfile path already compensates for this (it adds every optional snapshot to the transient optional_excluded skip set when Optional isn't requested); the fresh-resolve path did not.

Fix

In install_with_fresh_lockfile.rs, after resolution, mirror the frozen path: when Optional is not in the requested dependency_groups, add every built_lockfile snapshot with optional == true to skipped.add_optional_excluded(key). Those snapshots:

  • are excluded from materialization (through the same gate installability skips use),
  • stay out of .modules.yaml.skipped, so a later install without --no-optional brings them back,
  • remain in the lockfile.

The fresh path already re-derives snapshot.optional (optional-only-reachable) in dependencies_graph_to_lockfile.rs, so the flag is available.

Tests

  • New CLI integration test no_optional_excludes_transitive_optional_dependencies — installs @pnpm.e2e/pkg-with-good-optional (whose optionalDependencies pull in is-positive) with --no-optional and asserts the transitive optional is not materialized while the prod dep is. Verified it fails without the fix and passes with it.
  • Also adds a package-manager regression test install_with_drop_all_seed_policy_bumps_dependency_within_range guarding an adjacent path: Install with UpdateSeedPolicy::DropAll (what napi install({ update: true }) uses) must re-resolve within range and drop the lockfile pin. It passes on unchanged engine code — included to lock down the contract that programmatic install --update consumers depend on.

cargo fmt + clippy -D warnings clean; all install/prune integration tests and the 693 package-manager unit tests pass.

Context

Found while bringing Bit up on the Rust engine (bit install --no-optional leaked optional deps). No behavior change for installs that don't pass --no-optional / a restricted dependency-group set.

🤖 Generated with Claude Code


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes
    • Improved pnpm install --no-optional so optional-only snapshots are not materialized while their entries remain in the lockfile for future optional-enabled installs.
    • With seed-policy DropAll, installs now correctly pick the highest version within the compatible range after widening dependency ranges.
  • Tests
    • Added end-to-end coverage that verifies transitive optional dependencies are absent from node_modules after --no-optional, then restored by a subsequent standard install.
    • Added integration coverage for the DropAll update behavior during install({ update: true }).

Copilot AI review requested due to automatic review settings July 13, 2026 10:27

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 13, 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

Fresh installs now skip optional lockfile snapshots when optional dependencies are disabled. Tests cover transitive optional dependency exclusion and DropAll updates that re-resolve widened dependency ranges.

Changes

Install resolution behavior

Layer / File(s) Summary
Exclude optional snapshots during fresh installs
pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs, pnpm/crates/cli/tests/install.rs
Fresh installs record optional snapshots as skipped when optional dependencies are disabled, while preserving them in the lockfile; CLI coverage verifies exclusion and later restoration.
Re-resolve widened dependency ranges
pnpm/crates/package-manager/src/install/tests.rs
A two-pass install test verifies that UpdateSeedPolicy::DropAll replaces an exact 100.0.0 pin with the highest matching 100.1.0 version after widening the dependency range.

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

Sequence Diagram(s)

sequenceDiagram
  participant CLI test
  participant Fresh lockfile installer
  participant Lockfile
  participant Virtual store
  CLI test->>Fresh lockfile installer: install --no-optional
  Fresh lockfile installer->>Lockfile: mark optional snapshots skipped
  Fresh lockfile installer->>Virtual store: materialize non-optional dependencies
  CLI test->>Virtual store: verify optional package is absent
  CLI test->>Fresh lockfile installer: install with Optional enabled
  Fresh lockfile installer->>Virtual store: restore optional package
Loading

Possibly related PRs

  • pnpm/pnpm#11919: Changes how optional flags for transitive dependency snapshots are computed.
  • pnpm/pnpm#12809: Also updates fresh-lockfile installation to track skipped optional snapshots.

Suggested labels: product: pacquet

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-no-optional

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

Honor --no-optional for transitive optional deps on fresh installs

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Exclude optional-only snapshots from materialization when Optional dependency group is not
 requested.
• Add CLI integration test ensuring --no-optional does not install transitive optional
 dependencies.
• Add package-manager regression test for UpdateSeedPolicy::DropAll resolving highest in-range
 versions.
Diagram

graph TD
A["pacquet CLI"] --> B["Install fresh"] --> C["built lockfile"] --> D["SkippedSnapshots"] --> E["CreateVirtualStore"] --> F["node_modules"]
B --> G["dependency_groups"] --> D
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Filter optional edges during graph traversal
  • ➕ Reduces resolver graph size earlier; fewer snapshots to consider downstream
  • ➕ Makes omission of transitive optionals explicit at dependency extraction time
  • ➖ Riskier: changes resolver semantics and may diverge from frozen-lockfile behavior
  • ➖ Harder to preserve current lockfile contents while only affecting materialization
2. Unify frozen vs fresh enforcement in a shared helper
  • ➕ Eliminates behavior drift between install paths
  • ➕ Centralizes policy for optional/runtime exclusion in one place
  • ➖ Refactor effort: requires careful API design across install modules
  • ➖ May be too broad for a targeted bug fix PR

Recommendation: The chosen approach (mirroring the frozen-lockfile path by populating SkippedSnapshots.optional_excluded from snapshot.optional) is the best low-risk fix: it preserves lockfile contents, only affects materialization, and aligns fresh installs with the already-correct frozen path. A follow-up refactor to share enforcement logic between frozen/fresh paths could further reduce future drift.

Files changed (3) +186 / -0

Bug fix (1) +21 / -0
install_with_fresh_lockfile.rsSkip optional-only snapshots during fresh installs when Optional group is excluded +21/-0

Skip optional-only snapshots during fresh installs when Optional group is excluded

• When 'DependencyGroup::Optional' is not requested (e.g., '--no-optional'), iterates built lockfile snapshots and adds those marked 'snapshot.optional' to 'SkippedSnapshots' via 'add_optional_excluded'. This mirrors the frozen-lockfile path so transitive optional dependencies are not materialized while remaining in the lockfile and not persisted to '.modules.yaml.skipped'.

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

Tests (2) +165 / -0
install.rsAdd CLI test for transitive optional exclusion with --no-optional +36/-0

Add CLI test for transitive optional exclusion with --no-optional

• Adds an integration test that installs a package whose own 'optionalDependencies' include 'is-positive'. Asserts '--no-optional' still installs the prod dependency but does not materialize the transitive optional into the virtual store.

pnpm/crates/cli/tests/install.rs

tests.rsAdd regression test for DropAll update seed re-resolving within range +129/-0

Add regression test for DropAll update seed re-resolving within range

• Introduces a tokio integration test that first pins a dependency version via install, then widens the range and re-runs install with 'UpdateSeedPolicy::DropAll'. Verifies the second install re-resolves to the highest in-range version, guarding the NAPI 'install({ update: true })' contract.

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

@greptile-apps

greptile-apps Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge. The fix is a targeted, well-guarded addition to one code path, with no changes to the lockfile format or on-disk state files.

The change mirrors an already-working pattern from the frozen-lockfile path and is gated behind is_full_install to avoid incorrectly dropping optionals during pacquet add. Both the CLI test and the unit test provide concrete regression coverage. TypeScript pnpm already handles this correctly, so no cross-stack change is needed.

No files require special attention.

Reviews (7): Last reviewed commit: "fix(pacquet): scope the --no-optional ex..." | Re-trigger Greptile

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Action required

1. EngineStrict check bypassed ✓ Resolved 🐞 Bug ≡ Correctness
Description
InstallWithFreshLockfile now skips the only compute_skipped_snapshots call when
dependency_groups excludes Optional, which also suppresses engine_strict hard-fail behavior
for incompatible required (non-optional) packages. This can let a --no-optional +
engineStrict=true fresh install proceed without the intended error and diverges from the
frozen-lockfile path.
Code

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[R1464-1466]

        let needs_optional_installability_check = !config.force
+            && dependency_groups.contains(&DependencyGroup::Optional)
            && built_lockfile.packages.as_ref().is_some_and(|packages| {
Evidence
The fresh-lockfile path’s installability pass is now disabled whenever Optional isn’t requested,
but that pass is also the only place in this path that can raise an engine_strict error for
required deps. The frozen-lockfile path still performs this installability check independently of
--no-optional, and only then applies the transient optional exclusions.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1458-1470]
pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1576-1596]
pnpm/crates/package-manager/src/installability.rs[381-535]
pnpm/crates/package-manager/src/install_frozen_lockfile.rs[721-770]

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

## Issue description
`InstallWithFreshLockfile` now gates `needs_optional_installability_check` on `dependency_groups.contains(Optional)`. When the user runs with `--no-optional`, this prevents running `compute_skipped_snapshots` entirely, which is also the code path that enforces `engine_strict` as a hard error for incompatible *required* (non-optional) dependencies.

## Issue Context
- Fresh-lockfile path computes `skipped` via `compute_skipped_snapshots` only when `needs_optional_installability_check` is true.
- `compute_skipped_snapshots` enforces `engine_strict` by erroring on required engine mismatch.
- Frozen-lockfile path still runs `compute_skipped_snapshots` before applying `--no-optional` exclusions.

## Fix Focus Areas
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1458-1596]

### Suggested approach
- Decouple “do we need optional skipping?” from “do we need required engineStrict enforcement?”. For example:
 - Run `compute_skipped_snapshots` whenever `config.engine_strict` is true (and constraints exist), even if Optional isn’t requested.
 - Keep the new `--no-optional` optional-exclusion loop as-is.
- Consider adding a regression test covering `engineStrict=true` + `--no-optional` where a required dependency has an incompatible `engines.node` and the install must fail.

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



Remediation recommended

2. Brittle modules.yaml assertion 🐞 Bug ⚙ Maintainability ⭐ New
Description
The new test asserts .modules.yaml does not contain the substring is-positive, which can fail
even when behavior is correct if that string appears in unrelated .modules.yaml fields. This makes
the test prone to future false failures and does not precisely validate the intended invariant (“not
recorded in skipped”).
Code

pnpm/crates/cli/tests/install.rs[R99-104]

+    let modules_yaml = fs::read_to_string(workspace.join("node_modules/.modules.yaml"))
+        .expect("read .modules.yaml");
+    assert!(
+        !modules_yaml.contains("is-positive"),
+        "a `--no-optional` exclusion must not be recorded in .modules.yaml.skipped:\n{modules_yaml}",
+    );
Evidence
The test currently uses a raw substring check over the entire YAML file, while .modules.yaml has a
dedicated skipped array field and the test suite already uses the structured reader elsewhere—so
the current assertion is both less precise and more fragile than the established approach.

pnpm/crates/cli/tests/install.rs[93-104]
pnpm/crates/modules-yaml/src/lib.rs[218-248]
pnpm/crates/cli/tests/config_dependencies.rs[203-208]

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

### Issue description
`no_optional_excludes_transitive_optional_dependencies` reads `node_modules/.modules.yaml` as raw text and asserts `!modules_yaml.contains("is-positive")`. This is an imprecise proxy for “not recorded in `.modules.yaml.skipped` / `skipped`” and can become flaky if `.modules.yaml` gains/changes fields that legitimately mention the package name.

### Issue Context
The repo already has a typed reader for `.modules.yaml` (`pacquet_modules_yaml::read_modules_layout`) and the manifest schema includes a dedicated `skipped: Vec<String>` field.

### Fix Focus Areas
- pnpm/crates/cli/tests/install.rs[93-104]

### Suggested fix
Replace the substring assertion with structured parsing, e.g.:
- Read modules layout via `pacquet_modules_yaml::read_modules_layout::<pacquet_modules_yaml::Host>(&workspace.join("node_modules"))`.
- Assert `modules.skipped` does **not** contain the excluded package key (or is empty if that’s the intended invariant for this scenario).

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


3. Redundant no-optional host check ✓ Resolved 🐞 Bug ➹ Performance
Description
In InstallWithFreshLockfile::run, --no-optional now excludes every snapshot.optional == true
from materialization, but the code can still run the optional installability pass (and host/node
detection) even though it can no longer affect what gets installed. This adds avoidable overhead
(including potential node --version probing) to the install --no-optional hot path on graphs
with optional installability constraints.
Code

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[R1605-1613]

+        if !dependency_groups.contains(&DependencyGroup::Optional)
+            && let Some(snapshots) = built_lockfile.snapshots.as_ref()
+        {
+            for (key, snapshot) in snapshots {
+                if snapshot.optional {
+                    skipped.add_optional_excluded(key.clone());
+                }
+            }
+        }
Evidence
The fresh path computes needs_optional_installability_check based on optional constraints and may
run the installability/host detection pass regardless of requested dependency groups, but after this
PR it also unconditionally marks every snapshot.optional as optional_excluded when Optional
isn’t requested; CreateVirtualStore drops any snapshot where skipped.contains(key) is true, so
those optional snapshots won’t be installed anyway, making the optional installability work
redundant for --no-optional.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1458-1506]
pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1572-1613]
pnpm/crates/package-manager/src/installability.rs[403-516]
pnpm/crates/package-manager/src/create_virtual_store.rs[388-396]

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

### Issue description
After this PR, the fresh-lockfile install path excludes all `snapshot.optional == true` entries from materialization when `DependencyGroup::Optional` is not requested. However, the earlier `needs_optional_installability_check` gate can still trigger host detection + `compute_skipped_snapshots`, which is now redundant for `--no-optional` installs because those optional snapshots are already excluded via `SkippedSnapshots::optional_excluded`.

### Issue Context
- `needs_optional_installability_check` is currently computed solely from `any_optional_installability_constraint(...)` and does **not** consider whether Optional deps are requested.
- `compute_skipped_snapshots` only adds skips for `snapshot.optional` entries, i.e. the same population now excluded by `--no-optional`.

### Proposed fix
Gate `needs_optional_installability_check` (and therefore host detection + `compute_skipped_snapshots`) on `dependency_groups.contains(&DependencyGroup::Optional)`.
- Keep `needs_hoisted_installability_host` unchanged (it can still be required for hoisted installs).

### Fix Focus Areas
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1458-1506]
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1572-1613]

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



Informational

4. Unreserved optional_excluded HashSet 🐞 Bug ➹ Performance
Description
On --no-optional, InstallWithFreshLockfile::run inserts all snapshot.optional keys into
SkippedSnapshots one-by-one without reserving capacity, which can cause avoidable HashSet
growth/rehashing on large lockfiles. This is low impact (amortized, and only on the no-optional
path), but easy to tighten.
Code

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[R1602-1609]

+        if !dependency_groups.contains(&DependencyGroup::Optional)
+            && let Some(snapshots) = built_lockfile.snapshots.as_ref()
+        {
+            for (key, snapshot) in snapshots {
+                if snapshot.optional {
+                    skipped.add_optional_excluded(key.clone());
+                }
+            }
Evidence
The new --no-optional block inserts potentially many keys into SkippedSnapshots via
add_optional_excluded, and SkippedSnapshots stores optional_excluded as a default-capacity
HashSet with no reservation in the insertion path.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1594-1610]
pnpm/crates/package-manager/src/installability.rs[68-157]

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

### Issue description
`--no-optional` now loops all snapshots and calls `skipped.add_optional_excluded(key.clone())` for each optional snapshot. `SkippedSnapshots` uses default-capacity `HashSet`s, so inserting many entries can trigger a few realloc/rehash steps.

### Issue Context
This is a low-severity perf micro-optimization, but it’s on an install path and is easy to address with a small API addition on `SkippedSnapshots`.

### Fix Focus Areas
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1594-1610]
- pnpm/crates/package-manager/src/installability.rs[68-157]

### Suggested fix
- Add a small method on `SkippedSnapshots`, e.g. `reserve_optional_excluded(additional: usize)` that calls `self.optional_excluded.reserve(additional)`.
- In the new `--no-optional` block, call `skipped.reserve_optional_excluded(snapshots.len())` (or a tighter estimate if available) before the insert loop.

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


Grey Divider

Previous review results

Review updated until commit cfc640e

Results up to commit 6d0678e


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


Remediation recommended
1. Redundant no-optional host check ✓ Resolved 🐞 Bug ➹ Performance
Description
In InstallWithFreshLockfile::run, --no-optional now excludes every snapshot.optional == true
from materialization, but the code can still run the optional installability pass (and host/node
detection) even though it can no longer affect what gets installed. This adds avoidable overhead
(including potential node --version probing) to the install --no-optional hot path on graphs
with optional installability constraints.
Code

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[R1605-1613]

+        if !dependency_groups.contains(&DependencyGroup::Optional)
+            && let Some(snapshots) = built_lockfile.snapshots.as_ref()
+        {
+            for (key, snapshot) in snapshots {
+                if snapshot.optional {
+                    skipped.add_optional_excluded(key.clone());
+                }
+            }
+        }
Evidence
The fresh path computes needs_optional_installability_check based on optional constraints and may
run the installability/host detection pass regardless of requested dependency groups, but after this
PR it also unconditionally marks every snapshot.optional as optional_excluded when Optional
isn’t requested; CreateVirtualStore drops any snapshot where skipped.contains(key) is true, so
those optional snapshots won’t be installed anyway, making the optional installability work
redundant for --no-optional.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1458-1506]
pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1572-1613]
pnpm/crates/package-manager/src/installability.rs[403-516]
pnpm/crates/package-manager/src/create_virtual_store.rs[388-396]

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

### Issue description
After this PR, the fresh-lockfile install path excludes all `snapshot.optional == true` entries from materialization when `DependencyGroup::Optional` is not requested. However, the earlier `needs_optional_installability_check` gate can still trigger host detection + `compute_skipped_snapshots`, which is now redundant for `--no-optional` installs because those optional snapshots are already excluded via `SkippedSnapshots::optional_excluded`.

### Issue Context
- `needs_optional_installability_check` is currently computed solely from `any_optional_installability_constraint(...)` and does **not** consider whether Optional deps are requested.
- `compute_skipped_snapshots` only adds skips for `snapshot.optional` entries, i.e. the same population now excluded by `--no-optional`.

### Proposed fix
Gate `needs_optional_installability_check` (and therefore host detection + `compute_skipped_snapshots`) on `dependency_groups.contains(&DependencyGroup::Optional)`.
- Keep `needs_hoisted_installability_host` unchanged (it can still be required for hoisted installs).

### Fix Focus Areas
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1458-1506]
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1572-1613]

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


Results up to commit 311bb95


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


Informational
1. Unreserved optional_excluded HashSet 🐞 Bug ➹ Performance
Description
On --no-optional, InstallWithFreshLockfile::run inserts all snapshot.optional keys into
SkippedSnapshots one-by-one without reserving capacity, which can cause avoidable HashSet
growth/rehashing on large lockfiles. This is low impact (amortized, and only on the no-optional
path), but easy to tighten.
Code

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[R1602-1609]

+        if !dependency_groups.contains(&DependencyGroup::Optional)
+            && let Some(snapshots) = built_lockfile.snapshots.as_ref()
+        {
+            for (key, snapshot) in snapshots {
+                if snapshot.optional {
+                    skipped.add_optional_excluded(key.clone());
+                }
+            }
Evidence
The new --no-optional block inserts potentially many keys into SkippedSnapshots via
add_optional_excluded, and SkippedSnapshots stores optional_excluded as a default-capacity
HashSet with no reservation in the insertion path.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1594-1610]
pnpm/crates/package-manager/src/installability.rs[68-157]

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

### Issue description
`--no-optional` now loops all snapshots and calls `skipped.add_optional_excluded(key.clone())` for each optional snapshot. `SkippedSnapshots` uses default-capacity `HashSet`s, so inserting many entries can trigger a few realloc/rehash steps.

### Issue Context
This is a low-severity perf micro-optimization, but it’s on an install path and is easy to address with a small API addition on `SkippedSnapshots`.

### Fix Focus Areas
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1594-1610]
- pnpm/crates/package-manager/src/installability.rs[68-157]

### Suggested fix
- Add a small method on `SkippedSnapshots`, e.g. `reserve_optional_excluded(additional: usize)` that calls `self.optional_excluded.reserve(additional)`.
- In the new `--no-optional` block, call `skipped.reserve_optional_excluded(snapshots.len())` (or a tighter estimate if available) before the insert loop.

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


Results up to commit a4eb511


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


Action required
1. EngineStrict check bypassed ✓ Resolved 🐞 Bug ≡ Correctness
Description
InstallWithFreshLockfile now skips the only compute_skipped_snapshots call when
dependency_groups excludes Optional, which also suppresses engine_strict hard-fail behavior
for incompatible required (non-optional) packages. This can let a --no-optional +
engineStrict=true fresh install proceed without the intended error and diverges from the
frozen-lockfile path.
Code

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[R1464-1466]

        let needs_optional_installability_check = !config.force
+            && dependency_groups.contains(&DependencyGroup::Optional)
            && built_lockfile.packages.as_ref().is_some_and(|packages| {
Evidence
The fresh-lockfile path’s installability pass is now disabled whenever Optional isn’t requested,
but that pass is also the only place in this path that can raise an engine_strict error for
required deps. The frozen-lockfile path still performs this installability check independently of
--no-optional, and only then applies the transient optional exclusions.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1458-1470]
pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1576-1596]
pnpm/crates/package-manager/src/installability.rs[381-535]
pnpm/crates/package-manager/src/install_frozen_lockfile.rs[721-770]

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

## Issue description
`InstallWithFreshLockfile` now gates `needs_optional_installability_check` on `dependency_groups.contains(Optional)`. When the user runs with `--no-optional`, this prevents running `compute_skipped_snapshots` entirely, which is also the code path that enforces `engine_strict` as a hard error for incompatible *required* (non-optional) dependencies.

## Issue Context
- Fresh-lockfile path computes `skipped` via `compute_skipped_snapshots` only when `needs_optional_installability_check` is true.
- `compute_skipped_snapshots` enforces `engine_strict` by erroring on required engine mismatch.
- Frozen-lockfile path still runs `compute_skipped_snapshots` before applying `--no-optional` exclusions.

## Fix Focus Areas
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[1458-1596]

### Suggested approach
- Decouple “do we need optional skipping?” from “do we need required engineStrict enforcement?”. For example:
 - Run `compute_skipped_snapshots` whenever `config.engine_strict` is true (and constraints exist), even if Optional isn’t requested.
 - Keep the new `--no-optional` optional-exclusion loop as-is.
- Consider adding a regression test covering `engineStrict=true` + `--no-optional` where a required dependency has an incompatible `engines.node` and the install must fail.

ⓘ 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 13, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     23.3±0.86ms    16.1 MB/sec    1.00     23.4±2.52ms    16.0 MB/sec
packument/parse                1.00     78.9±0.62µs   840.9 MB/sec    1.01     79.3±1.13µs   836.2 MB/sec
tarball/download_dependency    1.01      6.5±0.19ms   662.7 KB/sec    1.00      6.5±0.08ms   666.4 KB/sec

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

🧹 Nitpick comments (3)
pnpm/crates/package-manager/src/install/tests.rs (2)

217-222: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Doc comment (///) on a private test function.

Per coding guidelines, rustdoc comments (///) are for public API contracts, and regular comments (//) are for implementation rationale. This is a private test fn explaining rationale, not a public contract.

As per coding guidelines: "Use rustdoc comments for public API contracts and regular comments for implementation rationale."

✏️ Suggested fix
-/// The napi `install` path with `update: true` — what `bit install
-/// --update` reaches — must re-resolve a dependency to the highest
-/// version in its range, overriding the lockfile pin. It runs through
-/// `Install` with `UpdateSeedPolicy::DropAll` (not the dedicated `Update`
-/// subcommand path), so this guards that the `DropAll` seed policy
-/// actually drops the pin and re-resolves.
+// The napi `install` path with `update: true` — what `bit install
+// --update` reaches — must re-resolve a dependency to the highest
+// version in its range, overriding the lockfile pin. It runs through
+// `Install` with `UpdateSeedPolicy::DropAll` (not the dedicated `Update`
+// subcommand path), so this guards that the `DropAll` seed policy
+// actually drops the pin and re-resolves.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/package-manager/src/install/tests.rs` around lines 217 - 222,
Replace the rustdoc comment above the private test function with a regular block
comment, preserving the existing rationale about the napi install path,
UpdateSeedPolicy::DropAll, and lockfile pin re-resolution.

217-345: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Solid regression test for DropAll seed-policy behavior.

The two-pass structure (pin exactly, widen the range, reload the lockfile, re-install with DropAll) correctly exercises the seed-drop + reuse-scope-none path in install_with_fresh_lockfile.rs and should fail without the fix.

Two small, optional improvements:

  • Consider also asserting that the old 100.0.0 slot under virtual_store_dir no longer exists after the DropAll install, to confirm the stale pinned version is pruned rather than just co-existing with the new one (mirrors the pattern in install_prunes_surplus_virtual_store_dir).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/package-manager/src/install/tests.rs` around lines 217 - 345,
Extend install_with_drop_all_seed_policy_bumps_dependency_within_range to assert
that the old 100.0.0 virtual-store slot no longer exists after the DropAll
install, alongside the existing 100.1.0 assertion, confirming stale pinned
packages are pruned.
pnpm/crates/cli/tests/install.rs (1)

56-90: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Good regression test for transitive optional exclusion; consider also covering the restorability claim.

This test correctly validates the core fix: the prod dependency stays installed and the transitive optional ([email protected]) is excluded. That directly guards against both under- and over-exclusion, per the review guide's "smallest correct change" concern.

The PR objective specifically calls out that excluded snapshots are "not recorded in .modules.yaml.skipped, allowing a later install without --no-optional to restore them" — that restorability behavior isn't exercised here. Consider adding an assertion (or a follow-up test) that inspects .modules.yaml for the absence of the optional exclusion from the permanent skipped list, or that a second install without --no-optional actually restores is-positive.

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

In `@pnpm/crates/cli/tests/install.rs` around lines 56 - 90, The regression test
no_optional_excludes_transitive_optional_dependencies should also verify
excluded optionals remain restorable. After the --no-optional install, run a
subsequent install without that flag and assert [email protected] is
materialized, or inspect .modules.yaml to confirm it was not permanently
recorded in the skipped list; prefer the end-to-end restoration assertion.
🤖 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.

Nitpick comments:
In `@pnpm/crates/cli/tests/install.rs`:
- Around line 56-90: The regression test
no_optional_excludes_transitive_optional_dependencies should also verify
excluded optionals remain restorable. After the --no-optional install, run a
subsequent install without that flag and assert [email protected] is
materialized, or inspect .modules.yaml to confirm it was not permanently
recorded in the skipped list; prefer the end-to-end restoration assertion.

In `@pnpm/crates/package-manager/src/install/tests.rs`:
- Around line 217-222: Replace the rustdoc comment above the private test
function with a regular block comment, preserving the existing rationale about
the napi install path, UpdateSeedPolicy::DropAll, and lockfile pin
re-resolution.
- Around line 217-345: Extend
install_with_drop_all_seed_policy_bumps_dependency_within_range to assert that
the old 100.0.0 virtual-store slot no longer exists after the DropAll install,
alongside the existing 100.1.0 assertion, confirming stale pinned packages are
pruned.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b76de492-323a-41c1-b848-3bce2ea0215c

📥 Commits

Reviewing files that changed from the base of the PR and between d3e1383 and 6d0678e.

📒 Files selected for processing (3)
  • pnpm/crates/cli/tests/install.rs
  • pnpm/crates/package-manager/src/install/tests.rs
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 13, 2026
@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix compilation error on generic IntoIterator

Replace .contains() with .into_iter().any(...) to fix a compilation error on the
generic IntoIterator.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs [1605-1608]

-if !dependency_groups.contains(&DependencyGroup::Optional)
+let has_optional = dependency_groups.into_iter().any(|g| matches!(g, DependencyGroup::Optional));
+if !has_optional
     && let Some(snapshots) = built_lockfile.snapshots.as_ref()
 {
     for (key, snapshot) in snapshots {
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: Identifies a compilation error because IntoIterator does not provide a .contains() method without further trait bounds, and provides a valid fix.

High
General
Separate let from boolean guard

Replace the let-chain syntax with a nested if-statement for compatibility and
readability.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs [1605-1607]

-if !dependency_groups.contains(&DependencyGroup::Optional)
-    && let Some(snapshots) = built_lockfile.snapshots.as_ref()
-{
-    // ...
+if let Some(snapshots) = built_lockfile.snapshots.as_ref() {
+    if !dependency_groups.contains(&DependencyGroup::Optional) {
+        // ...
+    }
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 1

__

Why: The project already uses the nightly let_chains feature, making this stylistic refactor unnecessary and potentially contrary to the established codebase style.

Low
  • More

Copilot AI review requested due to automatic review settings July 13, 2026 11:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@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/cli/tests/install.rs`:
- Around line 77-87: Extend the install test after the --no-optional assertions
by verifying the optional dependency snapshot remains in the lockfile and is
absent from .modules.yaml.skipped, then run a normal install and assert
virtual_store/[email protected] exists. Keep the existing assertions for
production dependency installation and initial optional-dependency exclusion.
🪄 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: 72485ee9-114b-48bc-a3ff-5d4b384f2443

📥 Commits

Reviewing files that changed from the base of the PR and between 6d0678e and 311bb95.

📒 Files selected for processing (3)
  • pnpm/crates/cli/tests/install.rs
  • pnpm/crates/package-manager/src/install/tests.rs
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs
  • pnpm/crates/package-manager/src/install/tests.rs

Comment thread pnpm/crates/cli/tests/install.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 311bb95

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

Auto-approved notes - no code suggestions found
- 'approve_pr_on_self_review' flag enabled

Copilot AI review requested due to automatic review settings July 13, 2026 11:13

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

Copy link
Copy Markdown
Member Author

Thanks — on the two Qodo findings:

  • Redundant no-optional host check (Bug 1) — fixed in f343e1c. needs_optional_installability_check is now gated on the Optional group being requested, so --no-optional skips the optional-installability pass (and its node --version probe) entirely. The hoisted-linker installability host detection is unaffected.
  • Unreserved optional_excluded HashSet (Bug 2) — declining. The optional-only snapshot set is small in practice and this runs only on the --no-optional path; a capacity reservation would add API surface to SkippedSnapshots for a negligible, amortized gain.

— Claude Code (Claude Fable 5)

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit cc1e265

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

Auto-approved notes - no code suggestions found
- 'approve_pr_on_self_review' flag enabled

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit a4eb511

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

Auto-approved notes - no code suggestions found
- 'approve_pr_on_self_review' flag enabled

Copilot AI review requested due to automatic review settings July 13, 2026 11:49

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

Copy link
Copy Markdown
Member Author

Update on the earlier "Redundant no-optional host check" reply: I've reverted that perf change. As the follow-up review caught, gating the optional-installability pass on the Optional group also suppressed engine_strict enforcement for required packages under --no-optional. Correctness over the minor perf win — the pass now runs unchanged.

— Claude Code (Claude Fable 5)

zkochan and others added 3 commits July 13, 2026 13:54
A fresh install with `--no-optional` dropped only the root importer's own
optionalDependencies. Transitive optionals — an `optionalDependencies` entry
of a resolved package — stayed in the graph and were materialized into
node_modules, so `install <pkg> --no-optional` still linked `<pkg>`'s optional
deps.

Mirror the frozen-lockfile path: after resolution, add every snapshot marked
optional (reachable only through optional edges, already computed on the fresh
lockfile) to the transient `optional_excluded` skip set when Optional is not in
the requested dependency groups. They propagate through the same gate as
installability skips, stay out of `.modules.yaml.skipped` (a later install
without the flag brings them back), and remain in the lockfile.

Co-Authored-By: Claude Fable 5 <[email protected]>
`install --update` reaches the engine as napi `install()` with `update: true`,
which runs `Install` with `UpdateSeedPolicy::DropAll` rather than the dedicated
`update` subcommand's `Update` path. Add a package-manager integration test
that pins a dependency at 100.0.0, then re-installs with `DropAll` against a
widened range and asserts it re-resolves to the highest in-range 100.1.0 — the
pin is dropped and the dependency is bumped.

Co-Authored-By: Claude Fable 5 <[email protected]>
…able

Strengthen the transitive-optional test to prove the full contract: the
excluded optional stays in the lockfile, is not recorded in
.modules.yaml.skipped, and is restored by a later install without
--no-optional.

Co-Authored-By: Claude Fable 5 <[email protected]>
@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.

Auto-approved notes - no code suggestions found
- 'approve_pr_on_self_review' flag enabled

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 2f53626

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

Auto-approved notes - no code suggestions found
- 'approve_pr_on_self_review' flag enabled

@zkochan

zkochan commented Jul 13, 2026

Copy link
Copy Markdown
Member Author

CI status: the failing tests are unrelated to this change

Every run of this branch fails only on the @pnpm/exe version-download tests, on all three platforms:

  • pacquet-cli::version version_flag_switches_to_project_package_manager_version
  • pacquet-cli::with with_version_downloads_and_runs_the_specified_pnpm_version
  • pacquet-cli::with with_version_ignores_the_package_manager_pin_and_uses_the_requested_version

They fail with no @pnpm/exe.<platform> native binary was found for this host — resolving @pnpm/[email protected]'s platform-specific binary (a transitive optional dependency, handled by the env-installer crate). Every other test passes (e.g. 1572/1572 non-version tests on ubuntu).

Why this is not caused by the change:

  • The change touches install_with_fresh_lockfile.rs (the fresh-install optional-exclusion path) plus two test files. @pnpm/exe resolution goes through env-installer (resolve_optional_subdeps.rs), which does not call that code, and the version/with tests are separate integration-test binaries from the added tests.
  • main passes these exact tests at the same base commit (e.g. run on 85efb4900b); only this branch fails them.
  • I rebased onto 85efb4900b (the #12866 concurrent-reads fix) on the chance it was resource-related — no change.

Best guess: the two added tests do real (npm-proxied) installs, and under nextest's parallelism the extra concurrent network load tips the large @pnpm/exe download over a resource limit — i.e. pre-existing fragility in these network tests rather than a logic issue. The PR's own tests (694 package-manager unit tests, the --no-optional and DropAll integration tests) pass locally and in CI.

Could a maintainer advise how you'd like to proceed — a re-run, or is this a known-flaky area? Happy to adjust the added tests if their network footprint is the trigger.

— Claude Code (Claude Fable 5)

The transitive-optional exclusion keyed off `dependency_groups` not containing
`Optional`. That is the right signal for a full `install --no-optional`, but a
partial `add` (and the package installs built on it — `dlx`, global add, and the
engine install in `self_update`) passes `dependency_groups` to name the manifest
group to save the added package under, not to express `--no-optional`. Those
callers pass `[Prod]`, so the exclusion wrongly dropped the added package's
transitive optionals — e.g. `@pnpm/exe`'s platform binary, which is an
optionalDependency — breaking `pnpm with <version>`, the packageManager-pinned
`--version`, and `dlx`.

Thread `is_full_install` into the fresh-lockfile path and gate the exclusion on
it. Full installs (including bit's napi `install`) still honor `--no-optional`;
partial add-style installs keep their optionals. The existing `version`, `with`,
and `dlx` integration tests cover the regression.

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings July 13, 2026 12:47

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

Copy link
Copy Markdown
Member Author

Correction: the version/with/dlx failures were caused by this change

My earlier note blaming flaky infra was wrong — thanks for pushing back. Root cause found and fixed in cfc640e.

The --no-optional exclusion keyed off dependency_groups not containing Optional. That's correct for a full install --no-optional, but a partial add — and the package installs built on it (dlx, global add, and the self_update engine install via run_install → add_package) — passes dependency_groups to name the manifest group to save under, not to express --no-optional. Those callers pass [Prod], so my exclusion wrongly dropped the added package's transitive optionals — including @pnpm/exe's platform binary (an optionalDependency), producing no @pnpm/exe.<platform> native binary was found. It only worked before my fix because the fresh-install path leaked transitive optionals unconditionally.

Fix: thread is_full_install into the fresh-lockfile path and gate the exclusion on it. Full installs (including bit's napi install) still honor --no-optional; partial add-style installs keep their optionals. Verified locally — version (3), with (9), dlx (3), global (7), install (33), and the 694 package-manager unit tests all pass. Those version/with/dlx tests are the regression guard.

— Claude Code (Claude Fable 5)

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit cfc640e

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

Auto-approved notes - no code suggestions found
- 'approve_pr_on_self_review' flag enabled

@zkochan
zkochan merged commit b8f856b into main Jul 13, 2026
30 of 32 checks passed
@zkochan
zkochan deleted the fix-no-optional branch July 13, 2026 13:12
zkochan added a commit to zkochan/bit that referenced this pull request Jul 13, 2026
Carries the --no-optional fix (pnpm/pnpm#12965): a fresh install with
--no-optional now excludes transitive optional dependencies from
materialization, scoped to full installs so partial add-style installs keep
their optionals. Verified: the install.e2e.ts "install --no-optional" test
("should not install optional dependencies") now passes.

Co-Authored-By: Claude Fable 5 <[email protected]>
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.

2 participants