fix(windows): skip stale child process cleanup #16850
main fromrefs/pull/16850/head·opened View on GitHubSuperseded by #16007, merged by juliusmarminge on 2026-10-11 at 17:14:37 UTC as 243c9994d047f3102a9622d1a5cff42ef78515ee. Fresh upstream main contains the same Windows completed-child guard, source/runtime patch, patch registration, and lockfile references for 4.0.2. The differences from this PR's patch are explanatory comments and patch formatting. Closing this duplicate rather than rebasing an already-landed fix. The independent native Windows measurements, runtime validation, screenshot, and reproduction assets below remain available as evidence; this PR itself was not merged. No installed-instance changes or new measurements were made.
Windows commands that exit nonzero currently launch taskkill /T /F twice after Node has observed their exit: once from the Effect spawner's exit listener and once from scoped release. Expected Git probes such as a missing show-ref --verify --quiet therefore incur process creation and cleanup overhead despite already being complete.
Guard the shared Windows taskkill helper when exitCode or signalCode is non-null, completing its callback without launching a command. The owner is @effect/platform-node-shared, re-exported by @effect/platform-node and used by both T3's server and desktop. This uses T3's existing pinned-dependency patch mechanism rather than adding per-caller workarounds. The three changed files contain only the source/runtime patch, patch registration, and generated lockfile references; no dependency versions change and no tests or measurement scripts are added.
Credit: @Alb11747 already proposed this guard in #16007, originally targeting 4.0.0-rc.115. That PR has since been updated to the pinned 4.0.2 and is also mergeable. This PR supplies an independent matched native Windows reproduction of the same guard. Maintainers may prefer the earlier PR and can use this linked evidence when reviewing it.
This qualifies as the small focused obvious-bug exception in CONTRIBUTING.md: skip redundant cleanup of completed Windows children, preserve running-tree termination and all POSIX behavior, add no settings or polling-policy changes. Detached descendants that outlive their leader are not reclaimed by PID-based cleanup in either version. The guard avoids knowingly using a completed leader's stale PID; it does not eliminate the race if a live leader exits between the check and taskkill.
Validation on Windows 11, Ryzen 7800X3D / 16 logical threads, Node 24.19.0. The runtime experiment and focused existing checks were rerun with pinned 4.0.2 after upstream #17571. The matched CPU comparison below remains the original 4.0.1 measurement:
Disposable runtime experiment through the unchanged T3
ProcessRunner: completed exits 1/128 spawn 2 → 0 taskkill calls; exit 0 remains zero. Explicit kill after exit also stops launching stale cleanup. Live explicit kill, scope release, fiber interruption, and timeout all stop owned descendant heartbeats, with one taskkill instead of redundant post-exit calls. A detached/ignored-stdio orphan survives leader exit in both variants and is disposed by the experiment.Matched ABBA measurement: two 22-second windows per variant, 20 one-second ticks, each issuing
git rev-parse --is-inside-work-tree(exit 0) andgit show-ref --verify --quiet refs/heads/absent(exit 1) in the same synthetic repository. Imports/warmup excluded. All 240 direct command processes were captured with retained native handles andGetProcessTimes; runner CPU usesprocess.cpuUsage. Means per window:Measure Baseline 611132c171f3Fixed 35f6135456dbGit invocations 40 40 taskkill invocations 40 0 Total direct command starts 80 40 Summed scoped command wall time 8.073 s 4.535 s Runner + direct-command CPU 3.907 s 1.414 s This is a 63.8% reduction in measured direct workload CPU, not a whole-machine or installed-app comparison. WMI, Defender, conhost, secondary processes, and unrelated jobs are excluded; wall times vary with scheduling. No Git polling change is justified by this experiment. The installed app was not modified, restarted, or replaced.
Existing
apps/server/src/processRunner.test.tsandapps/server/src/vcs/VcsProcess.test.ts: 43 passed, using an external minimal Vitest configuration with the patched published dependency. Selected existing vendored spawner checks for spawn options, unread stdout, nonzero exit, invalid command/cwd: 6 passed, 72 unselected. No new tests were written or committed.pnpm install --lockfile-only --frozen-lockfile --ignore-scripts,git diff --check, and applying the patch against the integrity-verified published4.0.2package withgit apply --check: passed. The original4.0.1strict source typecheck with repository-pinned@types/node@24.12.4reports the same existingExecException/ExecFileExceptioncallback mismatch on baseline and fixed source. No full application build, repo-wide checks, or POSIX runtime run.

Per-run numbers and reproducible disposable experiment. Evidence is hosted in the fork as release assets; no PR-only assets are committed to the production tree. Only synthetic technical diagnostics are included, with no raw ETL or private application data.
Implementation and verification: GPT-6.1-Sol, high reasoning effort, through the Codex harness in a visible T3 Code agent thread.
Rebase update (2026-10-10): upstream #17571 upgraded Effect to 4.0.2, causing a lockfile conflict. Rebased onto main 61eb4af69c38; the PR head is now bd794383058e. The same guard/documentation patch is retargeted to @effect/platform-node-shared@4.0.2 (patch contents unchanged). Comparing the published 4.0.1/4.0.2 spawners found only stability documentation additions, with cleanup logic unchanged and the guard still absent. No dependency versions are changed by this PR. Frozen-lockfile and published-package patch checks passed, the 43 current runner/VCS tests and six selected existing spawner checks passed, and the disposable completed-command/live-descendant experiment passed again with 4.0.2. The Git shell was added to this check process's PATH for the vendored nonzero-exit test; its initial run lacked sh. No new tests or full application build. The original CPU measurements and screenshot retain their original 611132c171f3 / 35f6135456db commits and 4.0.1 version; they are not a new 4.0.2 benchmark. No review was dismissed or repository policy changed.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
Approvability#
Verdict: Approved at
bd79438Macroscope's review found this PR approvable — This is a small, localized Windows cleanup fix implemented through the existing dependency patch mechanism. It preserves cleanup for running process trees while avoiding taskkill against an exited leader's potentially stale PID, with no product-default or static-analysis changes.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).coderabbitai[bot](GitHub profile, opens in a new tab) requested changes
Pre-merge checks failed. Please resolve the failing checks before merging.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
-
-
⚙️ Run configuration
-
-
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Advanced
- Run ID:
261cc05c-b2a0-464d-a204-af167a8267ae
-
📥 Commits
-
-
Reviewing files that changed from the base of the PR and between 9fc073bd67a2dd14c0855a88b01afc0e6c0e29aa and bd794383058eb1c82c426da2929c63db76e75a31.
-
⛔ Files ignored due to path filters (1)
-
-
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
-
📒 Files selected for processing (2)
-
-
patches/@effect__platform-node-shared@4.0.2.patchpnpm-workspace.yaml
-
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
-
-
📝 Walkthrough
-
📝 Walkthrough
-
Walkthrough#
The Windows cleanup patch skips
taskkillwhen the process leader has exited or received a signal. The workspace registers the patch for@effect/platform-node-shared@4.0.2.Changes#
Windows task cleanup
Layer / File(s) Summary Guard Windows task cleanup
patches/@effect__platform-node-shared@4.0.2.patch,pnpm-workspace.yamlThe JavaScript and TypeScript cleanup helpers call onExit(null)instead of invokingtaskkillwhenexitCodeorsignalCodeis non-null. The documentation notes that PID-based cleanup does not reclaim descendants that outlive the leader. The workspace registers the patch for the dependency version.Priority: ➖ Normal
Estimated code review effort: 2 (Simple) | ~10 minutes
Change: Bug fix
Suggested reviewers:
juliusmarminge
-
Merge Risk: ⚪ Minimal · up to
bd794No actionable issue remains from this review; the Windows cleanup change is mergeable after normal checks.
Architecture Summary#
Architecture risk: 🔵 Low · up to
bd794The change affects 2 systems.
Changed systems:
patches,pnpm-workspace.yamlArchitecture concerns No architecture-level concerns identified.
Review details
-
-
Systems and components
- observed — patches (service) was modified; 1 changed file maps to changed impact.
- observed — pnpm-workspace.yaml (service) was modified; 1 changed file maps to changed impact.
Before / after behavior
- observed — Modified behavior in patches/@effect__platform-node-shared@4.0.2.patch: The generated Windows cleanup now skips
taskkilland callsonExit(null)when the leader’sexitCodeorsignalCodeis non-null; otherwise, it invokestaskkillas before. - observed — Modified behavior in patches/@effect__platform-node-shared@4.0.2.patch: The Windows cleanup documentation now limits the stated tree termination to when the leader is running and notes that PID-based cleanup does not reclaim descendants that outlive it.
- observed — Modified behavior in patches/@effect__platform-node-shared@4.0.2.patch: The TypeScript Windows cleanup now skips
taskkilland callsonExit(null)when the leader’sexitCodeorsignalCodeis non-null; otherwise, it invokestaskkillas before. - observed — Modified behavior in pnpm-workspace.yaml: Added the
@effect/platform-node-shared@4.0.2patch mapping underpatchedDependencies.
-
Pre-merge checks |
4-
✅ Passed checks (4 passed)
-
Check name Status Explanation Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request. Title check The title clearly and concisely describes the main change: preventing stale Windows child-process cleanup. Description check The description explains the problem, implementation, scope rationale, limitations, and detailed verification results. It does not use the template's explicit section headings, but it provides the req…
-
✨ Finishing Touches
-
-
🧪 Generate unit tests (beta)
-
-
- Create a new PR
-
-
-
- Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Comment `@coderabbitai help` to get the list of available commands.-
Correction to my earlier policy acknowledgment: #17018 removed the custom Approvability check because “needs maintainer review” was misleadingly reported as requested changes. I verified the fresh upstream configuration and rebased this PR onto main (
a4c9494b0e36); the new head is9fc073bd67a2. CodeRabbit is reviewing the rebased head under the updated configuration. I have not dismissed any review or changed repository policy.The patch remains identical, and the pinned Effect
4.0.1spawner still contains the completed-child cleanup issue. That shared dependency owns Windows cleanup for both server and desktop, so its existing package-patch boundary remains the appropriate owner. Credit remains with the earlier guard proposed in #16007.The linked matched evidence is from the original commits, not a new measurement: Git volume stays at 40 per window, taskkill starts fall from 40 to 0, and measured runner/direct-command CPU falls from 3.907 to 1.414 seconds, excluding whole-PC/WMI CPU. Live cancellation still terminates descendants; the detached-orphan limitation is unchanged. Frozen-lockfile validation and integrity-verified published-package patch application passed again after the rebase. No further production change is indicated by the reviews so far.
Tested this on Windows 11 (Ryzen 7 5800X, git 2.55, Node 24.13) and it fixes a real stall.
On the current nightly, a 90 s CPU profile of the desktop server showed the main thread blocked inside
spawn()for 38.8 s. 106 of the 376 process launches in that window were these post-exittaskkillcalls, costing 10 s of blocking. On Windowsspawn()runs CreateProcess synchronously on the event loop, so every launch delays every WebSocket reply. When the stalls pass 5 to 10 s, clients miss the RPC ping and drop to "Connecting".Benchmark: 60 runs of
git config --get no.such.key(exit code 1) throughNodeChildProcessSpawnerfrom@effect/platform-node-shared4.0.1, alternating an unpatched copy of the package with this patch:run taskkill launches main thread blocked in launches wall time unpatched 120 62.1 s 127.5 s this PR 0 16.8 s 29.9 s unpatched 120 36.9 s 72.4 s this PR 0 2.5 s 10.7 s The machine was at 60 to 70% CPU from other work, so absolute times are noisy. The launch counts aren't: every failing git call costs two extra
taskkilllaunches without the patch and none with it.The guard also matches what
taskkillcan actually do. Once the leader has exited,taskkill /PID <pid> /Tcan't find its old tree, and if Windows has given the PID to a new process, it kills that process's tree instead. Children that are still running keep the tree kill.#16007 makes the same change against
4.0.0-rc.115, which main no longer uses.Benchmark script
// Runs failing git commands through Effect's NodeChildProcessSpawner (as T3's git layer does) // and counts taskkill launches plus main-thread time blocked inside spawn/execFile. // usage: node --experimental-import-meta-resolve spawner-bench.mjs <repo root> <runs> import cp from 'node:child_process'; import { syncBuiltinESMExports } from 'node:module'; import { pathToFileURL } from 'node:url'; const [root, runs = '60'] = process.argv.slice(2); let taskkills = 0, blockedMs = 0, spawns = 0; let depth = 0; const timed = (name, fn) => function (...args) { if (depth > 0) return fn.apply(this, args); depth++; const s = performance.now(); try { return fn.apply(this, args); } finally { depth--; blockedMs += performance.now() - s; if (args[0] === "taskkill") taskkills++; else spawns++; } }; cp.execFile = timed('execFile', cp.execFile); cp.spawn = timed('spawn', cp.spawn); syncBuiltinESMExports(); const parent = pathToFileURL(root + '/apps/server/package.json').href; const load = (s) => import(import.meta.resolve(s, parent)); const { Effect, Layer, Stream } = await load('effect'); const { ChildProcess, ChildProcessSpawner } = await load('effect/process').catch(() => load('effect/unstable/process')); const NodeServices = await load('@effect/platform-node/NodeServices'); const program = Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; for (let i = 0; i < Number(runs); i++) { yield* Effect.scoped(Effect.gen(function* () { const child = yield* spawner.spawn(ChildProcess.make('git', ['config', '--get', 'no.such.key'], { cwd: root })); yield* Stream.runDrain(child.all); yield* child.exitCode; })); } }); const t0 = performance.now(); const spawnerLayer = process.env.SPAWNER ? (await import(pathToFileURL(process.env.SPAWNER).href)).layer : null; const layer = spawnerLayer ? Layer.merge(NodeServices.layer, spawnerLayer.pipe(Layer.provide(NodeServices.layer))) : NodeServices.layer; await Effect.runPromise(program.pipe(Effect.provide(layer))); await new Promise((r) => setTimeout(r, 3000)); // let fire-and-forget taskkills from exit handlers start console.log(JSON.stringify({ spawner: process.env.SPAWNER ? "unpatched copy" : "installed", root, gitRuns: Number(runs), taskkillLaunches: taskkills, otherSpawns: spawns, mainThreadBlockedInLaunchMs: Math.round(blockedMs), wallMs: Math.round(performance.now() - t0) }));Run from the repo root with
node --experimental-import-meta-resolve spawner-bench.mjs <repo root> 60. SettingSPAWNER=<path to an unpatched dist/NodeChildProcessSpawner.js>loads that copy instead of the installed one.Rerun on a fresh boot of the same machine. The numbers in my comment above came from a machine with a kernel token leak that made every process launch slow, so their absolute times are inflated. Same benchmark, 60 runs of a failing
git configthroughNodeChildProcessSpawner, alternating:run taskkill launches main thread blocked in launches wall time per git command unpatched 120 0.84 s 267 ms this PR 0 0.16 s 29 ms unpatched 120 0.85 s 273 ms this PR 0 0.22 s 32 ms Each failing git command takes about 9 times as long without the patch, because the scope's release step waits for
taskkillto finish. In 60 seconds of the desktop server's normal work on this machine, 64 of its 168 process launches were thesetaskkillcalls.coderabbitai[bot](GitHub profile, opens in a new tab) approved these changes
juliusmarminge added labelsmacroscope-review
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
Krarilotus(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed