Skip to content

The agent that grows with you

fix(gateway): guard Windows post-drain taskkill with the pre-drain start time

teknium1d809057a12a4
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 1d7fff6fd78..3026d5012a5 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1837,14 +1837,18 @@ def stop_profile_gateway() -> bool:
# Windows maps SIGTERM to TerminateProcess. The marker watcher is the
# gateway's graceful-stop IPC, so wait for it before force-killing a
# wedged process.
+ from gateway.status import get_process_start_time
from hermes_cli.gateway_windows import (
_drain_gateway_pid,
_force_terminate_known_gateway_pids,
_windows_stop_drain_timeout,
)
+ # Capture identity BEFORE the drain (as _escalate_wedged_gateway does): if the PID is
+ # recycled during the wait, terminate_pid's start-time mismatch refuses the taskkill.
+ expected_start_time = get_process_start_time(pid)
if not _drain_gateway_pid(pid, _windows_stop_drain_timeout()):
- _force_terminate_known_gateway_pids([pid])
+ _force_terminate_known_gateway_pids({pid: expected_start_time})
else:
_mark_planned_stop(pid)
try:
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index d0087a28a7f..3eac5130a99 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -1425,24 +1425,35 @@ def _windows_stop_drain_timeout() -> float:
return max(1.0, min(configured, 30.0))
-def _force_terminate_known_gateway_pids(pids: list[int]) -> int:
- """Force-kill known gateway PIDs without a broad process sweep."""
+def _gateway_pid_identities(pids: list[int]) -> dict[int, int | None]:
+ """``{pid: start_time}`` fingerprints, captured BEFORE any drain/wait so a later force-kill can
+ detect that the PID was recycled meanwhile."""
try:
- from gateway.status import _pid_exists, get_process_start_time, terminate_pid
+ from gateway.status import get_process_start_time
+ except ImportError:
+ return {pid: None for pid in pids}
+ return {pid: get_process_start_time(pid) for pid in pids}
+
+
+def _force_terminate_known_gateway_pids(identities: dict[int, int | None]) -> int:
+ """Force-kill known gateway PIDs without a broad process sweep. ``identities`` maps each PID to
+ the start time observed when it was identified as a gateway (``_gateway_pid_identities``);
+ ``terminate_pid`` refuses the kill when the live process no longer matches. Re-reading the start
+ time here would compare the process with itself and taskkill whatever now owns the PID."""
+ try:
+ from gateway.status import _pid_exists, terminate_pid
except ImportError:
return 0
own_pid = os.getpid()
killed = 0
- seen: set[int] = set()
- for pid in pids:
- if pid <= 0 or pid == own_pid or pid in seen:
+ for pid, expected_start_time in identities.items():
+ if pid <= 0 or pid == own_pid:
continue
- seen.add(pid)
try:
if not _pid_exists(pid):
continue
- terminate_pid(pid, force=True, expected_start_time=get_process_start_time(pid))
+ terminate_pid(pid, force=True, expected_start_time=expected_start_time)
killed += 1
except ProcessLookupError:
continue
@@ -1479,6 +1490,8 @@ def stop() -> None:
pid = get_running_pid()
stop_pids = _collect_gateway_stop_pids(pid)
+ # Fingerprint before the drain: the kill below must refuse a PID recycled during the wait.
+ identities = _gateway_pid_identities(stop_pids)
drained = pid is not None and _drain_gateway_pid(pid, _windows_stop_drain_timeout())
stopped_any = drained
@@ -1491,8 +1504,9 @@ def stop() -> None:
print(f"⚠ schtasks /End returned code {code}: {err.strip()}")
# No generic process sweep: starts are profile-scoped and stop must stay bounded even if wedged.
- stop_pids.extend(pid for pid in _collect_gateway_stop_pids() if pid not in stop_pids)
- killed = _force_terminate_known_gateway_pids(stop_pids)
+ late_pids = [pid for pid in _collect_gateway_stop_pids() if pid not in identities]
+ identities.update(_gateway_pid_identities(late_pids))
+ killed = _force_terminate_known_gateway_pids(identities)
if killed:
stopped_any = True
print(f"✓ Killed {killed} gateway process(es)")
@@ -1528,7 +1542,7 @@ def restart() -> None:
if not _wait_for_gateway_absent(timeout_s=30.0):
print("⚠ Gateway still present after stop; forcing termination before restart...")
- _force_terminate_known_gateway_pids(_collect_gateway_stop_pids())
+ _force_terminate_known_gateway_pids(_gateway_pid_identities(_collect_gateway_stop_pids()))
if not _wait_for_gateway_absent(timeout_s=10.0):
raise RuntimeError(
"Gateway process still detected after force kill; refusing to "
diff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.py
index d8b6faf2436..d173728396b 100644
--- a/tests/hermes_cli/test_gateway.py
+++ b/tests/hermes_cli/test_gateway.py
@@ -566,6 +566,7 @@ class TestStopProfileGateway:
monkeypatch.setattr("gateway.status.get_running_pid", lambda: pid)
monkeypatch.setattr(gateway, "is_windows", lambda: True)
monkeypatch.setattr(gateway_windows, "_windows_stop_drain_timeout", lambda: 7.0)
+ monkeypatch.setattr("gateway.status.get_process_start_time", lambda target: 100)
monkeypatch.setattr(
gateway_windows,
"_drain_gateway_pid",
@@ -582,7 +583,45 @@ class TestStopProfileGateway:
monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)
assert gateway.stop_profile_gateway() is True
- assert calls == [("drain", pid, 7.0), ("force", [pid])]
+ assert calls == [("drain", pid, 7.0), ("force", {pid: 100})]
+
+ def test_windows_stop_force_kill_carries_pre_drain_identity(self, monkeypatch):
+ """The post-drain taskkill must be guarded by the start time captured BEFORE the <=30 s drain:
+ a PID recycled during the wait shows a different start time, so ``terminate_pid``'s mismatch
+ refusal fires instead of killing an unrelated process. Reading it at kill time is a vacuous
+ self-comparison."""
+ import gateway.status as status
+ import hermes_cli.gateway_windows as gateway_windows
+
+ pid = 4242
+ calls = []
+ clock = {"now": 0.0}
+ alive = {"value": True}
+
+ monkeypatch.setattr(gateway_windows.time, "monotonic", lambda: clock["now"])
+ monkeypatch.setattr(
+ gateway_windows.time, "sleep", lambda _s: clock.__setitem__("now", clock["now"] + 10.0)
+ )
+ monkeypatch.setattr(gateway, "is_windows", lambda: True)
+ monkeypatch.setattr(gateway_windows, "_windows_stop_drain_timeout", lambda: 7.0)
+ monkeypatch.setattr(status, "get_running_pid", lambda: pid if alive["value"] else None)
+ monkeypatch.setattr(status, "write_planned_stop_marker", lambda target: None)
+ monkeypatch.setattr(status, "_pid_exists", lambda target: alive["value"])
+ # The original gateway (start time 100) exits during the drain and its PID is recycled (999).
+ monkeypatch.setattr(
+ status, "get_process_start_time", lambda target: 100 if clock["now"] < 7.0 else 999
+ )
+
+ def _terminate(target, force=False, expected_start_time=None):
+ calls.append((target, force, expected_start_time))
+ alive["value"] = False
+
+ monkeypatch.setattr(status, "terminate_pid", _terminate)
+ monkeypatch.setattr(status, "remove_pid_file", lambda: None)
+ monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)
+
+ assert gateway.stop_profile_gateway() is True
+ assert calls == [(pid, True, 100)]
def test_stop_profile_gateway_keeps_pid_file_when_process_still_running(self, monkeypatch):
calls = {"kill": 0, "alive_probes": 0, "remove": 0, "reap_calls": 0}