Skip to content

test(pacquet): complete Stage 10 long-tail ports - #13161

Merged
zkochan merged 4 commits into
mainfrom
stage-10
Jul 19, 2026
Merged

zkochan merged 4 commits into
mainfrom
stage-10

Conversation

@zkochan

@zkochan zkochan commented Jul 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Completes Stage 10 of #13146 by porting the remaining long-tail pacquet suites for lockfile verification, optimistic repeat installs, catalogs, peer resolution, optional dependencies, install state, and hoisting.

Adds the missing optimistic repeat-install parity for ignored workspace-state settings and conflicted lockfiles. Features that are not implemented yet are represented by explicit known-failure boundaries in the port tracker.

This is Rust-only test/parity work. The corresponding TypeScript behavior is the upstream source coverage being ported.

Squash Commit Body

Port the remaining Stage 10 lockfile verification and optimistic repeat install coverage.

Add catalog, peer, optional dependency, install-state, and hoisting tests.

Record known-failure boundaries for features that are not implemented yet.

Related to pnpm/pnpm#13146.

Checklist

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

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


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
    • Prevents optimistic repeat installs when lockfiles include merge-conflict markers.
    • Re-adding packages via dist-tags now preserves the original dependency group (e.g., stays in devDependencies when appropriate).
    • Improves catalog save/persistence and lockfile snapshot accuracy across add/install/update flows.
    • Makes hoisting and lifecycle bin creation more resilient when target paths already exist.
    • Strengthens lockfile verification and cache consistency, including minimumReleaseAge edge cases.
  • Documentation
    • Updated the Rust test porting/coverage plan for newly handled scenarios.

Copilot AI review requested due to automatic review settings July 19, 2026 21:41

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 19, 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: 2a86fa8f-3025-4667-929c-26f8826465c8

📥 Commits

Reviewing files that changed from the base of the PR and between dae0c57 and 26ec0aa.

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

📝 Walkthrough

Walkthrough

This change adds merge-conflict detection to optimistic repeat installs and generalizes workspace-state drift handling. It also expands CLI, resolver, lockfile-verification, regression, known-failure, release, and test-porting coverage.

Changes

Pacquet behavior and test coverage

Layer / File(s) Summary
Optimistic repeat-install safeguards
pnpm/crates/package-manager/src/optimistic_repeat_install.rs, pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs
The fast path skips conflicted wanted or project lockfiles, supports ignored workspace-state settings, and tests pnpmfile, allowBuilds, and conflict behavior.
Lockfile verification and cache coverage
pnpm/crates/lockfile-verification/...
Tests cover cache fallback and invalidation, verifier policy handling, recorded paths, distinct resolutions, and rejected verification.
Dependency and peer resolution coverage
pnpm/crates/resolving-deps-resolver/..., pnpm/crates/resolving-npm-resolver/...
Tests cover optional flags, peer conflicts and workspace instances, release-age exclusions, and preservation of package metadata.
CLI workflow and install behavior
pnpm/crates/cli/tests/...
CLI tests cover dependency groups, catalogs, hoisting, reinstall artifacts, lifecycle-created bins, and known-failure boundaries.
Release and test-porting metadata
.changeset/calm-jars-smile.md, pnpm/plans/TEST_PORTING.md
The patch release note and porting plan record newly covered scenarios and known-failure boundaries.

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

Sequence Diagram(s)

sequenceDiagram
  participant Install as pacquet install
  participant Repeat as optimistic repeat-install check
  participant Lockfiles as workspace and project lockfiles
  Install->>Repeat: evaluate fast-path decision
  Repeat->>Lockfiles: scan modified lockfiles for conflict markers
  Lockfiles-->>Repeat: safe or conflict-marked status
  Repeat-->>Install: UpToDate or Skipped decision
Loading

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#12106 — Adjusts optimistic repeat-install handling for modified wanted lockfiles.
  • pnpm/pnpm#12315 — Modifies the same optimistic repeat-install fast-path logic.
  • pnpm/pnpm#13144 — Also changes optimistic repeat-install workspace-state matching.

Suggested labels: product: pacquet

Suggested reviewers: copilot

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

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

Stage 10 test ports + safer optimistic repeat installs (ignored settings, conflict locks)

🧪 Tests 🐞 Bug fix ✨ Enhancement 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Port remaining Stage 10 long-tail pnpm suites into pacquet’s Rust test harness.
• Harden optimistic repeat-install fast path by skipping on conflicted lockfiles and supporting
 ignored settings.
• Expand lockfile verification cache/recorder tests and document known-failure boundaries for
 unimplemented features.
Diagram

graph TD
  A["CLI integration tests"] --> B["pacquet CLI"] --> C["Optimistic repeat-install"] --> D["Workspace-state drift check"]
  C --> E["Lockfile conflict scan"]
  A --> F["Lockfile verification"] --> G["Verification cache + recorder"]
  A --> H["Resolvers (peer/optional/npm)"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Parse conflict markers as UTF-8 lines (instead of raw byte scan)
  • ➕ Can detect markers more semantically (e.g., ignore markers inside binary blobs).
  • ➕ Easier to extend to other marker variants if needed.
  • ➖ More overhead and complexity for a hot-path guard.
  • ➖ Lockfiles are text; byte-scan is typically sufficient and faster.
2. Use a HashSet for ignored workspace-state setting keys
  • ➕ O(1) membership checks and clearer intent when the ignore list grows.
  • ➖ Adds allocation/boilerplate; current lists are tiny and call sites are few.

Recommendation: Current approach is appropriate: the byte-level conflict-marker guard is cheap and avoids optimistic shortcuts in clearly unsafe states, and the per-call ignore list matches pnpm’s API shape while keeping the default path unchanged. If the ignore list grows or becomes user-configurable, consider switching to a set-like structure.

Files changed (20) +1199 / -146

Bug fix (1) +127 / -94
optimistic_repeat_install.rsAdd ignore list support and conflict-marker guard to optimistic repeat install +127/-94

Add ignore list support and conflict-marker guard to optimistic repeat install

• Refactors the optimistic repeat-install check to support excluding specific workspace-state setting keys from drift detection. Adds a guard that skips the fast path when the shared lockfile (or per-project lockfiles when not shared) contains merge conflict markers. Refactors settings drift detection into an iterable list and updates deps-status pre-run checks to ignore dev/optional/production via the new mechanism.

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

Tests (17) +1025 / -8
add.rsAdd dist-tag re-add devDependency group preservation test +26/-0

Add dist-tag re-add devDependency group preservation test

• Adds an integration test ensuring re-adding a dev dependency at a dist-tag keeps it in devDependencies and does not move it to dependencies.

pnpm/crates/cli/tests/add.rs

catalog.rsExpand catalog CLI integration tests + add known-failure for cleanup +88/-1

Expand catalog CLI integration tests + add known-failure for cleanup

• Ports additional catalog scenarios: --save-catalog default and named catalogs, install snapshot emission, and update --latest behavior in manual mode. Adds a known-failure boundary for pruning unused workspace catalog entries (not yet implemented).

pnpm/crates/cli/tests/catalog.rs

hoist.rsAdd public-hoist safety test for pre-existing root directories +24/-0

Add public-hoist safety test for pre-existing root directories

• Adds coverage ensuring public hoisting does not overwrite an existing directory in root node_modules, preserving external contents and avoiding symlink replacement.

pnpm/crates/cli/tests/hoist.rs

install_state.rsIntroduce install-state headless/frozen reinstall tests (with known failures) +57/-0

Introduce install-state headless/frozen reinstall tests (with known failures)

• Adds a new test module verifying frozen reinstalls write .modules.yaml, lockfile copy, and bins. Records known-failure boundaries for PnP-without-symlinks materialization and external-lockfile public-hoist scenarios not yet supported.

pnpm/crates/cli/tests/install_state.rs

lifecycle_scripts.rsAdd frozen reinstall hoisting + lifecycle bin timing regression test +35/-1

Add frozen reinstall hoisting + lifecycle bin timing regression test

• Extends lifecycle script coverage with a scenario ensuring hoisting tolerates bins created later in the lifecycle, including a frozen reinstall via the TS pnpm binary.

pnpm/crates/cli/tests/lifecycle_scripts.rs

lockfile_verification.rsAdd known-failure boundary for non-strict minimumReleaseAge fallback path +16/-1

Add known-failure boundary for non-strict minimumReleaseAge fallback path

• Adds an explicit known-failure test documenting that pacquet does not yet fall back to immature versions when non-strict minimumReleaseAge has no mature match.

pnpm/crates/cli/tests/lockfile_verification.rs

optional_dependencies.rsAdd known-failure stubs for fixture-scale optional-dependency graphs +16/-0

Add known-failure stubs for fixture-scale optional-dependency graphs

• Adds known-failure tests for upstream scenarios requiring large real-world graphs (mixed optional graph skipping and repeated optional classification) where a minimal fixture is not yet available.

pnpm/crates/cli/tests/optional_dependencies.rs

peer_resolution.rsAdd known-failure boundaries for peer range intersection and locked peer context +31/-0

Add known-failure boundaries for peer range intersection and locked peer context

• Introduces a peer-resolution test module that records unimplemented parity gaps: compatible semver range intersection for auto-installed peers and lockedPeerContext/resolvedPeerProviderPaths propagation.

pnpm/crates/cli/tests/peer_resolution.rs

tests.rsGreatly expand lockfile verification cache hit/miss coverage +181/-0

Greatly expand lockfile verification cache hit/miss coverage

• Adds explicit tests for path misses, stat/size mismatch fallthrough to content-hash, same-size content changes, verifier policy acceptance, multi-verifier merged policy trust, and missing-lockfile behavior. Adds a helper to mutate cached mtime fields to simulate stat drift.

pnpm/crates/lockfile-verification/src/cache/tests.rs

record_lockfile_verified.rsWire record_lockfile_verified unit tests +3/-0

Wire record_lockfile_verified unit tests

• Adds a test module hook so record_lockfile_verified behavior is covered by dedicated unit tests.

pnpm/crates/lockfile-verification/src/record_lockfile_verified.rs

tests.rsAdd recorder round-trip tests for hash equivalence and path persistence +93/-0

Add recorder round-trip tests for hash equivalence and path persistence

• Adds tests ensuring record_lockfile_verified stores a hash compatible with how the next install computes it from disk, and that it records the caller-supplied lockfile path (including non-standard filenames).

pnpm/crates/lockfile-verification/src/record_lockfile_verified/tests.rs

tests.rsAdd tests for distinct resolution candidates and cache suppression on failure +106/-0

Add tests for distinct resolution candidates and cache suppression on failure

• Pins behavior that multiple lockfile entries with same name/version but different resolutions are each verified, that the verifier receives the exact resolution object, and that rejected verification does not create a cache record.

pnpm/crates/lockfile-verification/src/verify_lockfile_resolutions/tests.rs

tests.rsAdd tests for ignored settings, pnpmfile drift, and conflicted lockfiles +118/-3

Add tests for ignored settings, pnpmfile drift, and conflicted lockfiles

• Adds coverage that pnpmfile modifications invalidate optimistic repeat-install, that ignoredWorkspaceStateSettings can suppress drift for selected keys (e.g., allowBuilds), and that merge-conflicted lockfiles (shared or per-project) skip the fast path. Updates helpers to record pnpmfiles in workspace state.

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

tests.rsExpand peer resolution tests for optional peer conflicts and per-importer instances +126/-0

Expand peer resolution tests for optional peer conflicts and per-importer instances

• Adds tests ensuring optional peer incompatibilities are reported as conflicts and that separate workspace importers can resolve distinct dep paths when peer versions differ.

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

tests.rsAdd test asserting optional flag is forwarded to resolver +63/-0

Add test asserting optional flag is forwarded to resolver

• Adds a resolver stub that captures wanted.optional and verifies optionalDependencies are resolved with optional=true when resolving the dependency tree for optional group installs.

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

tests.rsAdd minimumReleaseAge exclude tests for wildcard patterns and version unions +30/-0

Add minimumReleaseAge exclude tests for wildcard patterns and version unions

• Adds tests verifying the age-check is skipped when package matches an exclude glob pattern and when an exact version is excluded via a union expression.

pnpm/crates/resolving-npm-resolver/src/create_npm_resolution_verifier/tests.rs

tests.rsTighten optional metadata test and assert libc is preserved +12/-2

Tighten optional metadata test and assert libc is preserved

• Modifies the optional=true pick_package test to use a version spec and to assert the full metadata response (including libc) is carried into the picked package and cached separately from abbreviated metadata.

pnpm/crates/resolving-npm-resolver/src/pick_package/tests.rs

Documentation (2) +47 / -44
calm-jars-smile.mdAdd release note for conflicted-lockfile optimistic-repeat behavior +5/-0

Add release note for conflicted-lockfile optimistic-repeat behavior

• Introduces a patch changeset noting that optimistic repeat-install shortcuts are avoided when lockfiles contain merge conflict markers.

.changeset/calm-jars-smile.md

TEST_PORTING.mdMark Stage 10 long-tail ports complete and document remaining known failures +42/-44

Mark Stage 10 long-tail ports complete and document remaining known failures

• Updates the test porting tracker to mark many previously-missing Stage 10 scenarios as ported, referencing new tests and known-failure boundaries across catalogs, hoisting, install state, lockfile verification caching, minimumReleaseAge, optimistic repeat installs, and peer resolution.

pnpm/plans/TEST_PORTING.md

Port the remaining Stage 10 lockfile verification and optimistic repeat install coverage.

Add catalog, peer, optional dependency, install-state, and hoisting tests.

Record known-failure boundaries for features that are not implemented yet.

Related to #13146.
@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. allow_known_failure! skips new tests ✗ Dismissed 📘 Rule violation ☼ Reliability
Description
New tests call allow_known_failure!, which returns early on KnownFailure, effectively skipping
scenarios instead of asserting behavior. This violates the requirement to not ignore/skip failures
as acceptable.
Code

pnpm/crates/cli/tests/install_state.rs[R49-57]

+#[test]
+fn pnp_install_without_symlinks_still_writes_modules_manifest_and_bin_directory() {
+    allow_known_failure!(pnp_without_symlinks());
+}
+
+#[test]
+fn public_hoist_uses_the_project_root_when_the_lockfile_is_external() {
+    allow_known_failure!(external_lockfile_public_hoist());
+}
Evidence
PR Compliance ID 2 forbids leaving failures unfixed or effectively skipped. The newly added tests
call allow_known_failure!, and the macro implementation returns early on KnownFailure, so these
tests do not validate behavior and instead silently exit.

CLAUDE.md: All Tests Must Pass (Do Not Ignore or Skip Failures as Pre-existing)
pnpm/crates/cli/tests/install_state.rs[49-57]
pnpm/crates/testing-utils/src/known_failure.rs[16-25]

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

## Issue description
New tests are being short-circuited via `allow_known_failure!`, meaning missing functionality is treated as a passing test.

## Issue Context
`allow_known_failure!` returns from the test on `Err(KnownFailure)`, so the test suite stays green even though the behavior is unimplemented.

## Fix Focus Areas
- pnpm/crates/cli/tests/install_state.rs[49-57]
- pnpm/crates/testing-utils/src/known_failure.rs[16-25]

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


2. Unbounded lockfile scan ✓ Resolved 🐞 Bug ⛨ Security
Description
lockfile_contains_conflict_markers uses fs::read() to load the entire lockfile into memory; a
repo-controlled pnpm-lock.yaml symlink to a special/huge file can hang or OOM the process during
the optimistic fast path. This runs by default because optimistic_repeat_install defaults to
true, and it contradicts the documented “never reads the lockfile” behavior of the fast path.
Code

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[R340-355]

+fn has_conflicted_lockfile(check: &OptimisticRepeatInstallCheck<'_>) -> bool {
+    let shared_lockfile = check.workspace_root.join(Lockfile::FILE_NAME);
+    if lockfile_contains_conflict_markers(&shared_lockfile) {
+        return true;
+    }
+    !check.config.shared_workspace_lockfile
+        && check.project_manifests.iter().any(|(root_dir, _)| {
+            let lockfile_path = root_dir.join(Lockfile::FILE_NAME);
+            lockfile_path != shared_lockfile && lockfile_contains_conflict_markers(&lockfile_path)
+        })
+}
+
+fn lockfile_contains_conflict_markers(path: &Path) -> bool {
+    fs::read(path)
+        .is_ok_and(|contents| contents.windows(b"<<<<<<<".len()).any(|line| line == b"<<<<<<<"))
+}
Evidence
The fast path is documented as not reading the lockfile, but the new conflict-marker check reads
lockfile bytes via fs::read() and is executed on the optimistic repeat-install path which is
called from Install::run and is enabled by default in config.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1-10]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[151-154]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[340-355]
pnpm/crates/package-manager/src/install.rs[908-934]
pnpm/crates/config/src/lib.rs[758-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
`lockfile_contains_conflict_markers()` currently does an unbounded `fs::read()` of a repo-controlled path. This can hang or exhaust memory if the lockfile is a symlink to a special file (e.g. `/dev/zero`) or is unexpectedly large, and it adds hot-path I/O where docs state the fast path avoids lockfile reads.

## Issue Context
- The optimistic repeat-install check is on the install warm path and is default-enabled.
- The new conflict-marker check runs before workspace-state loading.

## Fix Focus Areas
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[340-355]

## What to change
1. Replace `fs::read()` with a bounded, streaming scan:
  - Use `std::fs::File` + `std::io::Read` (or `BufRead`) to scan in fixed-size chunks.
  - Avoid following non-regular files: use `symlink_metadata`/`file_type` and treat non-regular targets as “conflicted” (skip optimistic path) rather than trying to read.
2. Add a size guard:
  - If `metadata.len()` exceeds a reasonable threshold for a fast-path check, conservatively return `true` (skip optimistic path) to avoid large reads.
3. Update module/config docs to reflect that the fast path may perform a small lockfile scan (or, if you keep the contract, gate the scan so the fast path still doesn’t touch the lockfile in the common case).

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



Remediation recommended

3. Redundant lockfile stats 🐞 Bug ➹ Performance ⭐ New
Description
The new merge-conflict pre-scan calls first_lockfile_requiring_conflict_safe_install() (which
stats the lockfile via symlink_metadata and mtime extraction) and the code later still calls
wanted_lockfile_modified() (which stats again via fs::metadata), adding avoidable filesystem
work on the repeat-install and deps-status warm paths when no conflict/unsafe condition is found.
Code

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[R162-168]

+    if first_lockfile_requiring_conflict_safe_install(check, state.last_validated_timestamp)
+        .is_some()
+    {
+        return Decision::Skipped {
+            reason: "a changed lockfile contains or cannot be checked for merge conflict markers",
+        };
+    }
Evidence
The conflict gate already performs a metadata+mtime check to decide whether scanning is needed, and
the functions later perform another metadata call to compute lockfile_modified; this duplicates
filesystem work on warm paths, which the repo’s review guide flags as something to avoid/redesign
when possible.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[162-168]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[277-284]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[383-405]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1020-1023]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1102-1105]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1709-1722]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1774-1775]
REVIEW_GUIDE.md[115-127]

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

### Issue description
The optimistic repeat-install fast path now performs a lockfile conflict-marker gate (`first_lockfile_requiring_conflict_safe_install`) and later independently probes lockfile freshness (`wanted_lockfile_modified`). Both paths stat the same `pnpm-lock.yaml` again in the common “no conflict found” case, adding unnecessary filesystem syscalls on hot/warm command paths.

### Issue Context
- `first_lockfile_requiring_conflict_safe_install` ultimately calls `lockfile_conflict_check_failure`, which `symlink_metadata()`s the lockfile and checks mtime/size before possibly scanning.
- Later in the same function, the code computes `lockfile_modified = wanted_lockfile_modified(...)`, which calls `file_mtime()` and does another `fs::metadata()`.
- The same pattern exists in `check_deps_status_before_run`, so `pnpm run/exec` can also pay duplicate stats.

### Fix Focus Areas
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[159-168]
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[277-284]
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1709-1722]
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1774-1775]

### Suggested change
Refactor so lockfile freshness and conflict-marker safety share one metadata/mtime read:
- Option A: compute `lockfile_modified` once (single metadata read) and only if modified run the bounded marker scan.
- Option B: have the conflict-check helper return a small struct like `{ modified: bool, failure: Option<...> }` so callers can reuse `modified` instead of re-statting.

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


4. Symlink lockfile always “unsafe” 🐞 Bug ➹ Performance
Description
lockfile_conflict_check_failure() uses symlink_metadata() and immediately returns Unsafe when the
lockfile path is not a regular file, which includes a symlinked pnpm-lock.yaml, before any mtime
check. This forces check_optimistic_repeat_install() to skip the fast path and
check_deps_status_before_run() to report Outdated in environments that intentionally read
pnpm-lock.yaml via a symlink (e.g. sandboxed lockfile layouts).
Code

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[R387-394]

+    let metadata = match fs::symlink_metadata(path) {
+        Ok(metadata) => metadata,
+        Err(error) if error.kind() == ErrorKind::NotFound => return None,
+        Err(_) => return Some(LockfileConflictCheckFailure::Unsafe),
+    };
+    if !metadata.file_type().is_file() {
+        return Some(LockfileConflictCheckFailure::Unsafe);
+    }
Evidence
The new conflict-scan gate returns Unsafe for any non-regular lockfile path (including a symlink)
before checking whether the lockfile was modified, and this result is used both to skip optimistic
repeat installs and to report run-time deps as outdated. Separately, the lockfile writer documents
that symlinked lockfiles are expected to be readable, so the unconditional Unsafe classification
creates a persistent fast-path miss/outdated status for that supported read scenario.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[383-405]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[162-168]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1709-1722]
pnpm/crates/package-manager/src/install.rs[3443-3494]
pnpm/crates/lockfile/src/save_lockfile.rs[99-109]

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

### Issue description
`lockfile_conflict_check_failure()` currently treats any non-regular lockfile path as `Unsafe` based on `symlink_metadata()` + `file_type().is_file()`. Because `symlink_metadata()` describes the link itself, a *symlink to a regular lockfile* is unconditionally classified as unsafe, which defeats the optimistic repeat-install fast path and can make the pre-run deps status check perpetually report “outdated” in symlink-lockfile workflows.

### Issue Context
The lockfile layer explicitly allows *reads* to follow a symlinked `pnpm-lock.yaml` (it only refuses writes), so symlinked lockfiles are a supported/expected shape in some environments. The new conflict-marker gate should ideally preserve the same “reads may follow symlinks” posture while still avoiding scanning unsafe/special targets.

### Fix Focus Areas
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[383-405]
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[407-445]
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1685-1733]

### Suggested fix approach
1. If `symlink_metadata()` indicates `is_symlink()`, attempt to fetch *target* metadata via `fs::metadata(path)` and proceed **only if** the target is a regular file and under the size cap; otherwise treat as `Unsafe`.
2. Use the target mtime (from `fs::metadata`) for the `lockfile_modified_since()` decision.
3. Keep the bounded scan and the “don’t scan oversized files” behavior.
4. Add/adjust tests to cover:
  - symlink to a normal small regular file → scan applies and does not force outdated when unchanged
  - symlink to a special file (e.g. /dev/zero, FIFO) → still treated as Unsafe

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


5. Lockfile scan TOCTOU hang 🐞 Bug ⛨ Security
Description
The new conflict-marker scan checks the lockfile with symlink_metadata() and then later calls
File::open(path) in a separate step; a concurrent replacement of the path with a FIFO/special file
can block in open() (or read unintended content) before the post-open metadata guard runs. This can
hang the optimistic repeat-install fast path, turning installs into a local denial-of-service when
the workspace is writable by another process/user.
Code

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[R366-423]

+fn lockfile_requires_conflict_safe_install(path: &Path, last_validated_timestamp: i64) -> bool {
+    let metadata = match fs::symlink_metadata(path) {
+        Ok(metadata) => metadata,
+        Err(error) if error.kind() == ErrorKind::NotFound => return false,
+        Err(_) => return true,
+    };
+    if !metadata.file_type().is_file() {
+        return true;
+    }
+    let Some(mtime) = file_mtime_from_metadata(&metadata) else {
+        return true;
+    };
+    if !lockfile_modified_since(mtime, last_validated_timestamp) {
+        return false;
+    }
+    if metadata.len() >= MAX_LOCKFILE_CONFLICT_SCAN_BYTES {
+        return true;
+    }
+    modified_lockfile_contains_conflict_markers(path)
+}
+
+fn modified_lockfile_contains_conflict_markers(path: &Path) -> bool {
+    let Ok(mut file) = fs::File::open(path) else {
+        return true;
+    };
+    let Ok(metadata) = file.metadata() else {
+        return true;
+    };
+    if !metadata.file_type().is_file() || metadata.len() >= MAX_LOCKFILE_CONFLICT_SCAN_BYTES {
+        return true;
+    }
+
+    let mut buffer = [0; LOCKFILE_CONFLICT_SCAN_BUFFER_SIZE + CONFLICT_MARKER.len() - 1];
+    let mut carried = 0;
+    let mut scanned = 0_u64;
+    loop {
+        let remaining = MAX_LOCKFILE_CONFLICT_SCAN_BYTES.saturating_sub(scanned);
+        if remaining == 0 {
+            return true;
+        }
+        let read_capacity = LOCKFILE_CONFLICT_SCAN_BUFFER_SIZE.min(remaining as usize);
+        match file.read(&mut buffer[carried..carried + read_capacity]) {
+            Ok(0) => return false,
+            Ok(read) => {
+                scanned += read as u64;
+                let end = carried + read;
+                if buffer[..end]
+                    .windows(CONFLICT_MARKER.len())
+                    .any(|bytes| bytes == CONFLICT_MARKER)
+                {
+                    return true;
+                }
+                carried = end.min(CONFLICT_MARKER.len() - 1);
+                buffer.copy_within(end - carried..end, 0);
+            }
+            Err(error) if error.kind() == ErrorKind::Interrupted => {}
+            Err(_) => return true,
+        }
Evidence
The code first validates file type and mtime via fs::symlink_metadata(path) and then, if modified,
calls modified_lockfile_contains_conflict_markers(path), which does a separate
fs::File::open(path) before verifying the opened handle is a regular file. Because these are
separate path lookups, the path can be replaced between them; the post-open file-type check cannot
prevent a blocking open on FIFOs/special files.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[346-385]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[387-423]

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 lockfile conflict-marker scan is vulnerable to a TOCTOU window: it validates the path using `symlink_metadata()` and then later performs a path-based `File::open()`. If another process swaps the path to a FIFO/special file between those operations, `File::open()` can block (FIFO) or open an unintended target before the subsequent `file.metadata()` checks run.

## Issue Context
This code runs in the optimistic repeat-install fast path, so a hang here can stall installs early.

## Fix Focus Areas
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[366-425]

## Suggested remediation
- Avoid path-based TOCTOU by opening the file in a way that refuses symlinks and avoids blocking device/pipe opens where possible.
 - On Unix, consider `OpenOptionsExt` with `O_NOFOLLOW` (avoid symlink swaps) and `O_NONBLOCK` (avoid FIFO open blocking), then validate `file.metadata().file_type().is_file()` before reading.
 - If `O_NONBLOCK` causes read semantics issues, keep it only for open and then clear it (or treat any non-regular file as “cannot be checked” without reading).
- Keep the existing conservative behavior (returning `true`/skipping the shortcut) on any open/metadata/read error.

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


View more (3)
6. Flaky pnpmfile mtime test 🐞 Bug ☼ Reliability
Description
The new test returns_skipped_when_a_pnpmfile_is_modified writes workspace state using
now_millis() (wall clock) for last_validated_timestamp, but the production freshness logic is
defined in terms of filesystem mtimes; on whole-second mtime filesystems or under wall-clock vs
mtime skew this can fail to detect the pnpmfile as modified and intermittently fail.
Code

pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs[R108-129]

+#[test]
+fn returns_skipped_when_a_pnpmfile_is_modified() {
+    let (dir, config, manifest) =
+        setup_fresh_install(pacquet_config::NodeLinker::Isolated, "root", "1.0.0", "");
+    let pnpmfile = dir.path().join(".pnpmfile.cjs");
+    fs::write(&pnpmfile, "module.exports = {}\n").expect("write pnpmfile");
+    sleep(Duration::from_millis(20));
+    let mut projects = BTreeMap::new();
+    projects.insert(
+        dir.path().to_string_lossy().into_owned(),
+        ProjectEntry { name: Some("root".into()), version: Some("1.0.0".into()) },
+    );
+    write_state_with_pnpmfiles(
+        dir.path(),
+        now_millis(),
+        current_settings(config, pacquet_config::NodeLinker::Isolated, isolated_included(), None),
+        projects,
+        current_pnpmfiles(dir.path()),
+    );
+    sleep(Duration::from_millis(20));
+    fs::write(&pnpmfile, "module.exports = { hooks: {} }\n").expect("modify pnpmfile");
+
Evidence
The test currently uses a wall-clock timestamp for the state baseline, while the production module
explicitly documents that the validation baseline must come from filesystem mtimes to avoid
wall-vs-mtime skew; this mismatch can cause platform-dependent false negatives when checking whether
a pnpmfile was modified after validation.

pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs[108-141]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[964-975]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[945-962]

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 test `returns_skipped_when_a_pnpmfile_is_modified` records `last_validated_timestamp` via `now_millis()` (wall clock). The production logic is designed around a baseline derived from filesystem mtimes to avoid wall-vs-mtime skew and coarse timestamp resolution, so the test can become flaky on some filesystems/platforms.

### Issue Context
The check compares a filesystem mtime (`metadata.modified()`) against a millisecond baseline, with special handling for whole-second filesystems. Using wall clock in the test can make the baseline later than the file’s reported mtime even when the file was written “after” in real time.

### Fix Focus Areas
- pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs[108-141]

### Suggested fix
In `returns_skipped_when_a_pnpmfile_is_modified`, compute the validation timestamp from the pnpmfile’s actual filesystem mtime immediately after the first `fs::write(&pnpmfile, ...)` (e.g., `fs::metadata(&pnpmfile)?.modified()?` → duration since epoch → `as_millis()`), and pass that value to `write_state_with_pnpmfiles` instead of `now_millis()`. This removes the need for the short sleeps and makes the test deterministic across whole-second and sub-second mtime filesystems.

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


7. Eager drift comparisons ✓ Resolved 🐞 Bug ➹ Performance
Description
first_setting_drift now builds a fixed array of (key, differs) tuples, which eagerly evaluates
every comparison before find_map can short-circuit on the first drift. This adds avoidable work to
check_deps_status_before_run and the optimistic install fast-path gate when drift is present.
Code

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[R1125-1201]

    node_linker: NodeLinker,
    included: IncludedDependencies,
    supported_architectures: Option<&SupportedArchitectures>,
-    ignore_included_groups: bool,
+    ignored_workspace_state_settings: &[&str],
) -> Option<&'static str> {
    let current = current_settings(config, node_linker, included, supported_architectures);
    let recorded = &state.settings;
    let live = &current;
-    if !allow_builds_match(recorded.allow_builds.as_ref(), live.allow_builds.as_ref()) {
-        return Some("allowBuilds");
-    }
-    if recorded.auto_install_peers != live.auto_install_peers {
-        return Some("autoInstallPeers");
-    }
-    if recorded.dedupe_direct_deps != live.dedupe_direct_deps {
-        return Some("dedupeDirectDeps");
-    }
-    if recorded.dedupe_injected_deps != live.dedupe_injected_deps {
-        return Some("dedupeInjectedDeps");
-    }
-    if recorded.dedupe_peer_dependents != live.dedupe_peer_dependents {
-        return Some("dedupePeerDependents");
-    }
-    if recorded.dedupe_peers != live.dedupe_peers {
-        return Some("dedupePeers");
-    }
-    if !ignore_included_groups && recorded.dev != live.dev {
-        return Some("dev");
-    }
-    if !enable_global_virtual_store_match(
-        recorded.enable_global_virtual_store,
-        live.enable_global_virtual_store,
-    ) {
-        return Some("enableGlobalVirtualStore");
-    }
-    if recorded.exclude_links_from_lockfile != live.exclude_links_from_lockfile {
-        return Some("excludeLinksFromLockfile");
-    }
-    if recorded.hoist_pattern != live.hoist_pattern {
-        return Some("hoistPattern");
-    }
-    if recorded.hoist_workspace_packages != live.hoist_workspace_packages {
-        return Some("hoistWorkspacePackages");
-    }
-    if recorded.ignored_optional_dependencies != live.ignored_optional_dependencies {
-        return Some("ignoredOptionalDependencies");
-    }
-    if recorded.inject_workspace_packages != live.inject_workspace_packages {
-        return Some("injectWorkspacePackages");
-    }
-    if recorded.link_workspace_packages != live.link_workspace_packages {
-        return Some("linkWorkspacePackages");
-    }
-    if recorded.minimum_release_age != live.minimum_release_age {
-        return Some("minimumReleaseAge");
-    }
-    if recorded.minimum_release_age_ignore_missing_time
-        != live.minimum_release_age_ignore_missing_time
-    {
-        return Some("minimumReleaseAgeIgnoreMissingTime");
-    }
-    if recorded.node_linker != live.node_linker {
-        return Some("nodeLinker");
-    }
-    if !ignore_included_groups && recorded.optional != live.optional {
-        return Some("optional");
-    }
-    if recorded.overrides != live.overrides {
-        return Some("overrides");
-    }
-    if !package_extensions_match(
-        recorded.package_extensions.as_ref(),
-        live.package_extensions.as_ref(),
-    ) {
-        return Some("packageExtensions");
-    }
-    if recorded.patched_dependencies != live.patched_dependencies {
-        return Some("patchedDependencies");
-    }
-    if recorded.peers_suffix_max_length != live.peers_suffix_max_length {
-        return Some("peersSuffixMaxLength");
-    }
-    if recorded.prefer_workspace_packages != live.prefer_workspace_packages {
-        return Some("preferWorkspacePackages");
-    }
-    if !ignore_included_groups && recorded.production != live.production {
-        return Some("production");
-    }
-    if recorded.public_hoist_pattern != live.public_hoist_pattern {
-        return Some("publicHoistPattern");
-    }
-    if recorded.supported_architectures != live.supported_architectures {
-        return Some("supportedArchitectures");
-    }
-    None
+    [
+        (
+            "allowBuilds",
+            !allow_builds_match(recorded.allow_builds.as_ref(), live.allow_builds.as_ref()),
+        ),
+        ("autoInstallPeers", recorded.auto_install_peers != live.auto_install_peers),
+        ("dedupeDirectDeps", recorded.dedupe_direct_deps != live.dedupe_direct_deps),
+        ("dedupeInjectedDeps", recorded.dedupe_injected_deps != live.dedupe_injected_deps),
+        ("dedupePeerDependents", recorded.dedupe_peer_dependents != live.dedupe_peer_dependents),
+        ("dedupePeers", recorded.dedupe_peers != live.dedupe_peers),
+        ("dev", recorded.dev != live.dev),
+        (
+            "enableGlobalVirtualStore",
+            !enable_global_virtual_store_match(
+                recorded.enable_global_virtual_store,
+                live.enable_global_virtual_store,
+            ),
+        ),
+        (
+            "excludeLinksFromLockfile",
+            recorded.exclude_links_from_lockfile != live.exclude_links_from_lockfile,
+        ),
+        ("hoistPattern", recorded.hoist_pattern != live.hoist_pattern),
+        (
+            "hoistWorkspacePackages",
+            recorded.hoist_workspace_packages != live.hoist_workspace_packages,
+        ),
+        (
+            "ignoredOptionalDependencies",
+            recorded.ignored_optional_dependencies != live.ignored_optional_dependencies,
+        ),
+        (
+            "injectWorkspacePackages",
+            recorded.inject_workspace_packages != live.inject_workspace_packages,
+        ),
+        ("linkWorkspacePackages", recorded.link_workspace_packages != live.link_workspace_packages),
+        ("minimumReleaseAge", recorded.minimum_release_age != live.minimum_release_age),
+        (
+            "minimumReleaseAgeIgnoreMissingTime",
+            recorded.minimum_release_age_ignore_missing_time
+                != live.minimum_release_age_ignore_missing_time,
+        ),
+        ("nodeLinker", recorded.node_linker != live.node_linker),
+        ("optional", recorded.optional != live.optional),
+        ("overrides", recorded.overrides != live.overrides),
+        (
+            "packageExtensions",
+            !package_extensions_match(
+                recorded.package_extensions.as_ref(),
+                live.package_extensions.as_ref(),
+            ),
+        ),
+        ("patchedDependencies", recorded.patched_dependencies != live.patched_dependencies),
+        ("peersSuffixMaxLength", recorded.peers_suffix_max_length != live.peers_suffix_max_length),
+        (
+            "preferWorkspacePackages",
+            recorded.prefer_workspace_packages != live.prefer_workspace_packages,
+        ),
+        ("production", recorded.production != live.production),
+        ("publicHoistPattern", recorded.public_hoist_pattern != live.public_hoist_pattern),
+        (
+            "supportedArchitectures",
+            recorded.supported_architectures != live.supported_architectures,
+        ),
+    ]
+    .into_iter()
+    .find_map(|(key, differs)| {
+        (differs && !ignored_workspace_state_settings.contains(&key)).then_some(key)
+    })
Evidence
The new implementation constructs the entire tuple array (forcing all comparisons to run) and is
used by both the run-gate and the install fast-path gating codepaths.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1122-1201]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1597-1605]
pnpm/crates/package-manager/src/install.rs[908-934]

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 refactor to an array literal removes the previous early-return behavior: all `differs` expressions are evaluated even if the first setting already drifted. This is unnecessary work on frequently-invoked status/fast-path checks.

## Issue Context
This impacts:
- `check_optimistic_repeat_install_*` (install warm path)
- `check_deps_status_before_run` (run/exec gate)

## Fix Focus Areas
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1122-1201]
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[1597-1605]

## What to change
Use a lazy/short-circuit structure instead of eagerly computing booleans:
- Revert to ordered `if` checks (with an `if ignored.contains(key) { continue }` pattern), or
- Use an iterator of closures (e.g. `[("allowBuilds", || ...), ...]`) so expensive comparisons run only until the first non-ignored drift is found.

Keep the ordering stable so the reported “first drift” key remains deterministic.

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


8. lockfile_contains_conflict_markers swallows IO errors ✓ Resolved 📘 Rule violation ☼ Reliability
Description
lockfile_contains_conflict_markers() converts any fs::read() error into false via is_ok_and,
silently ignoring unexpected IO failures. This can let the optimistic repeat-install fast path
proceed when the lockfile is unreadable, and it hides errors that should be handled explicitly.
Code

pnpm/crates/package-manager/src/optimistic_repeat_install.rs[R352-355]

+fn lockfile_contains_conflict_markers(path: &Path) -> bool {
+    fs::read(path)
+        .is_ok_and(|contents| contents.windows(b"<<<<<<<".len()).any(|line| line == b"<<<<<<<"))
+}
Evidence
PR Compliance ID 5 requires that errors are not swallowed. The new implementation uses
fs::read(path).is_ok_and(...), which discards the error entirely and returns false for any read
failure, violating the “never swallow errors” handling convention.

CLAUDE.md, AGENTS.md: Use correct error types and handling conventions (PnpmError for user-facing errors; never swallow errors)
pnpm/crates/package-manager/src/optimistic_repeat_install.rs[352-355]

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

## Issue description
`lockfile_contains_conflict_markers()` uses `fs::read(path).is_ok_and(...)`, which treats *all* read failures as “no conflict markers”. This silently swallows unexpected IO errors and may allow the optimistic repeat-install fast path to run even when the lockfile couldn't be inspected.

## Issue Context
This code runs on the install path when `optimistic_repeat_install` is enabled. For safety and debuggability, unexpected IO failures should not be ignored.

## Fix Focus Areas
- pnpm/crates/package-manager/src/optimistic_repeat_install.rs[352-355]

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


Grey Divider

Qodo Logo

Copilot AI review requested due to automatic review settings July 19, 2026 21:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.05     11.6±0.12ms    32.3 MB/sec    1.00     11.0±0.01ms    34.0 MB/sec
packument/parse                1.03     39.3±0.09µs  1687.8 MB/sec    1.00     38.1±0.18µs  1741.8 MB/sec
tarball/download_dependency    1.00      2.2±0.06ms  1987.8 KB/sec    1.00      2.2±0.06ms  1985.1 KB/sec

@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 26ec0aa

Warning

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

CategorySuggestion                                                                                                                                    Impact
Security
Eliminate lockfile scan race

Prevent TOCTOU vulnerabilities by opening the lockfile first and reading its
metadata directly from the file handle. This ensures the checked file is exactly
the same as the one being scanned.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs [387-404]

-let metadata = match fs::symlink_metadata(path) {
-    Ok(metadata) => metadata,
+let mut file = match open_lockfile_without_following_links(path) {
+    Ok(file) => file,
     Err(error) if error.kind() == ErrorKind::NotFound => return None,
     Err(_) => return Some(LockfileConflictCheckFailure::Unsafe),
 };
-if !metadata.file_type().is_file() {
-    return Some(LockfileConflictCheckFailure::Unsafe);
-}
+let metadata = match file.metadata() {
+    Ok(metadata) if metadata.file_type().is_file() => metadata,
+    _ => return Some(LockfileConflictCheckFailure::Unsafe),
+};
 let Some(mtime) = file_mtime_from_metadata(&metadata) else {
     return Some(LockfileConflictCheckFailure::Unsafe);
 };
 if !lockfile_modified_since(mtime, last_validated_timestamp) {
     return None;
 }
 if metadata.len() >= MAX_LOCKFILE_CONFLICT_SCAN_BYTES {
     return Some(LockfileConflictCheckFailure::Unsafe);
 }
-modified_lockfile_conflict_check_failure(path)
+modified_lockfile_conflict_check_failure(&mut file)

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The suggestion identifies a valid Time-of-Check to Time-of-Use (TOCTOU) vulnerability where the lockfile can be swapped or replaced with a FIFO between the metadata check and file opening, improving the robustness and security of the optimistic install check.

Medium
  • Update

Previous suggestions

Suggestions up to commit dae0c57
CategorySuggestion                                                                                                                                    Impact
Security
Prevent lockfile open race

Fix a TOCTOU race condition by opening the file first and performing metadata
validation on the opened file handle.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs [387-404]

-let metadata = match fs::symlink_metadata(path) {
-    Ok(metadata) => metadata,
+let mut file = match open_regular_lockfile_without_following_links(path) {
+    Ok(file) => file,
     Err(error) if error.kind() == ErrorKind::NotFound => return None,
     Err(_) => return Some(LockfileConflictCheckFailure::Unsafe),
 };
-if !metadata.file_type().is_file() {
+let metadata = match file.metadata() {
+    Ok(metadata) if metadata.file_type().is_file() => metadata,
+    _ => return Some(LockfileConflictCheckFailure::Unsafe),
+};
+let Some(mtime) = file_mtime_from_metadata(&metadata) else {
+    return Some(LockfileConflictCheckFailure::Unsafe);
+};
+if !lockfile_modified_since(mtime, last_validated_timestamp) {
+    return None;
+}
+if metadata.len() >= MAX_LOCKFILE_CONFLICT_SCAN_BYTES {
     return Some(LockfileConflictCheckFailure::Unsafe);
 }
-...
-modified_lockfile_conflict_check_failure(path)
+modified_lockfile_conflict_check_failure(&mut file)
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a Time-of-Check to Time-of-Use (TOCTOU) race condition between fs::symlink_metadata and fs::File::open, mitigating potential security risks and indefinite blocking.

Medium
Suggestions up to commit 99bc970
CategorySuggestion                                                                                                                                    Impact
High-level
Avoid unconditional lockfile read on fast-path

Move the has_conflicted_lockfile check to only run when the lockfile has
actually been modified, preventing unnecessary file reads. Also, rewrite
first_setting_drift to evaluate conditions lazily and restore short-circuiting.

Examples:

pnpm/crates/package-manager/src/optimistic_repeat_install.rs [151-154]
pnpm/crates/package-manager/src/optimistic_repeat_install.rs [1133-1201]

Solution Walkthrough:

Before:

// Unconditional file read and linear scan on the fast-path
if has_conflicted_lockfile(check) {
    return Decision::Skipped { reason: "a lockfile contains merge conflict markers" };
}

// ...

// Eager evaluation of all drift conditions before finding the first match
[
    ("allowBuilds", !allow_builds_match(...)),
    ("autoInstallPeers", recorded.auto_install_peers != live.auto_install_peers),
    // ... all other settings
]
.into_iter()
.find_map(...)

After:

// ...
let state = match read_workspace_state(workspace_root) { /* ... */ };

// Only read and scan the lockfile if we know it was modified
if lockfile_modified_since(check, state.last_validated_timestamp) {
    if has_conflicted_lockfile(check) {
        return Decision::Skipped { reason: "a lockfile contains merge conflict markers" };
    }
    return Decision::Skipped { reason: "lockfile modified" };
}

// Restored short-circuiting for drift conditions
macro_rules! check_drift {
    ($key:expr, $cond:expr) => {
        if $cond && !ignored_workspace_state_settings.contains(&$key) {
            return Some($key);
        }
    };
}

check_drift!("allowBuilds", !allow_builds_match(...));
check_drift!("autoInstallPeers", recorded.auto_install_peers != live.auto_install_peers);
// ... check remaining settings
None
Suggestion importance[1-10]: 8

__

Why: Addresses two notable performance regressions on a critical fast-path: an unconditional entire-file read of the lockfile, and the loss of short-circuiting in settings drift evaluation.

Medium
General
Use optimized string search for conflict markers

Use optimized string search (contains) instead of byte-slice windows to detect
conflict markers.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs [352-355]

 fn lockfile_contains_conflict_markers(path: &Path) -> bool {
-    fs::read(path)
-        .is_ok_and(|contents| contents.windows(b"<<<<<<<".len()).any(|line| line == b"<<<<<<<"))
+    fs::read_to_string(path)
+        .is_ok_and(|contents| contents.contains("<<<<<<<"))
 }
Suggestion importance[1-10]: 7

__

Why: Using read_to_string and contains improves performance significantly over byte-slice windows due to optimized pattern matching, assuming lockfiles are valid UTF-8.

Medium
Add must_use to ignoring variant

Add #[must_use] to check_optimistic_repeat_install_ignoring.

pnpm/crates/package-manager/src/optimistic_repeat_install.rs [132-135]

+#[must_use]
 pub(crate) fn check_optimistic_repeat_install_ignoring(
     check: &OptimisticRepeatInstallCheck<'_>,
     ignored_workspace_state_settings: &[&str],
 ) -> Decision {
Suggestion importance[1-10]: 6

__

Why: Adding #[must_use] ensures the returned Decision is not accidentally ignored, maintaining consistency with check_optimistic_repeat_install.

Low

@greptile-apps

greptile-apps Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge — the change is test-only except for the conflict-marker scan and the settings-drift API refactor, both of which are internally consistent, well-tested, and conservative.

The conflict-marker scan is correctly implemented with proper symlink rejection, TOCTOU guards, boundary-spanning detection, and size limits. The settings-drift refactor preserves all previously tested behaviour. Tests follow all project conventions.

No files require special attention.

Reviews (4): Last reviewed commit: "test(pacquet): improve optimistic instal..." | Re-trigger Greptile

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 628809d

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@codecov-commenter

codecov-commenter commented Jul 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.39130% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.44%. Comparing base (ebacfa6) to head (26ec0aa).
⚠️ Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
...s/package-manager/src/optimistic_repeat_install.rs 92.39% 14 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13161      +/-   ##
==========================================
+ Coverage   85.85%   86.44%   +0.58%     
==========================================
  Files         505      508       +3     
  Lines       84029    85078    +1049     
==========================================
+ Hits        72147    73542    +1395     
+ Misses      11882    11536     -346     

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

Copilot AI review requested due to automatic review settings July 19, 2026 21:57

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

Caution

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

⚠️ Outside diff range comments (1)
pnpm/crates/package-manager/src/optimistic_repeat_install.rs (1)

1573-1606: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

check_deps_status_before_run lacks the merge-conflict lockfile guard added to its near-twin.

check_optimistic_repeat_install_ignoring now skips the fast path when a lockfile has merge-conflict markers, but check_deps_status_before_run — which mirrors the same fast-path logic for the pnpm run pre-flight check — has no equivalent call to has_conflicted_lockfile. A conflicted lockfile could still be reported as "up to date" (or fall through without the new diagnosability) for run, which is inconsistent with the install path's new safeguard.

🤖 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/optimistic_repeat_install.rs` around lines
1573 - 1606, Add the same has_conflicted_lockfile guard used by
check_optimistic_repeat_install_ignoring to check_deps_status_before_run, before
its fast-path status checks. Ensure conflicted lockfiles return the appropriate
outdated status with the existing install arguments and diagnostic behavior,
while preserving the current PnP and setting-drift handling.
🤖 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/package-manager/src/optimistic_repeat_install.rs`:
- Around line 151-154: Move the has_conflicted_lockfile(check) guard to after
the cheap load_workspace_state workspace-state check in the repeat-install
decision flow. Preserve the existing Decision::Skipped result and reason, while
ensuring missing or unchanged workspace state returns before scanning lockfiles.

---

Outside diff comments:
In `@pnpm/crates/package-manager/src/optimistic_repeat_install.rs`:
- Around line 1573-1606: Add the same has_conflicted_lockfile guard used by
check_optimistic_repeat_install_ignoring to check_deps_status_before_run, before
its fast-path status checks. Ensure conflicted lockfiles return the appropriate
outdated status with the existing install arguments and diagnostic behavior,
while preserving the current PnP and setting-drift handling.
🪄 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: cbc08245-542d-4632-a144-42611ede3fc3

📥 Commits

Reviewing files that changed from the base of the PR and between 51c623f and 628809d.

📒 Files selected for processing (20)
  • .changeset/calm-jars-smile.md
  • pnpm/crates/cli/tests/add.rs
  • pnpm/crates/cli/tests/catalog.rs
  • pnpm/crates/cli/tests/hoist.rs
  • pnpm/crates/cli/tests/install_state.rs
  • pnpm/crates/cli/tests/lifecycle_scripts.rs
  • pnpm/crates/cli/tests/lockfile_verification.rs
  • pnpm/crates/cli/tests/optional_dependencies.rs
  • pnpm/crates/cli/tests/peer_resolution.rs
  • pnpm/crates/lockfile-verification/src/cache/tests.rs
  • pnpm/crates/lockfile-verification/src/record_lockfile_verified.rs
  • pnpm/crates/lockfile-verification/src/record_lockfile_verified/tests.rs
  • pnpm/crates/lockfile-verification/src/verify_lockfile_resolutions/tests.rs
  • pnpm/crates/package-manager/src/optimistic_repeat_install.rs
  • pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/tests.rs
  • pnpm/crates/resolving-deps-resolver/src/tests.rs
  • pnpm/crates/resolving-npm-resolver/src/create_npm_resolution_verifier/tests.rs
  • pnpm/crates/resolving-npm-resolver/src/pick_package/tests.rs
  • pnpm/plans/TEST_PORTING.md

@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 (1)
pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs (1)

1970-1973: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add dbg!(&decision) before non-trivial assertions and clean up formatting.

As per path instructions in pnpm/CODE_STYLE_GUIDE.md, non-trivial assertions should log their inputs (e.g., using dbg!) so that test failures provide actionable context, since matches! hides the actual enum value on failure. Additionally, the trailing ,); inside the assert! macro can be cleaned up.

  • pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs#L1970-L1973: Log the decision and remove the trailing comma.
  • pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs#L1994-L1997: Log the decision and remove the trailing comma.
  • pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs#L2019-L2022: Log the decision and remove the trailing comma.
♻️ Proposed refactor (apply to all sites)
+    dbg!(&decision);
-    assert!(matches!(
-        decision,
-        Decision::Skipped { reason } if reason.contains("cannot be checked"),
-    ),);
+    assert!(matches!(
+        decision,
+        Decision::Skipped { reason } if reason.contains("cannot be checked")
+    ));
🤖 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/optimistic_repeat_install/tests.rs` around
lines 1970 - 1973, Update the three assertions matching Decision::Skipped in
pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs at lines
1970-1973, 1994-1997, and 2019-2022: add dbg!(&decision) immediately before each
non-trivial assert and remove the trailing comma after each assert! macro
invocation.

Source: Path instructions

🤖 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/package-manager/src/optimistic_repeat_install/tests.rs`:
- Around line 1970-1973: Update the three assertions matching Decision::Skipped
in pnpm/crates/package-manager/src/optimistic_repeat_install/tests.rs at lines
1970-1973, 1994-1997, and 2019-2022: add dbg!(&decision) immediately before each
non-trivial assert and remove the trailing comma after each assert! macro
invocation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 39bf589f-9f9c-4d84-bbfc-97a0b6a1862e

📥 Commits

Reviewing files that changed from the base of the PR and between 628809d and c2a686c.

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

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

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

Copilot AI review requested due to automatic review settings July 19, 2026 22:03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants