Skip to content

fix(executor): preserve inherited TMPDIR - #13445

Merged
zkochan merged 3 commits into
mainfrom
fix-13442
Jul 27, 2026
Merged

zkochan merged 3 commits into
mainfrom
fix-13442

Conversation

@zkochan

@zkochan zkochan commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Preserve a user-provided TMPDIR in pacquet script environments when scripts run with unsafePerm.
  • Keep the existing per-package node_modules/.tmp override when unsafePerm is disabled.
  • Add executor coverage for both branches and a CLI regression test that exercises Node.js os.tmpdir().
  • The TypeScript CLI already preserves inherited TMPDIR, so no TypeScript change is required.

Closes #13442.

Squash Commit Body

Pacquet's shared script environment builder treated TMPDIR as an
always-reserved stamp. Explicit pnpm run calls use unsafePerm, so no
replacement was written and the child lost the user-provided temporary
directory entirely.

Preserve inherited TMPDIR by default and continue replacing it with the
per-package node_modules/.tmp directory when unsafePerm is disabled. This
matches the TypeScript CLI and normal child-process environment inheritance.

Closes pnpm/pnpm#13442.

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.

Written by an agent (Codex, GPT-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
    • Scripts now preserve a user-provided TMPDIR when permissions allow it; otherwise they use the package’s dedicated temp directory.
    • Improved temporary-directory environment handling so TMPDIR (and the runtime temp directory) stay consistent, including correct case-insensitive behavior on Windows.
  • Tests
    • Added/updated coverage to verify pacquet run preserves an alternate temp directory and that unsafePerm controls whether TMPDIR is preserved or overridden.

Copilot AI review requested due to automatic review settings July 27, 2026 21:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Jul 27, 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: c53dabfe-59e0-4c00-895e-4f553b0222bc

📥 Commits

Reviewing files that changed from the base of the PR and between 5b11f05 and 5a5923e.

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

📝 Walkthrough

Walkthrough

Rust pnpm preserves inherited TMPDIR values when running scripts with unsafePerm enabled. With normal permissions, scripts continue using the package-local temporary directory. Executor and CLI tests cover POSIX and Windows behavior.

Changes

TMPDIR preservation

Layer / File(s) Summary
Update TMPDIR environment handling
pnpm/crates/executor/src/make_env.rs, pnpm/crates/executor/src/make_env/tests.rs
TMPDIR is removed from stamping-key filtering. build_env preserves the parent value with unsafe_perm=true and overrides it with the package temp directory otherwise, including case-insensitive cleanup on Windows.
Verify script-level preservation
pnpm/crates/cli/tests/run.rs, .changeset/pacquet-preserve-tmpdir.md
The CLI test verifies that scripts receive the configured TMPDIR and matching Node temp directory; a patch changeset documents the behavior.

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

Sequence Diagram(s)

sequenceDiagram
  participant Parent as Parent process
  participant BuildEnv as build_env_for_platform
  participant Script as pacquet script
  participant NodeOS as Node os.tmpdir()
  Parent->>BuildEnv: Provide TMPDIR
  BuildEnv->>Script: Preserve TMPDIR when unsafePerm is enabled
  Script->>NodeOS: Resolve temporary directory
  NodeOS-->>Script: Return inherited TMPDIR
Loading

Assessment against linked issues

Objective Addressed Explanation
Preserve user-provided TMPDIR when running scripts, matching TypeScript pnpm and child-process inheritance [#13442] ✅

Possibly related PRs

  • pnpm/pnpm#13403: Modifies the same environment stamping/filtering machinery for a different environment key.

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

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

Preserve inherited TMPDIR for unsafePerm script runs

🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Preserve inherited TMPDIR when running scripts with unsafePerm enabled.
• Keep node_modules/.tmp TMPDIR override when unsafePerm is disabled.
• Add executor + CLI regression tests validating TMPDIR and Node.js os.tmpdir().
Diagram

graph TD
  P[("Parent env") ] --> F["filter_parent_env()"] --> B["build_env()"] --> D{{"unsafePerm?"}}
  D -->|"true"| I["Keep inherited TMPDIR"] --> S["Spawn script child"]
  D -->|"false"| O["Override TMPDIR"] --> C["Create node_modules/.tmp"] --> S
  subgraph Legend
    direction LR
    _data[("Data input")] ~~~ _proc["Processing step"] ~~~ _dec{{"Decision"}}
  end
Loading
High-Level Assessment

The chosen approach (stop stripping TMPDIR from the inherited env, and only override it when unsafePerm is disabled) is the minimal change that matches normal child-process inheritance and the TypeScript CLI behavior. Alternatives like conditionally filtering TMPDIR or force-stamping a default TMPDIR add complexity without additional benefit.

Files changed (4) +59 / -11

Bug fix (1) +5 / -5
make_env.rsPreserve inherited TMPDIR when unsafePerm is enabled +5/-5

Preserve inherited TMPDIR when unsafePerm is enabled

• Updates the parent-env filter to no longer treat TMPDIR as a dropped/stamped key. This allows TMPDIR to be inherited when unsafePerm=true, while build_env still overrides TMPDIR to node_modules/.tmp when unsafePerm=false.

pnpm/crates/executor/src/make_env.rs

Tests (2) +49 / -6
run.rsAdd CLI regression test for TMPDIR preservation +42/-0

Add CLI regression test for TMPDIR preservation

• Adds a test that runs a Node.js script under pacquet with TMPDIR set and asserts the child sees the same TMPDIR. On non-Windows platforms it also asserts Node's os.tmpdir() reflects TMPDIR.

pnpm/crates/cli/tests/run.rs

tests.rsUpdate env-builder tests for TMPDIR inheritance vs override +7/-6

Update env-builder tests for TMPDIR inheritance vs override

• Adjusts unit tests to assert TMPDIR remains present when unsafePerm=true and is overridden to <pkg>/node_modules/.tmp when unsafePerm=false. Updates is_stamping_key expectations so TMPDIR is no longer considered a stamping key on POSIX or Windows.

pnpm/crates/executor/src/make_env/tests.rs

Documentation (1) +5 / -0
pacquet-preserve-tmpdir.mdAdd changeset for TMPDIR inheritance fix +5/-0

Add changeset for TMPDIR inheritance fix

• Adds a patch changeset for pacquet documenting that user-provided TMPDIR is preserved when running scripts, aligning behavior with the TypeScript pnpm CLI.

.changeset/pacquet-preserve-tmpdir.md

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
pnpm/crates/cli/tests/run.rs (1)

399-404: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Pin this regression test to the unsafePerm branch.

The test sets TMPDIR but never explicitly enables unsafePerm, so it relies on an implicit default or fixture configuration. Select the supported unsafePerm=true configuration explicitly to ensure this test always covers the preservation path; the executor test already covers the false branch. As per path instructions, CLI regression tests should prove the changed behavior through real command wiring.

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

In `@pnpm/crates/cli/tests/run.rs` around lines 399 - 404, Update the regression
test invoking the pacquet command with show-tmp to explicitly select the
supported unsafePerm=true configuration, while preserving the existing TMPDIR
setup and assertions. Ensure it exercises the preservation path through real CLI
wiring and leaves the false branch to the executor test.

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/pacquet-preserve-tmpdir.md:
- Line 5: Update the changeset release note to state that inherited
user-provided TMPDIR is preserved only when unsafePerm is enabled, while normal
permissions continue using the package-local temporary directory. Keep the
wording concise and accurate.

---

Nitpick comments:
In `@pnpm/crates/cli/tests/run.rs`:
- Around line 399-404: Update the regression test invoking the pacquet command
with show-tmp to explicitly select the supported unsafePerm=true configuration,
while preserving the existing TMPDIR setup and assertions. Ensure it exercises
the preservation path through real CLI wiring and leaves the false branch to the
executor test.
🪄 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: 77685b55-1713-46c1-97ee-a1d0b32b5a79

📥 Commits

Reviewing files that changed from the base of the PR and between 81411d3 and 1e59871.

📒 Files selected for processing (4)
  • .changeset/pacquet-preserve-tmpdir.md
  • pnpm/crates/cli/tests/run.rs
  • pnpm/crates/executor/src/make_env.rs
  • pnpm/crates/executor/src/make_env/tests.rs

Comment thread .changeset/pacquet-preserve-tmpdir.md Resolved
@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. Windows TMPDIR collision ✓ Resolved 🐞 Bug ⛨ Security
Description
On Windows, filter_parent_env now preserves inherited TMPDIR (including case-variants like
tmpdir), but build_env still inserts its own TMPDIR when unsafe_perm is false, leaving two
keys that name the same variable on Windows. This can make the effective TMPDIR value ambiguous at
spawn time, so the intended node_modules/.tmp override may not reliably take effect.
Code

pnpm/crates/executor/src/make_env.rs[R193-194]

+    const DROPPED: [&str; 4] =
+        ["NODE", "INIT_CWD", "PNPM_SCRIPT_SRC_DIR", DEV_PREINSTALL_ALREADY_RAN_ENV];
Relevance

⭐⭐ Medium

Windows case-insensitive env-key leak/collision fixes accepted (PR 13403), but no direct TMPDIR-dup
precedent found.

PR-#13403
PR-#12943

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
is_stamping_key no longer treats TMPDIR as a dropped/stamping key, so filter_parent_env will
preserve it on Windows (where key casing is not significant). When unsafe_perm is false,
build_env still inserts TMPDIR for the per-package .tmp directory, which can leave two
differently-cased keys in the env map; the lifecycle runner already documents that this produces an
“unspecified winner” problem for PATH on Windows, indicating the same risk applies to TMPDIR
collisions.

pnpm/crates/executor/src/make_env.rs[139-148]
pnpm/crates/executor/src/make_env.rs[157-169]
pnpm/crates/executor/src/make_env.rs[171-199]
pnpm/crates/executor/src/lifecycle.rs[327-335]
PR-#13403

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

### Issue description
On Windows, environment variable names are case-insensitive; if the inherited/extra env contains `tmpdir` (or any non-`TMPDIR` casing) and we later insert `TMPDIR` for `unsafe_perm=false`, the child env can end up with two entries for the same logical variable. Spawn-time behavior is then unspecified/ambiguous, and the `node_modules/.tmp` override may not apply.

### Issue Context
- This PR removes `TMPDIR` from the set of keys dropped by `filter_parent_env`.
- `build_env` still stamps `TMPDIR` for `unsafe_perm=false`.
- The lifecycle runner already has a comment + mitigation for this exact collision pattern for `PATH`, but there is no analogous handling for `TMPDIR`.

### Fix Focus Areas
- pnpm/crates/executor/src/make_env.rs[139-148]
- pnpm/crates/executor/src/make_env.rs[183-199]
- pnpm/crates/executor/src/make_env/tests.rs[159-176]

### Suggested fix
In `build_env`, right before inserting the stamped `TMPDIR` (the `unsafe_perm=false` branch), remove any existing key whose name equals `TMPDIR` case-insensitively **when building for Windows** (covers both inherited `parent_env` and user `extra_env`). Then insert the stamped `TMPDIR`.

### Regression test
Add a Windows-only unit test (or `#[cfg(windows)]`) that passes `parent_env` containing `tmpdir` (lowercase) and `unsafe_perm=false`, and asserts:
- the built env contains `TMPDIR` set to `<pkg_root>/node_modules/.tmp`
- and does **not** contain any other-cased `tmpdir` key.

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



Informational

2. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset only bumps pacquet and does not declare a bump for pnpm, which violates the
requirement that changesets explicitly include pnpm with a valid bump type. This can lead to
incomplete or inconsistent release metadata.
Code

.changeset/pacquet-preserve-tmpdir.md[R1-3]

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

⭐ Low

Same “add pnpm to changeset front-matter” suggestion repeatedly rejected in many merged PRs.

PR-#13417
PR-#13347
PR-#12981

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires new/modified changesets to explicitly list pnpm with an
appropriate bump type. The added changeset front-matter includes only pacquet: --- then
"pacquet": patch and no pnpm entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/pacquet-preserve-tmpdir.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 new changeset file does not include a `pnpm` entry, but the compliance checklist requires that every new/modified changeset explicitly declares `pnpm` with a valid bump type (`patch`/`minor`/`major`).

## Issue Context
Current changeset front-matter only lists `pacquet`.

## Fix Focus Areas
- .changeset/pacquet-preserve-tmpdir.md[1-3]

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


Grey Divider

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.

@greptile-apps

greptile-apps Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (3): Last reviewed commit: "fix(executor): deduplicate Windows `TMPD..." | Re-trigger Greptile

@github-actions

github-actions Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                                            main                                   pr
-----                                            ----                                   --
lockfile/parse_pnpm_lock                         1.00     13.5±0.62ms    27.7 MB/sec    1.16     15.7±0.63ms    23.8 MB/sec
packument/parse                                  1.00     44.3±0.37µs  1496.2 MB/sec    1.08     47.7±1.34µs  1389.4 MB/sec
tarball/download_dependency                      1.00      3.2±0.15ms  1345.9 KB/sec    1.07      3.4±0.55ms  1259.7 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.00   199.3±13.20ms 80.3 KElem/sec    1.25    248.7±8.74ms 64.3 KElem/sec

Copilot AI review requested due to automatic review settings July 27, 2026 21:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@zkochan

zkochan commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

I also verified the review’s test-configuration nit. No test change is needed: explicit pnpm run reaches run_script, which sets EnvOptions::unsafe_perm to true unconditionally. The workspace unsafePerm setting is intentionally not threaded into this trusted foreground-script path, so adding it to the fixture would not select the branch. The CLI regression already exercises the production unsafe_perm: true wiring, while the executor test covers both branches directly.


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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5b11f05

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@codecov-commenter

codecov-commenter commented Jul 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.65%. Comparing base (81411d3) to head (5a5923e).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13445      +/-   ##
==========================================
+ Coverage   87.64%   87.65%   +0.01%     
==========================================
  Files         545      545              
  Lines       93978    94022      +44     
==========================================
+ Hits        82367    82417      +50     
+ Misses      11611    11605       -6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copilot AI review requested due to automatic review settings July 27, 2026 21:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@zkochan

zkochan commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

Addressed the valid Windows environment-key collision in commit 5a5923e3f2. Before inserting the authoritative package-local TMPDIR for unsafePerm: false, the builder now removes every case-insensitive spelling on Windows. The regression test simulates Windows on every host and covers collisions from both inherited environment variables and extraEnv.

The changeset intentionally remains pacquet-only. This is a Rust-only fix: the TypeScript CLI already preserves inherited TMPDIR and has no implementation change here. The repository release instructions explicitly require Rust-only changesets targeting pacquet to omit pnpm, because pnpm in changeset metadata denotes the TypeScript CLI package.


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

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5a5923e

@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 960aba3 into main Jul 27, 2026
32 checks passed
@zkochan
zkochan deleted the fix-13442 branch July 27, 2026 21:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rust pnpm drops TMPDIR from script environments

3 participants