Skip to content

fix(fs): distinguish an unavailable lock from a busy one - #13377

Merged
zkochan merged 4 commits into
mainfrom
fix-dir-lock-error-visibility
Jul 25, 2026
Merged

zkochan merged 4 commits into
mainfrom
fix-dir-lock-error-visibility

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to #13375. This was raised in review there (by Qodo) after the PR had already merged, so it lands on its own.

DirLock::acquire folded a failure to write the lock's owner record into Ok(None) — the same answer it gives when another process holds the lock. Those are different situations. One is the wait doing its job; the other means the locking mechanism itself is broken and the caller is about to run without the lock and without knowing why. That distinction matters most at the engine install, which is exactly where the lock exists to keep concurrent destructive installs out of a shared global-virtual-store slot.

The write failure now propagates as Err, alongside the parent-directory failure that already did. The engine-install caller still proceeds — a lock it cannot take is not a reason to refuse to run — but logs what happened instead of silently reverting to the racy behavior that #13375 set out to fix.

Notes for reviewers

  • No test. Making create_dir succeed while a write inside it fails needs a filesystem fault-injection seam pacquet-fs does not have. pnpm/AGENTS.md sanctions the Sys seam for exactly this kind of error-kind branch, but adding one to DirLock for a single assertion costs more than the signature change is worth. The existing four dir_lock tests still cover acquire/release, contention, takeover, and the stale-successor case.
  • The behavior on the busy path is unchanged — a lock another process holds is still waited for, then reported as Ok(None).

Squash Commit Body

`DirLock::acquire` folded a failure to write the owner record into
`Ok(None)`, which is the same answer it gives when another process holds
the lock. Those are different situations: one is the wait doing its job,
the other means the locking mechanism itself is broken and the caller is
about to run without the lock and without knowing why. That matters most
at the engine install, where the lock exists to keep concurrent
destructive installs out of a shared store slot.

The write failure now propagates as `Err`, alongside the parent-directory
failure that already did. The engine-install caller still proceeds — a
lock it cannot take is not a reason to refuse to run — but logs what
happened rather than silently reverting to the racy behavior.

Follow-up to pnpm/pnpm#13375, raised in review there after it merged.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
    (Rust-only: DirLock has no TypeScript counterpart.)
  • 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. (See "Notes for reviewers".)

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


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes
    • Pinned package manager installations now emit a warning when the install lock can’t be acquired (e.g., unwritable store or lock mechanism failures), including the lock path and underlying error.
    • Lock acquisition failures are no longer silently ignored; installs proceed without the lock, while waiting on locks held by other processes is unchanged.
  • Documentation
    • Updated lock acquisition documentation to clarify the difference between lock contention and lock mechanism failures.
  • Tests
    • Added a unit test covering failure to claim the lock directory when the owner record can’t be written.

`DirLock::acquire` folded a failure to write the owner record into
`Ok(None)`, which is the same answer it gives when another process holds
the lock. Those are different situations: one is the wait doing its job,
the other means the locking mechanism itself is broken and the caller is
about to run without the lock and without knowing why. That matters most
at the engine install, where the lock exists to keep concurrent
destructive installs out of a shared store slot.

The write failure now propagates as `Err`, alongside the parent-directory
failure that already did. The engine-install caller still proceeds — a
lock it cannot take is not a reason to refuse to run — but logs what
happened rather than silently reverting to the racy behavior.

Follow-up to #13375, raised in review there after it merged.

Not covered by a test: making `create_dir` succeed while a write inside
it fails needs a filesystem fault-injection seam this crate does not
have, and the alternatives are unportable enough to be worth less than
the signature itself.
Copilot AI review requested due to automatic review settings July 25, 2026 22:24

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 25, 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: e784326f-ad2d-4bc5-b031-7f6345376607

📥 Commits

Reviewing files that changed from the base of the PR and between 7ef402a and 2eda840.

📒 Files selected for processing (1)
  • pnpm/crates/fs/src/dir_lock/tests.rs

📝 Walkthrough

Walkthrough

The lock implementation now distinguishes contention from mechanism failures. Engine installation warns when the lock cannot be acquired, continues without serialization, and documents the behavior in a patch Changeset.

Changes

Engine lock failure reporting

Layer / File(s) Summary
Directory lock error semantics and validation
pnpm/crates/fs/src/dir_lock.rs, pnpm/crates/fs/src/dir_lock/tests.rs
DirLock::acquire documents and returns owner-record write failures as errors while retaining Ok(None) for locks held by another process; a test verifies cleanup and the propagated error.
Engine install warning and release note
pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs, .changeset/engine-lock-failure-is-reported.md
Engine installation logs lock-acquisition errors before proceeding without serialization, and the Changeset records the updated behavior.

Estimated code review effort: 2 (Simple) | ~10 minutes

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 fix-dir-lock-error-visibility

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix DirLock: surface lock mechanism failures separately from contention

🐞 Bug fix ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• Treat lock owner-record write failures as hard errors, not lock contention.
• Warn during engine installs when lock acquisition fails due to unwritable store.
• Add changeset documenting the new warning behavior for pinned engine installs.
Diagram

graph TD
  A["CLI: engine_install_lock"] --> B["fs: DirLock::acquire"] --> C[("Filesystem / store tmp")] --> D{"Acquire outcome"}
  D -->|"Ok(Some)"| E["Serialized install"]
  D -->|"Ok(None)"| F["Waited out; run unlocked"]
  D -->|"Err"| G["tracing::warn + run unlocked"]

  subgraph Legend
    direction LR
    _fn["Function/module"] ~~~ _fs[("Filesystem")] ~~~ _dec{"Decision"}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Introduce a dedicated outcome enum (Acquired/Busy/Broken)
  • ➕ Encodes semantics explicitly without overloading Option for contention
  • ➕ Allows attaching richer context for 'broken' (e.g., which step failed)
  • ➖ Wider API churn than leveraging existing io::Result>
  • ➖ More refactors across call sites and tests for a narrowly scoped behavior fix
2. Log inside the fs crate when lock owner write fails
  • ➕ Guarantees visibility even if callers ignore Err
  • ➕ Centralizes observability of lock mechanism failures
  • ➖ Library-level logging may be undesirable/too noisy for non-CLI consumers
  • ➖ Reduces flexibility for callers to decide severity and messaging

Recommendation: Current approach is appropriate: keep contention as Ok(None), but propagate true lock mechanism failures as Err and let the engine-install caller decide how to degrade (warn + proceed). This minimizes API churn, preserves the existing "busy" contract, and improves debuggability exactly where the lock matters most.

Files changed (3) +41 / -15

Bug fix (2) +36 / -15
install_pnpm_to_store.rsWarn when engine-install lock acquisition fails with an error +15/-1

Warn when engine-install lock acquisition fails with an error

• Updates engine lock acquisition to handle DirLock::acquire errors explicitly. On Err, emits a tracing::warn with the lock path and error, then proceeds without a lock as before.

pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs

dir_lock.rsDirLock::acquire: return Err when owner record cannot be written +21/-14

DirLock::acquire: return Err when owner record cannot be written

• Refines DirLock::acquire semantics: Ok(None) is reserved for true contention/timeouts, while failures to write the owner file now propagate as Err. On owner-write failure, the lock directory is still cleaned up best-effort to avoid leaving an unidentifiable lock behind.

pnpm/crates/fs/src/dir_lock.rs

Other (1) +5 / -0
engine-lock-failure-is-reported.mdChangeset: report engine-lock failures when store is unwritable +5/-0

Changeset: report engine-lock failures when store is unwritable

• Adds a patch-level changeset for pacquet describing that engine installs now report when they cannot take the lock due to an unwritable store. Clarifies that normal contention behavior (wait then Ok(None)) is unchanged.

.changeset/engine-lock-failure-is-reported.md

@greptile-apps

greptile-apps Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

The previously invisible warning now reaches the normal default and NDJSON reporters, and no blocking failure remains.

Reviews (4): Last reviewed commit: "test(fs): make the unrecordable-lock ass..." | Re-trigger Greptile

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. Claim test ineffective ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The new test forces claim() to fail via a missing directory (ErrorKind::NotFound), but claim()
is only called after DirLock::acquire has successfully created the lock directory, so the
production failure mode is “existing dir, owner write fails.” As written, the cleanup assertion
(!path.exists()) will pass even if the cleanup-on-write-failure path regresses, because the
directory was never created.
Code

pnpm/crates/fs/src/dir_lock/tests.rs[R92-101]

+fn claiming_a_directory_that_cannot_hold_the_record_fails() {
+    let root = tempdir().expect("create tempdir");
+    // Nothing at this path, so writing the owner record inside it fails —
+    // standing in for the unwritable store the real caller hits.
+    let path = root.path().join("missing").join("engine.lock");
+
+    let error = super::claim(path.clone()).expect_err("an unrecordable lock is not taken");
+
+    assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
+    assert!(!path.exists(), "no lock is left behind");
Relevance

⭐⭐⭐ High

Repo often accepts strengthening tests to match real behavior and avoid false positives/flakiness;
this aligns with that pattern.

PR-#13375
PR-#13372

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
claim() is only called after the lock directory is created (so the directory exists in the real
failure case), but the test calls claim() on a path whose parent doesn’t exist, so it can’t
validate cleanup of a just-created lock directory when writing the owner record fails.

pnpm/crates/fs/src/dir_lock.rs[62-65]
pnpm/crates/fs/src/dir_lock.rs[109-116]
pnpm/crates/fs/src/dir_lock/tests.rs[91-101]

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

## Issue description
`claim()` is only reached after `fs::create_dir(&path)` succeeds, but the new test calls `claim()` with a non-existent path (triggering `NotFound`). This doesn’t validate the intended scenario (“lock dir exists but writing `OWNER_FILE` fails”) and makes the cleanup assertion non-actionable.

## Issue Context
- Production call path: `DirLock::acquire` invokes `claim(path)` only after creating the directory.
- The test currently simulates failure by not creating the directory at all.

## Fix Focus Areas
- pnpm/crates/fs/src/dir_lock/tests.rs[91-102]

## Suggested fix
Change the test setup to create the lock directory first, then force a deterministic failure when writing the owner record **inside an existing directory**. For example:

- `fs::create_dir_all(&path)` to ensure the lock directory exists.
- Create a directory at `path.join("owner")` (or otherwise make that path non-writable) so `fs::write(path.join("owner"), ...)` fails reliably.
- Assert `claim(path.clone())` returns `Err(_)` and that `path` is removed (verifying the cleanup path actually runs).
- Avoid asserting a single cross-platform `ErrorKind` if it varies (e.g., `IsADirectory` vs `PermissionDenied`); instead assert it is an error and that cleanup occurred.

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


2. Terminal escape injection 🐞 Bug ⛨ Security
Description
engine_install_lock() emits a warning that interpolates a filesystem path and raw io::Error into
PnpmLog.message, and the default reporter prints that message directly to the terminal without
sanitization. Because environment variables and filesystem paths are treated as attacker-controlled
in this repo, a crafted store/PNPM_HOME path (or error text that includes it) can inject
ANSI/control sequences into user output.
Code

pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R188-195]

+    Reporter::emit(&LogEvent::Pnpm(PnpmLog {
+        level: LogLevel::Warn,
+        message: format!(
+            "Could not lock the pnpm engine install at {}: {error}. Installing without it, which is unsafe if another pnpm is installing the same version.",
+            path.display(),
+        ),
+        prefix: String::new(),
+    }));
Relevance

⭐⭐⭐ High

Repo recently accepted stripping control characters from untrusted strings before terminal output
(paths/errors) to prevent escape injection.

PR-#13287
PR-#13230
PR-#13202

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new warning formats a message with raw path.display() and {error}. The default reporter
routes PnpmLog warnings to push_warning(), which directly interpolates the message into terminal
output without sanitization. The repo’s review guide explicitly treats env vars and filesystem paths
as attacker-controlled, and there is existing precedent for stripping control characters before
terminal output.

pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[179-196]
pnpm/crates/default-reporter/src/state.rs[1094-1105]
pnpm/crates/default-reporter/src/state.rs[1215-1222]
REVIEW_GUIDE.md[30-46]
pnpm/crates/pack/src/lib.rs[469-513]
PR-#13287

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

### Issue description
`engine_install_lock()` emits a warning that includes `path.display()` and `{error}` verbatim. These values can contain control characters (paths come from env/config), and the default reporter prints warning messages to the terminal without stripping control characters, enabling terminal escape/control-sequence injection.

### Issue Context
- The warning is newly added on the lock-establishment failure path.
- Repo guidance treats env vars and filesystem paths as attacker-controlled.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[188-195]

### Recommended fix
- Strip terminal control characters from the interpolated values before constructing `PnpmLog.message`.
 - e.g., introduce/reuse a small helper (similar to `sanitize_for_terminal` in `pnpm/crates/pack`) and apply it to `path.display().to_string()` and `error.to_string()`.
- Alternative (more comprehensive): sanitize `PnpmLog` messages at the output boundary in the default reporter (e.g., in `on_pnpm` / `push_warning`), but that is a broader behavior change.

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


3. Invalid lock path treated busy 🐞 Bug ☼ Reliability
Description
DirLock::acquire treats any create_dir() error with kind AlreadyExists as normal contention, so if
the lock path exists as a non-directory (e.g., a stale file/symlink), it will wait and return
Ok(None) rather than Err. That bypasses the new “mechanism failed” warning in engine_install_lock
and can add an unnecessary WAIT delay before proceeding unserialized.
Code

pnpm/crates/fs/src/dir_lock.rs[R66-86]

            match fs::create_dir(&path) {
                Ok(()) => {
                    let token = mint_token();
-                    if fs::write(path.join(OWNER_FILE), &token).is_ok() {
-                        return Ok(Some(DirLock { path, token }));
-                    }
-                    // Without its owner record this lock cannot tell, at
-                    // release time, whether it is still the one it took.
-                    // Rather than hold an unidentifiable lock, give the
-                    // directory back and report the lock as not taken —
-                    // the caller's documented degradation is to proceed
-                    // unserialized, which is no worse than not having
-                    // tried.
-                    let _ = fs::remove_dir_all(&path);
-                    return Ok(None);
+                    return match fs::write(path.join(OWNER_FILE), &token) {
+                        Ok(()) => Ok(Some(DirLock { path, token })),
+                        // Without its owner record this lock cannot tell,
+                        // at release time, whether it is still the one it
+                        // took, so hand the directory back rather than
+                        // hold an unidentifiable lock. Reported as an
+                        // error, not as a busy lock: a store this process
+                        // cannot write is not the same as one another
+                        // process is using, and the caller should be able
+                        // to say which happened.
+                        Err(error) => {
+                            let _ = fs::remove_dir_all(&path);
+                            Err(error)
+                        }
+                    };
                }
                Err(error) if error.kind() != io::ErrorKind::AlreadyExists => return Err(error),
                Err(_) => {}
Relevance

⭐⭐ Medium

Repo accepts DirLock hardening, but no close precedent on non-directory AlreadyExists being
misclassified as contention.

PR-#13375

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The acquire loop explicitly treats all AlreadyExists outcomes as contention (no check that the
existing path is a lock directory). The engine-install caller only warns on Err; an Ok(None) return
remains silent and therefore would not report this mechanism-failure case.

pnpm/crates/fs/src/dir_lock.rs[56-99]
pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[159-188]

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

## Issue description
`DirLock::acquire` currently treats `io::ErrorKind::AlreadyExists` from `fs::create_dir(&path)` as “another process holds the lock” without validating what actually exists at `path`. If `path` is a file (or other non-directory), acquisition will spin/sleep until the deadline and then return `Ok(None)`, which callers interpret as ordinary contention.

This undermines the PR’s goal of distinguishing “busy” from “lock mechanism failed”, because this mechanism-failure mode will not produce an `Err` and therefore won’t trigger the new warning in the engine install flow.

## Issue Context
This is not a regression introduced by this PR, but it is a gap relative to the new error-visibility behavior: callers now warn on `Err`, but this failure mode is still surfaced as `Ok(None)`.

## Fix Focus Areas
- pnpm/crates/fs/src/dir_lock.rs[66-99]
- pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[167-187]

### Suggested approach (performance-conscious)
- In the `AlreadyExists` branch, verify that `path` is a directory.
 - If it is not a directory, return `Err(...)` (so callers can warn).
- Avoid adding extra syscalls on the normal contention hot-path:
 - Keep a boolean (e.g. `validated_existing_dir: bool`) outside the loop; only `metadata()`-check once when you first see `AlreadyExists`, and only re-check if subsequent operations indicate the path changed.

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



Informational

4. Hardcoded owner record name 🐞 Bug ⚙ Maintainability ⭐ New
Description
The new test hardcodes "owner" when setting up the blocked owner-record path, duplicating the
production OWNER_FILE constant. If OWNER_FILE is ever renamed, the test setup will no longer
match the implementation and will likely fail for the wrong reason (or need manual updates) instead
of remaining coupled to the source of truth.
Code

pnpm/crates/fs/src/dir_lock/tests.rs[98]

+    fs::create_dir_all(path.join("owner")).expect("block the owner record");
Relevance

⭐⭐⭐ High

Team has accepted replacing hardcoded test paths with shared constants to prevent drift on
refactors.

PR-#12831

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test currently creates a directory at path/owner using a string literal, while the production
code uses the OWNER_FILE constant to choose the owner-record path; this is unnecessary duplication
and can drift on refactor.

pnpm/crates/fs/src/dir_lock/tests.rs[92-103]
pnpm/crates/fs/src/dir_lock.rs[26-28]
pnpm/crates/fs/src/dir_lock.rs[112-116]

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

### Issue description
A test hardcodes the owner-record filename ("owner") instead of using the implementation constant (`OWNER_FILE`). This couples the test to an implementation detail and makes future refactors (renaming the owner record file) require coordinated manual updates.

### Issue Context
`DirLock::claim()` writes to `path.join(OWNER_FILE)`. The test should block *that* exact path using the same constant.

### Fix Focus Areas
- pnpm/crates/fs/src/dir_lock/tests.rs[94-98]

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


5. pnpm missing changeset entry 📘 Rule violation § Compliance
Description
The new changeset front-matter declares only pacquet and omits a pnpm entry. This violates the
requirement that changesets explicitly declare the pnpm package and its bump type.
Code

.changeset/engine-lock-failure-is-reported.md[R1-3]

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

⭐ Low

Very similar “add pnpm entry to pacquet-only changeset” suggestions were repeatedly rejected in
recent PRs.

PR-#12981
PR-#12991
PR-#13346

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each newly added/modified changeset to include an explicit pnpm
package entry and bump type. The added changeset front-matter includes only "pacquet": patch and
does not list pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/engine-lock-failure-is-reported.md[1-3]

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

## Issue description
The changeset `.changeset/engine-lock-failure-is-reported.md` is missing a `pnpm` package entry in its front-matter.

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

## Fix Focus Areas
- .changeset/engine-lock-failure-is-reported.md[1-3]

ⓘ 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 2eda840

Results up to commit c79f3e9 ⚖️ Balanced


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


Remediation recommended
1. Invalid lock path treated busy 🐞 Bug ☼ Reliability
Description
DirLock::acquire treats any create_dir() error with kind AlreadyExists as normal contention, so if
the lock path exists as a non-directory (e.g., a stale file/symlink), it will wait and return
Ok(None) rather than Err. That bypasses the new “mechanism failed” warning in engine_install_lock
and can add an unnecessary WAIT delay before proceeding unserialized.
Code

pnpm/crates/fs/src/dir_lock.rs[R66-86]

            match fs::create_dir(&path) {
                Ok(()) => {
                    let token = mint_token();
-                    if fs::write(path.join(OWNER_FILE), &token).is_ok() {
-                        return Ok(Some(DirLock { path, token }));
-                    }
-                    // Without its owner record this lock cannot tell, at
-                    // release time, whether it is still the one it took.
-                    // Rather than hold an unidentifiable lock, give the
-                    // directory back and report the lock as not taken —
-                    // the caller's documented degradation is to proceed
-                    // unserialized, which is no worse than not having
-                    // tried.
-                    let _ = fs::remove_dir_all(&path);
-                    return Ok(None);
+                    return match fs::write(path.join(OWNER_FILE), &token) {
+                        Ok(()) => Ok(Some(DirLock { path, token })),
+                        // Without its owner record this lock cannot tell,
+                        // at release time, whether it is still the one it
+                        // took, so hand the directory back rather than
+                        // hold an unidentifiable lock. Reported as an
+                        // error, not as a busy lock: a store this process
+                        // cannot write is not the same as one another
+                        // process is using, and the caller should be able
+                        // to say which happened.
+                        Err(error) => {
+                            let _ = fs::remove_dir_all(&path);
+                            Err(error)
+                        }
+                    };
                }
                Err(error) if error.kind() != io::ErrorKind::AlreadyExists => return Err(error),
                Err(_) => {}
Relevance

⭐⭐ Medium

Repo accepts DirLock hardening, but no close precedent on non-directory AlreadyExists being
misclassified as contention.

PR-#13375

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The acquire loop explicitly treats all AlreadyExists outcomes as contention (no check that the
existing path is a lock directory). The engine-install caller only warns on Err; an Ok(None) return
remains silent and therefore would not report this mechanism-failure case.

pnpm/crates/fs/src/dir_lock.rs[56-99]
pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[159-188]

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

## Issue description
`DirLock::acquire` currently treats `io::ErrorKind::AlreadyExists` from `fs::create_dir(&path)` as “another process holds the lock” without validating what actually exists at `path`. If `path` is a file (or other non-directory), acquisition will spin/sleep until the deadline and then return `Ok(None)`, which callers interpret as ordinary contention.

This undermines the PR’s goal of distinguishing “busy” from “lock mechanism failed”, because this mechanism-failure mode will not produce an `Err` and therefore won’t trigger the new warning in the engine install flow.

## Issue Context
This is not a regression introduced by this PR, but it is a gap relative to the new error-visibility behavior: callers now warn on `Err`, but this failure mode is still surfaced as `Ok(None)`.

## Fix Focus Areas
- pnpm/crates/fs/src/dir_lock.rs[66-99]
- pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[167-187]

### Suggested approach (performance-conscious)
- In the `AlreadyExists` branch, verify that `path` is a directory.
 - If it is not a directory, return `Err(...)` (so callers can warn).
- Avoid adding extra syscalls on the normal contention hot-path:
 - Keep a boolean (e.g. `validated_existing_dir: bool`) outside the loop; only `metadata()`-check once when you first see `AlreadyExists`, and only re-check if subsequent operations indicate the path changed.

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



Informational
2. pnpm missing changeset entry 📘 Rule violation § Compliance
Description
The new changeset front-matter declares only pacquet and omits a pnpm entry. This violates the
requirement that changesets explicitly declare the pnpm package and its bump type.
Code

.changeset/engine-lock-failure-is-reported.md[R1-3]

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

⭐ Low

Very similar “add pnpm entry to pacquet-only changeset” suggestions were repeatedly rejected in
recent PRs.

PR-#12981
PR-#12991
PR-#13346

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each newly added/modified changeset to include an explicit pnpm
package entry and bump type. The added changeset front-matter includes only "pacquet": patch and
does not list pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/engine-lock-failure-is-reported.md[1-3]

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

## Issue description
The changeset `.changeset/engine-lock-failure-is-reported.md` is missing a `pnpm` package entry in its front-matter.

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

## Fix Focus Areas
- .changeset/engine-lock-failure-is-reported.md[1-3]

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


Results up to commit c4679ff ⚖️ Balanced


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


Remediation recommended
1. Terminal escape injection 🐞 Bug ⛨ Security
Description
engine_install_lock() emits a warning that interpolates a filesystem path and raw io::Error into
PnpmLog.message, and the default reporter prints that message directly to the terminal without
sanitization. Because environment variables and filesystem paths are treated as attacker-controlled
in this repo, a crafted store/PNPM_HOME path (or error text that includes it) can inject
ANSI/control sequences into user output.
Code

pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R188-195]

+    Reporter::emit(&LogEvent::Pnpm(PnpmLog {
+        level: LogLevel::Warn,
+        message: format!(
+            "Could not lock the pnpm engine install at {}: {error}. Installing without it, which is unsafe if another pnpm is installing the same version.",
+            path.display(),
+        ),
+        prefix: String::new(),
+    }));
Relevance

⭐⭐⭐ High

Repo recently accepted stripping control characters from untrusted strings before terminal output
(paths/errors) to prevent escape injection.

PR-#13287
PR-#13230
PR-#13202

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new warning formats a message with raw path.display() and {error}. The default reporter
routes PnpmLog warnings to push_warning(), which directly interpolates the message into terminal
output without sanitization. The repo’s review guide explicitly treats env vars and filesystem paths
as attacker-controlled, and there is existing precedent for stripping control characters before
terminal output.

pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[179-196]
pnpm/crates/default-reporter/src/state.rs[1094-1105]
pnpm/crates/default-reporter/src/state.rs[1215-1222]
REVIEW_GUIDE.md[30-46]
pnpm/crates/pack/src/lib.rs[469-513]
PR-#13287

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

### Issue description
`engine_install_lock()` emits a warning that includes `path.display()` and `{error}` verbatim. These values can contain control characters (paths come from env/config), and the default reporter prints warning messages to the terminal without stripping control characters, enabling terminal escape/control-sequence injection.

### Issue Context
- The warning is newly added on the lock-establishment failure path.
- Repo guidance treats env vars and filesystem paths as attacker-controlled.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[188-195]

### Recommended fix
- Strip terminal control characters from the interpolated values before constructing `PnpmLog.message`.
 - e.g., introduce/reuse a small helper (similar to `sanitize_for_terminal` in `pnpm/crates/pack`) and apply it to `path.display().to_string()` and `error.to_string()`.
- Alternative (more comprehensive): sanitize `PnpmLog` messages at the output boundary in the default reporter (e.g., in `on_pnpm` / `push_warning`), but that is a broader behavior change.

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


Results up to commit 7ef402a ⚖️ Balanced


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


Remediation recommended
1. Claim test ineffective ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The new test forces claim() to fail via a missing directory (ErrorKind::NotFound), but claim()
is only called after DirLock::acquire has successfully created the lock directory, so the
production failure mode is “existing dir, owner write fails.” As written, the cleanup assertion
(!path.exists()) will pass even if the cleanup-on-write-failure path regresses, because the
directory was never created.
Code

pnpm/crates/fs/src/dir_lock/tests.rs[R92-101]

+fn claiming_a_directory_that_cannot_hold_the_record_fails() {
+    let root = tempdir().expect("create tempdir");
+    // Nothing at this path, so writing the owner record inside it fails —
+    // standing in for the unwritable store the real caller hits.
+    let path = root.path().join("missing").join("engine.lock");
+
+    let error = super::claim(path.clone()).expect_err("an unrecordable lock is not taken");
+
+    assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
+    assert!(!path.exists(), "no lock is left behind");
Relevance

⭐⭐⭐ High

Repo often accepts strengthening tests to match real behavior and avoid false positives/flakiness;
this aligns with that pattern.

PR-#13375
PR-#13372

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
claim() is only called after the lock directory is created (so the directory exists in the real
failure case), but the test calls claim() on a path whose parent doesn’t exist, so it can’t
validate cleanup of a just-created lock directory when writing the owner record fails.

pnpm/crates/fs/src/dir_lock.rs[62-65]
pnpm/crates/fs/src/dir_lock.rs[109-116]
pnpm/crates/fs/src/dir_lock/tests.rs[91-101]

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

## Issue description
`claim()` is only reached after `fs::create_dir(&path)` succeeds, but the new test calls `claim()` with a non-existent path (triggering `NotFound`). This doesn’t validate the intended scenario (“lock dir exists but writing `OWNER_FILE` fails”) and makes the cleanup assertion non-actionable.

## Issue Context
- Production call path: `DirLock::acquire` invokes `claim(path)` only after creating the directory.
- The test currently simulates failure by not creating the directory at all.

## Fix Focus Areas
- pnpm/crates/fs/src/dir_lock/tests.rs[91-102]

## Suggested fix
Change the test setup to create the lock directory first, then force a deterministic failure when writing the owner record **inside an existing directory**. For example:

- `fs::create_dir_all(&path)` to ensure the lock directory exists.
- Create a directory at `path.join("owner")` (or otherwise make that path non-writable) so `fs::write(path.join("owner"), ...)` fails reliably.
- Assert `claim(path.clone())` returns `Err(_)` and that `path` is removed (verifying the cleanup path actually runs).
- Avoid asserting a single cross-platform `ErrorKind` if it varies (e.g., `IsADirectory` vs `PermissionDenied`); instead assert it is an error and that cleanup occurred.

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


Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@github-actions

github-actions Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.01     11.8±0.03ms    31.7 MB/sec    1.00     11.7±0.09ms    32.1 MB/sec
packument/parse                1.00     36.4±0.32µs  1821.9 MB/sec    1.03     37.6±0.29µs  1762.8 MB/sec
tarball/download_dependency    1.00      2.4±0.07ms  1823.2 KB/sec    1.00      2.4±0.07ms  1825.8 KB/sec

@codecov-commenter

codecov-commenter commented Jul 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 62.96296% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.25%. Comparing base (d17710c) to head (2eda840).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
...tes/cli/src/cli_args/with/install_pnpm_to_store.rs 44.44% 10 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13377      +/-   ##
==========================================
+ Coverage   87.22%   87.25%   +0.03%     
==========================================
  Files         536      540       +4     
  Lines       92059    92662     +603     
==========================================
+ Hits        80297    80854     +557     
- Misses      11762    11808      +46     

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

`tracing::warn!` only reaches a subscriber when `TRACE` is set, so the
diagnostic this was supposed to add was dropped on every ordinary run —
the caller went on installing without a lock and without saying so, which
is the behavior the warning existed to avoid. It now goes through the
reporter, as every other user-facing warning in the CLI does.

Flattened while here: `DirLock::acquire` had grown to `loop` → `match` →
arm → `match` → arm → block. Recording ownership of a directory this
process just created is its own step, so it is its own function, and the
`create_dir` match is back to one level of arms.
Copilot AI review requested due to automatic review settings July 25, 2026 22:36

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 c4679ff

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

The failure path was described in three places and asserted in none.
Extracting `claim` for the nesting made it directly testable, so it is
now tested — and the paragraphs restating what the test and the code
already say are gone.

What is left is the part neither can carry: `io::Result<Option<DirLock>>`
does not say which of its two negative answers means what, and the
reporter call does not say why it is not `tracing`.
Copilot AI review requested due to automatic review settings July 25, 2026 22:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In `@pnpm/crates/fs/src/dir_lock/tests.rs`:
- Around line 90-102: Update claiming_a_directory_that_cannot_hold_the_record to
create an existing lock directory while making the owner-record write fail, then
assert claim propagates the error and removes the lock directory. Ensure the
test exercises the DirLock::acquire path so claim errors are not converted into
Ok(None); keep the missing-parent scenario separate if retained, and revise the
comment to describe the missing parent accurately.
🪄 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: 10c21371-cc5f-403c-b0e4-088e8d65d8bc

📥 Commits

Reviewing files that changed from the base of the PR and between c4679ff and 7ef402a.

📒 Files selected for processing (3)
  • pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs
  • pnpm/crates/fs/src/dir_lock.rs
  • pnpm/crates/fs/src/dir_lock/tests.rs
💤 Files with no reviewable changes (1)
  • pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • pnpm/crates/fs/src/dir_lock.rs

Comment thread pnpm/crates/fs/src/dir_lock/tests.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 7ef402a

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

The path handed to `claim` never existed, so asserting it was gone
afterwards proved nothing — the test passed whether or not the cleanup
ran. It now blocks the owner record with a directory of that name, so
the lock directory is real and its removal is observable. Verified by
deleting the cleanup: the old test still passed, this one fails.
Copilot AI review requested due to automatic review settings July 25, 2026 22:50

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 2eda840

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

@zkochan
zkochan merged commit 46c80bb into main Jul 25, 2026
35 checks passed
@zkochan
zkochan deleted the fix-dir-lock-error-visibility branch July 25, 2026 23:02
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
`DirLock::acquire` folded a failure to write the owner record into
`Ok(None)`, which is the same answer it gives when another process holds
the lock. Those are different situations: one is the wait doing its job,
the other means the locking mechanism itself is broken and the caller is
about to run without the lock and without knowing why. That matters most
at the engine install, where the lock exists to keep concurrent
destructive installs out of a shared store slot.

The write failure now propagates as `Err`, alongside the parent-directory
failure that already did. The engine-install caller still proceeds — a
lock it cannot take is not a reason to refuse to run — but logs what
happened rather than silently reverting to the racy behavior.

Follow-up to pnpm#13375, raised in review there after it merged.
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 state: automerge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants