Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix: harden fd lifecycle and SystemError handling in runtime and proxy kill (#1556)

guyoron1f42ce4a2399f
diff --git a/headroom/_subprocess.py b/headroom/_subprocess.py
index f563826ab..938c9eebd 100644
--- a/headroom/_subprocess.py
+++ b/headroom/_subprocess.py
@@ -1,32 +1,42 @@
import os
import subprocess as _sp
+import sys
from typing import Any
+def _win32_pid_alive(pid: int) -> bool:
+ """Non-destructive PID liveness probe for Windows via ``kernel32``."""
+ import ctypes
+
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
+ handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
+ if handle:
+ kernel32.CloseHandle(handle)
+ return True
+ ERROR_ACCESS_DENIED = 5
+ return kernel32.GetLastError() == ERROR_ACCESS_DENIED
+
+
def pid_alive(pid: int) -> bool:
- """Return True if ``pid`` names a live process (Windows-safe).
-
- ``os.kill(pid, 0)`` is the usual Unix liveness probe, but on Windows it can
- fail against a detached/stale/invalid PID with ``WinError 87`` ("The
- parameter is incorrect"). CPython sometimes surfaces that as a
- ``SystemError`` rather than an ``OSError``; since ``SystemError`` is not an
- ``OSError`` subclass, a bare ``except OSError`` lets it escape and crash the
- caller — and in the detached-agent path it took down the supervised proxy
- (issue #1544). Prefer ``psutil.pid_exists`` and treat ``SystemError`` as
- "not alive".
- """
+ """Return True if *pid* names a live process (non-destructive on all platforms)."""
if pid <= 0:
- return False # non-positive PIDs are never valid liveness targets
+ return False
try:
- import psutil # type: ignore[import-untyped] # optional dep, already used elsewhere
+ import psutil # type: ignore[import-untyped] # optional dep
return bool(psutil.pid_exists(pid))
except Exception:
pass
+ if sys.platform == "win32":
+ try:
+ return _win32_pid_alive(pid)
+ except Exception:
+ return True
try:
os.kill(pid, 0)
except PermissionError:
- return True # exists but owned by another user
+ return True
except (ProcessLookupError, OSError, SystemError):
return False
return True
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index 0dee5a053..30850c04b 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -3128,11 +3128,11 @@ def _kill_proxy_by_pid(pid: int, port: int) -> bool:
"""
try:
os.kill(pid, signal.SIGTERM)
- except ProcessLookupError:
- pass # Already gone
except PermissionError:
click.echo(f" Warning: No permission to kill proxy PID {pid}")
return False
+ except (ProcessLookupError, OSError, SystemError):
+ pass
# Wait for port to free (up to 5 seconds)
for _ in range(50):
@@ -3144,7 +3144,7 @@ def _kill_proxy_by_pid(pid: int, port: int) -> bool:
try:
_kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM)
os.kill(pid, _kill_signal)
- except (ProcessLookupError, PermissionError):
+ except (ProcessLookupError, PermissionError, OSError, SystemError):
pass
for _ in range(20):
diff --git a/tests/test_pid_alive.py b/tests/test_pid_alive.py
index db866e169..20b2ebb39 100644
--- a/tests/test_pid_alive.py
+++ b/tests/test_pid_alive.py
@@ -48,3 +48,95 @@ def test_pid_alive_only_uses_signal_zero(monkeypatch) -> None:
monkeypatch.setattr("headroom._subprocess.os.kill", lambda pid, sig: sent.append(sig))
assert pid_alive(4321) is True
assert sent == [0]
+
+
+def test_pid_alive_win32_no_psutil_never_calls_os_kill(monkeypatch) -> None:
+ """On Windows without psutil, pid_alive must not call os.kill (it routes through TerminateProcess)."""
+ monkeypatch.setitem(
+ sys.modules,
+ "psutil",
+ types.SimpleNamespace(pid_exists=lambda pid: (_ for _ in ()).throw(RuntimeError())),
+ )
+ monkeypatch.setattr("headroom._subprocess.sys.platform", "win32")
+
+ fake_handle = 42
+ opened: list[int] = []
+
+ def fake_open_process(access, inherit, pid):
+ opened.append(pid)
+ return fake_handle
+
+ closed: list[int] = []
+
+ def fake_close_handle(handle):
+ closed.append(handle)
+
+ fake_kernel32 = types.SimpleNamespace(
+ OpenProcess=fake_open_process,
+ CloseHandle=fake_close_handle,
+ )
+ fake_ctypes = types.SimpleNamespace(windll=types.SimpleNamespace(kernel32=fake_kernel32))
+ monkeypatch.setitem(sys.modules, "ctypes", fake_ctypes)
+
+ def boom(pid: int, sig: int) -> None:
+ raise AssertionError("os.kill must not be called on Windows")
+
+ monkeypatch.setattr("headroom._subprocess.os.kill", boom)
+
+ assert pid_alive(4321) is True
+ assert opened == [4321]
+ assert closed == [fake_handle]
+
+
+def test_pid_alive_win32_no_psutil_no_ctypes_returns_conservative(monkeypatch) -> None:
+ """On Windows without psutil AND ctypes failure, return True (assume alive) rather than crash."""
+ monkeypatch.setitem(
+ sys.modules,
+ "psutil",
+ types.SimpleNamespace(pid_exists=lambda pid: (_ for _ in ()).throw(RuntimeError())),
+ )
+ monkeypatch.setattr("headroom._subprocess.sys.platform", "win32")
+ monkeypatch.setitem(
+ sys.modules,
+ "ctypes",
+ types.SimpleNamespace(
+ windll=types.SimpleNamespace(
+ kernel32=types.SimpleNamespace(
+ OpenProcess=lambda *a: (_ for _ in ()).throw(OSError("no kernel32")),
+ )
+ )
+ ),
+ )
+
+ def boom(pid: int, sig: int) -> None:
+ raise AssertionError("os.kill must not be called on Windows")
+
+ monkeypatch.setattr("headroom._subprocess.os.kill", boom)
+
+ assert pid_alive(4321) is True
+
+
+def test_pid_alive_win32_access_denied_returns_alive(monkeypatch) -> None:
+ """OpenProcess returning NULL with ERROR_ACCESS_DENIED means the process exists but is protected."""
+ monkeypatch.setitem(
+ sys.modules,
+ "psutil",
+ types.SimpleNamespace(pid_exists=lambda pid: (_ for _ in ()).throw(RuntimeError())),
+ )
+ monkeypatch.setattr("headroom._subprocess.sys.platform", "win32")
+
+ ERROR_ACCESS_DENIED = 5
+
+ fake_kernel32 = types.SimpleNamespace(
+ OpenProcess=lambda access, inherit, pid: 0,
+ GetLastError=lambda: ERROR_ACCESS_DENIED,
+ )
+ fake_ctypes = types.SimpleNamespace(windll=types.SimpleNamespace(kernel32=fake_kernel32))
+ monkeypatch.setitem(sys.modules, "ctypes", fake_ctypes)
+
+ def boom(pid: int, sig: int) -> None:
+ raise AssertionError("os.kill must not be called on Windows")
+
+ monkeypatch.setattr("headroom._subprocess.os.kill", boom)
+
+ assert pid_alive(4321) is True