Skip to content

The agent that grows with you

fix(windows): require process identity before taskkill

burak33bbed6d5fc803a1
diff --git a/gateway/run.py b/gateway/run.py
index 77915549b25..ab4a56f7558 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -32559,7 +32559,11 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
existing_pid,
)
try:
- terminate_pid(existing_pid, force=True)
+ terminate_pid(
+ existing_pid,
+ force=True,
+ expected_start_time=existing_start_time,
+ )
except ProcessLookupError:
old_gateway_exited = True
except (PermissionError, OSError):
diff --git a/gateway/status.py b/gateway/status.py
index 6e9ab03826d..9b5b62b0e1b 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -302,13 +302,41 @@ def normalize_updated_at(value: Any) -> Optional[str]:
return None
-def terminate_pid(pid: int, *, force: bool = False) -> None:
+def _assert_process_start_time_matches(
+ pid: int, expected_start_time: Optional[float]
+) -> None:
+ """Fail closed unless ``pid`` still names the recorded process object."""
+ if expected_start_time is None:
+ raise OSError(
+ f"refusing to force-kill PID {pid} without a process start-time guard"
+ )
+ current_start_time = _get_process_start_time(pid)
+ if current_start_time is None:
+ raise OSError(
+ f"refusing to force-kill PID {pid}; process start time is unavailable"
+ )
+ try:
+ expected = float(expected_start_time)
+ current = float(current_start_time)
+ except (TypeError, ValueError) as exc:
+ raise OSError(f"refusing to force-kill PID {pid}; malformed start time") from exc
+ if expected <= 0 or current <= 0 or abs(expected - current) > 0.001:
+ raise OSError(f"refusing to force-kill PID {pid}; process identity changed")
+
+
+def terminate_pid(
+ pid: int,
+ *,
+ force: bool = False,
+ expected_start_time: Optional[float] = None,
+) -> None:
"""Terminate a PID with platform-appropriate force semantics.
POSIX uses SIGTERM/SIGKILL. Windows uses taskkill /T /F for true force-kill
because os.kill(..., SIGTERM) is not equivalent to a tree-killing hard stop.
"""
if force and _IS_WINDOWS:
+ _assert_process_start_time_matches(pid, expected_start_time)
# CREATE_NO_WINDOW: terminate_pid runs from the windowless pythonw.exe
# gateway/desktop backend, so a bare taskkill spawn would flash a
# conhost window on every force-kill.
@@ -2234,7 +2262,11 @@ def _terminate_scoped_lock_owner_once(
return None
try:
- terminate_pid(owner_pid, force=True)
+ terminate_pid(
+ owner_pid,
+ force=True,
+ expected_start_time=owner_start_time,
+ )
except ProcessLookupError:
return owner_pid
except (PermissionError, OSError):
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 729f471ead7..96ebcaa11ff 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -656,6 +656,9 @@ def _escalate_wedged_gateway(
Returns True once the PID has left the process table.
"""
+ from gateway.status import get_process_start_time
+
+ expected_start_time = get_process_start_time(pid)
try:
terminate_pid(pid, force=False)
except (ProcessLookupError, PermissionError, OSError):
@@ -663,7 +666,7 @@ def _escalate_wedged_gateway(
if _wait_for_pid_exit(pid, max(float(term_grace), 0.0)):
return True
try:
- terminate_pid(pid, force=True)
+ terminate_pid(pid, force=True, expected_start_time=expected_start_time)
print(f"⚠ Gateway PID {pid} unresponsive to SIGTERM; sent SIGKILL")
except (ProcessLookupError, PermissionError, OSError):
pass
@@ -2148,7 +2151,12 @@ def kill_gateway_processes(
for pid in pids:
try:
- terminate_pid(pid, force=force)
+ expected_start_time = None
+ if force:
+ from gateway.status import get_process_start_time
+
+ expected_start_time = get_process_start_time(pid)
+ terminate_pid(pid, force=force, expected_start_time=expected_start_time)
killed += 1
except ProcessLookupError:
# Process already gone
@@ -5776,7 +5784,7 @@ def _wait_for_gateway_exit(
force_after: Seconds of graceful waiting before escalating to force-kill.
"""
import time
- from gateway.status import get_running_pid
+ from gateway.status import get_process_start_time, get_running_pid
deadline = time.monotonic() + timeout
force_deadline = (
@@ -5796,7 +5804,11 @@ def _wait_for_gateway_exit(
):
# Grace period expired — force-kill the specific PID.
try:
- terminate_pid(pid, force=True)
+ terminate_pid(
+ pid,
+ force=True,
+ expected_start_time=get_process_start_time(pid),
+ )
print(f"⚠ Gateway PID {pid} did not exit gracefully; sent SIGKILL")
except (ProcessLookupError, PermissionError, OSError):
return True # Already gone or we can't touch it.
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index 59a1d285421..de394d39ee9 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -1570,7 +1570,7 @@ def _windows_stop_drain_timeout() -> float:
def _force_terminate_known_gateway_pids(pids: list[int]) -> int:
"""Force-kill known gateway PIDs without a broad process sweep."""
try:
- from gateway.status import _pid_exists, terminate_pid
+ from gateway.status import _pid_exists, get_process_start_time, terminate_pid
except ImportError:
return 0
@@ -1584,7 +1584,11 @@ def _force_terminate_known_gateway_pids(pids: list[int]) -> int:
try:
if not _pid_exists(pid):
continue
- terminate_pid(pid, force=True)
+ terminate_pid(
+ pid,
+ force=True,
+ expected_start_time=get_process_start_time(pid),
+ )
killed += 1
except ProcessLookupError:
continue
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index 50b329a4b6d..91d997b8a50 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -1625,7 +1625,11 @@ def _stop_profile_backends(canon: str, profile_dir: Path) -> None:
return
try:
- from gateway.status import _pid_exists, terminate_pid as _terminate_pid
+ from gateway.status import (
+ _pid_exists,
+ get_process_start_time,
+ terminate_pid as _terminate_pid,
+ )
except Exception:
return
@@ -1645,7 +1649,11 @@ def _stop_profile_backends(canon: str, profile_dir: Path) -> None:
for pid in pids:
if _pid_exists(pid):
try:
- _terminate_pid(pid, force=True)
+ _terminate_pid(
+ pid,
+ force=True,
+ expected_start_time=get_process_start_time(pid),
+ )
except (ProcessLookupError, PermissionError, OSError):
pass
@@ -2007,6 +2015,11 @@ def _stop_gateway_process(profile_dir: Path) -> None:
# the same way taskkill /T does.
from gateway.status import terminate_pid as _terminate_pid
from gateway.status import _pid_exists
+ expected_start_time = data.get("start_time")
+ if expected_start_time is None:
+ from gateway.status import get_process_start_time
+
+ expected_start_time = get_process_start_time(pid)
_terminate_pid(pid) # graceful first
# Wait up to 10s for graceful shutdown. On Windows, os.kill(pid, 0)
# is NOT a no-op — use the handle-based existence check.
@@ -2017,7 +2030,7 @@ def _stop_gateway_process(profile_dir: Path) -> None:
return
# Force kill
try:
- _terminate_pid(pid, force=True)
+ _terminate_pid(pid, force=True, expected_start_time=expected_start_time)
except (ProcessLookupError, OSError):
pass
print(f"✓ Gateway force-stopped (PID {pid})")
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index df225813e8f..4c19f69bd19 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -6112,7 +6112,7 @@ def _pause_windows_gateways_for_update() -> dict | None:
return None
try:
- from gateway.status import terminate_pid
+ from gateway.status import get_process_start_time, terminate_pid
from hermes_cli.gateway import (
_capture_gateway_argv,
_get_restart_drain_timeout,
@@ -6302,8 +6302,13 @@ def _pause_windows_gateways_for_update() -> dict | None:
force_killed = []
for pid in sorted(set(survivors).union(unmapped_pids).union(launcher_pids)):
try:
- terminate_pid(int(pid), force=True)
- force_killed.append(int(pid))
+ pid_int = int(pid)
+ terminate_pid(
+ pid_int,
+ force=True,
+ expected_start_time=get_process_start_time(pid_int),
+ )
+ force_killed.append(pid_int)
except (ProcessLookupError, PermissionError, OSError):
pass
@@ -7802,7 +7807,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
# does not map. Stop them and re-check instead of
# dead-ending; the post-update resume (and the supervisor
# that respawned them) brings gateways back afterwards.
- from gateway.status import terminate_pid
+ from gateway.status import get_process_start_time, terminate_pid
print(
f" ⚠ {len(_gateway_holders)} gateway process(es) still "
@@ -7810,7 +7815,12 @@ def _cmd_update_impl(args, gateway_mode: bool):
)
for _pid in _gateway_holders:
try:
- terminate_pid(int(_pid), force=True)
+ pid_int = int(_pid)
+ terminate_pid(
+ pid_int,
+ force=True,
+ expected_start_time=get_process_start_time(pid_int),
+ )
except Exception as exc:
logger.debug(
"Could not stop leftover gateway %s: %s", _pid, exc
@@ -10020,14 +10030,21 @@ def _cmd_update_impl(args, gateway_mode: bool):
print(
f" ⚠ {len(_stuck)} gateway process(es) ignored SIGTERM — force-killing"
)
- from gateway.status import terminate_pid as _terminate_pid
+ from gateway.status import (
+ get_process_start_time as _get_process_start_time,
+ terminate_pid as _terminate_pid,
+ )
for pid in _stuck:
try:
# Routes through taskkill /T /F on Windows,
# SIGKILL on POSIX — _signal.SIGKILL doesn't
# exist on Windows so the old raw os.kill call
# used to crash the entire update path.
- _terminate_pid(pid, force=True)
+ _terminate_pid(
+ pid,
+ force=True,
+ expected_start_time=_get_process_start_time(pid),
+ )
except (ProcessLookupError, PermissionError, OSError):
pass
# Give the OS a beat to reap the processes so the
diff --git a/tests/gateway/test_runner_startup_failures.py b/tests/gateway/test_runner_startup_failures.py
index b76c39d4c11..68fbfdf1624 100644
--- a/tests/gateway/test_runner_startup_failures.py
+++ b/tests/gateway/test_runner_startup_failures.py
@@ -136,7 +136,7 @@ async def test_start_gateway_replace_aborts_when_force_killed_pid_still_alive(
)
monkeypatch.setattr(
"gateway.status.terminate_pid",
- lambda pid, force=False: calls.append((pid, force)),
+ lambda pid, force=False, **kwargs: calls.append((pid, force)),
)
# Ownership guard (#89315): legitimate same-home replace fixture — the
# persisted record is bound to target pid 42 in this home.
@@ -206,7 +206,7 @@ async def test_start_gateway_replace_writes_takeover_marker_before_sigterm(
})
return True
- def record_terminate(pid, force=False):
+ def record_terminate(pid, force=False, **kwargs):
events.append(f"terminate_pid(pid={pid}, force={force})")
class _CleanExitRunner:
@@ -295,7 +295,7 @@ async def test_start_gateway_replace_clears_marker_on_permission_denied(
})
return True
- def raise_permission(pid, force=False):
+ def raise_permission(pid, force=False, **kwargs):
raise PermissionError("simulated EPERM")
monkeypatch.setattr("gateway.status.get_running_pid", lambda: 42)
@@ -443,5 +443,3 @@ async def test_start_gateway_propagates_fatal_config_exit_code(monkeypatch, tmp_
await start_gateway(config=GatewayConfig(), replace=False, verbosity=0)
assert exc_info.value.code == GATEWAY_FATAL_CONFIG_EXIT_CODE
-
-
diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.py
index 8306e305e7c..d17e47fa86b 100644
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@ -403,7 +403,9 @@ class TestTerminatePid:
monkeypatch.setattr(status.subprocess, "run", fake_run)
- status.terminate_pid(123, force=True)
+ monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 456)
+
+ status.terminate_pid(123, force=True, expected_start_time=456)
# taskkill is spawned with the no-window flag so the windowless
# pythonw.exe backend doesn't flash a conhost window on force-kill.
@@ -413,6 +415,27 @@ class TestTerminatePid:
(["taskkill", "/PID", "123", "/T", "/F"], True, True, 10, windows_hide_flags())
]
+ def test_windows_force_refuses_pid_without_start_time_guard(self, monkeypatch):
+ monkeypatch.setattr(status, "_IS_WINDOWS", True)
+ calls = []
+ monkeypatch.setattr(status.subprocess, "run", lambda *args, **kwargs: calls.append(args))
+
+ with pytest.raises(OSError, match="without a process start-time guard"):
+ status.terminate_pid(123, force=True)
+
+ assert calls == []
+
+ def test_windows_force_refuses_reused_pid(self, monkeypatch):
+ monkeypatch.setattr(status, "_IS_WINDOWS", True)
+ monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 999)
+ calls = []
+ monkeypatch.setattr(status.subprocess, "run", lambda *args, **kwargs: calls.append(args))
+
+ with pytest.raises(OSError, match="process identity changed"):
+ status.terminate_pid(123, force=True, expected_start_time=456)
+
+ assert calls == []
+
class TestScopedLocks:
@pytest.mark.windows_only
@@ -1436,4 +1459,3 @@ def test_strict_gateway_identity_rejects_reused_pid(tmp_path, monkeypatch):
with pytest.raises(RuntimeError, match="identity changed"):
status.get_running_pid_identity_strict(pid_path)
-
diff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.py
index 05b03c340f9..f62eb86eb51 100644
--- a/tests/hermes_cli/test_gateway.py
+++ b/tests/hermes_cli/test_gateway.py
@@ -473,7 +473,7 @@ class TestWaitForGatewayExit:
return call_num * 2.0 # 2, 4, 6, 8, ...
kills = []
- def mock_terminate(pid, force=False):
+ def mock_terminate(pid, force=False, **kwargs):
kills.append((pid, force))
# get_running_pid returns the PID until kill is sent, then None
@@ -493,7 +493,11 @@ class TestWaitForGatewayExit:
calls = []
monkeypatch.setattr(gateway, "find_gateway_pids", lambda exclude_pids=None, all_profiles=False: [11, 22])
- monkeypatch.setattr(gateway, "terminate_pid", lambda pid, force=False: calls.append((pid, force)))
+ monkeypatch.setattr(
+ gateway,
+ "terminate_pid",
+ lambda pid, force=False, **kwargs: calls.append((pid, force)),
+ )
killed = gateway.kill_gateway_processes(force=True)
diff --git a/tests/hermes_cli/test_update_concurrent_quarantine.py b/tests/hermes_cli/test_update_concurrent_quarantine.py
index f23d9d858be..631e9102a83 100644
--- a/tests/hermes_cli/test_update_concurrent_quarantine.py
+++ b/tests/hermes_cli/test_update_concurrent_quarantine.py
@@ -232,7 +232,7 @@ def test_pause_windows_gateways_for_update_stops_profile_and_unmapped_pids(
monkeypatch.setattr(
status_mod,
"terminate_pid",
- lambda pid, force=False: terminated.append((pid, force)),
+ lambda pid, force=False, **kwargs: terminated.append((pid, force)),
)
token = cli_main._pause_windows_gateways_for_update()
@@ -692,7 +692,7 @@ def test_pause_kill_set_covers_venv_guard_abort_set(
monkeypatch.setattr(
status_mod,
"terminate_pid",
- lambda pid, force=False: terminated.append(int(pid)),
+ lambda pid, force=False, **kwargs: terminated.append(int(pid)),
)
cli_main._pause_windows_gateways_for_update()
@@ -1034,4 +1034,3 @@ def test_stop_service_refuses_pid_reuse_before_sc_stop(monkeypatch):
-
diff --git a/tests/hermes_cli/test_update_wedged_gateway.py b/tests/hermes_cli/test_update_wedged_gateway.py
index 87e57f70740..71349e3e7a1 100644
--- a/tests/hermes_cli/test_update_wedged_gateway.py
+++ b/tests/hermes_cli/test_update_wedged_gateway.py
@@ -205,7 +205,7 @@ def _launchd_harness(monkeypatch, tmp_path, pid):
monkeypatch.setattr(
gateway_cli,
"terminate_pid",
- lambda pid, force=False: events.append(("kill" if force else "term", pid)),
+ lambda pid, force=False, **kwargs: events.append(("kill" if force else "term", pid)),
)
# Never let a real SIGUSR1 escape to the live test PID — the drain path
# goes through _graceful_restart_via_sigusr1 (in-place restart) before
@@ -326,7 +326,7 @@ class TestEscalateWedgedGateway:
monkeypatch.setattr(
gateway_cli,
"terminate_pid",
- lambda pid, force=False: signals.append(("kill" if force else "term", pid)),
+ lambda pid, force=False, **kwargs: signals.append(("kill" if force else "term", pid)),
)
monkeypatch.setattr(
gateway_cli, "_wait_for_pid_exit", lambda pid, timeout: True
@@ -347,7 +347,7 @@ class TestEscalateWedgedGateway:
monkeypatch.setattr(
gateway_cli,
"terminate_pid",
- lambda pid, force=False: signals.append(("kill" if force else "term", pid)),
+ lambda pid, force=False, **kwargs: signals.append(("kill" if force else "term", pid)),
)
monkeypatch.setattr(gateway_cli, "_wait_for_pid_exit", fake_wait)
@@ -357,7 +357,7 @@ class TestEscalateWedgedGateway:
def test_total_wait_budget_is_bounded_well_under_drain(self, monkeypatch):
"""Worst case must be seconds, never the 180s drain budget."""
waits = []
- monkeypatch.setattr(gateway_cli, "terminate_pid", lambda pid, force=False: None)
+ monkeypatch.setattr(gateway_cli, "terminate_pid", lambda pid, force=False, **kwargs: None)
monkeypatch.setattr(
gateway_cli,
"_wait_for_pid_exit",
@@ -368,7 +368,7 @@ class TestEscalateWedgedGateway:
assert sum(waits) < 30.0
def test_process_already_gone_is_success(self, monkeypatch):
- def raise_gone(pid, force=False):
+ def raise_gone(pid, force=False, **kwargs):
raise ProcessLookupError
monkeypatch.setattr(gateway_cli, "terminate_pid", raise_gone)
@@ -381,7 +381,7 @@ class TestEscalateWedgedGateway:
def test_sigkill_permission_error_does_not_raise(self, monkeypatch):
calls = []
- def term(pid, force=False):
+ def term(pid, force=False, **kwargs):
calls.append(force)
if force:
raise PermissionError
@@ -420,9 +420,9 @@ class TestLaunchdRestartWedgedIntegration:
lambda pid, **kw: events.append("escalate") or True,
)
monkeypatch.setattr(
- gateway_cli,
- "terminate_pid",
- lambda pid, force=False: events.append("sigterm"),
+ gateway_cli,
+ "terminate_pid",
+ lambda pid, force=False, **kwargs: events.append("sigterm"),
)
# Never let a real SIGUSR1 escape to PID 4242 during tests.
monkeypatch.setattr(
@@ -585,7 +585,7 @@ class TestLoopTickWitness:
monkeypatch.setattr(
gateway_cli,
"terminate_pid",
- lambda pid, force=False: events.append(("kill" if force else "term", pid)),
+ lambda pid, force=False, **kwargs: events.append(("kill" if force else "term", pid)),
)
# Never let a real SIGUSR1 escape to os.getpid() — the drain
# path now goes through _graceful_restart_via_sigusr1 (in-place
diff --git a/tests/tools/test_windows_native_support.py b/tests/tools/test_windows_native_support.py
index 699e8c42c03..1a04a28f55a 100644
--- a/tests/tools/test_windows_native_support.py
+++ b/tests/tools/test_windows_native_support.py
@@ -107,7 +107,8 @@ class TestTerminatePidRoutingOnWindows:
return result
monkeypatch.setattr(status.subprocess, "run", fake_run)
- status.terminate_pid(12345, force=True)
+ monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 123456)
+ status.terminate_pid(12345, force=True, expected_start_time=123456)
assert captured["args"][0] == "taskkill"
assert "/PID" in captured["args"]
@@ -126,8 +127,9 @@ class TestTerminatePidRoutingOnWindows:
return result
monkeypatch.setattr(status.subprocess, "run", fake_run)
+ monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 123456)
with pytest.raises(OSError, match="cannot be terminated"):
- status.terminate_pid(12345, force=True)
+ status.terminate_pid(12345, force=True, expected_start_time=123456)
def test_graceful_on_windows_uses_os_kill_sigterm(self, monkeypatch):
"""Non-force path calls os.kill with SIGTERM (Windows has no SIGKILL).
@@ -165,7 +167,8 @@ class TestTerminatePidRoutingOnWindows:
monkeypatch.setattr(status.subprocess, "run", fake_run)
monkeypatch.setattr(status.os, "kill", fake_kill)
- status.terminate_pid(42, force=True)
+ monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 123456)
+ status.terminate_pid(42, force=True, expected_start_time=123456)
assert captured["pid"] == 42
assert captured["sig"] == signal.SIGTERM
diff --git a/tools/environments/local.py b/tools/environments/local.py
index b9b0cc7c40a..f876753adae 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -2203,9 +2203,13 @@ class LocalEnvironment(BaseEnvironment):
try:
if _IS_WINDOWS:
try:
- from gateway.status import terminate_pid
+ from gateway.status import get_process_start_time, terminate_pid
- terminate_pid(proc.pid, force=True)
+ terminate_pid(
+ proc.pid,
+ force=True,
+ expected_start_time=get_process_start_time(proc.pid),
+ )
except Exception:
proc.kill()
try: