Skip to content

fix: bound descendant-process lookup on error exit to avoid a Windows hang - #12403

Merged
zkochan merged 3 commits into
mainfrom
win-e2e-trust-lockfile
Jun 14, 2026
Merged

zkochan merged 3 commits into
mainfrom
win-e2e-trust-lockfile

Conversation

@zkochan

@zkochan zkochan commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Problem

On Windows, any failed pnpm command hangs 20–46 seconds before exiting. The error handler (pnpm/src/errorHandler.ts) enumerates descendant processes via pidtree to terminate them on every error exit. On Windows pidtree shells out to wmic and, where wmic has been removed, a PowerShell Get-CimInstance Win32_Process fallback — a process listing that takes tens of seconds on busy CI runners.

This also broke Windows CI: the verifyDepsBeforeRun/* e2e suites are full of intentional-failure assertions (e.g. pnpm start with --config.verify-deps-before-run=error when deps aren't installed). Each failure paid the ~23 s error-handler tax, so the suite blew past the 70-minute cap. pnpm install and success paths never hit the error handler, which is why only failures were slow.

Diagnosed by sampling process.getActiveResourcesInfo() during the hang: it showed a lingering ProcessWrap (a spawned child), and hooking child_process.spawn named it (wmic → powershell … Get-CimInstance Win32_Process, exiting after ~23–46 s).

Fix

Race the descendant-process lookup against a 2 s timeout. If it doesn't return in time, skip the kill and exit — exit() calls process.exit, which abandons the still-running (harmless, read-only) process query instead of blocking on it. The fast path (Unix, fast Windows) is unchanged.

Confirmed on Windows CI: the failing start invocations dropped from ~23 s to ~2.7 s, and multiProjectWorkspace.ts went from 716 s to 124 s.

Also included

The CI pnpr-binary cache is split into restore + an explicit save step that runs right after the build, so a failing test step no longer discards the ~20-minute Rust build (the combined actions/cache only saved in a post-job step that gets skipped on failure).

Changeset: pnpm patch.


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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (10) 📘 Rule violations (0)

Grey Divider


Remediation recommended

1. Timeout may leak children 🐞 Bug ☼ Reliability
Description
killProcesses() now races descendant PID enumeration against a 2s timeout and may proceed with an
empty PID list, skipping child termination when enumeration is slow. This can leave long-lived child
processes (e.g. dev servers from failed scripts) running after pnpm exits, keeping ports open and
interfering with subsequent commands/CI steps.
Code

pnpm/src/errorHandler.ts[R57-66]

+const DESCENDANT_LOOKUP_TIMEOUT = 2000
+
async function killProcesses (status: number): Promise<void> {
try {
-    const descendentProcesses = await getDescendentProcesses(process.pid)
+    const descendentProcesses = await Promise.race([
+      getDescendentProcesses(process.pid).catch(() => [] as number[]),
+      new Promise<number[]>((resolve) => {
+        setTimeout(() => resolve([]), DESCENDANT_LOOKUP_TIMEOUT).unref()
+      }),
+    ])
Evidence
The new Promise.race timeout can resolve to an empty PID list, so the subsequent kill loop becomes a
no-op before exiting. A repository test documents the expectation that pnpm exits should clean up
child processes to prevent lingering servers/ports, which is exactly what the timeout path can
violate when enumeration is slow.

pnpm/src/errorHandler.ts[50-78]
pnpm/test/errorHandler.test.ts[49-63]

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

## Issue description
`pnpm/src/errorHandler.ts` now bounds descendant process lookup via `Promise.race(...)` with a 2s timeout that returns `[]`. When the timeout wins (the exact scenario this change is meant to address on busy Windows CI), `killProcesses()` skips killing descendants and immediately exits, potentially leaving child processes running.
### Issue Context
There is already a test documenting that pnpm should clean up child processes on exit (to avoid lingering servers/ports). Even though that test is skipped on Windows due to flakiness, it demonstrates the intended invariant the error handler is supposed to preserve.
### Fix Focus Areas
- pnpm/src/errorHandler.ts[50-78]
### Suggested fix approach
- Restrict the 2s timeout behavior to Windows only (`process.platform === 'win32'`) so other platforms retain the previous behavior.
- On Windows, if the timeout path is taken, add a best-effort fallback that still kills the process tree without requiring a full enumeration (e.g. spawn `taskkill /T /F /PID <pid>` and ignore errors), then continue to `exit(status)`.
- Keep the current fast path (pidTree result returned within deadline) to kill specific PIDs as before.

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


2. NODE_OPTIONS shim leaks 🐞 Bug ☼ Reliability
Description
execPnpmSync() forces NODE_OPTIONS="--require=<winDiagNet.cjs>" for every pnpm invocation, which can
be inherited/propagated into Node subprocesses spawned by pnpm (e.g. lifecycle hooks),
unintentionally preloading the diagnostic shim into code under test. This can alter stderr/output
and runtime behavior of those subprocesses, reducing test reliability and the diagnostic signal
quality.
Code

pnpm/test/utils/execPnpm.ts[R150-154]

env: {
 ...createEnv({ omitEnvDefaults: opts?.omitEnvDefaults }),
+      NODE_OPTIONS: `--require=${WIN_DIAG_NET_SHIM}`, // WIN-DIAG
 ...opts?.env,
} as NodeJS.ProcessEnv,
Evidence
The PR adds a forced NODE_OPTIONS-based preload in execPnpmSync(), while the shim writes to stderr
and monkeypatches net/dns. Separately, pnpm’s lifecycle helper constructs NODE_OPTIONS for hook
execution by appending to the current process.env.NODE_OPTIONS, demonstrating a propagation path
into lifecycle hook subprocesses.

pnpm/test/utils/execPnpm.ts[143-166]
pnpm/test/utils/winDiagNet.cjs[3-12]
pnpm/test/utils/winDiagNet.cjs[29-41]
exec/lifecycle/src/index.ts[6-9]

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

## Issue description
`execPnpmSync()` injects the diagnostic preload via `NODE_OPTIONS=--require=...`. Because `NODE_OPTIONS` is an environment variable, it can be inherited by (and in some cases further appended/forwarded into) Node processes that pnpm spawns (notably lifecycle hooks), causing the diagnostic shim to run in unintended subprocesses.
### Issue Context
The shim (`winDiagNet.cjs`) monkeypatches `dns.lookup` and `net.Socket.prototype.connect` and writes diagnostic lines to `stderr`. pnpm lifecycle code also builds `NODE_OPTIONS` for hook execution by appending `--require=...` to any existing `process.env.NODE_OPTIONS`, so starting pnpm with `NODE_OPTIONS` set can bleed into hook processes.
### Fix Focus Areas
- pnpm/test/utils/execPnpm.ts[143-166]
### Suggested fix
- Avoid using `NODE_OPTIONS` to preload the shim for the pnpm process. Instead, add the require preload directly to the Node argv used to launch pnpm, e.g.:
- `crossSpawn.sync(process.execPath, ['--require', WIN_DIAG_NET_SHIM, pnpmBinLocation, ...args], ...)`
- This keeps the preload scoped to the pnpm process invocation itself.
- If you must keep `NODE_OPTIONS`, ensure it is **appended** rather than overwritten and consider explicitly clearing/unsetting it for subprocesses (where possible), and/or gate the preload behind `isWindows()` and a dedicated opt-in env flag (e.g. `PNPM_WIN_DIAG=1`).

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


3. Cache save key collision 🐞 Bug ☼ Reliability
Description
test.yml now explicitly saves the pnpr-bins cache mid-job, but the cache key is only runner.os
+ Rust-source hash, so multiple matrix jobs on the same OS can miss the cache and then attempt to
save the same key concurrently. This can make CI nondeterministic (one job wins the save, others may
fail/skip) and reintroduce flaky failures right where the workflow is being tightened as a
Windows-first gate.
Code

.github/workflows/test.yml[R119-127]

+    # Save the binaries to the cache right after they build, not in a post-job
+    # step: a later step failing (e.g. a crashing test) would otherwise skip
+    # the save and force a full ~20-minute rebuild on the next run.
+    - name: Save prebuilt pnpr binaries
+      if: steps.pnpr-bins.outputs.cache-hit != 'true'
+      uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
+      with:
+        path: .pnpr-bin
+        key: ${{ steps.pnpr-bins.outputs.cache-primary-key }}
Evidence
The matrix fan-out runs multiple jobs per OS concurrently, while the .pnpr-bin cache key does not
vary by Node version, so multiple jobs can compute the same key and hit the new unconditional save
path on cache-miss.

.github/workflows/ci.yml[61-82]
.github/workflows/test.yml[26-28]
.github/workflows/test.yml[98-103]
.github/workflows/test.yml[119-127]

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

## Issue description
The new `actions/cache/save` step can be executed by multiple parallel jobs that share the same cache key (key does not include Node version / job identity). When several jobs miss the cache (e.g., first run after Rust changes), they may race to save the same key, making CI behavior nondeterministic.
## Issue Context
The reusable workflow runs in a matrix (multiple `inputs.node` values per OS), while the cache key for `.pnpr-bin` is shared across those jobs.
## Fix Focus Areas
- .github/workflows/test.yml[98-103]
- .github/workflows/test.yml[119-127]
- .github/workflows/ci.yml[61-82]
## Suggested fixes (pick one)
1) **Designate a single saver job per OS** (recommended): gate the save step so only one specific job saves the cache, e.g. only when `inputs.garnet == true` (Linux) and only when `inputs.platform == 'windows-latest' && inputs.node == '22.13.0'` (Windows smoke).
2) **Add job identity to the cache key**: include `${{ inputs.node }}` in the key to prevent collisions (at the cost of storing multiple identical caches per OS).
3) **Use a two-phase approach**: keep restore-only in most jobs and move building+saving into a dedicated preparatory job that other jobs `needs` and that uploads `.pnpr-bin` as an artifact.

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


View more (6)
4. NODE_DEBUG forced globally 🐞 Bug ➹ Performance
Description
execPnpmSync() now unconditionally sets NODE_DEBUG='net,dns', which makes every sync pnpm
invocation emit verbose net/dns debug to stderr and adds significant overhead across the test suite.
Because execPnpmSync() is used heavily in e2e tests, this can distort the Windows slowdown
diagnosis and bloat CI logs.
Code

pnpm/test/utils/execPnpm.ts[R146-165]

+  const diagStart = Date.now() // WIN-DIAG
const execResult = crossSpawn.sync(process.execPath, [pnpmBinLocation, ...args], {
cwd: opts?.cwd,
env: {
...createEnv({ omitEnvDefaults: opts?.omitEnvDefaults }),
+      NODE_DEBUG: 'net,dns', // WIN-DIAG
...opts?.env,
} as NodeJS.ProcessEnv,
stdio: opts?.stdio ?? 'pipe',
timeout: opts?.timeout ?? DEFAULT_EXEC_PNPM_TIMEOUT,
})
+  const diagMs = Date.now() - diagStart // WIN-DIAG
+  process.stderr.write(`[WIN-DIAG] execPnpmSync ${diagMs}ms :: ${args.join(' ')}\n`) // WIN-DIAG
+  if (diagMs > 5000) { // WIN-DIAG: dump socket/dns activity for the slow calls only
+    const netLines = (execResult.stderr?.toString() ?? '')
+      .split('\n')
+      .filter((l) => /NET|DNS|connect|lookup|::1|127\.0\.0\.1|socket|family|refused|timed/i.test(l))
+      .slice(0, 60)
+    process.stderr.write(`[WIN-DIAG-NET ${args.join(' ')}]\n${netLines.join('\n')}\n[/WIN-DIAG-NET]\n`)
+  }
Evidence
The helper now forces NODE_DEBUG and writes diagnostic timing for every execPnpmSync() call, and
execPnpmSync() is invoked repeatedly in Windows-e2e suites (and throughout pnpm tests), so the
overhead is amplified across the run.

pnpm/test/utils/execPnpm.ts[142-165]
pnpm/test/verifyDepsBeforeRun/multiProjectWorkspace.ts[66-90]
pnpm/test/bin.ts[8-18]

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

## Issue description
`execPnpmSync()` always injects `NODE_DEBUG='net,dns'` and always prints `[WIN-DIAG]` timing lines, which increases stderr volume and runtime for the entire synchronous test surface.
### Issue Context
This helper is used widely throughout `pnpm/test/**`, including the Windows-regressed `verifyDepsBeforeRun/*` suites.
### Fix Focus Areas
- pnpm/test/utils/execPnpm.ts[142-165]
### Suggested fix
- Only set `NODE_DEBUG` (and emit `[WIN-DIAG]` logs) when explicitly enabled, e.g. via `process.env.WIN_DIAG === '1'` and/or `isWindows()`.
- Keep the diagnostic behavior opt-in so normal CI runs don’t pay the logging/debug overhead.

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


5. Dead test-scope step 🐞 Bug ☼ Reliability
Description
The reusable workflow still runs “Determine test scope” (including a git fetch origin main) and
exports TEST_SCRIPT, but the updated “Run tests” step ignores TEST_SCRIPT and always runs `pn
--filter=pnpm .test`. This adds unnecessary work and an avoidable network-dependent failure point to
every CI job using this workflow.
Code

.github/workflows/test.yml[R151-154]

+      # TEMPORARY (Windows e2e diagnostic): run only the pnpm package's tests
+      # instead of the full affected-packages sweep, for fast turnaround.
+      # `.test` runs jest against the prebuilt artifacts (no recompile).
+      run: pn prepare-fixtures && pn --filter=pnpm .test
Evidence
The workflow computes steps.test-scope.outputs.script via a git fetch, sets it into TEST_SCRIPT,
but then hardcodes a different command in the run step; therefore the scope computation is redundant
and still executed for every job.

.github/workflows/test.yml[126-154]
.github/workflows/test.yml[47-55]

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

## Issue description
`Determine test scope` is now effectively dead code: it performs a fetch/diff to compute `TEST_SCRIPT`, but the test step no longer uses `TEST_SCRIPT`.
### Issue Context
Keeping the step increases CI time and introduces an extra git network operation that can fail independently of the test command.
### Fix Focus Areas
- .github/workflows/test.yml[126-154]
### Suggested fix
- Either:
- Restore using `TEST_SCRIPT` in the run step (and keep the scope logic), **or**
- Remove the `Determine test scope` step and the `TEST_SCRIPT` env var while this temporary diagnostic command is in place, **or**
- Guard the scope step behind a diagnostic input/flag so it only runs when needed.

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


6. Unconditional stderr diagnostics 🐞 Bug ➹ Performance
Description
execPnpm() now writes a “[WIN-DIAG] …” line to the parent process stderr on every spawned pnpm close
event, which will spam CI logs across the e2e suite and adds avoidable I/O on a hot path. This is
labeled WIN-DIAG but is currently enabled for all platforms/runs rather than being gated behind
Windows and/or an explicit debug flag.
Code

pnpm/test/utils/execPnpm.ts[R28-31]

+  const diagStart = Date.now() // WIN-DIAG
await new Promise<void>((resolve, reject) => {
const proc = crossSpawn.spawn(process.execPath, [pnpmBinLocation, ...args], {
env: {
Evidence
The PR adds unconditional process.stderr.write(...) calls for execPnpm/execPnpmSync, and those
helpers are used throughout the test suite, so the new logging will appear for many test invocations
and can inflate log volume and add overhead.

pnpm/test/utils/execPnpm.ts[20-63]
pnpm/test/utils/execPnpm.ts[142-167]
pnpm/test/install/misc.ts[23-57]
pnpm/test/verifyDepsBeforeRun/multiProjectWorkspace.ts[10-15]

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

## Issue description
`execPnpm()`/`execPnpmSync()` unconditionally write diagnostic timing lines to the parent process stderr on every pnpm invocation. This is noisy and adds extra synchronous-ish I/O work on a frequently-called helper.
## Issue Context
These helpers are used broadly across pnpm’s e2e test suite. The new logging is tagged `WIN-DIAG` but is not currently scoped to Windows and not controlled via an opt-in env flag.
## Fix Focus Areas
- pnpm/test/utils/execPnpm.ts[20-63]
- pnpm/test/utils/execPnpm.ts[142-167]
## Proposed fix
- Only emit the diagnostic line when `(process.platform === 'win32')` **and** an explicit opt-in env var is set (e.g. `process.env.PNPM_WIN_DIAG === '1'`).
- Optionally, only log when duration exceeds a threshold (e.g. >2s) or when a timeout occurs, to keep logs actionable.
- Ensure both async and sync helpers follow the same gating rule.

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


7. Unguarded Garnet token usage 🐞 Bug ☼ Reliability
Description
The new garnet-scan job enables the Garnet action, but the reusable workflow declares
GARNET_API_TOKEN as not required and does not guard the Garnet step against an empty/missing
token. This makes CI success dependent on how the action behaves when api_token is empty and can
create avoidable failures in contexts where the secret isn’t available.
Code

.github/workflows/ci.yml[R48-54]

+  # The Garnet supply-chain scan needs Linux; run it ungated alongside the
+  # Windows smoke rather than blocking the matrix on it.
+  garnet-scan:
+    name: ubuntu-latest / Node.js 24 (garnet)
needs: compile-and-lint
uses: ./.github/workflows/test.yml
with:
Evidence
garnet-scan always enables garnet: true in ci.yml, while test.yml explicitly marks the secret
optional yet still runs the Garnet action whenever inputs.garnet is true, without any presence
check for the token.

.github/workflows/ci.yml[38-60]
.github/workflows/test.yml[4-19]
.github/workflows/test.yml[51-55]

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 workflow call marks `GARNET_API_TOKEN` as optional, but the Garnet step still runs whenever `inputs.garnet` is true and passes `secrets.GARNET_API_TOKEN` directly. If the secret is not set/available, the job behavior becomes dependent on the external action’s handling of an empty token.
## Issue Context
`ci.yml` introduces a dedicated `garnet-scan` job that always sets `garnet: true` and forwards `secrets.GARNET_API_TOKEN`.
## Fix Focus Areas
- .github/workflows/ci.yml[48-60]
- .github/workflows/test.yml[4-19]
- .github/workflows/test.yml[51-55]
## Proposed fix
- Guard the Garnet step in `test.yml` so it only runs when the token is present, e.g.:
- `if: ${{ inputs.garnet && secrets.GARNET_API_TOKEN != '' }}`
- Alternatively (or additionally), add an `if:` on the `garnet-scan` job in `ci.yml` to skip the job when the token is empty.
- Keep `GARNET_API_TOKEN` optional if you intend the rest of tests to run even when Garnet is skipped.

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


8. Verifier disabled by default 🐞 Bug ⚙ Maintainability
Description
createEnv() now sets pnpm_config_trust_lockfile='true', causing installs spawned by pnpm e2e
tests to skip verifyLockfileResolutions() entirely. Since the npm resolution verifier is always
present, this reduces default test coverage of the lockfile-verification path unless each
verifier-dependent test explicitly opts out.
Code

pnpm/test/utils/execPnpm.ts[R212-218]

+    // Trust the lockfile by default so the post-resolution lockfile
+    // verifier (an unconditional per-package registry round trip) doesn't
+    // run on every spawned install. The bursts of localhost connections it
+    // issues are cheap on Linux but pathological on Windows runners, where
+    // they dominated the e2e suite wall-clock. Suites that exercise the
+    // verifier opt out via `omitEnvDefaults: ['pnpm_config_trust_lockfile']`.
+    pnpm_config_trust_lockfile: 'true',
Evidence
The test harness now sets pnpm_config_trust_lockfile to true, and the installer only runs
lockfile verification when trustLockfile is falsy. Additionally, the resolver always supplies at
least one verifier (npm verifier), so this default suppresses the verifier path broadly across
installs spawned by this harness.

pnpm/test/utils/execPnpm.ts[205-221]
installing/deps-installer/src/install/index.ts[395-407]
resolving/default-resolver/src/index.ts[196-237]

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

## Issue description
`pnpm/test/utils/execPnpm.ts#createEnv()` now exports `pnpm_config_trust_lockfile=true` by default, which disables the lockfile verification pass (`verifyLockfileResolutions`) for most test-spawned installs. Because resolution verifiers are always present (at least the npm verifier), this changes baseline e2e semantics and can mask verifier regressions unless tests remember to opt out.
### Issue Context
- The pnpm test harness is used by many suites; changing its defaults changes what the majority of tests actually exercise.
- Tests that *intentionally* exercise verifier behavior should be protected against accidentally running with `trustLockfile=true`.
### Fix Focus Areas
- pnpm/test/utils/execPnpm.ts[205-231]

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


9. Async execPnpm can't omit defaults 🐞 Bug ⚙ Maintainability
Description
createEnv() now documents opting out of the default pnpm_config_trust_lockfile via
omitEnvDefaults, but execPnpm()/spawnPnpm() don’t accept omitEnvDefaults, so async tests
can’t use the documented mechanism. This inconsistency is misleading and makes future
verifier-dependent async tests harder to write correctly.
Code

pnpm/test/utils/execPnpm.ts[R212-218]

+    // Trust the lockfile by default so the post-resolution lockfile
+    // verifier (an unconditional per-package registry round trip) doesn't
+    // run on every spawned install. The bursts of localhost connections it
+    // issues are cheap on Linux but pathological on Windows runners, where
+    // they dominated the e2e suite wall-clock. Suites that exercise the
+    // verifier opt out via `omitEnvDefaults: ['pnpm_config_trust_lockfile']`.
+    pnpm_config_trust_lockfile: 'true',
Evidence
The shared createEnv() now instructs callers to opt out via omitEnvDefaults, but the async
helpers don’t have an omitEnvDefaults option to forward into createEnv(), while the sync helper
explicitly does.

pnpm/test/utils/execPnpm.ts[20-35]
pnpm/test/utils/execPnpm.ts[64-77]
pnpm/test/utils/execPnpm.ts[141-151]
pnpm/test/utils/execPnpm.ts[186-225]

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

## Issue description
`createEnv()` supports `omitEnvDefaults` and the newly-added comment says verifier suites can opt out via `omitEnvDefaults: ['pnpm_config_trust_lockfile']`. However, only `execPnpmSync()` can actually pass `omitEnvDefaults` into `createEnv()` today; `execPnpm()` and `spawnPnpm()` don’t expose that option.
### Issue Context
This mismatch is easy to miss because the comment lives in `createEnv()` (shared by sync+async helpers), but the option is only wired for the sync path.
### Fix Focus Areas
- pnpm/test/utils/execPnpm.ts[20-77]
- pnpm/test/utils/execPnpm.ts[141-165]
- pnpm/test/utils/execPnpm.ts[186-226]
### Suggested fix
1) Add `omitEnvDefaults?: PnpmEnvDefault[]` to the `execPnpm()` and `spawnPnpm()` option types.
2) Pass `omitEnvDefaults` through to `createEnv({ storeDir, omitEnvDefaults })` similarly to `execPnpmSync()`.
3) (Alternative if you don’t want API expansion) Adjust the new comment to clarify `omitEnvDefaults` is only available on `execPnpmSync()`, and document the async opt-out as `opts.env = { pnpm_config_trust_lockfile: 'false' }`.

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



Informational

10. JobGuard semantics misleading 🐞 Bug ⚙ Maintainability ⭐ New
Description
job_control::setup() claims it returns a guard representing an open Job Object handle held for
process lifetime, but JobGuard is an empty marker and does not actually store the handle. This is
not a runtime bug today (the handle is intentionally leaked), but the API/docs suggest a lifetime
guarantee that the type does not enforce, increasing maintenance risk for future refactors or
additional call sites.
Code

pacquet/crates/cli/src/job_control.rs[R13-65]

+/// Marker that process-tree cleanup has been installed; hold it for the
+/// lifetime of the process.
+///
+/// On Windows it stands for a Job Object whose handle is intentionally kept
+/// open for the whole run: the OS closes it at exit, which is what fires
+/// `KILL_ON_JOB_CLOSE`. On Unix the kernel's process-group and signal model
+/// already tears down descendants, so the guard is inert.
+pub struct JobGuard;
+
+#[cfg(windows)]
+pub fn setup() -> Option<JobGuard> {
+    use core::mem::{size_of, zeroed};
+    use core::ptr;
+    use windows_sys::Win32::Foundation::CloseHandle;
+    use windows_sys::Win32::System::JobObjects::{
+        AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
+        JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
+        SetInformationJobObject,
+    };
+    use windows_sys::Win32::System::Threading::GetCurrentProcess;
+
+    // SAFETY: these are standard Win32 Job Object calls. Every pointer
+    // argument is either null or a stack local that outlives the call,
+    // `GetCurrentProcess` returns a pseudo-handle that must not be closed,
+    // and the job handle is released by the OS at process exit.
+    unsafe {
+        let job = CreateJobObjectW(ptr::null(), ptr::null());
+        if job.is_null() {
+            return None;
+        }
+        let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = zeroed();
+        info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+        let set = SetInformationJobObject(
+            job,
+            JobObjectExtendedLimitInformation,
+            ptr::addr_of!(info).cast(),
+            size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
+        );
+        if set == 0 {
+            CloseHandle(job);
+            return None;
+        }
+        // Fails when pacquet is already inside a job that forbids nesting;
+        // fall back to no tree cleanup rather than aborting the command.
+        if AssignProcessToJobObject(job, GetCurrentProcess()) == 0 {
+            CloseHandle(job);
+            return None;
+        }
+        // Deliberately do not close `job`: it must stay open until the process
+        // exits so `KILL_ON_JOB_CLOSE` fires then. Closing it now would also
+        // terminate this process, since it is assigned to the job.
+        Some(JobGuard)
+    }
Evidence
The file documents that the returned guard represents a Job Object handle kept open, but the
implementation returns JobGuard while never storing the job handle anywhere (and deliberately
not closing it), making the guard a marker rather than a lifetime owner.

pacquet/crates/cli/src/job_control.rs[13-65]
pacquet/crates/cli/src/lib.rs[24-42]

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

### Issue description
`JobGuard` is an empty marker type, but the module docs describe it as standing for a Job Object handle that must be held open for the program lifetime. In reality, the handle is intentionally leaked (never closed), so the guard does not actually control the handle lifetime.

### Issue Context
This is primarily a documentation/API clarity issue: the behavior works because the handle is not managed via RAII.

### Fix Focus Areas
- pacquet/crates/cli/src/job_control.rs[13-65]

Concrete fix options:
- Update docs/comments to say explicitly that the handle is intentionally leaked and that `JobGuard` is only a marker indicating setup succeeded.
- Alternatively, change the API to return a `bool`/`Result<()>` to represent “installed or not,” if a guard is not actually providing lifetime management.

ⓘ 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 889cfc6

Results up to commit a2aebd9


🐞 Bugs (9) 📘 Rule violations (0)


Remediation recommended
1. Timeout may leak children 🐞 Bug ☼ Reliability
Description
killProcesses() now races descendant PID enumeration against a 2s timeout and may proceed with an
empty PID list, skipping child termination when enumeration is slow. This can leave long-lived child
processes (e.g. dev servers from failed scripts) running after pnpm exits, keeping ports open and
interfering with subsequent commands/CI steps.
Code

pnpm/src/errorHandler.ts[R57-66]

+const DESCENDANT_LOOKUP_TIMEOUT = 2000
+
async function killProcesses (status: number): Promise<void> {
try {
-    const descendentProcesses = await getDescendentProcesses(process.pid)
+    const descendentProcesses = await Promise.race([
+      getDescendentProcesses(process.pid).catch(() => [] as number[]),
+      new Promise<number[]>((resolve) => {
+        setTimeout(() => resolve([]), DESCENDANT_LOOKUP_TIMEOUT).unref()
+      }),
+    ])
Evidence
The new Promise.race timeout can resolve to an empty PID list, so the subsequent kill loop becomes a
no-op before exiting. A repository test documents the expectation that pnpm exits should clean up
child processes to prevent lingering servers/ports, which is exactly what the timeout path can
violate when enumeration is slow.

pnpm/src/errorHandler.ts[50-78]
pnpm/test/errorHandler.test.ts[49-63]

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

## Issue description
`pnpm/src/errorHandler.ts` now bounds descendant process lookup via `Promise.race(...)` with a 2s timeout that returns `[]`. When the timeout wins (the exact scenario this change is meant to address on busy Windows CI), `killProcesses()` skips killing descendants and immediately exits, potentially leaving child processes running.
### Issue Context
There is already a test documenting that pnpm should clean up child processes on exit (to avoid lingering servers/ports). Even though that test is skipped on Windows due to flakiness, it demonstrates the intended invariant the error handler is supposed to preserve.
### Fix Focus Areas
- pnpm/src/errorHandler.ts[50-78]
### Suggested fix approach
- Restrict the 2s timeout behavior to Windows only (`process.platform === 'win32'`) so other platforms retain the previous behavior.
- On Windows, if the timeout path is taken, add a best-effort fallback that still kills the process tree without requiring a full enumeration (e.g. spawn `taskkill /T /F /PID <pid>` and ignore errors), then continue to `exit(status)`.
- Keep the current fast path (pidTree result returned within deadline) to kill specific PIDs as before.

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


2. NODE_OPTIONS shim leaks 🐞 Bug ☼ Reliability
Description
execPnpmSync() forces NODE_OPTIONS="--require=<winDiagNet.cjs>" for every pnpm invocation, which can
be inherited/propagated into Node subprocesses spawned by pnpm (e.g. lifecycle hooks),
unintentionally preloading the diagnostic shim into code under test. This can alter stderr/output
and runtime behavior of those subprocesses, reducing test reliability and the diagnostic signal
quality.
Code

pnpm/test/utils/execPnpm.ts[R150-154]

env: {
  ...createEnv({ omitEnvDefaults: opts?.omitEnvDefaults }),
+      NODE_OPTIONS: `--require=${WIN_DIAG_NET_SHIM}`, // WIN-DIAG
  ...opts?.env,
} as NodeJS.ProcessEnv,
Evidence
The PR adds a forced NODE_OPTIONS-based preload in execPnpmSync(), while the shim writes to stderr
and monkeypatches net/dns. Separately, pnpm’s lifecycle helper constructs NODE_OPTIONS for hook
execution by appending to the current process.env.NODE_OPTIONS, demonstrating a propagation path
into lifecycle hook subprocesses.

pnpm/test/utils/execPnpm.ts[143-166]
pnpm/test/utils/winDiagNet.cjs[3-12]
pnpm/test/utils/winDiagNet.cjs[29-41]
exec/lifecycle/src/index.ts[6-9]

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

## Issue description
`execPnpmSync()` injects the diagnostic preload via `NODE_OPTIONS=--require=...`. Because `NODE_OPTIONS` is an environment variable, it can be inherited by (and in some cases further appended/forwarded into) Node processes that pnpm spawns (notably lifecycle hooks), causing the diagnostic shim to run in unintended subprocesses.
### Issue Context
The shim (`winDiagNet.cjs`) monkeypatches `dns.lookup` and `net.Socket.prototype.connect` and writes diagnostic lines to `stderr`. pnpm lifecycle code also builds `NODE_OPTIONS` for hook execution by appending `--require=...` to any existing `process.env.NODE_OPTIONS`, so starting pnpm with `NODE_OPTIONS` set can bleed into hook processes.
### Fix Focus Areas
- pnpm/test/utils/execPnpm.ts[143-166]
### Suggested fix
- Avoid using `NODE_OPTIONS` to preload the shim for the pnpm process. Instead, add the require preload directly to the Node argv used to launch pnpm, e.g.:
- `crossSpawn.sync(process.execPath, ['--require', WIN_DIAG_NET_SHIM, pnpmBinLocation, ...args], ...)`
- This keeps the preload scoped to the pnpm process invocation itself.
- If you must keep `NODE_OPTIONS`, ensure it is **appended** rather than overwritten and consider explicitly clearing/unsetting it for subprocesses (where possible), and/or gate the preload behind `isWindows()` and a dedicated opt-in env flag (e.g. `PNPM_WIN_DIAG=1`).

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


3. Cache save key collision 🐞 Bug ☼ Reliability
Description
test.yml now explicitly saves the pnpr-bins cache mid-job, but the cache key is only runner.os
+ Rust-source hash, so multiple matrix jobs on the same OS can miss the cache and then attempt to
save the same key concurrently. This can make CI nondeterministic (one job wins the save, others may
fail/skip) and reintroduce flaky failures right where the workflow is being tightened as a
Windows-first gate.
Code

.github/workflows/test.yml[R119-127]

+    # Save the binaries to the cache right after they build, not in a post-job
+    # step: a later step failing (e.g. a crashing test) would otherwise skip
+    # the save and force a full ~20-minute rebuild on the next run.
+    - name: Save prebuilt pnpr binaries
+      if: steps.pnpr-bins.outputs.cache-hit != 'true'
+      uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
+      with:
+        path: .pnpr-bin
+        key: ${{ steps.pnpr-bins.outputs.cache-primary-key }}
Evidence
The matrix fan-out runs multiple jobs per OS concurrently, while the .pnpr-bin cache key does not
vary by Node version, so multiple jobs can compute the same key and hit the new unconditional save
path on cache-miss.

.github/workflows/ci.yml[61-82]
.github/workflows/test.yml[26-28]
.github/workflows/test.yml[98-103]
.github/workflows/test.yml[119-127]

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

## Issue description
The new `actions/cache/save` step can be executed by multiple parallel jobs that share the same cache key (key does not include Node version / job identity). When several jobs miss the cache (e.g., first run after Rust changes), they may race to save the same key, making CI behavior nondeterministic.
## Issue Context
The reusable workflow runs in a matrix (multiple `inputs.node` values per OS), while the cache key for `.pnpr-bin` is shared across those jobs.
## Fix Focus Areas
- .github/workflows/test.yml[98-103]
- .github/workflows/test.yml[119-127]
- .github/workflows/ci.yml[61-82]
## Suggested fixes (pick one)
1) **Designate a single saver job per OS** (recommended): gate the save step so only one specific job saves the cache, e.g. only when `inputs.garnet == true` (Linux) and only when `inputs.platform == 'windows-latest' && inputs.node == '22.13.0'` (Windows smoke).
2) **Add job identity to the cache key**: include `${{ inputs.node }}` in the key to prevent collisions (at the cost of storing multiple identical caches per OS).
3) **Use a two-phase approach**: keep restore-only in most jobs and move building+saving into a dedicated preparatory job that other jobs `needs` and that uploads `.pnpr-bin` as an artifact.

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


View more (6)
4. NODE_DEBUG forced globally 🐞 Bug ➹ Performance
Description
execPnpmSync() now unconditionally sets NODE_DEBUG='net,dns', which makes every sync pnpm
invocation emit verbose net/dns debug to stderr and adds significant overhead across the test suite.
Because execPnpmSync() is used heavily in e2e tests, this can distort the Windows slowdown
diagnosis and bloat CI logs.
Code

pnpm/test/utils/execPnpm.ts[R146-165]

+  const diagStart = Date.now() // WIN-DIAG
const execResult = crossSpawn.sync(process.execPath, [pnpmBinLocation, ...args], {
cwd: opts?.cwd,
env: {
...createEnv({ omitEnvDefaults: opts?.omitEnvDefaults }),
+      NODE_DEBUG: 'net,dns', // WIN-DIAG
...opts?.env,
} as NodeJS.ProcessEnv,
stdio: opts?.stdio ?? 'pipe',
timeout: opts?.timeout ?? DEFAULT_EXEC_PNPM_TIMEOUT,
})
+  const diagMs = Date.now() - diagStart // WIN-DIAG
+  process.stderr.write(`[WIN-DIAG] execPnpmSync ${diagMs}ms :: ${args.join(' ')}\n`) // WIN-DIAG
+  if (diagMs > 5000) { // WIN-DIAG: dump socket/dns activity for the slow calls only
+    const netLines = (execResult.stderr?.toString() ?? '')
+      .split('\n')
+      .filter((l) => /NET|DNS|connect|lookup|::1|127\.0\.0\.1|socket|family|refused|timed/i.test(l))
+      .slice(0, 60)
+    process.stderr.write(`[WIN-DIAG-NET ${args.join(' ')}]\n${netLines.join('\n')}\n[/WIN-DIAG-NET]\n`)
+  }
Evidence
The helper now forces NODE_DEBUG and writes diagnostic timing for every execPnpmSync() call, and
execPnpmSync() is invoked repeatedly in Windows-e2e suites (and throughout pnpm tests), so the
overhead is amplified across the run.

pnpm/test/utils/execPnpm.ts[142-165]
pnpm/test/verifyDepsBeforeRun/multiProjectWorkspace.ts[66-90]
pnpm/test/bin.ts[8-18]

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

## Issue description
`execPnpmSync()` always injects `NODE_DEBUG='net,dns'` and always prints `[WIN-DIAG]` timing lines, which increases stderr volume and runtime for the entire synchronous test surface.
### Issue Context
This helper is used widely throughout `pnpm/test/**`, including the Windows-regressed `verifyDepsBeforeRun/*` suites.
### Fix Focus Areas
- pnpm/test/utils/execPnpm.ts[142-165]
### Suggested fix
- Only set `NODE_DEBUG` (and emit `[WIN-DIAG]` logs) when explicitly enabled, e.g. via `process.env.WIN_DIAG === '1'` and/or `isWindows()`.
- Keep the diagnostic behavior opt-in so normal CI runs don’t pay the logging/debug overhead.

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


5. Dead test-scope step 🐞 Bug ☼ Reliability
Description
The reusable workflow still runs “Determine test scope” (including a git fetch origin main) and
exports TEST_SCRIPT, but the updated “Run tests” step ignores TEST_SCRIPT and always runs `pn
--filter=pnpm .test`. This adds unnecessary work and an avoidable network-dependent failure point to
every CI job using this workflow.
Code

.github/workflows/test.yml[R151-154]

+      # TEMPORARY (Windows e2e diagnostic): run only the pnpm package's tests
+      # instead of the full affected-packages sweep, for fast turnaround.
+      # `.test` runs jest against the prebuilt artifacts (no recompile).
+      run: pn prepare-fixtures && pn --filter=pnpm .test
Evidence
The workflow computes steps.test-scope.outputs.script via a git fetch, sets it into TEST_SCRIPT,
but then hardcodes a different command in the run step; therefore the scope computation is redundant
and still executed for every job.

.github/workflows/test.yml[126-154]
.github/workflows/test.yml[47-55]

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

## Issue description
`Determine test scope` is now effectively dead code: it performs a fetch/diff to compute `TEST_SCRIPT`, but the test step no longer uses `TEST_SCRIPT`.
### Issue Context
Keeping the step increases CI time and introduces an extra git network operation that can fail independently of the test command.
### Fix Focus Areas
- .github/workflows/test.yml[126-154]
### Suggested fix
- Either:
- Restore using `TEST_SCRIPT` in the run step (and keep the scope logic), **or**
- Remove the `Determine test scope` step and the `TEST_SCRIPT` env var while this temporary diagnostic command is in place, **or**
- Guard the scope step behind a diagnostic input/flag so it only runs when needed.

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


6. Unconditional stderr diagnostics 🐞 Bug ➹ Performance
Description
execPnpm() now writes a “[WIN-DIAG] …” line to the parent process stderr on every spawned pnpm close
event, which will spam CI logs across the e2e suite and adds avoidable I/O on a hot path. This is
labeled WIN-DIAG but is currently enabled for all platforms/runs rather than being gated behind
Windows and/or an explicit debug flag.
Code

pnpm/test/utils/execPnpm.ts[R28-31]

+  const diagStart = Date.now() // WIN-DIAG
await new Promise<void>((resolve, reject) => {
const proc = crossSpawn.spawn(process.execPath, [pnpmBinLocation, ...args], {
env: {
Evidence
The PR adds unconditional process.stderr.write(...) calls for execPnpm/execPnpmSync, and those
helpers are used throughout the test suite, so the new logging will appear for many test invocations
and can inflate log volume and add overhead.

pnpm/test/utils/execPnpm.ts[20-63]
pnpm/test/utils/execPnpm.ts[142-167]
pnpm/test/install/misc.ts[23-57]
pnpm/test/verifyDepsBeforeRun/multiProjectWorkspace.ts[10-15]

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

## Issue description
`execPnpm()`/`execPnpmSync()` unconditionally write diagnostic timing lines to the parent process stderr on every pnpm invocation. This is noisy and adds extra synchronous-ish I/O work on a frequently-called helper.
## Issue Context
These helpers are used broadly across pnpm’s e2e test suite. The new logging is tagged `WIN-DIAG` but is not currently scoped to Windows and not controlled via an opt-in env flag.
## Fix Focus Areas
- pnpm/test/utils/execPnpm.ts[20-63]
- pnpm/test/utils/execPnpm.ts[142-167]
## Proposed fix
- Only emit the diagnostic line when `(process.platform === 'win32')` **and** an explicit opt-in env var is set (e.g. `process.env.PNPM_WIN_DIAG === '1'`).
- Optionally, only log when duration exceeds a threshold (e.g. >2s) or when a timeout occurs, to keep logs actionable.
- Ensure both async and sync helpers follow the same gating rule.

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


7. Unguarded Garnet token usage 🐞 Bug ☼ Reliability
Description
The new garnet-scan job enables the Garnet action, but the reusable workflow declares
GARNET_API_TOKEN as not required and does not guard the Garnet step against an empty/missing
token. This makes CI success dependent on how the action behaves when api_token is empty and can
create avoidable failures in contexts where the secret isn’t available.
Code

.github/workflows/ci.yml[R48-54]

+  # The Garnet supply-chain scan needs Linux; run it ungated alongside the
+  # Windows smoke rather than blocking the matrix on it.
+  garnet-scan:
+    name: ubuntu-latest / Node.js 24 (garnet)
needs: compile-and-lint
uses: ./.github/workflows/test.yml
with:
Evidence
garnet-scan always enables garnet: true in ci.yml, while test.yml explicitly marks the secret
optional yet still runs the Garnet action whenever inputs.garnet is true, without any presence
check for the token.

.github/workflows/ci.yml[38-60]
.github/workflows/test.yml[4-19]
.github/workflows/test.yml[51-55]

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 workflow call marks `GARNET_API_TOKEN` as optional, but the Garnet step still runs whenever `inputs.garnet` is true and passes `secrets.GARNET_API_TOKEN` directly. If the secret is not set/available, the job behavior becomes dependent on the external action’s handling of an empty token.
## Issue Context
`ci.yml` introduces a dedicated `garnet-scan` job that always sets `garnet: true` and forwards `secrets.GARNET_API_TOKEN`.
## Fix Focus Areas
- .github/workflows/ci.yml[48-60]
- .github/workflows/test.yml[4-19]
- .github/workflows/test.yml[51-55]
## Proposed fix
- Guard the Garnet step in `test.yml` so it only runs when the token is present, e.g.:
- `if: ${{ inputs.garnet && secrets.GARNET_API_TOKEN != '' }}`
- Alternatively (or additionally), add an `if:` on the `garnet-scan` job in `ci.yml` to skip the job when the token is empty.
- Keep `GARNET_API_TOKEN` optional if you intend the rest of tests to run even when Garnet is skipped.

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


8. Verifier disabled by default 🐞 Bug ⚙ Maintainability
Description
createEnv() now sets pnpm_config_trust_lockfile='true', causing installs spawned by pnpm e2e
tests to skip verifyLockfileResolutions() entirely. Since the npm resolution verifier is always
present, this reduces default test coverage of the lockfile-verification path unless each
verifier-dependent test explicitly opts out.
Code

pnpm/test/utils/execPnpm.ts[R212-218]

+    // Trust the lockfile by default so the post-resolution lockfile
+    // verifier (an unconditional per-package registry round trip) doesn't
+    // run on every spawned install. The bursts of localhost connections it
+    // issues are cheap on Linux but pathological on Windows runners, where
+    // they dominated the e2e suite wall-clock. Suites that exercise the
+    // verifier opt out via `omitEnvDefaults: ['pnpm_config_trust_lockfile']`.
+    pnpm_config_trust_lockfile: 'true',
Evidence
The test harness now sets pnpm_config_trust_lockfile to true, and the installer only runs
lockfile verification when trustLockfile is falsy. Additionally, the resolver always supplies at
least one verifier (npm verifier), so this default suppresses the verifier path broadly across
installs spawned by this harness.

pnpm/test/utils/execPnpm.ts[205-221]
installing/deps-installer/src/install/index.ts[395-407]
resolving/default-resolver/src/index.ts[196-237]

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

@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The CI workflow gains a dedicated Windows smoke job (Node 22.13.0) and a separate garnet-scan job (Ubuntu/Node 24), both gated on compile-and-lint, with the test matrix exclude comments updated to match. execPnpm and execPnpmSync in the test utilities are instrumented to write WIN-DIAG elapsed-time lines to process.stderr.

Changes

Windows CI smoke job and timing diagnostics

Layer / File(s) Summary
Windows smoke and garnet-scan CI jobs
.github/workflows/ci.yml
Replaces the previous Ubuntu/Node 24 smoke entry with a windows-smoke job (Windows-latest/Node 22.13.0) and adds a parallel garnet-scan job (Ubuntu/Node 24, garnet: true), both gated on compile-and-lint; updates matrix exclude comments to reflect the new coverage split.
Windows diagnostic test execution step
.github/workflows/test.yml
Replaces the prior pn run "$TEST_SCRIPT" invocation with a temporary diagnostic flow: pn prepare-fixtures followed by pn --filter=pnpm .test to run only the pnpm package's Jest suite.
WIN-DIAG timing instrumentation
pnpm/test/utils/execPnpm.ts
Adds diagStart = Date.now() captures and process.stderr.write('[WIN-DIAG ...]') calls reporting elapsed milliseconds and args in both execPnpm's close callback and execPnpmSync's post-execution path; conditionally emits [WIN-DIAG-NET ...] blocks filtering network/DNS/socket lines when elapsed time exceeds 5000ms.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Poem

🐇 Tick-tock goes the Windows clock,
A WIN-DIAG line upon each knock.
Smoke on Windows, garnet gleams,
The pipeline splits in tidy streams.
Elapsed milliseconds, args in row—
Now we know just how tests go! 🕐

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ⚠️ Warning The title references 'bound descendant-process lookup' and 'Windows hang', but the actual changes implement diagnostic instrumentation (elapsed time logging) and CI reordering. The real changes do not address descendant-process lookup or prevent any hang. Revise the title to accurately reflect the PR's actual purpose, such as 'Diagnostic: add Windows e2e invocation timing instrumentation and reorder CI matrix' to clarify this is diagnostic work-in-progress, not a functional fix.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch win-e2e-trust-lockfile

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 and usage tips.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Test: default pnpm e2e installs to trust lockfile to unblock Windows CI
🐞 Bug fix 🧪 Tests ⚙️ Configuration changes 🕐 10-20 Minutes

Grey Divider

Walkthroughs

Description
• Default e2e execPnpm environment to pnpm_config_trust_lockfile=true to skip verifier
• Opt specific verifier-focused suites back in by omitting the new env default
• Prevent Windows CI timeouts caused by per-package registry round trips during installs
Diagram
graph TD
  T["E2E suites"] --> E["execPnpm createEnv"] --> I["Spawned pnpm install"] --> V{"Verifier runs?"}
  V -- "trustLockfile=true (default)" --> S["Skip verifier"]
  V -- "omitEnvDefaults" --> R["Run verifier"] --> M["Registry mock"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Lower pnpm network concurrency for e2e runs
  • ➕ Targets the underlying Windows localhost-connection bottleneck
  • ➕ Keeps verifier enabled without per-test opt-outs
  • ➖ May slow down other parts of the suite
  • ➖ Harder to guarantee it eliminates timeouts across runner variability
2. Disable verifier via a dedicated test-only CLI/config flag
  • ➕ More explicit intent than an env default
  • ➕ Could centralize control without per-test call-site changes
  • ➖ Requires additional plumbing/flag surface area
  • ➖ Still needs opt-in behavior for verifier-specific tests
3. Increase Windows test timeouts
  • ➕ Zero behavioral change to installs/verifier
  • ➕ Fastest operational workaround
  • ➖ Does not address the pathological performance regression
  • ➖ Risks masking future slowdowns and still hitting job-level caps

Recommendation: Keep the PR’s approach: defaulting e2e installs to trust_lockfile=true directly removes the dominant Windows CI cost (verifier registry round trips) while preserving coverage by explicitly opting verifier-focused tests back in via omitEnvDefaults. It’s a low-risk, test-scoped change with clear intent and minimal maintenance overhead.

Grey Divider

File Changes

Tests (2)
minimumReleaseAge.ts Opt out of trustLockfile default for minimumReleaseAge verifier assertions +8/-5

Opt out of trustLockfile default for minimumReleaseAge verifier assertions

• Updates the helper env omission constant to also omit 'pnpm_config_trust_lockfile'. This ensures minimumReleaseAge tests still execute the lockfile verifier and validate strict policy rejection behavior.

pnpm/test/install/minimumReleaseAge.ts


misc.ts Ensure trust-policy downgrade tests still exercise the lockfile verifier +6/-2

Ensure trust-policy downgrade tests still exercise the lockfile verifier

• Adds 'omitEnvDefaults: ['pnpm_config_trust_lockfile']' to the two '--frozen-lockfile' trust-policy tests that specifically validate verifier behavior. Includes comments clarifying why the opt-out is required.

pnpm/test/install/misc.ts


Other (1)
execPnpm.ts Default e2e createEnv to trust lockfile and allow opt-out +8/-0

Default e2e createEnv to trust lockfile and allow opt-out

• Extends the 'PnpmEnvDefault' union to include 'pnpm_config_trust_lockfile' and sets it to ''true'' in 'createEnv'. Documents the Windows CI motivation and directs verifier-focused suites to opt out via 'omitEnvDefaults'.

pnpm/test/utils/execPnpm.ts


Grey Divider

Qodo Logo

@zkochan
zkochan force-pushed the win-e2e-trust-lockfile branch from 0adceaa to 6c2e2b2 Compare June 14, 2026 10:59
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6c2e2b2

@zkochan zkochan changed the title test(pnpm): trust the lockfile by default in e2e installs to fix Windows CI test(pnpm): resolve the registry mock IPv4-first to fix Windows CI timeouts Jun 14, 2026
@zkochan
zkochan force-pushed the win-e2e-trust-lockfile branch from 6c2e2b2 to cb9f3d4 Compare June 14, 2026 11:48
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

@zkochan zkochan changed the title test(pnpm): resolve the registry mock IPv4-first to fix Windows CI timeouts test(pnpm): trust the lockfile by default in e2e installs to fix Windows CI timeouts Jun 14, 2026
@zkochan
zkochan force-pushed the win-e2e-trust-lockfile branch from cb9f3d4 to cebb342 Compare June 14, 2026 12:46
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

@zkochan zkochan changed the title test(pnpm): trust the lockfile by default in e2e installs to fix Windows CI timeouts WIP: diagnose Windows e2e slowdown (+ Windows-first CI gate) Jun 14, 2026
@zkochan
zkochan force-pushed the win-e2e-trust-lockfile branch from cebb342 to 1524665 Compare June 14, 2026 13:53
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

coderabbitai[bot]
coderabbitai Bot previously requested changes Jun 14, 2026

@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 @.github/workflows/test.yml:
- Around line 151-154: The run command at lines 151-154 executes the pnpm-only
test on all platforms instead of Windows only, which reduces test coverage on
Linux and macOS. Add a platform-specific condition (using runner.os) to the step
containing this run command to restrict its execution to Windows only, so that
non-Windows platforms continue executing the full affected-packages test sweep
via ${TEST_SCRIPT}.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d90ac5c6-07d0-447a-9890-283db57b7eb6

📥 Commits

Reviewing files that changed from the base of the PR and between cebb342 and 7f6a6c3.

📒 Files selected for processing (3)
  • .github/workflows/ci.yml
  • .github/workflows/test.yml
  • pnpm/test/utils/execPnpm.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm/test/utils/execPnpm.ts
  • .github/workflows/ci.yml
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: windows-latest / Node.js 22.13.0 / Test

Comment thread .github/workflows/test.yml Resolved
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4df8144

… hang

On every error exit the error handler enumerates descendant processes via
pidtree to terminate them. On Windows pidtree shells out to wmic and, where
wmic is removed, a PowerShell Get-CimInstance fallback that can take 20-46s
on busy machines, so any failed pnpm command hung that long before exiting
(and the verifyDepsBeforeRun e2e suites, full of intentional failures, blew
past the 70-minute CI cap). Race the lookup against a 2s timeout so
process.exit is no longer stalled by it.

Also split the CI pnpr-binary cache into restore + an explicit save step so
a failing test step no longer discards the Rust build.
@zkochan
zkochan force-pushed the win-e2e-trust-lockfile branch from 4df8144 to 4ce3f8b Compare June 14, 2026 15:56
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4ce3f8b

@zkochan zkochan changed the title WIP: diagnose Windows e2e slowdown (+ Windows-first CI gate) fix: bound descendant-process lookup on error exit to avoid a Windows hang Jun 14, 2026
The lookup is instant on POSIX (one ps), so the bound only ever clips the
pathologically slow Windows path; 500ms keeps margin for a loaded machine
while cutting the worst-case error-exit delay.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

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

@github-actions

github-actions Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
tarball/download_dependency    1.04      7.8±0.31ms   554.0 KB/sec    1.00      7.5±0.09ms   575.7 KB/sec

…Object

pnpm's error handler kills descendant processes on exit; pacquet had no
equivalent, so a lifecycle script's detached grandchild could outlive a
failed or interrupted install. Mirror Cargo and Bun: assign the pacquet
process to a Job Object with KILL_ON_JOB_CLOSE so the OS tears down the
whole tree when pacquet exits — the robust mechanism on Windows, which has
no process groups. Best-effort (silently skips if the job can't be created
or assigned) and a no-op on Unix, where the kernel's process-group and
signal model already covers it.

This deliberately diverges from pnpm's pidtree mechanism: pnpm is Node and
has no Job Object binding, whereas pacquet is native and can use the better
primitive. Implemented with raw windows-sys FFI (already in the dependency
tree), so no new crates are added.
@codecov-commenter

codecov-commenter commented Jun 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.14%. Comparing base (23716ed) to head (889cfc6).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #12403   +/-   ##
=======================================
  Coverage   88.14%   88.14%           
=======================================
  Files         300      301    +1     
  Lines       39730    39734    +4     
=======================================
+ Hits        35020    35024    +4     
  Misses       4710     4710           

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

@zkochan

zkochan commented Jun 14, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@zkochan
zkochan force-pushed the win-e2e-trust-lockfile branch from a2aebd9 to 889cfc6 Compare June 14, 2026 16:35
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 889cfc6

@zkochan

zkochan commented Jun 14, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai approve

@coderabbitai

coderabbitai Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Comments resolved. Approval is disabled; enable reviews.request_changes_workflow to allow explicit top-level @coderabbitai resolve or @coderabbitai approve commands.

@zkochan
zkochan merged commit 5f63458 into main Jun 14, 2026
26 checks passed
@zkochan
zkochan deleted the win-e2e-trust-lockfile branch June 14, 2026 16:45
zkochan pushed a commit to Arman-Luthra/pnpm that referenced this pull request Jul 13, 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants