Skip to content

ConPTY: the pseudoconsole is never closed on a natural shell exit — the exit watcher erases the baton before onExit, leaking one conhost.exe per pty #965

Description

@yiliang114

Summary

On Windows/ConPTY, when a shell exits on its own (rather than via kill()), ClosePseudoConsole is never called. The pty_baton is erased by the exit-watcher thread before the JS onExit is delivered, struct pty_baton has no destructor, and PtyKill — the only JS-reachable route to ClosePseudoConsole — silently no-ops once the baton is gone.

The result is one orphaned conhost.exe --headless (~8 MB working set) per pty, held for the lifetime of the host process. Because the erase happens before any JS callback runs, no client of node-pty can work around this: there is no point at which a consumer could call kill() and still find a live baton.

Present on main today, and on 1.2.0-beta.10 / 1.2.0-beta.14.

Where

src/win/conpty.cc on main:

// struct has a ctor, no dtor — nothing closes hpc when the unique_ptr dies
:43-52   struct pty_baton {
           int id; HANDLE hIn; HANDLE hOut; HPCON hpc; HANDLE hShell = nullptr;
           pty_baton(int _id, HANDLE _hIn, HANDLE _hOut, HPCON _hpc) : ... {};
         };
:54      static std::vector<std::unique_ptr<pty_baton>> ptyHandles;

// SetupExitCallback's watcher thread
:95      WaitForSingleObject(baton->hShell, INFINITE);
:96-104  {
           std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);
           GetExitCodeProcess(...); CloseHandle(baton->hShell);
           std::erase_if(ptyHandles, ...);      // <-- baton destroyed here; hpc NOT closed
         }
:106     auto status = tsfn.BlockingCall(exit_event, callback);  // <-- JS onExit, AFTER the erase

// PtyKill — the only exported route to ClosePseudoConsole
:569-571 std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);
         pty_baton* handle = get_pty_baton(lock, id);
:572     if (handle != nullptr) {
:582       pfnClosePseudoConsole(handle->hpc);  // <-- skipped when the baton is gone
:599     return env.Undefined();                // <-- silent: no throw, no diagnostic

init() exports only startProcess | connect | resize | clear | kill, and pfnClosePseudoConsole is called from exactly one place, so PtyKill really is the only way for a consumer to reach it.

Worth noting the defensive CloseHandle(handle->hIn / handle->hOut) recently added inside PtyKill is unreachable on this same path, for the same reason.

On 1.2.0-beta.10, the erase is a side effect inside assert()

The shipped beta line has this shape, which is worth calling out because it inverts the usual expectation:

:105   CloseHandle(baton->hShell);
:106   assert(remove_pty_baton(baton->id));
:108   auto status = tsfn.BlockingCall(exit_event, callback);

Under NDEBUG, assert(expr) expands to ((void)0) and remove_pty_baton never runs — the baton survives and PtyKill closes the HPCON correctly. So on that version the leak exists only when asserts are enabled.

They are enabled in the published binaries. strings -a -el on @lydell/[email protected]'s prebuilds/win32-x64/conpty.node (which is built from [email protected]) yields, in UTF-16LE:

remove_pty_baton(baton->id)
Assertion failed: %Ts, file %Ts, line %d
D:\a\_work\1\s\src\win\conpty.cc

The literal expression text is only emitted for a compiled-in MSVC assert, and binding.gyp defines no NDEBUG.

Hoisting it out of the assert to an unconditional std::erase_if (done at 1.2.0-beta.14, :101, still before BlockingCall at :106) fixes the side-effect-in-assert anti-pattern, but it makes the erase reliable and therefore makes the HPCON leak deterministic on every build rather than only on assert-enabled ones.

Field evidence

From a downstream report against a CLI that creates one pty per shell command (QwenLM/qwen-code#11303 — that project pins @lydell/node-pty 1.2.0-beta.10):

  • 347 orphaned conhost.exe --headless under a single host process after ~12 h, ~2.8 GB working set.
  • Growth is 1:1 with pty creations: +7 orphans for exactly 7 shell commands, across two independent samples.
  • The processes die only when the host process itself exits.

The same report shows the parent's thread count growing in lockstep (353 threads against 347 orphans) — that is the per-pty ConoutConnection worker, which ConoutConnection.dispose() frees and which is likewise reachable only from kill(). Downstream can fix that half by calling dispose() directly; the HPCON half has no such workaround.

Reproduction

I do not have a Windows machine, so I have not run this myself — the analysis above is from the source at the affected versions plus the shipped prebuild's strings, and the counts are the downstream reporter's. A maintainer should be able to confirm quickly:

  1. Spawn a pty running a short command that exits on its own (cmd.exe /c echo hi).
  2. Let it exit naturally; do not call ptyProcess.kill().
  3. Repeat N times.
  4. Count conhost.exe --headless children of the host process — it should grow by N and never shrink.

Contrast with the same loop where kill() is called before the shell exits, which closes the HPCON correctly.

Suggested fix

Close the pseudoconsole where the baton is destroyed, so it does not depend on a consumer calling kill() in a window that no longer exists. Either:

  • give pty_baton a destructor that calls ClosePseudoConsole(hpc) (and closes hIn/hOut if still open), so std::erase_if / unique_ptr teardown does the right thing everywhere; or
  • call ClosePseudoConsole(baton->hpc) explicitly in the watcher, immediately before the erase_if.

The destructor is the more robust of the two — it also covers the remove_pty_baton call sites and any future erase — but it needs LoadConptyDll's function pointer to be resolvable from that context, which is why the explicit call in the watcher may be the smaller change.

Either way PtyKill's existing close stays correct for the kill-before-exit path, and becomes a no-op-after-close rather than the only close.

Related

Activity

  1. yiliang114 commented on Sep 9, 2026

    @yiliang114
    Author

    I can reproduce this deterministically on a real Windows host now: Windows Server 2025 build 26100, Node 22.23.1, @lydell/node-pty / @lydell/node-pty-win32-x64 1.2.0-beta.10.

    I spawned 8 PTYs running cmd.exe /d /s /c exit 0 and kept the parent Node process alive. All 8 reported onExit(0). The baseline conhost.exe count then increased by exactly 8; all 8 new processes were conhost.exe --headless direct children of the parent Node process. The same 8 PIDs remained at +0 s, +2 s, and +10 s.

    Calling public kill() on 4 exited PTYs and destroy() on the other 4 returned, but removed none of the 8 hosts after another 10 s. Each cleanup attempt emitted:

    conpty_console_list_agent.js:13
    Error: AttachConsole failed
    

    When the parent Node process exited, all 8 target conhost.exe processes disappeared and the machine returned to its baseline count.

    As an A/B check, running the same PTYs with useConptyDll: true left 0 conhost.exe children. That is not a general replacement recommendation—the bundled backend performs a terminal capability handshake that clients must answer—but it confirms the persistent processes come specifically from the system CreatePseudoConsole path described here.

  2. lydell commented on Sep 9, 2026

    @lydell
    Contributor

    1.2.0-beta.10 is not the latest version. 1.2.0-beta.15 is. It’s also better to reproduce with the official node-pty package rather than @lydell/node-pty, just in case.

  3. binaryfire commented on Sep 26, 2026

    @binaryfire

    Can confirm this on Windows 11 Pro 25H2 (26200.9457), Node 24.13.1, node-pty 1.1.0.

    Ran three cmd.exe /d /c echo sessions, read their output and waited for each to exit. All exited with code 0, but left three headless conhost processes, three MessagePorts and three PipeWraps behind. Node was still running when I killed it after 12 seconds.

    This was a standalone node-pty script, with no app code involved.

  4. roidayan1 commented on Oct 11, 2026

    @roidayan1

    Reproduced with the official [email protected] from npm (its prebuilt win32-x64
    binaries), Node 24.19.0, Windows 11 Pro build 26300, x64. Five shells, each exiting on its own;
    nothing else is called on them:

    // microsoft/node-pty#965: each shell that exits on its own leaves its conhost.exe behind
    const { execFileSync } = require('child_process');
    const pty = require('node-pty');
    
    const hosts = () => Number(execFileSync('powershell.exe', ['-NoProfile', '-Command',
      `@(Get-CimInstance Win32_Process -Filter "ParentProcessId=${process.pid} AND Name='conhost.exe'").Count`],
      { encoding: 'utf8' }).trim());
    
    (async () => {
      console.log(`node-pty ${require('node-pty/package.json').version}, node ${process.version}, Windows ${require('os').release()}`);
      console.log(`conhost.exe children before: ${hosts()}`);
      for (let i = 0; i < 5; i++) {
        const term = pty.spawn('cmd.exe', ['/d', '/c', 'echo hi'], {});
        const { exitCode } = await new Promise((resolve) => term.onExit(resolve));
        console.log(`shell ${i + 1} exited with ${exitCode}`);
      }
      await new Promise((resolve) => setTimeout(resolve, 5000));
      console.log(`conhost.exe children 5 s after all five exited: ${hosts()}`);
      process.exit(0);
    })();
    node-pty 1.2.0-beta.15, node v24.19.0, Windows 10.0.26300
    conhost.exe children before: 0
    shell 1 exited with 0
    shell 2 exited with 0
    shell 3 exited with 0
    shell 4 exited with 0
    shell 5 exited with 0
    conhost.exe children 5 s after all five exited: 5
    

    With useConptyDll: true the bundled OpenConsole.exe exits on its own, since PtyConnect releases
    it with ConptyReleasePseudoConsole. But its HPCON is never closed either. 20 natural exits on
    beta.15 grew the process's handle count by 280 with the default ConPTY and by 220 with
    conpty.dll.

  5. Cifixie commented on Nov 13, 2026

    @Cifixie

    Were doing on my own issue while found this: So asked an agent help me to compose a proper comment from our discovery:

    Another data point, plus a handle breakdown that may matter for #990 / #991.

    Official [email protected] from npm (prebuilt win32-x64), Node 24.22.1, Windows 11 Enterprise 10.0.26100, default ConPTY (useConptyDll: false). 30 ptys of cmd.exe /c exit after one warm-up, counting the host's (Get-Process -Id $pid).HandleCount, each variant run twice with identical results:

    What the host does after onExit Handle count Per ended pty
    nothing 212 → 632 14.00
    _agent._conoutSocketWorker.dispose(), _agent._inSocket.destroy(), _agent._outSocket.destroy() 211 → 291 2.67
    cmd.exe /k, kill() while the shell is still alive, plus the same cleanup 206 → 198 no growth
    Script: node leak-variants.js A|B|C node-pty
    // Runs the repro (variant A) plus the two comparison variants.
    // usage: node leak-variants.js <A|B|C> <path-to-node-pty>
    const variant = process.argv[2] || 'A';
    const pty = require(process.argv[3]);
    const { execFileSync } = require('child_process');
    
    const handles = () => Number(execFileSync('powershell.exe', ['-NoProfile', '-Command',
      `(Get-Process -Id ${process.pid}).HandleCount`]).toString().trim());
    
    function cleanup(p) {
      const a = p._agent;
      if (a && a._conoutSocketWorker) a._conoutSocketWorker.dispose();
      if (a && a._inSocket) a._inSocket.destroy();
      if (a && a._outSocket) a._outSocket.destroy();
    }
    
    function once() {
      return new Promise((resolve) => {
        // C: a shell that stays alive until we kill it
        const args = variant === 'C' ? ['/k'] : ['/c', 'exit'];
        const p = pty.spawn('cmd.exe', args, { cols: 80, rows: 24 });
        p.onData(() => {});
        p.onExit(() => {
          if (variant === 'B' || variant === 'C') cleanup(p);
          setTimeout(resolve, 500);
        });
        if (variant === 'C') setTimeout(() => p.kill(), 700);
      });
    }
    
    (async () => {
      await once(); // warm-up
      const before = handles();
      const N = 30;
      for (let i = 0; i < N; i++) await once();
      await new Promise((r) => setTimeout(r, 2000));
      const after = handles();
      console.log(`${variant}: ${before} -> ${after}, handles per ended pty: ${((after - before) / N).toFixed(2)}`);
      process.exit(0);
    })();

    Opening and closing a named pipe 30 times, or starting and terminating a Worker 30 times, grows by 0, so the ~3 left in the second row are the HPCON (plus its conhost.exe, which we see one of per pty, as reported above).

    Two things that may help the fixes:

    1. Most of the per-exit handles are on the JS side, and neither PR touches it. On a natural exit, WindowsPtyAgent never disposes the conout worker and never destroys _inSocket (the fs.openSync(conin) fd). Together they account for about 11 of the 14 handles per exit. This matches Raj Siva-Rajah (@binaryfire)'s "MessagePorts and PipeWraps" left behind, and the thread count growing in lockstep in the downstream report. fix(win): close the pseudoconsole when the shell exits on its own #990 and fix(win): close the pseudoconsole when the shell exits on its own #991 change only src/win/conpty.cc. With them, conhost should exit and the conout pipe should end, but I could not check whether the worker and _inSocket are then released, because I have no build toolchain here. Could someone with a build of either PR run the 30-pty loop above with no cleanup and see whether the count still grows by ~11 per exit? If it does, _cleanUpProcess (or the exit path in windowsPtyAgent.ts) probably wants a this._conoutSocketWorker.dispose() and this._inSocket.destroy() as well. Today consumers can only reach those through private fields.
    2. The official 1.1.0 prebuild has the assert compiled in too, not just @lydell/node-pty beta.10. Its conpty.cc has assert(remove_pty_baton(baton->id)), and on that build kill() after a natural exit frees nothing. Every such call also prints conpty_console_list_agent.js:13 Error: AttachConsole failed from the console-list helper, the same as 易良 (@yiliang114) saw. So on 1.1.0 the baton is erased, and the leak is not only a beta.14+ effect.

    Our workaround in the meantime, for anyone who finds this: after onExit, dispose the worker and destroy both sockets through the private fields as in row 2. Then find the conhost.exe children of the host process (Win32_Process by ParentProcessId), match each one to the pty by creation time, and end it about 1 s after the exit. That ends the orphaned hosts; the ~3 handles of the HPCON itself are the only part left, until #990 or #991 lands.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions