Skip to content

fix: finish global virtual store behavior - #13170

Merged
zkochan merged 6 commits into
mainfrom
gvs
Jul 20, 2026
Merged

zkochan merged 6 commits into
mainfrom
gvs

Conversation

@zkochan

@zkochan zkochan commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Completes the remaining Global virtual store work tracked in #13167 for pacquet:

  • atomically imports .pnpm-needs-build into buildable GVS slots, detects interrupted slots across warm and no-op install paths, reimports them, and removes the marker before side-effects upload
  • makes pnpm fetch use virtual-store-only materialization, including the global virtual store, without creating importer links
  • replaces the known-failure marker coverage and rewrites the fetch tests around the virtual-store contract

Related to #13167.

Squash Commit Body

Complete pacquet global virtual store recovery by importing an incomplete-build marker with pristine package files and checking it before warm or no-op install shortcuts. Marked slots are reimported and rebuilt, while successful builds remove the marker before side-effects are uploaded.

Route fetch through virtual-store-only install semantics so it populates the standard or global virtual store without linking dependencies into the project.

Related to pnpm/pnpm#13167.

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

    • Improved Global Virtual Store recovery after interrupted build/patch installs using .pnpm-needs-build markers.
    • Prevented incorrect “already up to date” and frozen-lockfile no-ops when marker-based recovery is required.
    • Ensured markers are cleaned up after successful completion and excluded from side-effects cache uploads.
  • Behavior Changes

    • pnpm fetch now populates the (global) virtual store in virtual-store-only mode without creating top-level importer links.
  • Tests / Documentation

    • Expanded Global Virtual Store and fetch test coverage; updated GVS documentation accordingly.

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

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

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@zkochan, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 23 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e9665061-f0d1-40d2-ad93-bffcf1300d98

📥 Commits

Reviewing files that changed from the base of the PR and between 0011e05 and fce5588.

📒 Files selected for processing (3)
  • pnpm/crates/package-manager/src/create_virtual_store.rs
  • pnpm/crates/package-manager/src/import_indexed_dir.rs
  • pnpm/crates/package-manager/src/import_indexed_dir/tests.rs
📝 Walkthrough

Walkthrough

Fetch now uses a virtual-store-only configuration and avoids importer links. Global Virtual Store installs propagate .pnpm-needs-build markers, rebuild marked slots, remove markers after success, and prevent no-op paths from skipping recovery.

Changes

Fetch and GVS recovery

Layer / File(s) Summary
Fetch virtual-store-only behavior
pnpm/crates/cli/src/cli_args/fetch.rs, pnpm/crates/cli/tests/fetch.rs, .changeset/calm-spiders-rebuild.md
fetch derives virtual-store-only settings, populates dependency groups in the virtual store, and verifies that importer links are absent.
Build-marker import handling
pnpm/crates/package-manager/src/lib.rs, pnpm/crates/package-manager/src/import_indexed_dir.rs, pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs, pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot/tests.rs, pnpm/crates/package-manager/src/install_package_by_snapshot.rs
Virtual-directory creation accepts an optional marker source, imports .pnpm-needs-build during fresh or interrupted builds, and updates callers and unit tests.
GVS marker lifecycle
pnpm/crates/package-manager/src/create_virtual_store.rs, pnpm/crates/package-manager/src/build_modules.rs
GVS creates marker sources, identifies slots requiring rebuilds, excludes marked slots from side-effects overlays, propagates marker state, and removes markers after builds.
Install recovery gates and regression coverage
pnpm/crates/package-manager/src/install.rs, pnpm/crates/cli/tests/global_virtual_store.rs, pnpm/crates/cli/tests/install.rs, pnpm/crates/package-manager/Cargo.toml, pnpm/plans/TEST_PORTING.md
Install up-to-date checks detect actionable markers, while GVS tests cover interrupted-build recovery, marker cleanup, side-effects exclusion, and read-only GVS materialization.

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

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#13060: Modifies the same virtual-directory and CAS import path.
  • pnpm/pnpm#13145: Updates the same Global Virtual Store test-porting documentation.
  • pnpm/pnpm#13156: Provides related GVS .pnpm-needs-build test coverage.

Suggested labels: product: pacquet

Suggested reviewers: copilot

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch gvs

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

Finish Global Virtual Store recovery and make fetch virtual-store-only

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Import and honor .pnpm-needs-build to recover interrupted GVS builds safely.
• Route pnpm fetch through virtual-store-only install semantics (no importer links).
• Replace known-failure stubs with contract-based fetch/GVS tests and update porting docs.
Diagram

graph TD
  A["CLI: install / fetch"] --> B["Derived config\n(virtual-store-only)"] --> C["CreateVirtualStore"] --> D{{"GVS marker\npresent?"}} --> E["CreateVirtualDirBySnapshot\n(import CAS + marker)"] --> F["BuildModules\n(remove marker on success)"] --> G[("StoreIndex\nside-effects")]
  subgraph Legend
    direction LR
    _cli["Entry point"] ~~~ _cfg["Config/module"] ~~~ _dec{{"Decision"}} ~~~ _db[("Persistent store")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Persist marker state in StoreIndex (metadata flag) instead of a file
  • ➕ Avoids filesystem scanning of version/hash directories during fast-path checks
  • ➕ Centralizes state in a single durable metadata source
  • ➕ Easier to query for "any interrupted slot" across lockfile packages
  • ➖ Requires careful transactional updates to keep index and on-disk slot contents consistent
  • ➖ More invasive schema/compatibility considerations for StoreIndex consumers
  • ➖ Still needs to handle crash windows where slot exists but index update did not
2. Recompute expected GVS hash dirs deterministically (no directory enumeration)
  • ➕ Avoids walking version directories at startup/no-op checks
  • ➕ More direct mapping from snapshot → expected slot path
  • ➖ Buildable GVS hashes include runtime engine inputs; fast paths intentionally avoid resolving them
  • ➖ Risk of reintroducing the very dependency on runtime resolution this PR sidesteps
  • ➖ Complexity increases for peer/patch variants and future hash scheme changes

Recommendation: The PR’s file-based marker approach is appropriate given GVS crash-recovery semantics: it is simple, durable across crashes, and can be detected without resolving runtime-engine inputs. The targeted directory enumeration in gvs_build_marker_present is a pragmatic tradeoff to keep fast paths correct while avoiding premature runtime resolution.

Files changed (13) +475 / -96

Enhancement (2) +39 / -3
create_virtual_dir_by_snapshot.rsImport build marker atomically and force reimport for interrupted slots +31/-3

Import build marker atomically and force reimport for interrupted slots

• Threads an optional marker source file into slot creation and injects it into CAS paths when a build/patch is expected or recovery is required. Detects interrupted builds by marker presence in the save path, forces 'import_indexed_dir' with 'force=true' and 'keep_modules_dir=true', and ensures marker is imported before completion marker when needed.

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

lib.rsDefine '.pnpm-needs-build' constant and patch detection helper +8/-0

Define '.pnpm-needs-build' constant and patch detection helper

• Adds a shared 'NEEDS_BUILD_MARKER' constant and a helper to detect whether a snapshot key includes a patch hash, enabling consistent marker and rebuild logic across modules.

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

Bug fix (4) +232 / -27
fetch.rsForce fetch to run as virtual-store-only materialization +18/-7

Force fetch to run as virtual-store-only materialization

• Derives a fetch-specific config with 'virtual_store_only=true' and 'enable_modules_dir=true', applies virtual-store-only derivation, and uses it for install orchestration. Ensures fetch populates store/virtual store (including GVS) without relying on importer-link semantics.

pnpm/crates/cli/src/cli_args/fetch.rs

build_modules.rsRemove '.pnpm-needs-build' after successful isolated GVS build and gate overlay reuse +20/-2

Remove '.pnpm-needs-build' after successful isolated GVS build and gate overlay reuse

• In isolated GVS builds that run scripts or apply patches, removes the build marker after success (best-effort, warn on failure). Prevents treating a slot as carrying an overlay if the marker is present, avoiding reuse of half-built slots.

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

create_virtual_store.rsCreate marker source file and reimport marked GVS warm slots +85/-13

Create marker source file and reimport marked GVS warm slots

• Creates a shared empty marker source file in the store root when GVS is enabled and threads it into slot linking when builds/patches are involved. Detects actionable marked slots to avoid warm-path shortcuts and skips applying prefetched side-effects maps when a marker-triggered rebuild is required.

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

install.rsPrevent install fast paths when actionable GVS build markers exist +109/-5

Prevent install fast paths when actionable GVS build markers exist

• Adds detection for '.pnpm-needs-build' in buildable/patched GVS slots and gates both the frozen up-to-date shortcut and the optimistic repeat-install shortcut on marker absence. Implements marker scanning by enumerating hash dirs under relevant name/version dirs to avoid requiring runtime-engine resolution in early fast paths.

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

Refactor (2) +2 / -1
import_indexed_dir.rsExpose completion-marker presence check for reuse by virtual-dir creation +1/-1

Expose completion-marker presence check for reuse by virtual-dir creation

• Makes 'marker_present' visible within the crate so 'create_virtual_dir_by_snapshot' can decide whether it must inject the build marker prior to completion marker logic.

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

install_package_by_snapshot.rsThread marker-source parameter through single-package install path +1/-0

Thread marker-source parameter through single-package install path

• Updates 'CreateVirtualDirBySnapshot' invocation to include the new 'needs_build_marker_source' field (set to None) for the single-package install path.

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

Tests (3) +196 / -64
fetch.rsRewrite fetch tests to assert virtual-store contract (no importer links) +59/-18

Rewrite fetch tests to assert virtual-store contract (no importer links)

• Updates assertions to verify packages materialize under '.pnpm/<slot>/node_modules/<name>' rather than importer symlinks. Adds checks that 'node_modules/<dep>' links are absent and that '.modules.yaml' records 'virtual_store_only: true'; adds a new test for GVS population during fetch.

pnpm/crates/cli/tests/fetch.rs

global_virtual_store.rsAdd GVS interrupted-build marker recovery coverage and remove known-failure stubs +91/-46

Add GVS interrupted-build marker recovery coverage and remove known-failure stubs

• Adds assertions that successful builds remove '.pnpm-needs-build' and that it is not uploaded into side-effects diffs. Implements an end-to-end test that simulates a crash by writing the marker, corrupting pristine files, and validating reimport+rebuild on both frozen and warm/no-op install paths; removes the 'known_failures' module.

pnpm/crates/cli/tests/global_virtual_store.rs

tests.rsAdd unit test ensuring '.pnpm-needs-build' is imported for fresh packages +46/-0

Add unit test ensuring '.pnpm-needs-build' is imported for fresh packages

• Extends test fixtures to pass 'needs_build_marker_source' and adds a focused test that imports a marker into the slot alongside 'package.json', asserting the marker file exists in the extracted package directory.

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

Documentation (2) +6 / -1
calm-spiders-rebuild.mdAdd patch changeset for GVS recovery and fetch semantics +5/-0

Add patch changeset for GVS recovery and fetch semantics

• Introduces a pacquet patch changeset describing improved recovery from interrupted GVS builds and fetch behavior that populates the virtual store without importer linking.

.changeset/calm-spiders-rebuild.md

TEST_PORTING.mdMark GVS needs-build marker test as ported and document behavior +1/-1

Mark GVS needs-build marker test as ported and document behavior

• Updates the test-porting plan entry for the '.pnpm-needs-build' recovery scenario from unchecked/known-failure to completed, describing the new pacquet behavior (import marker, force reimport/rebuild, remove marker, exclude from side-effects uploads).

pnpm/plans/TEST_PORTING.md

@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     11.7±0.09ms    32.0 MB/sec    1.00     11.7±0.04ms    32.0 MB/sec
packument/parse                1.00     39.1±0.06µs  1695.7 MB/sec    1.04     40.7±0.08µs  1628.9 MB/sec
tarball/download_dependency    1.00      2.3±0.08ms  1906.4 KB/sec    1.01      2.3±0.06ms  1882.5 KB/sec

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@greptile-apps

greptile-apps Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge — the changes are well-scoped, guarded at every error path, and covered by integration tests that exercise the marker write, detect, re-import, removal, and side-effects exclusion cycle end-to-end.

The .pnpm-needs-build marker lifecycle is implemented consistently: it is written atomically with the pristine package files, detected at all three no-op shortcuts before they fire, removed only after a confirmed successful build or patch, excluded from side-effects uploads, and treated as absent in the completion-marker check so a warm slot is never incorrectly trusted. The fetch routing to virtual-store-only mode is straightforward and verified by new tests. No unguarded I/O, no data-loss paths, and the tempfile dependency migration from dev to runtime is correct.

No files require special attention.

Reviews (4): Last reviewed commit: "fix: keep GVS marker source on store fil..." | Re-trigger Greptile

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Temp marker breaks clone ✓ Resolved 🐞 Bug ☼ Reliability
Description
CreateVirtualStore now sources the .pnpm-needs-build marker from a NamedTempFile in the system
temp directory, but packageImportMethod=clone uses reflink cloning without an EXDEV/cross-device
fallback, so installs can fail when temp and store are on different filesystems. This is a
PR-introduced failure mode that can break otherwise-valid installs in common CI/container layouts
(separate /tmp mount, store on another volume).
Code

pnpm/crates/package-manager/src/create_virtual_store.rs[R296-304]

+        let needs_build_marker_source =
+            if !config.frozen_store && layout.enable_global_virtual_store() {
+                Some(tempfile::NamedTempFile::new().map_err(|error| {
+                    CreateVirtualStoreError::CreateBuildMarker { path: std::env::temp_dir(), error }
+                })?)
+            } else {
+                None
+            };
+
Evidence
The PR creates the marker source with tempfile::NamedTempFile::new() (system temp), and the import
path can use PackageImportMethod::Clone, which calls reflink_copy::reflink and propagates errors
(no EXDEV fallback). Therefore, if the marker source and destination are on different filesystems,
reflink can fail and the install will error out while importing the marker.

pnpm/crates/package-manager/src/create_virtual_store.rs[296-304]
pnpm/crates/package-manager/src/link_file.rs[208-236]
pnpm/crates/package-manager/src/link_file.rs[253-258]

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 GVS needs-build marker source is created via `tempfile::NamedTempFile::new()` (system temp). When `packageImportMethod=clone`, the import path uses reflink (`reflink_copy::reflink`) without a cross-device fallback, so importing the marker can fail if the temp directory is on a different filesystem than the store/virtual-store, aborting the install.

### Issue Context
This marker is synthetic and exists only to be imported into GVS slots. Unlike normal CAS files (which live in the store), the marker source being placed in the OS temp dir makes cross-device failures plausible.

### Fix Focus Areas
- pnpm/crates/package-manager/src/create_virtual_store.rs[296-304]

### Suggested fix
Prefer creating the marker source in the *store’s filesystem* (security-safe, unpredictable filename) so reflink/hardlink/copy semantics behave consistently:

- Use `tempfile::NamedTempFile::new_in(store_dir.root())` (or equivalent) instead of `NamedTempFile::new()`.
- Keep the existing safety properties (random name, no following attacker-controlled symlinks).

Alternative (less preferred): special-case the marker import so it’s created directly in the target package dir (atomic temp+rename) rather than imported via `link_file` tiers.

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


2. Marker hijacks completion ✓ Resolved 🐞 Bug ≡ Correctness
Description
CreateVirtualDirBySnapshot injects .pnpm-needs-build into the cas_paths map, but
import_indexed_dir selects the completion marker as package.json or else the
lexicographically-smallest key; for CAS entries without package.json, the injected
.pnpm-needs-build can become the completion marker. That conflates “import complete” with “needs
build” and can trigger unnecessary force reimports (because .pnpm-needs-build is also used as
the interrupted-build signal) and/or persist until a build/patch runs and removes it.
Code

pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs[R144-165]

+        let interrupted_build = save_path.join(NEEDS_BUILD_MARKER).is_file();
+        let should_mark_build = needs_build_marker_source.is_some()
+            && (interrupted_build || !marker_present(&save_path, cas_paths));
+        let marked_cas_paths;
+        let cas_paths = if should_mark_build {
+            marked_cas_paths = {
+                let mut paths = cas_paths.clone();
+                paths.insert(
+                    NEEDS_BUILD_MARKER.to_string(),
+                    needs_build_marker_source.expect("checked above").to_path_buf(),
+                );
+                paths
+            };
+            &marked_cas_paths
+        } else {
+            cas_paths
+        };
+        let import_opts = if interrupted_build {
+            ImportIndexedDirOpts { force: true, keep_modules_dir: true }
+        } else {
+            ImportIndexedDirOpts::default()
+        };
Evidence
The injected .pnpm-needs-build key can change import_indexed_dir’s completion-marker choice
because that code explicitly falls back to the lexicographically-smallest key when package.json is
missing. Since .pnpm-needs-build sorts before typical file names, it can become the completion
marker; separately, the recovery path treats .pnpm-needs-build presence as an interrupted build
signal, creating a direct interaction.

pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs[140-166]
pnpm/crates/package-manager/src/import_indexed_dir.rs[250-271]
pnpm/crates/package-manager/src/build_modules.rs[1206-1221]

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

## Issue description
`CreateVirtualDirBySnapshot` may add `.pnpm-needs-build` to `cas_paths` before calling `import_indexed_dir`. `import_indexed_dir::marker_file` falls back to the lexicographically-smallest key when `package.json` is absent, so `.pnpm-needs-build` can become the *completion* marker for legacy/odd entries that lack `package.json`, conflating completion with the build marker.

## Issue Context
- `CreateVirtualDirBySnapshot` injects `NEEDS_BUILD_MARKER` into `cas_paths`.
- `import_indexed_dir::marker_file` uses `package.json` if present, else `min()` over keys.
- The interrupted-build detection also keys off `.pnpm-needs-build`, so making it the completion marker creates unwanted interactions.

## Fix Focus Areas
- pnpm/crates/package-manager/src/import_indexed_dir.rs[250-271]
- pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs[144-166]

## Concrete fix
- Update `marker_file` to ignore `crate::NEEDS_BUILD_MARKER` when selecting the fallback marker (i.e., when `package.json` is absent).
- Add a regression test where `cas_paths` lacks `package.json` and `needs_build_marker_source` is set, asserting the chosen completion marker is *not* `.pnpm-needs-build` and that `.pnpm-needs-build` does not force repeated imports.

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


3. Symlink-clobber marker source ✓ Resolved 🐞 Bug ⛨ Security
Description
The marker-source file is written via fs::write to a predictable path under the (often shared)
store root, which follows symlinks and truncates targets. If an attacker can create/replace
<store>/v11/.pnpm-needs-build-marker with a symlink (e.g., group-writable or otherwise untrusted
store location), running pacquet can overwrite arbitrary files writable by the victim user.
Code

pnpm/crates/package-manager/src/create_virtual_store.rs[R296-304]

+        let needs_build_marker_source = layout
+            .enable_global_virtual_store()
+            .then(|| store_dir.root().join(".pnpm-needs-build-marker"));
+        if let Some(path) = &needs_build_marker_source {
+            fs::write(path, "").map_err(|error| CreateVirtualStoreError::CreateBuildMarker {
+                path: path.clone(),
+                error,
+            })?;
+        }
Evidence
The code writes an empty marker-source file directly into the store root with fs::write, and the
store is described as a shared cache across installs/workspaces. This combination creates an
attacker-controlled path risk when the store directory is not exclusively controlled by the current
user/process.

pnpm/crates/package-manager/src/create_virtual_store.rs[296-304]
pnpm/crates/store-dir/src/store_dir.rs[22-31]

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

## Issue description
`fs::write(path, "")` will follow symlinks. Writing a predictable file name inside a shared/cache directory enables a classic symlink-clobber scenario if the store directory is attacker-writable (or otherwise untrusted), allowing overwrite/truncation of an arbitrary victim-writable target.

## Issue Context
The pnpm store is explicitly designed to be a shared cache across workspaces. Even if the default is per-user, configurations (CI caches, shared volumes, mis-permissioned directories) can make the store writable by other principals.

## Fix Focus Areas
- pnpm/crates/package-manager/src/create_virtual_store.rs[296-304]

## Suggested fix
Implement symlink-resistant creation/update:
- Prefer “write-to-temp + atomic rename” into `<store>/.pnpm-needs-build-marker` (rename replaces the symlink itself rather than following it).
- If the destination exists:
 - validate it is a regular file (via `symlink_metadata`), not a symlink/dir.
 - avoid truncating if not necessary (empty file can be created once and reused).
- On Unix, consider `O_NOFOLLOW` (via `OpenOptionsExt`) for additional defense-in-depth.
- If you cannot safely create/update the marker source, return a structured error that clearly explains the store path is unsafe/corrupted.

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


View more (1)
4. Frozen store writes marker ✓ Resolved 🐞 Bug ☼ Reliability
Description
CreateVirtualStore unconditionally writes .pnpm-needs-build-marker under the store root whenever
GVS is enabled, even when config.frozen_store is true. This breaks the read-only contract of
frozen_store and can fail otherwise-valid installs with PermissionDenied on read-only store
mounts.
Code

pnpm/crates/package-manager/src/create_virtual_store.rs[R296-304]

+        let needs_build_marker_source = layout
+            .enable_global_virtual_store()
+            .then(|| store_dir.root().join(".pnpm-needs-build-marker"));
+        if let Some(path) = &needs_build_marker_source {
+            fs::write(path, "").map_err(|error| CreateVirtualStoreError::CreateBuildMarker {
+                path: path.clone(),
+                error,
+            })?;
+        }
Evidence
The store is explicitly treated as read-only under frozen_store (e.g., directory creation is
skipped), and the build pipeline documents that frozen_store promises the store is read-only.
Despite that, CreateVirtualStore writes the new marker source file unconditionally whenever GVS is
enabled.

pnpm/crates/package-manager/src/create_virtual_store.rs[285-305]
pnpm/crates/package-manager/src/build_modules.rs[66-81]

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

## Issue description
When `config.frozen_store` is enabled, the store must be treated as read-only. The new GVS marker-source creation (`fs::write(<store>/.pnpm-needs-build-marker, "")`) currently runs even under `frozen_store`, which can cause installs to fail on read-only store directories and violates the frozen-store contract.

## Issue Context
This marker source is only needed as an import source when we intend to materialize build markers (i.e., when GVS is enabled and a build/patch might be performed/recovered). Under `frozen_store`, builds/patches that would write into the store should already be rejected or skipped; therefore the marker source should not be created/modified.

## Fix Focus Areas
- pnpm/crates/package-manager/src/create_virtual_store.rs[292-305]

## Suggested fix
- Gate marker-source creation behind `!config.frozen_store`.
- Additionally, consider gating creation behind the same “might need recovery” condition used elsewhere (e.g., only if there are any buildable/patchable packages or config allows builds/patches), so installs that can never consume the marker don’t touch the store.
- Ensure downstream code paths correctly handle `needs_build_marker_source: None` (they already accept `Option<&Path>`).

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



Remediation recommended

5. Marker ignores build policy 🐞 Bug ➹ Performance ⭐ New
Description
snapshot_needs_build_marker() marks GVS slots for any package that "requires build" even when
AllowBuildPolicy will later suppress scripts, so .pnpm-needs-build can persist on
intentionally-unbuilt packages. When such a slot is later materialized, CreateVirtualDirBySnapshot
treats the marker as an interrupted build and forces a re-import path, adding avoidable filesystem
work.
Code

pnpm/crates/package-manager/src/create_virtual_store.rs[R1082-1084]

+fn snapshot_needs_build_marker(snapshot_key: &PackageKey, requires_build: bool) -> bool {
+    requires_build || crate::snapshot_has_patch(snapshot_key)
+}
Evidence
The marker predicate currently ignores allow-build gating, while both build execution and marker
removal depend on AllowBuildPolicy/should_run_scripts. This mismatch allows .pnpm-needs-build
to be imported into slots that will never run scripts, and CreateVirtualDirBySnapshot will later
treat the marker as an interrupted build and force a reimport.

pnpm/crates/package-manager/src/create_virtual_store.rs[672-708]
pnpm/crates/package-manager/src/create_virtual_store.rs[1082-1103]
pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs[144-165]
pnpm/crates/package-manager/src/build_modules.rs[834-899]
pnpm/crates/package-manager/src/build_modules.rs[1206-1220]

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

### Issue description
Global-virtual-store slots are currently marked with `.pnpm-needs-build` whenever a snapshot "requires build" (or has a patch), but the marking decision does not consider whether scripts are actually allowed to run under `AllowBuildPolicy`/`ignore_scripts`. Because marker removal is conditioned on `has_patch || should_run_scripts`, packages whose scripts are disallowed can keep the marker indefinitely, and later slot materializations will take the forced reimport path.

### Issue Context
- Marker creation predicate is `requires_build || snapshot_has_patch(...)`.
- Script execution is separately gated by `AllowBuildPolicy::check(...)` and `ignore_scripts`.
- Marker removal only happens when a patch was applied or scripts actually ran.

### Fix Focus Areas
- pnpm/crates/package-manager/src/create_virtual_store.rs[672-708]
- pnpm/crates/package-manager/src/create_virtual_store.rs[1082-1103]
- pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs[144-165]
- pnpm/crates/package-manager/src/build_modules.rs[834-899]
- pnpm/crates/package-manager/src/build_modules.rs[1206-1220]

### What to change
- Compute “needs marker” as: `has_patch || (requires_build && allow_build_policy.check(dep_path) == Some(true) && !config.ignore_scripts)` (or equivalent), and only pass `needs_build_marker_source` when that is true.
- Keep the existing behavior for patched snapshots (patches should still mark and later remove).
- Ensure the marker is **not** imported for snapshots where scripts are suppressed by policy, so those slots don’t get stuck in “interrupted build” semantics.

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


6. cas_paths cloned for marker 📘 Rule violation ➹ Performance
Description
To import .pnpm-needs-build, the code clones the entire cas_paths map and inserts one extra
entry, which repeats potentially large allocations per snapshot and can regress install performance.
This violates the performance guidance to avoid repeated invariant work/allocation in hot paths when
a narrower approach is available.
Code

pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs[R144-160]

+        let interrupted_build = save_path.join(NEEDS_BUILD_MARKER).is_file();
+        let should_mark_build = needs_build_marker_source.is_some()
+            && (interrupted_build || !marker_present(&save_path, cas_paths));
+        let marked_cas_paths;
+        let cas_paths = if should_mark_build {
+            marked_cas_paths = {
+                let mut paths = cas_paths.clone();
+                paths.insert(
+                    NEEDS_BUILD_MARKER.to_string(),
+                    needs_build_marker_source.expect("checked above").to_path_buf(),
+                );
+                paths
+            };
+            &marked_cas_paths
+        } else {
+            cas_paths
+        };
Evidence
PR Compliance ID 8 requires avoiding unnecessary serialized work and hoisting/avoiding repeated
invariant computation; cloning a whole map per snapshot is repeated allocation work that can be
avoided by passing an extra file entry without duplicating the map. The cited lines show the
cas_paths.clone() performed solely to insert NEEDS_BUILD_MARKER.

CLAUDE.md: Async and loops: prefer async fs and async/await; parallelize independent work; hoist invariants out of loops
pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs[144-160]

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 implementation clones `cas_paths` (a per-package file map) just to add one marker entry, which can add significant overhead when many packages are marked.

## Issue Context
This code runs per snapshot in the virtual-store materialization path; avoid repeated large clones and prefer passing a small overlay/extra-entry to the importer.

## Fix Focus Areas
- pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs[144-160]

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


7. Marker removal errors ignored 📘 Rule violation ☼ Reliability
Description
The new .pnpm-needs-build cleanup ignores any remove_file error (except NotFound) by only
logging a warning, which can leave a slot permanently “half-built” and trigger repeated
rebuild/reimport behavior. This violates the repo’s error-handling convention to avoid swallowing
actionable errors in user-reachable flows.
Code

pnpm/crates/package-manager/src/build_modules.rs[R1206-1219]

+    let built_in_isolated_gvs = layout.enable_global_virtual_store() && pkg_roots_by_key.is_none();
+    if built_in_isolated_gvs && (has_patch || should_run_scripts) {
+        for built_dir in pkg_roots_for_key(layout, pkg_roots_by_key, snapshot_key) {
+            if let Err(error) = std::fs::remove_file(built_dir.join(NEEDS_BUILD_MARKER))
+                && error.kind() != std::io::ErrorKind::NotFound
+            {
+                tracing::warn!(
+                    target: "pacquet::build",
+                    ?error,
+                    dep_path = %snapshot_key,
+                    "failed to remove the global virtual store build marker",
+                );
+            }
+        }
Evidence
PR Compliance ID 5 requires no swallowed errors and specific handling; the new code logs and
continues on marker-removal errors, making failures non-fatal and potentially persistent. The cited
lines show the remove_file error path is degraded to tracing::warn! with no propagation.

CLAUDE.md: Use correct error types and handling conventions (PnpmError for user-facing errors; specific catches; no swallowed errors)
pnpm/crates/package-manager/src/build_modules.rs[1206-1219]

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

## Issue description
`std::fs::remove_file(.../.pnpm-needs-build)` failures are logged and ignored, which can leave the marker behind and cause repeated recovery/rebuild work without surfacing a real underlying filesystem/permission problem.

## Issue Context
This marker is used as correctness state for GVS recovery; failing to remove it after a successful build is an actionable failure.

## Fix Focus Areas
- pnpm/crates/package-manager/src/build_modules.rs[1206-1219]

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


View more (2)
8. Fetch leaks cloned config 🐞 Bug ➹ Performance
Description
FetchArgs::run clones the full Config, mutates it, and calls Config::leak(), permanently
allocating a second config per fetch invocation; in long-lived/embedded use, repeated fetches will
monotonically grow memory and keep auth/config data resident. This is a new permanent-allocation
behavior introduced by routing fetch through a modified config instance.
Code

pnpm/crates/cli/src/cli_args/fetch.rs[R19-34]

+        let mut fetch_config = (*state.config).clone();
+        fetch_config.virtual_store_only = true;
+        fetch_config.enable_modules_dir = true;
+        fetch_config.apply_virtual_store_only_derivation();
+        let fetch_config = fetch_config.leak();
+        let State {
+            tarball_mem_cache,
+            http_client,
+            config: _,
+            manifest,
+            lockfile,
+            resolved_packages,
+        } = &state;

        let &FetchArgs { prod, dev } = &self;
        let has_both = prod == dev;
Evidence
The new fetch implementation explicitly calls Config::leak() on a cloned config, and
Config::leak() is implemented via Box::leak to persist until program termination. This is
required because Install stores config as &'static Config.

pnpm/crates/cli/src/cli_args/fetch.rs[17-67]
pnpm/crates/config/src/lib.rs[2511-2514]
pnpm/crates/package-manager/src/install.rs[147-149]

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

## Issue description
`FetchArgs::run` clones `Config` and uses `Config::leak()` to satisfy `Install`’s `&'static Config` requirement. This permanently leaks memory per invocation and extends the lifetime of any sensitive config fields.

## Issue Context
- `Config::leak()` is explicitly documented to persist until program termination.
- `Install` currently stores `config: &'static Config`, forcing callers to leak when they need a modified config.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/fetch.rs[19-43]
- pnpm/crates/config/src/lib.rs[2511-2514]
- pnpm/crates/package-manager/src/install.rs[147-149]

## Concrete fix options
- Preferably: refactor `Install` to accept `&Config` with a normal lifetime parameter (or `Arc<Config>`), removing the need for `&'static` and `leak()`.
- If a broader refactor is too large: introduce an `InstallConfigOverrides`/`InstallOptions` struct for per-command tweaks (`virtual_store_only`, `enable_modules_dir`, derived fields) so fetch can reuse `state.config` without cloning/leaking.

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


9. Slow marker fast-path 🐞 Bug ➹ Performance
Description
gvs_build_marker_present() is now consulted on “already up to date”/no-op decision paths and it
constructs VirtualStoreLayout::new (which computes calc_graph_node_hash per snapshot) and then
enumerates hash directories via read_dir. On large lockfiles/stores—especially with
dangerously_allow_all_builds or many patched deps—this can significantly increase CPU and
filesystem I/O on the fast path.
Code

pnpm/crates/package-manager/src/install.rs[R2763-2842]

+/// Whether a GVS install can own slots whose interrupted build or patch
+/// application must be recovered from `.pnpm-needs-build`.
+///
+/// The marker is shared store state, so neither optimistic workspace state nor
+/// the frozen importer's symlinks can prove it absent. Only configurations
+/// capable of acting on one need to leave those no-op paths.
+fn gvs_build_markers_may_require_recovery(config: &Config) -> bool {
+    config.enable_global_virtual_store
+        && (config.dangerously_allow_all_builds
+            || config.allow_builds.values().any(|allowed| *allowed)
+            || config.patched_dependencies.as_ref().is_some_and(|patches| !patches.is_empty()))
+}
+
+/// Probe the GVS name/version directories that can contain an actionable
+/// marker for this lockfile. Hash directories are enumerated rather than
+/// recomputed because buildable slots include the runtime engine in their
+/// graph hash, which the pre-runtime fast path deliberately has not resolved.
+fn gvs_build_marker_present(wanted: &Lockfile, config: &Config) -> bool {
+    if !gvs_build_markers_may_require_recovery(config) {
+        return false;
+    }
+    let Ok(policy) = crate::AllowBuildPolicy::from_config(config) else {
+        return true;
+    };
+    let layout = crate::VirtualStoreLayout::new(
+        config,
+        None,
+        wanted.snapshots.as_ref(),
+        wanted.packages.as_ref(),
+        Some(&policy),
+    );
+    if crate::validate_virtual_store_slot_containment(wanted.snapshots.as_ref(), &layout).is_err() {
+        return true;
+    }
+    let Some(snapshots) = wanted.snapshots.as_ref() else {
+        return false;
+    };
+
+    let mut visited_version_dirs = HashSet::new();
+    for snapshot_key in snapshots.keys() {
+        let can_recover = crate::snapshot_has_patch(snapshot_key)
+            || policy.check(&snapshot_key.without_peer().to_string()) == Some(true);
+        if !can_recover {
+            continue;
+        }
+        let Some(version_dir) = layout.slot_dir(snapshot_key).parent().map(Path::to_path_buf)
+        else {
+            return true;
+        };
+        if !visited_version_dirs.insert(version_dir.clone()) {
+            continue;
+        }
+        let hash_dirs = match std::fs::read_dir(&version_dir) {
+            Ok(hash_dirs) => hash_dirs,
+            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
+            Err(_) => return true,
+        };
+        for hash_dir in hash_dirs {
+            let Ok(hash_dir) = hash_dir else {
+                return true;
+            };
+            let Ok(file_type) = hash_dir.file_type() else {
+                return true;
+            };
+            if !file_type.is_dir() {
+                continue;
+            }
+            let Ok(pkg_dir) = crate::safe_join_modules_dir::safe_join_modules_dir(
+                &hash_dir.path().join("node_modules"),
+                &snapshot_key.name.to_string(),
+            ) else {
+                return true;
+            };
+            if pkg_dir.join(crate::NEEDS_BUILD_MARKER).is_file() {
+                return true;
+            }
+        }
+    }
+    false
+}
Evidence
The new fast-path gates call gvs_build_marker_present before returning success. That function
constructs VirtualStoreLayout::new (which iterates all snapshots and calls calc_graph_node_hash)
and then performs filesystem directory enumerations to find markers, adding CPU and I/O to what used
to be a quick up-to-date check.

pnpm/crates/package-manager/src/install.rs[947-955]
pnpm/crates/package-manager/src/install.rs[1546-1551]
pnpm/crates/package-manager/src/install.rs[3491-3496]
pnpm/crates/package-manager/src/install.rs[2776-2841]
pnpm/crates/package-manager/src/virtual_store_layout.rs[153-231]

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

## Issue description
The new GVS recovery probe runs on no-op install paths and currently pays for:
1) constructing a full `VirtualStoreLayout::new` (hash computation across all snapshots), and
2) per-version-dir `read_dir` enumeration.
This can erode fast-path performance on large dependency graphs.

## Issue Context
`gvs_build_marker_present` only needs to discover whether any buildable/patchable package version directory contains a `.pnpm-needs-build` marker under any hash directory. It does **not** need the full `<...>/<hash>` path per snapshot (and therefore does not need to compute graph hashes).

## Fix Focus Areas
- pnpm/crates/package-manager/src/install.rs[2780-2841]
- pnpm/crates/package-manager/src/virtual_store_layout.rs[153-231]
- pnpm/crates/package-manager/src/install.rs[947-975]
- pnpm/crates/package-manager/src/install.rs[1546-1551]
- pnpm/crates/package-manager/src/install.rs[3491-3496]

## Suggested fix
- Replace `VirtualStoreLayout::new(...)` in `gvs_build_marker_present` with a cheaper derivation of the *version directory*:
 - Build `version_dir` as `<config.global_virtual_store_dir>/<scope-or-@>/<name>/<version>` using the same formatting rules as `format_global_virtual_store_path` (but without requiring `<hash>`).
 - This avoids `calc_graph_node_hash` entirely.
- Keep the existing `visited_version_dirs` de-dup.
- Optional: short-circuit quickly when `config.global_virtual_store_dir` does not exist.
- Optional: consider a persistent index/flag to avoid `read_dir` of hash dirs on every no-op run (more invasive, but can restore near-O(1) fast-path behavior).

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

Results up to commit 93c7b85 ⚖️ Balanced


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


Action required
1. Frozen store writes marker ✓ Resolved 🐞 Bug ☼ Reliability
Description
CreateVirtualStore unconditionally writes .pnpm-needs-build-marker under the store root whenever
GVS is enabled, even when config.frozen_store is true. This breaks the read-only contract of
frozen_store and can fail otherwise-valid installs with PermissionDenied on read-only store
mounts.
Code

pnpm/crates/package-manager/src/create_virtual_store.rs[R296-304]

+        let needs_build_marker_source = layout
+            .enable_global_virtual_store()
+            .then(|| store_dir.root().join(".pnpm-needs-build-marker"));
+        if let Some(path) = &needs_build_marker_source {
+            fs::write(path, "").map_err(|error| CreateVirtualStoreError::CreateBuildMarker {
+                path: path.clone(),
+                error,
+            })?;
+        }
Evidence
The store is explicitly treated as read-only under frozen_store (e.g., directory creation is
skipped), and the build pipeline documents that frozen_store promises the store is read-only.
Despite that, CreateVirtualStore writes the new marker source file unconditionally whenever GVS is
enabled.

pnpm/crates/package-manager/src/create_virtual_store.rs[285-305]
pnpm/crates/package-manager/src/build_modules.rs[66-81]

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

## Issue description
When `config.frozen_store` is enabled, the store must be treated as read-only. The new GVS marker-source creation (`fs::write(<store>/.pnpm-needs-build-marker, "")`) currently runs even under `frozen_store`, which can cause installs to fail on read-only store directories and violates the frozen-store contract.

## Issue Context
This marker source is only needed as an import source when we intend to materialize build markers (i.e., when GVS is enabled and a build/patch might be performed/recovered). Under `frozen_store`, builds/patches that would write into the store should already be rejected or skipped; therefore the marker source should not be created/modified.

## Fix Focus Areas
- pnpm/crates/package-manager/src/create_virtual_store.rs[292-305]

## Suggested fix
- Gate marker-source creation behind `!config.frozen_store`.
- Additionally, consider gating creation behind the same “might need recovery” condition used elsewhere (e.g., only if there are any buildable/patchable packages or config allows builds/patches), so installs that can never consume the marker don’t touch the store.
- Ensure downstream code paths correctly handle `needs_build_marker_source: None` (they already accept `Option<&Path>`).

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


2. Symlink-clobber marker source ✓ Resolved 🐞 Bug ⛨ Security
Description
The marker-source file is written via fs::write to a predictable path under the (often shared)
store root, which follows symlinks and truncates targets. If an attacker can create/replace
<store>/v11/.pnpm-needs-build-marker with a symlink (e.g., group-writable or otherwise untrusted
store location), running pacquet can overwrite arbitrary files writable by the victim user.
Code

pnpm/crates/package-manager/src/create_virtual_store.rs[R296-304]

+        let needs_build_marker_source = layout
+            .enable_global_virtual_store()
+            .then(|| store_dir.root().join(".pnpm-needs-build-marker"));
+        if let Some(path) = &needs_build_marker_source {
+            fs::write(path, "").map_err(|error| CreateVirtualStoreError::CreateBuildMarker {
+                path: path.clone(),
+                error,
+            })?;
+        }
Evidence
The code writes an empty marker-source file directly into the store root with fs::write, and the
store is described as a shared cache across installs/workspaces. This combination creates an
attacker-controlled path risk when the store directory is not exclusively controlled by the current
user/process.

pnpm/crates/package-manager/src/create_virtual_store.rs[296-304]
pnpm/crates/store-dir/src/store_dir.rs[22-31]

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

## Issue description
`fs::write(path, "")` will follow symlinks. Writing a predictable file name inside a shared/cache directory enables a classic symlink-clobber scenario if the store directory is attacker-writable (or otherwise untrusted), allowing overwrite/truncation of an arbitrary victim-writable target.

## Issue Context
The pnpm store is explicitly designed to be a shared cache across workspaces. Even if the default is per-user, configurations (CI caches, shared volumes, mis-permissioned directories) can make the store writable by other principals.

## Fix Focus Areas
- pnpm/crates/package-manager/src/create_virtual_store.rs[296-304]

## Suggested fix
Implement symlink-resistant creation/update:
- Prefer “write-to-temp + atomic rename” into `<store>/.pnpm-needs-build-marker` (rename replaces the symlink itself rather than following it).
- If the destination exists:
 - validate it is a regular file (via `symlink_metadata`), not a symlink/dir.
 - avoid truncating if not necessary (empty file can be created once and reused).
- On Unix, consider `O_NOFOLLOW` (via `OpenOptionsExt`) for additional defense-in-depth.
- If you cannot safely create/update the marker source, return a structured error that clearly explains the store path is unsafe/corrupted.

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



Remediation recommended
3. Slow marker fast-path 🐞 Bug ➹ Performance
Description
gvs_build_marker_present() is now consulted on “already up to date”/no-op decision paths and it
constructs VirtualStoreLayout::new (which computes calc_graph_node_hash per snapshot) and then
enumerates hash directories via read_dir. On large lockfiles/stores—especially with
dangerously_allow_all_builds or many patched deps—this can significantly increase CPU and
filesystem I/O on the fast path.
Code

pnpm/crates/package-manager/src/install.rs[R2763-2842]

+/// Whether a GVS install can own slots whose interrupted build or patch
+/// application must be recovered from `.pnpm-needs-build`.
+///
+/// The marker is shared store state, so neither optimistic workspace state nor
+/// the frozen importer's symlinks can prove it absent. Only configurations
+/// capable of acting on one need to leave those no-op paths.
+fn gvs_build_markers_may_require_recovery(config: &Config) -> bool {
+    config.enable_global_virtual_store
+        && (config.dangerously_allow_all_builds
+            || config.allow_builds.values().any(|allowed| *allowed)
+            || config.patched_dependencies.as_ref().is_some_and(|patches| !patches.is_empty()))
+}
+
+/// Probe the GVS name/version directories that can contain an actionable
+/// marker for this lockfile. Hash directories are enumerated rather than
+/// recomputed because buildable slots include the runtime engine in their
+/// graph hash, which the pre-runtime fast path deliberately has not resolved.
+fn gvs_build_marker_present(wanted: &Lockfile, config: &Config) -> bool {
+    if !gvs_build_markers_may_require_recovery(config) {
+        return false;
+    }
+    let Ok(policy) = crate::AllowBuildPolicy::from_config(config) else {
+        return true;
+    };
+    let layout = crate::VirtualStoreLayout::new(
+        config,
+        None,
+        wanted.snapshots.as_ref(),
+        wanted.packages.as_ref(),
+        Some(&policy),
+    );
+    if crate::validate_virtual_store_slot_containment(wanted.snapshots.as_ref(), &layout).is_err() {
+        return true;
+    }
+    let Some(snapshots) = wanted.snapshots.as_ref() else {
+        return false;
+    };
+
+    let mut visited_version_dirs = HashSet::new();
+    for snapshot_key in snapshots.keys() {
+        let can_recover = crate::snapshot_has_patch(snapshot_key)
+            || policy.check(&snapshot_key.without_peer().to_string()) == Some(true);
+        if !can_recover {
+            continue;
+        }
+        let Some(version_dir) = layout.slot_dir(snapshot_key).parent().map(Path::to_path_buf)
+        else {
+            return true;
+        };
+        if !visited_version_dirs.insert(version_dir.clone()) {
+            continue;
+        }
+        let hash_dirs = match std::fs::read_dir(&version_dir) {
+            Ok(hash_dirs) => hash_dirs,
+            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
+            Err(_) => return true,
+        };
+        for hash_dir in hash_dirs {
+            let Ok(hash_dir) = hash_dir else {
+                return true;
+            };
+            let Ok(file_type) = hash_dir.file_type() else {
+                return true;
+            };
+            if !file_type.is_dir() {
+                continue;
+            }
+            let Ok(pkg_dir) = crate::safe_join_modules_dir::safe_join_modules_dir(
+                &hash_dir.path().join("node_modules"),
+                &snapshot_key.name.to_string(),
+            ) else {
+                return true;
+            };
+            if pkg_dir.join(crate::NEEDS_BUILD_MARKER).is_file() {
+                return true;
+            }
+        }
+    }
+    false
+}
Evidence
The new fast-path gates call gvs_build_marker_present before returning success. That function
constructs VirtualStoreLayout::new (which iterates all snapshots and calls calc_graph_node_hash)
and then performs filesystem directory enumerations to find markers, adding CPU and I/O to what used
to be a quick up-to-date check.

pnpm/crates/package-manager/src/install.rs[947-955]
pnpm/crates/package-manager/src/install.rs[1546-1551]
pnpm/crates/package-manager/src/install.rs[3491-3496]
pnpm/crates/package-manager/src/install.rs[2776-2841]
pnpm/crates/package-manager/src/virtual_store_layout.rs[153-231]

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

## Issue description
The new GVS recovery probe runs on no-op install paths and currently pays for:
1) constructing a full `VirtualStoreLayout::new` (hash computation across all snapshots), and
2) per-version-dir `read_dir` enumeration.
This can erode fast-path performance on large dependency graphs.

## Issue Context
`gvs_build_marker_present` only needs to discover whether any buildable/patchable package version directory contains a `.pnpm-needs-build` marker under any hash directory. It does **not** need the full `<...>/<hash>` path per snapshot (and therefore does not need to compute graph hashes).

## Fix Focus Areas
- pnpm/crates/package-manager/src/install.rs[2780-2841]
- pnpm/crates/package-manager/src/virtual_store_layout.rs[153-231]
- pnpm/crates/package-manager/src/install.rs[947-975]
- pnpm/crates/package-manager/src/install.rs[1546-1551]
- pnpm/crates/package-manager/src/install.rs[3491-3496]

## Suggested fix
- Replace `VirtualStoreLayout::new(...)` in `gvs_build_marker_present` with a cheaper derivation of the *version directory*:
 - Build `version_dir` as `<config.global_virtual_store_dir>/<scope-or-@>/<name>/<version>` using the same formatting rules as `format_global_virtual_store_path` (but without requiring `<hash>`).
 - This avoids `calc_graph_node_hash` entirely.
- Keep the existing `visited_version_dirs` de-dup.
- Optional: short-circuit quickly when `config.global_virtual_store_dir` does not exist.
- Optional: consider a persistent index/flag to avoid `read_dir` of hash dirs on every no-op run (more invasive, but can restore near-O(1) fast-path behavior).

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


Results up to commit eb41848 ⚖️ Balanced


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


Action required
1. Temp marker breaks clone ✓ Resolved 🐞 Bug ☼ Reliability
Description
CreateVirtualStore now sources the .pnpm-needs-build marker from a NamedTempFile in the system
temp directory, but packageImportMethod=clone uses reflink cloning without an EXDEV/cross-device
fallback, so installs can fail when temp and store are on different filesystems. This is a
PR-introduced failure mode that can break otherwise-valid installs in common CI/container layouts
(separate /tmp mount, store on another volume).
Code

pnpm/crates/package-manager/src/create_virtual_store.rs[R296-304]

+        let needs_build_marker_source =
+            if !config.frozen_store && layout.enable_global_virtual_store() {
+                Some(tempfile::NamedTempFile::new().map_err(|error| {
+                    CreateVirtualStoreError::CreateBuildMarker { path: std::env::temp_dir(), error }
+                })?)
+            } else {
+                None
+            };
+
Evidence
The PR creates the marker source with tempfile::NamedTempFile::new() (system temp), and the import
path can use PackageImportMethod::Clone, which calls reflink_copy::reflink and propagates errors
(no EXDEV fallback). Therefore, if the marker source and destination are on different filesystems,
reflink can fail and the install will error out while importing the marker.

pnpm/crates/package-manager/src/create_virtual_store.rs[296-304]
pnpm/crates/package-manager/src/link_file.rs[208-236]
pnpm/crates/package-manager/src/link_file.rs[253-258]

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 GVS needs-build marker source is created via `tempfile::NamedTempFile::new()` (system temp). When `packageImportMethod=clone`, the import path uses reflink (`reflink_copy::reflink`) without a cross-device fallback, so importing the marker can fail if the temp directory is on a different filesystem than the store/virtual-store, aborting the install.

### Issue Context
This marker is synthetic and exists only to be imported into GVS slots. Unlike normal CAS files (which live in the store), the marker source being placed in the OS temp dir makes cross-device failures plausible.

### Fix Focus Areas
- pnpm/crates/package-manager/src/create_virtual_store.rs[296-304]

### Suggested fix
Prefer creating the marker source in the *store’s filesystem* (security-safe, unpredictable filename) so reflink/hardlink/copy semantics behave consistently:

- Use `tempfile::NamedTempFile::new_in(store_dir.root())` (or equivalent) instead of `NamedTempFile::new()`.
- Keep the existing safety properties (random name, no following attacker-controlled symlinks).

Alternative (less preferred): special-case the marker import so it’s created directly in the target package dir (atomic temp+rename) rather than imported via `link_file` tiers.

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


Qodo Logo

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

1546-1553: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Reorder cheap rebuild.is_none() before the FS-probing checks.

rebuild.is_none() is a plain field check, yet it sits after gvs_build_marker_present(...) (a read_dir-based scan) and before frozen_tree_intact(...) (another FS probe). Since the comment on the next line states an explicit rebuild "never short-circuits here" regardless of markers, moving rebuild.is_none() earlier in the && chain lets a pacquet rebuild skip both FS probes entirely.

♻️ Suggested reordering
         && !has_newly_allowed_ignored_builds(modules, config)
         && !has_revoked_allowed_builds(modules, config)
-            // A build marker lives in the shared slot, outside every
-            // project-state input checked above. Let materialization inspect
-            // buildable and patched GVS slots instead of declaring the local
-            // tree complete from importer links alone.
-            && !gvs_build_marker_present(wanted_lockfile, config)
-            // An explicit `pacquet rebuild` always re-runs the build phase,
-            // so it never short-circuits here.
-            && rebuild.is_none()
+            // An explicit `pacquet rebuild` always re-runs the build phase,
+            // so it never short-circuits here.
+            && rebuild.is_none()
+            // A build marker lives in the shared slot, outside every
+            // project-state input checked above. Let materialization inspect
+            // buildable and patched GVS slots instead of declaring the local
+            // tree complete from importer links alone.
+            && !gvs_build_marker_present(wanted_lockfile, config)
             && frozen_tree_intact(wanted_lockfile, modules, config, &workspace_root, node_linker)
🤖 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.rs` around lines 1546 - 1553, Reorder
the condition in the surrounding install-state check so rebuild.is_none() is
evaluated before gvs_build_marker_present(...) and frozen_tree_intact(...).
Preserve the existing behavior that an explicit rebuild bypasses the
short-circuit, while ensuring it avoids both filesystem-probing checks.

2763-2843: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

gvs_build_marker_present can run twice per install for the same answer. When the optimistic fast path finds marker_safe == false (i.e. a marker is actually present), execution falls through and can later re-enter the frozen "no-op" check, which calls the same read_dir-based scan against the same wanted lockfile again. With a broad allowBuilds/dangerouslyAllowAllBuilds config (exactly the scenario REVIEW_GUIDE.md's performance-second guidance warns about), this doubles an already lockfile-wide FS scan.

  • pnpm/crates/package-manager/src/install.rs#L2763-L2843: introduce a small cache (e.g. compute lazily once into a Cell<Option<bool>>/OnceCell<bool> scoped to run_inner) so the second caller reuses the first result instead of re-walking the store.
  • pnpm/crates/package-manager/src/install.rs#L947-L955: on first need, compute and stash the marker-presence result in the shared cache instead of only using it locally.
  • pnpm/crates/package-manager/src/install.rs#L1546-L1550: read from the shared cache here instead of calling gvs_build_marker_present a second time.
🤖 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.rs` around lines 2763 - 2843, Cache
the result of gvs_build_marker_present once per run_inner invocation, using a
shared lazy Cell/OnceCell, and reuse it at both call sites. In
pnpm/crates/package-manager/src/install.rs:947-955, compute and store the result
on first use; in pnpm/crates/package-manager/src/install.rs:1546-1550, read the
cached value instead of rescanning; update gvs_build_marker_present at
pnpm/crates/package-manager/src/install.rs:2763-2843 only as needed to support
this cache.

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.

Inline comments:
In @.changeset/calm-spiders-rebuild.md:
- Around line 1-5: Update the changeset frontmatter to include both the existing
"pacquet" patch entry and a "pnpm" patch entry, reflecting the user-visible
parity changes described in the summary.

In `@pnpm/crates/package-manager/src/create_virtual_store.rs`:
- Around line 296-305: Gate creation and writing of needs_build_marker_source on
both global virtual store being enabled and config.frozen_store being false.
Update the logic around needs_build_marker_source in create_virtual_store so
frozen-store + GVS installs avoid all writes under the read-only store root
while preserving marker creation for writable GVS installs; add a regression
test in global_virtual_store.rs for a frozen-store GVS install with no build
required.

---

Nitpick comments:
In `@pnpm/crates/package-manager/src/install.rs`:
- Around line 1546-1553: Reorder the condition in the surrounding install-state
check so rebuild.is_none() is evaluated before gvs_build_marker_present(...) and
frozen_tree_intact(...). Preserve the existing behavior that an explicit rebuild
bypasses the short-circuit, while ensuring it avoids both filesystem-probing
checks.
- Around line 2763-2843: Cache the result of gvs_build_marker_present once per
run_inner invocation, using a shared lazy Cell/OnceCell, and reuse it at both
call sites. In pnpm/crates/package-manager/src/install.rs:947-955, compute and
store the result on first use; in
pnpm/crates/package-manager/src/install.rs:1546-1550, read the cached value
instead of rescanning; update gvs_build_marker_present at
pnpm/crates/package-manager/src/install.rs:2763-2843 only as needed to support
this cache.
🪄 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: 33c4ae71-cc9d-41cd-b1a3-dbdca6bd61d4

📥 Commits

Reviewing files that changed from the base of the PR and between b92edcb and 19f3963.

📒 Files selected for processing (13)
  • .changeset/calm-spiders-rebuild.md
  • pnpm/crates/cli/src/cli_args/fetch.rs
  • pnpm/crates/cli/tests/fetch.rs
  • pnpm/crates/cli/tests/global_virtual_store.rs
  • pnpm/crates/package-manager/src/build_modules.rs
  • pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot/tests.rs
  • pnpm/crates/package-manager/src/create_virtual_store.rs
  • pnpm/crates/package-manager/src/import_indexed_dir.rs
  • pnpm/crates/package-manager/src/install.rs
  • pnpm/crates/package-manager/src/install_package_by_snapshot.rs
  • pnpm/crates/package-manager/src/lib.rs
  • pnpm/plans/TEST_PORTING.md

Comment thread .changeset/calm-spiders-rebuild.md Resolved
@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 20, 2026 11:21

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

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

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@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 20, 2026 11:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants