Skip to content

fix: kill spawned process trees with taskkill on Windows error exits - #12925

Merged
zkochan merged 9 commits into
pnpm:mainfrom
Arman-Luthra:fix/windows-taskkill-process-trees
Jul 13, 2026
Merged

zkochan merged 9 commits into
pnpm:mainfrom
Arman-Luthra:fix/windows-taskkill-process-trees

Conversation

@Arman-Luthra

@Arman-Luthra Arman-Luthra commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Related to pnpm/tasks#37 (implements the Windows taskkill mechanism for exec/dlx; the lifecycle layer needs a pnpm/npm-lifecycle change, described below).

On Windows, when pnpm exits on an error while commands it spawned are still running, the descendant-process cleanup in the error handler is effectively skipped: the pidtree enumeration shells out to wmic — or a PowerShell Get-CimInstance fallback — and regularly exceeds the 500 ms budget introduced in #12403. Children spawned by still-running commands were therefore orphaned (e.g. a dev server started by one project while another project's command fails a pnpm --recursive exec).

This PR adopts the approach the issue proposes — kill the spawned child's process tree at the spawn layer with taskkill /pid <pid> /T /F, no process-list enumeration — for the spawn sites that live in this repository:

  • New trackChildProcess() / killTrackedProcessTrees() in @pnpm/exec.lifecycle. Spawn sites register the child PID; the registry drops it when the child closes. On Windows, killTrackedProcessTrees() spawns taskkill /pid <pid> /T /F (no shell, windowsHide) for every still-running tracked child. taskkill failures are ignored (exit code 128 means the tree root already exited).
  • pnpm exec (both the prefixed-output and inherit-stdio branches) and pnpm dlx register the subprocesses they spawn.
  • On Windows the error handler now calls killTrackedProcessTrees() instead of enumerating descendants. The POSIX path is unchanged: one ps call is fast there, and the enumeration also reaches descendants of children pnpm cannot track.

What still needs the lifecycle layer (follow-up)

pnpm run and install lifecycle scripts are spawned inside @pnpm/npm-lifecycle, which does not expose the spawned child process, so they cannot be registered from this repository yet. Wiring them up needs a small change there — exposing cooked.pid in lib/spawn.js and an opts.onChildProcess?.(proc) callback after the spawn in runCmd_ — after which runLifecycleHook can pass onChildProcess: trackChildProcess and the Windows-skipped test should clean up child processes when process exited can be re-enabled.

I first attempted to carry that change in this repo via patchedDependencies, but pacquet's resolver currently panics on a patched dependency that also has a peer suffix, so the patch route is not shippable:

Main thread panicked: begin > end (105 > 28) when slicing
`@pnpm/[email protected](patch_hash=e3541c…)([email protected])`
at pacquet/crates/resolving-deps-resolver/src/resolve_peers.rs:2490:51

Verification on Windows

  • Unit tests (pnpm11/exec/lifecycle/test/trackChildProcess.ts) spawn a real two-level process tree, kill it through the tracker, and assert the grandchild is gone (Windows) and the child terminated (all platforms).
  • Regression e2e (pnpm11/pnpm/test/errorHandler.test.ts, fixture pnpm11/__fixtures__/exec-error-exit): a two-project workspace where pnpm --recursive exec node script.js fails in project-b only once project-a's grandchild HTTP server is listening, so the failure deterministically happens while the tree is running. Asserts the exit status, the ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL marker, and that the grandchild's port is free after pnpm exits. The wmic/powershell directories are stripped from the child's PATH to emulate the wmic-less Windows the issue describes and keep the test deterministic (taskkill lives in System32 itself and stays reachable).
  • Manual run on Windows 11 with the built dist/pnpm.mjs and wmic/powershell removed from PATH: before the fix the grandchild server survives pnpm's error exit and keeps its port bound; with the fix, taskkill /pid <pid> /T /F fires for the still-running exec child and netstat shows the port free afterwards.
  • Fail-before-fix on real Windows (windows-latest): on main plus only the new test, the test fails 3/3 runs at the port-in-use assertion (the orphaned grandchild still holds its port) - https://github.com/Arman-Luthra/pnpm/actions/runs/29119779498; with the fix it passes 3/3 runs - https://github.com/Arman-Luthra/pnpm/actions/runs/29119776972.

Squash Commit Body

On an error exit the error handler terminated descendant processes by
enumerating them with pidtree, which on Windows shells out to wmic (or a
PowerShell fallback) and regularly exceeds the 500 ms budget introduced
in https://github.com/pnpm/pnpm/pull/12403 - so the cleanup was
effectively skipped there and children spawned by still-running commands
were orphaned.

Track the PIDs of the child processes spawned for pnpm exec and pnpm dlx
in a registry in `@pnpm/exec.lifecycle`. On Windows the error handler
now kills the process tree of every still-running tracked child with
taskkill /T /F - the PID is already known, so no process-list
enumeration is needed. taskkill failures (exit code 128 when the tree
root already exited) are ignored. On POSIX the existing enumeration is
kept: one ps call is fast there and also reaches the descendants of
children that pnpm cannot track.

Lifecycle scripts (pnpm run and install hooks) are spawned inside
`@pnpm/npm-lifecycle`, which does not expose the spawned child process,
so they cannot be registered from this repository yet. Wiring them up
needs a small change in pnpm/npm-lifecycle (exposing the child PID and
an on-spawn callback); the tracker in `@pnpm/exec.lifecycle` is written
so runLifecycleHook can reuse it once that lands.

Related to https://github.com/pnpm/tasks/issues/37

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pacquet/ port, or the description notes what still needs porting. —
    pacquet already ties spawned process trees to its own lifetime with a
    Job Object (KILL_ON_JOB_CLOSE, added in fix: bound descendant-process lookup on error exit to avoid a Windows hang #12403), which covers
    this behavior natively, so no pacquet change is needed.
  • 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 (Claude Code, Claude Fable 5).

Summary by CodeRabbit

  • Bug Fixes
    • Improved cleanup of processes started by pnpm exec, pnpm dlx, and recursive exec when commands fail.
    • On Windows, pnpm now tracks spawned command processes and terminates their full process trees on error exit, reducing orphaned processes and preventing lingering ports.
  • Tests
    • Added/updated Jest coverage for tracking and process-tree termination, including Windows-specific recursive exec error scenarios and cases where tracked processes have already exited.

@Arman-Luthra
Arman-Luthra requested a review from zkochan as a code owner July 10, 2026 22:08
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Jul 10, 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: db0bd373-5ed7-477a-b7d6-69a7b5411110

📥 Commits

Reviewing files that changed from the base of the PR and between 5b75b9b and 8a1a4da.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (2)
  • .changeset/windows-kill-tracked-process-trees.md
  • cspell.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/windows-kill-tracked-process-trees.md

📝 Walkthrough

Walkthrough

pnpm tracks exec and dlx child processes, terminates their Windows process trees with taskkill, preserves non-Windows cleanup behavior, and adds lifecycle and error-handler coverage for descendant termination.

Changes

Process cleanup

Layer / File(s) Summary
Child tracking and termination
pnpm11/exec/lifecycle/src/*
Adds PID tracking, close/error cleanup, platform-specific termination, and lifecycle exports.
Exec and dlx tracking integration
pnpm11/exec/commands/src/*, pnpm11/exec/commands/test/*
Registers execa children from exec and dlx before awaiting them and updates subprocess mocks.
Error-handler cleanup integration
pnpm11/pnpm/src/*, pnpm11/pnpm/test/*, pnpm11/pnpm/package.json, pnpm11/pnpm/tsconfig.json, .changeset/*, cspell.json
Uses tracked process-tree cleanup on Windows, retains bounded non-Windows cleanup, and updates integration, build, package, changeset, and spelling metadata.
Process-tree lifecycle validation
pnpm11/exec/lifecycle/test/*
Adds detached process-tree fixtures and tests for descendant termination and already-exited children.

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

Sequence Diagram(s)

sequenceDiagram
  participant pnpmExec
  participant trackChildProcess
  participant errorHandler
  participant taskkill
  pnpmExec->>trackChildProcess: register spawned child
  pnpmExec-->>errorHandler: command exits with error
  errorHandler->>trackChildProcess: killTrackedProcessTrees()
  trackChildProcess->>taskkill: kill tracked PID tree
  taskkill-->>errorHandler: cleanup completes
Loading

Possibly related issues

  • pnpm/pnpm#12406 — The PR implements tracked exec/dlx child PIDs and Windows taskkill /T /F cleanup described by the issue.

Suggested labels: product: pnpm@11

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@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)
pnpm11/exec/lifecycle/src/trackChildProcess.ts (1)

42-54: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add a timeout to the taskkill call for bounded Windows cleanup.

killProcessTree on Windows awaits the taskkill child process without a timeout. If taskkill hangs (e.g., due to a kernel-level issue), killTrackedProcessTrees() never resolves and pnpm hangs during error exit. The non-Windows error-handler path bounds its descendant lookup with DESCENDANT_LOOKUP_TIMEOUT = 500, but the Windows path is unbounded. Adding a timeout with unref() keeps the Windows path consistent and prevents a stuck taskkill from blocking exit.

♻️ Proposed timeout for `killProcessTree` on Windows
 async function killProcessTree (pid: number): Promise<void> {
   if (process.platform === 'win32') {
     await new Promise<void>((resolve) => {
       const taskkill = spawn('taskkill', ['/pid', pid.toString(), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
       // A non-zero exit code (128 when the process is already gone, 1 when
       // access is denied) is deliberately ignored.
+      const timer = setTimeout(() => {
+        taskkill.kill()
+        resolve()
+      }, 5000).unref()
       taskkill.once('error', () => {
+        clearTimeout(timer)
         resolve()
       })
       taskkill.once('exit', () => {
+        clearTimeout(timer)
         resolve()
       })
     })
   } else {
🤖 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 `@pnpm11/exec/lifecycle/src/trackChildProcess.ts` around lines 42 - 54, Add a
bounded timeout to the Windows branch of killProcessTree around the taskkill
child process, resolving the promise if taskkill neither exits nor emits an
error before the timeout. Use the existing timeout convention where appropriate,
call unref() on the timer, and ensure cleanup clears the timer when taskkill
completes.
🤖 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 `@pnpm11/pnpm/test/errorHandler.test.ts`:
- Around line 111-137: Restore the original working directory after the test
that calls process.chdir(execErrorExit). Update the test setup/cleanup, such as
using a try/finally around the command and assertions or an afterEach hook, and
ensure process.chdir returns to the directory captured before the test so later
tests are isolated.

---

Nitpick comments:
In `@pnpm11/exec/lifecycle/src/trackChildProcess.ts`:
- Around line 42-54: Add a bounded timeout to the Windows branch of
killProcessTree around the taskkill child process, resolving the promise if
taskkill neither exits nor emits an error before the timeout. Use the existing
timeout convention where appropriate, call unref() on the timer, and ensure
cleanup clears the timer when taskkill completes.
🪄 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: 28c60fc0-aee2-4570-a898-0f4b7e785c60

📥 Commits

Reviewing files that changed from the base of the PR and between 84e3d3b and b8538c7.

⛔ Files ignored due to path filters (9)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
  • pnpm11/__fixtures__/exec-error-exit/package.json is excluded by !**/__fixtures__/**
  • pnpm11/__fixtures__/exec-error-exit/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/__fixtures__/**
  • pnpm11/__fixtures__/exec-error-exit/pnpm-workspace.yaml is excluded by !**/__fixtures__/**
  • pnpm11/__fixtures__/exec-error-exit/project-a/package.json is excluded by !**/__fixtures__/**
  • pnpm11/__fixtures__/exec-error-exit/project-a/script.js is excluded by !**/__fixtures__/**
  • pnpm11/__fixtures__/exec-error-exit/project-a/server.js is excluded by !**/__fixtures__/**
  • pnpm11/__fixtures__/exec-error-exit/project-b/package.json is excluded by !**/__fixtures__/**
  • pnpm11/__fixtures__/exec-error-exit/project-b/script.js is excluded by !**/__fixtures__/**
📒 Files selected for processing (14)
  • .changeset/windows-kill-tracked-process-trees.md
  • cspell.json
  • pnpm11/exec/commands/src/dlx.ts
  • pnpm11/exec/commands/src/exec.ts
  • pnpm11/exec/commands/test/dlx.ts
  • pnpm11/exec/commands/test/exec.ts
  • pnpm11/exec/lifecycle/src/index.ts
  • pnpm11/exec/lifecycle/src/trackChildProcess.ts
  • pnpm11/exec/lifecycle/test/fixtures/process-tree/child.cjs
  • pnpm11/exec/lifecycle/test/fixtures/process-tree/parent.cjs
  • pnpm11/exec/lifecycle/test/trackChildProcess.ts
  • pnpm11/pnpm/package.json
  • pnpm11/pnpm/src/errorHandler.ts
  • pnpm11/pnpm/test/errorHandler.test.ts

Comment thread pnpm11/pnpm/test/errorHandler.test.ts Resolved
@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 5b75b9b7fc1d

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.112 ± 0.160 3.955 4.380 1.91 ± 0.11
pacquet@main 4.142 ± 0.176 3.945 4.379 1.92 ± 0.11
pnpr@HEAD 2.202 ± 0.100 2.038 2.368 1.02 ± 0.06
pnpr@main 2.156 ± 0.084 2.067 2.308 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.1122907358,
      "stddev": 0.1601363442782634,
      "median": 4.0356519709,
      "user": 3.8446371399999997,
      "system": 3.5384085999999995,
      "min": 3.9548087804,
      "max": 4.3796485274000005,
      "times": [
        4.1461075534,
        4.0654720264,
        4.3796485274000005,
        4.3111559494,
        4.2962184394000005,
        3.9919105624,
        3.9885140194,
        3.9832395844,
        3.9548087804,
        4.0058319154
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.1421658937,
      "stddev": 0.17609252003031003,
      "median": 4.1306513014,
      "user": 3.8381761399999994,
      "system": 3.5123154999999997,
      "min": 3.9454952874,
      "max": 4.3791084544,
      "times": [
        3.9454952874,
        3.9646912474000002,
        4.1655518304,
        4.2514988824,
        4.3791084544,
        4.0957507724,
        4.3748120274,
        3.9864365934,
        3.9568351974000002,
        4.3014786444
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.2020262696,
      "stddev": 0.09952417584940877,
      "median": 2.2015412339000004,
      "user": 2.656496839999999,
      "system": 3.0677192999999994,
      "min": 2.0382867944000003,
      "max": 2.3680752004000003,
      "times": [
        2.2983417154000003,
        2.1621193274,
        2.0382867944000003,
        2.2601466004,
        2.1604336314,
        2.2549787014000002,
        2.1026718504,
        2.1342457344000003,
        2.3680752004000003,
        2.2409631404000003
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.1559390274,
      "stddev": 0.08406574380953817,
      "median": 2.1181413559,
      "user": 2.67535074,
      "system": 3.0539014999999994,
      "min": 2.0673296844,
      "max": 2.3077906884,
      "times": [
        2.0849966594000002,
        2.1182996904,
        2.1020444814,
        2.1179830214,
        2.2852693024,
        2.1510583424000003,
        2.0673296844,
        2.2126420034,
        2.1119764004,
        2.3077906884
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 668.7 ± 16.9 638.5 693.3 1.01 ± 0.05
pacquet@main 663.2 ± 24.7 641.9 724.1 1.00
pnpr@HEAD 738.1 ± 85.2 677.3 971.9 1.11 ± 0.14
pnpr@main 748.5 ± 64.3 709.1 928.5 1.13 ± 0.11
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.6686607576399999,
      "stddev": 0.016869477129139984,
      "median": 0.66965709204,
      "user": 0.39628106,
      "system": 1.3442269999999998,
      "min": 0.63847284404,
      "max": 0.69328662504,
      "times": [
        0.66859592404,
        0.64672731804,
        0.65952489004,
        0.63847284404,
        0.66926145804,
        0.67005272604,
        0.68674083004,
        0.67937756804,
        0.67456739304,
        0.69328662504
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.66320188254,
      "stddev": 0.024736354491781198,
      "median": 0.6562373025400001,
      "user": 0.37840295999999995,
      "system": 1.3243630999999998,
      "min": 0.64191927604,
      "max": 0.72405365704,
      "times": [
        0.67706078804,
        0.6547799750400001,
        0.67325905504,
        0.6499709300400001,
        0.66615842904,
        0.72405365704,
        0.6576946300400001,
        0.64436680404,
        0.64191927604,
        0.64275528104
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.7380543091399999,
      "stddev": 0.0852450179090643,
      "median": 0.72241954804,
      "user": 0.40496326,
      "system": 1.3691741,
      "min": 0.67725262604,
      "max": 0.9718917770400001,
      "times": [
        0.74186869704,
        0.68822732304,
        0.72024573604,
        0.69651303404,
        0.7245933600400001,
        0.73749305204,
        0.73199863204,
        0.67725262604,
        0.6904588540400001,
        0.9718917770400001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.74848154544,
      "stddev": 0.06428625924209548,
      "median": 0.73041056504,
      "user": 0.41580226,
      "system": 1.3809885,
      "min": 0.70908027304,
      "max": 0.9284728160400001,
      "times": [
        0.7392346160400001,
        0.72884698004,
        0.74761335904,
        0.7262495960400001,
        0.73790371404,
        0.71877405204,
        0.70908027304,
        0.71666589804,
        0.9284728160400001,
        0.73197415004
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.326 ± 0.035 4.284 4.382 1.95 ± 0.12
pacquet@main 4.296 ± 0.053 4.242 4.416 1.94 ± 0.12
pnpr@HEAD 2.218 ± 0.137 2.073 2.456 1.00
pnpr@main 2.240 ± 0.128 2.094 2.454 1.01 ± 0.09
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.32589110682,
      "stddev": 0.03542201659370801,
      "median": 4.31399246492,
      "user": 3.7689327000000006,
      "system": 3.4337104000000003,
      "min": 4.28369957542,
      "max": 4.381710132419999,
      "times": [
        4.30336780442,
        4.37572103542,
        4.30411290242,
        4.36214768442,
        4.32911753642,
        4.381710132419999,
        4.29743291442,
        4.29772945542,
        4.32387202742,
        4.28369957542
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.295809781819999,
      "stddev": 0.05251047924487228,
      "median": 4.28244177142,
      "user": 3.7609033000000003,
      "system": 3.4124305999999995,
      "min": 4.24246954842,
      "max": 4.4158369644199995,
      "times": [
        4.4158369644199995,
        4.2555642554199995,
        4.331251111419999,
        4.26337966142,
        4.24246954842,
        4.27759635142,
        4.30760690642,
        4.32720576542,
        4.28728719142,
        4.24990006242
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.2176070311199996,
      "stddev": 0.13741892343695025,
      "median": 2.16561809542,
      "user": 2.4976901,
      "system": 2.9296811,
      "min": 2.07253327242,
      "max": 2.4559882474199997,
      "times": [
        2.11377897542,
        2.07626365442,
        2.07253327242,
        2.2341765894199996,
        2.16163798942,
        2.2984150304199997,
        2.16488974942,
        2.16634644142,
        2.43204036142,
        2.4559882474199997
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.24020005492,
      "stddev": 0.12844036738911788,
      "median": 2.19143367642,
      "user": 2.4742887,
      "system": 2.9383431,
      "min": 2.09354460442,
      "max": 2.45360004842,
      "times": [
        2.1644171764199998,
        2.18892885042,
        2.19393850242,
        2.09354460442,
        2.45360004842,
        2.12997640442,
        2.1134363334199997,
        2.3255812094199997,
        2.40151496942,
        2.33706245042
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.388 ± 0.018 1.351 1.406 2.08 ± 0.08
pacquet@main 1.376 ± 0.022 1.337 1.413 2.06 ± 0.08
pnpr@HEAD 0.697 ± 0.052 0.660 0.842 1.04 ± 0.09
pnpr@main 0.668 ± 0.023 0.655 0.732 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.3884120669,
      "stddev": 0.018064882462561466,
      "median": 1.3954707559000001,
      "user": 1.3358369799999996,
      "system": 1.72940906,
      "min": 1.3510243534000002,
      "max": 1.4061672284,
      "times": [
        1.3964733024000002,
        1.3944682094,
        1.3510243534000002,
        1.4017958654,
        1.3736328354,
        1.3899470964,
        1.3971836574,
        1.3688297484,
        1.4045983724,
        1.4061672284
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.3756803308000003,
      "stddev": 0.021670662626716217,
      "median": 1.3779400884,
      "user": 1.3305810799999997,
      "system": 1.7007101599999999,
      "min": 1.3367013354000001,
      "max": 1.4125706384,
      "times": [
        1.3862848044,
        1.3833161494000001,
        1.3776452394,
        1.3519461124,
        1.3782349374,
        1.3367013354000001,
        1.3734836764,
        1.3953862624,
        1.4125706384,
        1.3612341524
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6967789340999999,
      "stddev": 0.05244837493870851,
      "median": 0.6851155233999999,
      "user": 0.34385237999999996,
      "system": 1.30527196,
      "min": 0.6603161004,
      "max": 0.8415951974,
      "times": [
        0.6817234954,
        0.6904957974,
        0.6603161004,
        0.6687673764,
        0.8415951974,
        0.6975823423999999,
        0.6885075514,
        0.6955751504,
        0.6774555244,
        0.6657708054
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.6680875486999999,
      "stddev": 0.022902207315221607,
      "median": 0.6616818484,
      "user": 0.33184628,
      "system": 1.2894357599999997,
      "min": 0.6550880624,
      "max": 0.7323832404,
      "times": [
        0.6644276764,
        0.6550880624,
        0.6633267214,
        0.6556721554,
        0.6581449514,
        0.6671367264,
        0.6617709563999999,
        0.7323832404,
        0.6615927404,
        0.6613322564
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.019 ± 0.027 2.988 3.058 4.60 ± 0.06
pacquet@main 3.044 ± 0.024 3.022 3.094 4.64 ± 0.06
pnpr@HEAD 0.656 ± 0.007 0.648 0.668 1.00
pnpr@main 0.663 ± 0.005 0.654 0.670 1.01 ± 0.01
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.0194248229,
      "stddev": 0.02659626704091203,
      "median": 3.019939552,
      "user": 1.7364109999999997,
      "system": 2.0004645400000003,
      "min": 2.9883890794999997,
      "max": 3.0580843355,
      "times": [
        2.9965213115,
        2.9884448275,
        3.0141109485,
        3.0412656234999997,
        2.9883890794999997,
        3.0580843355,
        3.0289664175,
        2.9972650335,
        3.0554324965,
        3.0257681555
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.0444285265,
      "stddev": 0.024147846614990844,
      "median": 3.0352281175,
      "user": 1.7669767,
      "system": 1.95268284,
      "min": 3.0218055235,
      "max": 3.0943225974999997,
      "times": [
        3.0943225974999997,
        3.0469054485,
        3.0305565075,
        3.0339742555,
        3.0486615825,
        3.0364819795,
        3.0218055235,
        3.0227350175,
        3.0787892625,
        3.0300530905
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6562260405,
      "stddev": 0.006591367338123226,
      "median": 0.654526705,
      "user": 0.3515693,
      "system": 1.2648180399999995,
      "min": 0.6477944675,
      "max": 0.6677788915,
      "times": [
        0.6627456605000001,
        0.6522524535,
        0.6477944675,
        0.6557155545,
        0.6542972315,
        0.6677788915,
        0.6645153995,
        0.6547561785,
        0.6500128815,
        0.6523916865
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.6625668222,
      "stddev": 0.005302404853515592,
      "median": 0.6635681215,
      "user": 0.3375365,
      "system": 1.28717164,
      "min": 0.6537205905,
      "max": 0.6698287565,
      "times": [
        0.6628493655,
        0.6698287565,
        0.6584451215,
        0.6569896895,
        0.6670319505,
        0.6642868775,
        0.6682249335,
        0.6651958825000001,
        0.6590950545,
        0.6537205905
      ]
    }
  ]
}

Scenario: Isolated linker: fresh resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 672.7 ± 14.6 651.2 700.9 6.23 ± 0.14
pacquet@main 652.9 ± 15.4 637.4 678.6 6.05 ± 0.15
pnpr@HEAD 107.9 ± 0.7 106.2 110.1 1.00
pnpr@main 108.0 ± 0.8 106.0 109.5 1.00 ± 0.01
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.67267045296,
      "stddev": 0.014613540309902544,
      "median": 0.67106969816,
      "user": 0.63694952,
      "system": 0.1544776,
      "min": 0.65119259516,
      "max": 0.70085450216,
      "times": [
        0.65119259516,
        0.66450684816,
        0.6575861321600001,
        0.6651383361600001,
        0.67911881916,
        0.70085450216,
        0.68755943716,
        0.67860846316,
        0.67349858716,
        0.66864080916
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6529271571599999,
      "stddev": 0.015447789141529687,
      "median": 0.6487955431600001,
      "user": 0.61788392,
      "system": 0.15405349999999998,
      "min": 0.6373590141600001,
      "max": 0.67861123116,
      "times": [
        0.66771909716,
        0.67861123116,
        0.67290768816,
        0.65479394016,
        0.64279714616,
        0.63870172616,
        0.6373590141600001,
        0.6554075231600001,
        0.6418135351600001,
        0.63916067016
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.10789969480000003,
      "stddev": 0.0006790338620303291,
      "median": 0.10793351516000001,
      "user": 0.02749954,
      "system": 0.01884936,
      "min": 0.10620787816,
      "max": 0.11006737816,
      "times": [
        0.10824105816000001,
        0.10793611816000001,
        0.10782925916000001,
        0.10813951716,
        0.10879186316000002,
        0.10727186916,
        0.10744050516,
        0.10764924416,
        0.10776963916000001,
        0.10829835316000001,
        0.10725388716,
        0.10801555416000001,
        0.10807836216000001,
        0.11006737816,
        0.10620787816,
        0.10803288916,
        0.10802930916000002,
        0.10746591216000001,
        0.10853006516000001,
        0.10812604016,
        0.10785797216000001,
        0.10793351516000001,
        0.10734841416000002,
        0.10742859316000002,
        0.10774917316000002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.10798242407999999,
      "stddev": 0.0008135935630399215,
      "median": 0.10805837716000001,
      "user": 0.026567580000000004,
      "system": 0.019845999999999996,
      "min": 0.10599323916000002,
      "max": 0.10954205016000002,
      "times": [
        0.10690195516,
        0.10954205016000002,
        0.10636522216000001,
        0.10805837716000001,
        0.10840070416000001,
        0.10818883216000001,
        0.10757145916000001,
        0.10874686916000001,
        0.10728338216000001,
        0.10795623616000001,
        0.10834520816000001,
        0.10779398016000001,
        0.10809662716000001,
        0.10877379916000002,
        0.10705800916000001,
        0.10787246216000002,
        0.10866581516000001,
        0.10783794216,
        0.10843085016000001,
        0.10759429116000001,
        0.10857799716000001,
        0.10801042716,
        0.10907128616000002,
        0.10599323916000002,
        0.10842358016
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, cold cache + cold store + cold pnpr

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 7.139 ± 0.322 6.762 7.850 1.41 ± 0.07
pacquet@main 7.047 ± 0.106 6.886 7.207 1.39 ± 0.03
pnpr@HEAD 5.104 ± 0.082 4.992 5.267 1.01 ± 0.03
pnpr@main 5.077 ± 0.098 4.918 5.253 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 7.139103716939999,
      "stddev": 0.321690086937458,
      "median": 7.06733218414,
      "user": 4.15693242,
      "system": 3.82295296,
      "min": 6.76168715714,
      "max": 7.850449923139999,
      "times": [
        7.20572080914,
        7.24913839014,
        6.76168715714,
        6.9406888341399995,
        6.850042192139999,
        6.96580723814,
        7.432838257139999,
        7.850449923139999,
        6.97562757414,
        7.1590367941399995
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 7.047081826039999,
      "stddev": 0.10587395097991775,
      "median": 7.03642103364,
      "user": 4.141299219999999,
      "system": 3.795641860000001,
      "min": 6.885799403139999,
      "max": 7.20671454814,
      "times": [
        6.885799403139999,
        6.958811101139999,
        6.97220391714,
        7.08271816114,
        7.20671454814,
        7.04885011814,
        7.14102097314,
        7.02399194914,
        6.966355935139999,
        7.18435215414
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 5.10354269464,
      "stddev": 0.0815278002888752,
      "median": 5.10044244514,
      "user": 2.83370092,
      "system": 3.24548986,
      "min": 4.991760032139999,
      "max": 5.266672199139999,
      "times": [
        5.10535555114,
        5.075738749139999,
        5.117942256139999,
        5.266672199139999,
        4.991760032139999,
        5.158297139139999,
        5.16534032514,
        5.059842167139999,
        5.09552933914,
        4.99894918814
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 5.07666424284,
      "stddev": 0.09845811160380773,
      "median": 5.06748499264,
      "user": 2.81885662,
      "system": 3.28627076,
      "min": 4.9176693371399995,
      "max": 5.253104403139999,
      "times": [
        4.9176693371399995,
        5.123474863139999,
        5.02318781514,
        4.99791360114,
        5.01724726114,
        5.11178217014,
        5.15195847414,
        5.018048224139999,
        5.1522562791399995,
        5.253104403139999
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12925
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
4,325.89 ms
(+1.50%)Baseline: 4,262.02 ms
5,114.42 ms
(84.58%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,019.42 ms
(-0.54%)Baseline: 3,035.76 ms
3,642.91 ms
(82.88%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,388.41 ms
(+1.97%)Baseline: 1,361.62 ms
1,633.94 ms
(84.97%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
672.67 ms
(+3.87%)Baseline: 647.58 ms
777.10 ms
(86.56%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,112.29 ms
(+0.20%)Baseline: 4,104.26 ms
4,925.11 ms
(83.50%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
7,139.10 ms
(+2.77%)Baseline: 6,946.97 ms
8,336.36 ms
(85.64%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
668.66 ms
(+4.47%)Baseline: 640.06 ms
768.07 ms
(87.06%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12925
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,217.61 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
656.23 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
696.78 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
107.90 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,202.03 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
5,103.54 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
738.05 ms
🐰 View full continuous benchmarking report in Bencher

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 10, 2026
On an error exit the error handler terminated descendant processes by
enumerating them with pidtree, which on Windows shells out to wmic (or a
PowerShell fallback) and regularly exceeds the 500 ms budget introduced
in pnpm#12403 - so the cleanup was
effectively skipped there and children spawned by still-running commands
were orphaned.

Track the PIDs of the child processes spawned for pnpm exec and pnpm dlx
in a registry in `@pnpm/exec.lifecycle`. On Windows the error handler
now kills the process tree of every still-running tracked child with
taskkill /T /F - the PID is already known, so no process-list
enumeration is needed. taskkill failures (exit code 128 when the tree
root already exited) are ignored. On POSIX the existing enumeration is
kept: one ps call is fast there and also reaches the descendants of
children that pnpm cannot track.

Lifecycle scripts (pnpm run and install hooks) are spawned inside
`@pnpm/npm-lifecycle`, which does not expose the spawned child process,
so they cannot be registered from this repository yet. Wiring them up
needs a small change in pnpm/npm-lifecycle (exposing the child PID and
an on-spawn callback); the tracker in `@pnpm/exec.lifecycle` is written
so runLifecycleHook can reuse it once that lands.

Fixes https://github.com/pnpm/pnpm/issues/12406
Strip the wmic and powershell directories from PATH in the regression
test to emulate a Windows installation where descendant enumeration is
unavailable, assert the failure actually came from the recursive exec,
and return a minimal subprocess-like object from the mocked safeExeca
since the exec and dlx handlers now register the returned subprocess
with the child process tracker. Add the new terms to the cspell
dictionary.
A child spawned without detached joins the libuv Job Object of its
parent on Windows and is killed together with it, so the previous
fixtures could never leave an orphan behind and the assertions passed
vacuously. Only a detached grandchild reproduces the orphaned-process
scenario the regression test exists for.
…rences

Addresses the automated review feedback: the taskkill spawn now has a
10s timeout so cleanup is bounded if taskkill itself hangs, and the
recursive-exec cleanup test restores the working directory it changes.
Also adds the exec/lifecycle project reference the meta-updater check
expects after the new dependency.
The 100ms delay between liveness probes is intentionally sequential;
the same inline suppression is used for the equivalent poll loop in the
default-reporter tests.
@zkochan
zkochan force-pushed the fix/windows-taskkill-process-trees branch from 5b75b9b to 04b6ba3 Compare July 13, 2026 11:52
@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 📎 Requirement gaps (1) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Action required

1. Taskkill wait can hang ✓ Resolved 🐞 Bug ☼ Reliability ⭐ New
Description
On Windows, killProcessTree() awaits a Promise that only resolves on taskkill 'exit'/'error', so if
taskkill hangs (or its termination never yields those events) pnpm’s error exit can block
indefinitely. This is on the hot error-exit path because errorHandler() awaits
killTrackedProcessTrees() before calling exit().
Code

pnpm11/exec/lifecycle/src/trackChildProcess.ts[R50-61]

+    await new Promise<void>((resolve) => {
+      // The timeout bounds the wait in case taskkill itself hangs; the kill
+      // is best-effort either way, and pnpm is exiting on an error already.
+      const taskkill = spawn(taskkillPath, ['/pid', pid.toString(), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10_000 })
+      // A non-zero exit code (128 when the process is already gone, 1 when
+      // access is denied) is deliberately ignored.
+      taskkill.once('error', () => {
+        resolve()
+      })
+      taskkill.once('exit', () => {
+        resolve()
+      })
Evidence
The Windows branch resolves only on taskkill events, with no independent timer/race in the Promise;
the error handler awaits this cleanup before exiting, so a stuck taskkill can stall pnpm
termination.

pnpm11/exec/lifecycle/src/trackChildProcess.ts[50-61]
pnpm11/pnpm/src/errorHandler.ts[62-70]

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

### Issue description
`killProcessTree()` claims to bound the wait with a `timeout` option on `spawn()`, but the surrounding Promise only resolves on `exit`/`error`. If `taskkill.exe` hangs (or its termination does not result in these events being observed), `killTrackedProcessTrees()` can block and delay/hang pnpm’s error exit.

### Issue Context
This function is awaited from the Windows branch of the error handler, so any hang here directly impacts the CLI exiting on failures.

### Fix Focus Areas
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[50-61]

### Suggested fix
Implement a real Promise-level deadline by racing against a JS timer (and clearing it on completion), e.g.:
- Start a `setTimeout(..., 10_000).unref()` that resolves the Promise (best-effort) and optionally calls `taskkill.kill()`.
- Keep the existing `exit`/`error` handlers (and consider listening to `close` as well).
- Alternatively (Node >=22), prefer `signal: AbortSignal.timeout(10_000)` and still keep a Promise-level fallback timer so the function always resolves.

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


2. Taskkill path hijack ✓ Resolved 🐞 Bug ⛨ Security
Description
On Windows, killProcessTree() spawns taskkill by bare name, so Windows executable resolution may
run a shadowed taskkill.exe from the working directory or PATH during error cleanup. This can lead
to arbitrary code execution with pnpm's privileges when run in an environment where an attacker can
control a searched directory/PATH segment.
Code

pnpm11/exec/lifecycle/src/trackChildProcess.ts[R44-48]

+    await new Promise<void>((resolve) => {
+      // The timeout bounds the wait in case taskkill itself hangs; the kill
+      // is best-effort either way, and pnpm is exiting on an error already.
+      const taskkill = spawn('taskkill', ['/pid', pid.toString(), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10_000 })
+      // A non-zero exit code (128 when the process is already gone, 1 when
Evidence
The code uses a bare executable name (taskkill) when spawning, and the Windows error handler will
call this cleanup path, so a shadowed executable could be invoked during error exits.

pnpm11/exec/lifecycle/src/trackChildProcess.ts[42-55]
pnpm11/pnpm/src/errorHandler.ts[62-70]

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

## Issue description
`spawn('taskkill', ...)` relies on Windows executable search (CWD/PATH). A malicious `taskkill.exe` placed in a searched directory can be executed during error handling.

## Issue Context
This new `taskkill` path is invoked from the global error handler on Windows.

## Fix Focus Areas
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[42-56]
- pnpm11/pnpm/src/errorHandler.ts[62-70]

## Suggested fix
- Resolve `taskkill.exe` to an absolute, trusted location, e.g. `path.join(process.env.SystemRoot ?? process.env.WINDIR ?? 'C:\\Windows', 'System32', 'taskkill.exe')`.
- Spawn that absolute path (still `shell: false`, `windowsHide: true`, `stdio: 'ignore'`).
- If the path cannot be resolved, skip silently (best-effort) rather than falling back to PATH search.

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



Remediation recommended

3. Stale PID reuse window 🐞 Bug ☼ Reliability
Description
trackChildProcess() only untracks on close/error, so a child PID can remain tracked briefly
after the process has exited but before streams close. In that narrow window, PID reuse could cause
taskkill /T /F to target an unrelated process tree.
Code

pnpm11/exec/lifecycle/src/trackChildProcess.ts[R15-24]

+export function trackChildProcess (child: TrackableChildProcess): void {
+  const pid = child.pid
+  if (pid == null) return
+  trackedChildPids.add(pid)
+  const untrack = () => {
+    trackedChildPids.delete(pid)
+  }
+  child.once('close', untrack)
+  child.once('error', untrack)
+}
Evidence
PIDs are stored as numbers and removed only on close/error, while cleanup uses taskkill /T /F
keyed only by PID, so an exited-but-still-tracked PID is the critical condition for a PID-reuse
race.

pnpm11/exec/lifecycle/src/trackChildProcess.ts[15-24]
pnpm11/exec/lifecycle/src/trackChildProcess.ts[42-50]

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

## Issue description
Using only the `close` event to untrack can keep exited PIDs in the tracked set slightly longer than needed. If cleanup runs during that interval and the OS reuses the PID, the wrong process tree could be killed.

## Issue Context
This is a best-effort cleanup path, but `taskkill /T /F` is forceful, so reducing stale-PID windows is worthwhile.

## Fix Focus Areas
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[15-24]
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[42-56]

## Suggested fix
- Also untrack on the earliest exit notification: register `child.once('exit', untrack)` in addition to `close`/`error`.
- Update `TrackableChildProcess` to allow the `exit` event.
- Keep `close` untracking as a fallback for implementations that may not emit `exit` as expected.

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


4. Windows cleanup kills only tracked 📎 Requirement gap ☼ Reliability
Description
On Windows, the error handler now only calls killTrackedProcessTrees(), so any subprocesses
spawned outside trackChildProcess() (e.g. lifecycle scripts via @pnpm/npm-lifecycle) will not be
terminated on error exit. This falls short of the requirement to reliably kill spawned process trees
at the spawn layer for run/exec/lifecycle scripts on Windows.
Code

pnpm11/pnpm/src/errorHandler.ts[R62-70]

async function killProcesses (status: number): Promise<void> {
-  try {
-    const descendentProcesses = await Promise.race([
-      getDescendentProcesses(process.pid).catch(() => [] as number[]),
-      new Promise<number[]>((resolve) => {
-        setTimeout(() => resolve([]), DESCENDANT_LOOKUP_TIMEOUT).unref()
-      }),
-    ])
-    for (const pid of descendentProcesses) {
-      try {
-        process.kill(pid)
-      } catch {
-        // ignore error here
+  if (process.platform === 'win32') {
+    // Enumerating descendant processes on Windows shells out to `wmic` — or,
+    // where wmic has been removed, a PowerShell `Get-CimInstance` fallback —
+    // which can take tens of seconds. Instead of enumerating, kill the
+    // process trees of the still-running child processes whose PIDs were
+    // recorded at their spawn sites.
+    await killTrackedProcessTrees()
+  } else {
Evidence
killProcesses() now takes the Windows path that only calls killTrackedProcessTrees(), so cleanup
depends entirely on processes being registered via the tracker. runLifecycleHook() delegates to
@pnpm/npm-lifecycle without any registration hook, indicating lifecycle-spawned subprocesses are
not tracked and therefore won't be killed by the new Windows error-exit cleanup path.

Windows: kill spawned process trees at run/exec/lifecycle spawn layer using taskkill /T /F (no pidtree enumeration)
pnpm11/pnpm/src/errorHandler.ts[62-70]
pnpm11/exec/lifecycle/src/runLifecycleHook.ts[115-145]

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, `errorHandler()` now skips descendant enumeration and only kills process trees for PIDs previously registered via `trackChildProcess()`. This means subprocess trees spawned through mechanisms that do not register a child process (notably lifecycle scripts via `@pnpm/npm-lifecycle`) can remain running after pnpm exits on an error.

## Issue Context
The compliance requirement is to reliably kill spawned process trees for run/exec/lifecycle scripts on Windows using `taskkill /T /F` at the spawn layer (known child PID), without relying on slow pidtree enumeration.

## Fix Focus Areas
- pnpm11/pnpm/src/errorHandler.ts[62-70]
- pnpm11/exec/lifecycle/src/runLifecycleHook.ts[115-145]
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[15-40]

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


5. Taskkill burst on failures 🐞 Bug ➹ Performance
Description
killTrackedProcessTrees() spawns one taskkill process per tracked PID concurrently via
Promise.all, which can create a process-creation burst on error exit when workspace concurrency is
configured high. This can add CPU/process pressure right when pnpm is already failing.
Code

pnpm11/exec/lifecycle/src/trackChildProcess.ts[R38-40]

+export async function killTrackedProcessTrees (): Promise<void> {
+  await Promise.all(Array.from(trackedChildPids, killProcessTree))
+}
Evidence
The cleanup launches one kill operation per tracked PID with no limit, and workspace concurrency is
configurable to any positive value, so the number of simultaneous tracked children (and thus
taskkills) can scale up.

pnpm11/exec/lifecycle/src/trackChildProcess.ts[38-40]
pnpm11/config/reader/src/concurrency.ts[23-33]
pnpm11/exec/commands/src/exec.ts[169-181]

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, `Promise.all` over the full PID set can start many `taskkill` processes at once. With high `workspaceConcurrency`, this can create avoidable overhead during error exits.

## Issue Context
Default workspace concurrency is small, but users can configure it to any positive number.

## Fix Focus Areas
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[38-56]
- pnpm11/config/reader/src/concurrency.ts[23-33]

## Suggested fix
Choose one:
1) **Batch**: spawn a single `taskkill.exe` with repeated `/PID <pid>` arguments (or chunk into batches to avoid command-line length limits).
2) **Bound concurrency**: use a small limiter (e.g. 4–8) when spawning per-PID `taskkill` processes.
Either way, keep best-effort semantics and keep the overall cleanup bounded.

ⓘ 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 8a1a4da

Results up to commit 04b6ba3


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


Action required
1. Taskkill path hijack ✓ Resolved 🐞 Bug ⛨ Security
Description
On Windows, killProcessTree() spawns taskkill by bare name, so Windows executable resolution may
run a shadowed taskkill.exe from the working directory or PATH during error cleanup. This can lead
to arbitrary code execution with pnpm's privileges when run in an environment where an attacker can
control a searched directory/PATH segment.
Code

pnpm11/exec/lifecycle/src/trackChildProcess.ts[R44-48]

+    await new Promise<void>((resolve) => {
+      // The timeout bounds the wait in case taskkill itself hangs; the kill
+      // is best-effort either way, and pnpm is exiting on an error already.
+      const taskkill = spawn('taskkill', ['/pid', pid.toString(), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10_000 })
+      // A non-zero exit code (128 when the process is already gone, 1 when
Evidence
The code uses a bare executable name (taskkill) when spawning, and the Windows error handler will
call this cleanup path, so a shadowed executable could be invoked during error exits.

pnpm11/exec/lifecycle/src/trackChildProcess.ts[42-55]
pnpm11/pnpm/src/errorHandler.ts[62-70]

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

## Issue description
`spawn('taskkill', ...)` relies on Windows executable search (CWD/PATH). A malicious `taskkill.exe` placed in a searched directory can be executed during error handling.

## Issue Context
This new `taskkill` path is invoked from the global error handler on Windows.

## Fix Focus Areas
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[42-56]
- pnpm11/pnpm/src/errorHandler.ts[62-70]

## Suggested fix
- Resolve `taskkill.exe` to an absolute, trusted location, e.g. `path.join(process.env.SystemRoot ?? process.env.WINDIR ?? 'C:\\Windows', 'System32', 'taskkill.exe')`.
- Spawn that absolute path (still `shell: false`, `windowsHide: true`, `stdio: 'ignore'`).
- If the path cannot be resolved, skip silently (best-effort) rather than falling back to PATH search.

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



Remediation recommended
2. Windows cleanup kills only tracked 📎 Requirement gap ☼ Reliability
Description
On Windows, the error handler now only calls killTrackedProcessTrees(), so any subprocesses
spawned outside trackChildProcess() (e.g. lifecycle scripts via @pnpm/npm-lifecycle) will not be
terminated on error exit. This falls short of the requirement to reliably kill spawned process trees
at the spawn layer for run/exec/lifecycle scripts on Windows.
Code

pnpm11/pnpm/src/errorHandler.ts[R62-70]

async function killProcesses (status: number): Promise<void> {
-  try {
-    const descendentProcesses = await Promise.race([
-      getDescendentProcesses(process.pid).catch(() => [] as number[]),
-      new Promise<number[]>((resolve) => {
-        setTimeout(() => resolve([]), DESCENDANT_LOOKUP_TIMEOUT).unref()
-      }),
-    ])
-    for (const pid of descendentProcesses) {
-      try {
-        process.kill(pid)
-      } catch {
-        // ignore error here
+  if (process.platform === 'win32') {
+    // Enumerating descendant processes on Windows shells out to `wmic` — or,
+    // where wmic has been removed, a PowerShell `Get-CimInstance` fallback —
+    // which can take tens of seconds. Instead of enumerating, kill the
+    // process trees of the still-running child processes whose PIDs were
+    // recorded at their spawn sites.
+    await killTrackedProcessTrees()
+  } else {
Evidence
killProcesses() now takes the Windows path that only calls killTrackedProcessTrees(), so cleanup
depends entirely on processes being registered via the tracker. runLifecycleHook() delegates to
@pnpm/npm-lifecycle without any registration hook, indicating lifecycle-spawned subprocesses are
not tracked and therefore won't be killed by the new Windows error-exit cleanup path.

Windows: kill spawned process trees at run/exec/lifecycle spawn layer using taskkill /T /F (no pidtree enumeration)
pnpm11/pnpm/src/errorHandler.ts[62-70]
pnpm11/exec/lifecycle/src/runLifecycleHook.ts[115-145]

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, `errorHandler()` now skips descendant enumeration and only kills process trees for PIDs previously registered via `trackChildProcess()`. This means subprocess trees spawned through mechanisms that do not register a child process (notably lifecycle scripts via `@pnpm/npm-lifecycle`) can remain running after pnpm exits on an error.

## Issue Context
The compliance requirement is to reliably kill spawned process trees for run/exec/lifecycle scripts on Windows using `taskkill /T /F` at the spawn layer (known child PID), without relying on slow pidtree enumeration.

## Fix Focus Areas
- pnpm11/pnpm/src/errorHandler.ts[62-70]
- pnpm11/exec/lifecycle/src/runLifecycleHook.ts[115-145]
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[15-40]

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


3. Stale PID reuse window 🐞 Bug ☼ Reliability
Description
trackChildProcess() only untracks on close/error, so a child PID can remain tracked briefly
after the process has exited but before streams close. In that narrow window, PID reuse could cause
taskkill /T /F to target an unrelated process tree.
Code

pnpm11/exec/lifecycle/src/trackChildProcess.ts[R15-24]

+export function trackChildProcess (child: TrackableChildProcess): void {
+  const pid = child.pid
+  if (pid == null) return
+  trackedChildPids.add(pid)
+  const untrack = () => {
+    trackedChildPids.delete(pid)
+  }
+  child.once('close', untrack)
+  child.once('error', untrack)
+}
Evidence
PIDs are stored as numbers and removed only on close/error, while cleanup uses taskkill /T /F
keyed only by PID, so an exited-but-still-tracked PID is the critical condition for a PID-reuse
race.

pnpm11/exec/lifecycle/src/trackChildProcess.ts[15-24]
pnpm11/exec/lifecycle/src/trackChildProcess.ts[42-50]

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

## Issue description
Using only the `close` event to untrack can keep exited PIDs in the tracked set slightly longer than needed. If cleanup runs during that interval and the OS reuses the PID, the wrong process tree could be killed.

## Issue Context
This is a best-effort cleanup path, but `taskkill /T /F` is forceful, so reducing stale-PID windows is worthwhile.

## Fix Focus Areas
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[15-24]
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[42-56]

## Suggested fix
- Also untrack on the earliest exit notification: register `child.once('exit', untrack)` in addition to `close`/`error`.
- Update `TrackableChildProcess` to allow the `exit` event.
- Keep `close` untracking as a fallback for implementations that may not emit `exit` as expected.

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


4. Taskkill burst on failures 🐞 Bug ➹ Performance
Description
killTrackedProcessTrees() spawns one taskkill process per tracked PID concurrently via
Promise.all, which can create a process-creation burst on error exit when workspace concurrency is
configured high. This can add CPU/process pressure right when pnpm is already failing.
Code

pnpm11/exec/lifecycle/src/trackChildProcess.ts[R38-40]

+export async function killTrackedProcessTrees (): Promise<void> {
+  await Promise.all(Array.from(trackedChildPids, killProcessTree))
+}
Evidence
The cleanup launches one kill operation per tracked PID with no limit, and workspace concurrency is
configurable to any positive value, so the number of simultaneous tracked children (and thus
taskkills) can scale up.

pnpm11/exec/lifecycle/src/trackChildProcess.ts[38-40]
pnpm11/config/reader/src/concurrency.ts[23-33]
pnpm11/exec/commands/src/exec.ts[169-181]

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, `Promise.all` over the full PID set can start many `taskkill` processes at once. With high `workspaceConcurrency`, this can create avoidable overhead during error exits.

## Issue Context
Default workspace concurrency is small, but users can configure it to any positive number.

## Fix Focus Areas
- pnpm11/exec/lifecycle/src/trackChildProcess.ts[38-56]
- pnpm11/config/reader/src/concurrency.ts[23-33]

## Suggested fix
Choose one:
1) **Batch**: spawn a single `taskkill.exe` with repeated `/PID <pid>` arguments (or chunk into batches to avoid command-line length limits).
2) **Bound concurrency**: use a small limiter (e.g. 4–8) when spawning per-PID `taskkill` processes.
Either way, keep best-effort semantics and keep the overall cleanup bounded.

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


Qodo Logo

@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 8a1a4da

Warning

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

CategorySuggestion                                                                                                                                    Impact
Possible issue
Untrack only after process closure

Untrack the child process only on the close event, not on the error event, to
avoid untracking live processes.

pnpm11/exec/lifecycle/src/trackChildProcess.ts [23-24]

 child.once('close', untrack)
-child.once('error', untrack)
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The error event does not guarantee that the child process has exited, so keeping it tracked until close prevents live processes from being incorrectly orphaned.

Medium
  • More

Previous suggestions

Suggestions up to commit e8fde33
CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve cleanup for untracked subprocesses

Retain the bounded process enumeration on Windows as a fallback alongside the
new tracking mechanism, or ensure all user-command spawn paths are tracked. This
prevents regressions for non-tracked subprocesses on systems where the
enumeration successfully completes.

pnpm11/pnpm/src/errorHandler.ts [63-88]

-if (process.platform === 'win32') {
-  await killTrackedProcessTrees()
-} else {
+await Promise.all([
+  process.platform === 'win32'
+    ? killTrackedProcessTrees()
+    : Promise.resolve(),
+  killEnumeratedDescendants(),
+])
+
+async function killEnumeratedDescendants (): Promise<void> {
   try {
     const descendentProcesses = await Promise.race([
       getDescendentProcesses(process.pid).catch(() => [] as number[]),
       new Promise<number[]>((resolve) => {
         setTimeout(() => resolve([]), DESCENDANT_LOOKUP_TIMEOUT).unref()
       }),
     ])
     for (const pid of descendentProcesses) {
       try {
         process.kill(pid)
       } catch {
         // ignore error here
       }
     }
   } catch {
     // ignore error here
   }
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a regression where untracked processes (like lifecycle scripts) will be orphaned on Windows systems where the previous enumeration worked within the timeout, and proposes a valid fallback approach.

Medium
Suggestions up to commit 04b6ba3
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent killing reused process IDs

Untrack the child PID on the exit event instead of close. This prevents the risk
of killing unrelated processes if the original child's PID is reused while its
descendants keep stdio handles open.

pnpm11/exec/lifecycle/src/trackChildProcess.ts [3-24]

 export interface TrackableChildProcess {
   pid?: number
-  once: (event: 'close' | 'error', listener: () => void) => unknown
+  once: (event: 'exit' | 'error', listener: () => void) => unknown
 }
 
 export function trackChildProcess (child: TrackableChildProcess): void {
   const pid = child.pid
   if (pid == null) return
   trackedChildPids.add(pid)
   const untrack = () => {
     trackedChildPids.delete(pid)
   }
-  child.once('close', untrack)
+  child.once('exit', untrack)
   child.once('error', untrack)
 }
Suggestion importance[1-10]: 9

__

Why: Changing the untrack event to exit prevents potential bugs where reused PIDs lead to unrelated process trees being incorrectly terminated on Windows.

High
Preserve cleanup for untracked subprocesses

Keep the bounded descendant process lookup on Windows as a fallback. Relying
solely on killTrackedProcessTrees misses untracked subprocesses like lifecycle
scripts, causing regressions in cleanup behavior.

pnpm11/pnpm/src/errorHandler.ts [63-87]

 if (process.platform === 'win32') {
-  // Enumerating descendant processes on Windows shells out to `wmic` — or,
-  // where wmic has been removed, a PowerShell `Get-CimInstance` fallback —
-  // which can take tens of seconds. Instead of enumerating, kill the
-  // process trees of the still-running child processes whose PIDs were
-  // recorded at their spawn sites.
   await killTrackedProcessTrees()
-} else {
-  try {
-    const descendentProcesses = await Promise.race([
-      getDescendentProcesses(process.pid).catch(() => [] as number[]),
-      new Promise<number[]>((resolve) => {
-        setTimeout(() => resolve([]), DESCENDANT_LOOKUP_TIMEOUT).unref()
-      }),
-    ])
-    for (const pid of descendentProcesses) {
-      try {
-        process.kill(pid)
-      } catch {
-        // ignore error here
-      }
-    }
-  } catch {
-    // ignore error here
-  }
 }
 
+try {
+  const descendentProcesses = await Promise.race([
+    getDescendentProcesses(process.pid).catch(() => [] as number[]),
+    new Promise<number[]>((resolve) => {
+      setTimeout(() => resolve([]), DESCENDANT_LOOKUP_TIMEOUT).unref()
+    }),
+  ])
+  for (const pid of descendentProcesses) {
+    try {
+      process.kill(pid)
+    } catch {
+      // ignore error here
+    }
+  }
+} catch {
+  // ignore error here
+}
+
Suggestion importance[1-10]: 8

__

Why: Restoring the fallback descendant lookup ensures that untracked child processes (such as those from lifecycle scripts) are still appropriately cleaned up on Windows during a failure.

Medium

@greptile-apps

greptile-apps Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge — the change is well-scoped, the POSIX path is untouched, and the Windows path is well-protected against path injection by resolving taskkill to its absolute System32 location.

The Windows cleanup logic is straightforward and hard to break: it reads a known PID from the registry, resolves taskkill to a hardcoded System32 path, ignores expected non-zero exit codes, and is bounded by an unref'd 10-second timer that prevents hanging on error exit. The POSIX path in errorHandler is entirely unchanged. Unit and e2e tests exercise actual process-tree kills on real OS processes, and the PR includes cross-platform CI evidence.

No files require special attention.

Reviews (2): Last reviewed commit: "fix: guarantee the taskkill wait always ..." | Re-trigger Greptile

zkochan and others added 3 commits July 13, 2026 14:38
Register the spawned subprocess with the child-process tracker inside a
small `trackedExeca` helper local to `@pnpm/exec.commands`, so the exec
and dlx spawn sites can't spawn a command without also tracking it. The
tracker itself stays spawn-library-agnostic (a structural
`TrackableChildProcess`) so `@pnpm/npm-lifecycle` can reuse it for the
raw-spawn lifecycle path in the follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
killProcessTree() spawned taskkill by bare name, so Windows executable
resolution could run a taskkill.exe planted in the current directory or
on PATH during error cleanup - arbitrary code execution with pnpm's
privileges, since the error handler runs with the cwd set to a possibly
untrusted project directory. Resolve taskkill to its absolute
%SystemRoot%\System32\taskkill.exe location instead. It is still spawned
with shell: false and windowsHide: true; if the resolved path is missing,
spawn emits 'error' and the best-effort kill is skipped rather than
falling back to a PATH search.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The first test waited on 'exit', but the tracker untracks a PID on
'close', which fires later. If 'close' had not fired before the next
test ran, the first test's PID lingered in the module-level registry and
the "no-op for an already-exited child" test was not exercising a truly
empty registry. Await 'close' so untrack has run before the test ends.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

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

killProcessTree() awaited a Promise that only settled on taskkill's
'exit'/'error'. The spawn `timeout` option force-kills a hung taskkill
but the Promise still waits for an event a stuck taskkill might never
emit, so pnpm's error exit could block indefinitely - errorHandler()
awaits killTrackedProcessTrees() before calling exit(). Bound the wait
with an unref'd 10s timer that resolves the Promise regardless (and
reaps a stuck taskkill), clearing it when 'exit'/'error' arrives first.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8a1a4da

@zkochan
zkochan merged commit b46f961 into pnpm:main Jul 13, 2026
28 of 30 checks passed
@welcome

welcome Bot commented Jul 13, 2026

Copy link
Copy Markdown

Congrats on merging your first pull request! 🎉🎉🎉

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

Labels

product: pnpm@11 reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants