The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): drain Windows profile stop before kill
KoNit-Kfd1582f63bad
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex da048c18425..b74d41611ab 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -1696,6 +1696,12 @@ def _reap_unsupervised_gateway_orphans(extra_exclude: set | None = None) -> boolfor pid in orphans:with contextlib.suppress(Exception):write_planned_stop_marker(pid)+ # ``os.kill(..., SIGTERM)`` maps to TerminateProcess on Windows, so it+ # would kill the gateway before its marker watcher can drain and close+ # state cleanly. Let the bounded survivor wait below escalate instead.+ if is_windows():+ reaped = True+ continuetry:os.kill(pid, signal.SIGTERM)except ProcessLookupError:@@ -1826,14 +1832,27 @@ def stop_profile_gateway() -> bool:if pid is None:return _reap_unsupervised_gateway_orphans()- _mark_planned_stop(pid)- try:- os.kill(pid, signal.SIGTERM)- except ProcessLookupError:- pass # Already gone- except PermissionError:- print(f"⚠ Permission denied to kill PID {pid}")- return False+ if is_windows():+ # 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 hermes_cli.gateway_windows import (+ _drain_gateway_pid,+ _force_terminate_known_gateway_pids,+ _windows_stop_drain_timeout,+ )++ if not _drain_gateway_pid(pid, _windows_stop_drain_timeout()):+ _force_terminate_known_gateway_pids([pid])+ else:+ _mark_planned_stop(pid)+ try:+ os.kill(pid, signal.SIGTERM)+ except ProcessLookupError:+ pass # Already gone+ except PermissionError:+ print(f"⚠ Permission denied to kill PID {pid}")+ return False# ``_pid_exists``, NOT ``os.kill(pid, 0)`` (TerminateProcess on Windows).from gateway.status import _pid_existsdiff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.pyindex 41696183fe9..d8b6faf2436 100644--- a/tests/hermes_cli/test_gateway.py+++ b/tests/hermes_cli/test_gateway.py@@ -530,6 +530,60 @@ class TestWaitForGatewayExit:class TestStopProfileGateway:+ def test_windows_stop_drains_marker_before_force_termination(self, monkeypatch):+ """Windows must let the marker watcher run before escalating (#112750)."""+ import hermes_cli.gateway_windows as gateway_windows++ pid = 12345+ calls = []+ 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_windows,+ "_drain_gateway_pid",+ lambda target, timeout: calls.append(("drain", target, timeout)) or True,+ )+ monkeypatch.setattr(+ gateway_windows,+ "_force_terminate_known_gateway_pids",+ lambda pids: calls.append(("force", pids)),+ )+ monkeypatch.setattr(gateway.os, "kill", lambda *_: calls.append(("kill",)))+ monkeypatch.setattr("gateway.status._pid_exists", lambda target: False)+ monkeypatch.setattr("gateway.status.remove_pid_file", lambda: None)+ monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)++ assert gateway.stop_profile_gateway() is True+ assert calls == [("drain", pid, 7.0)]++ def test_windows_stop_force_terminates_only_after_drain_timeout(self, monkeypatch):+ """A wedged Windows gateway still has a bounded force-stop fallback (#112750)."""+ import hermes_cli.gateway_windows as gateway_windows++ pid = 12345+ calls = []+ 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_windows,+ "_drain_gateway_pid",+ lambda target, timeout: calls.append(("drain", target, timeout)) or False,+ )+ monkeypatch.setattr(+ gateway_windows,+ "_force_terminate_known_gateway_pids",+ lambda pids: calls.append(("force", pids)),+ )+ monkeypatch.setattr(gateway.os, "kill", lambda *_: calls.append(("kill",)))+ monkeypatch.setattr("gateway.status._pid_exists", lambda target: False)+ monkeypatch.setattr("gateway.status.remove_pid_file", lambda: None)+ monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)++ assert gateway.stop_profile_gateway() is True+ assert calls == [("drain", pid, 7.0), ("force", [pid])]+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}@@ -722,19 +776,18 @@ class TestReapUnsupervisedGatewayOrphansWindows:)killed_pids = []+ marked_pids = []monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)- monkeypatch.setattr("gateway.status.write_planned_stop_marker", lambda pid: None)+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)monkeypatch.setattr("time.sleep", lambda _: None)monkeypatch.setattr("time.monotonic", lambda: 1.0)result = gateway._reap_unsupervised_gateway_orphans()assert result is True # at least one orphan was reaped- killed = [pid for pid, _ in killed_pids]- assert orphan_pid in killed # the real orphan was killed- assert recorded_pid not in killed # the recorded gateway was NOT killed- assert bootstrap_pid not in killed # its supervision chain was NOT killed+ assert marked_pids == [orphan_pid] # the real orphan was asked to drain+ assert killed_pids == [] # Windows SIGTERM must not TerminateProcessdef test_windows_no_orphans_when_only_recorded_gateway_running(self, monkeypatch):"""If the only gateway processes are the recorded one and its@@ -892,19 +945,18 @@ class TestReaperCandidateIsSupervisorOwned:)killed_pids = []+ marked_pids = []monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)- monkeypatch.setattr("gateway.status.write_planned_stop_marker", lambda pid: None)+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)monkeypatch.setattr("time.sleep", lambda _: None)monkeypatch.setattr("time.monotonic", lambda: 1.0)result = gateway._reap_unsupervised_gateway_orphans()assert result is True # the genuine orphan was reaped- killed = [pid for pid, _ in killed_pids]- assert orphan_pid in killed # orphan killed- assert gateway_pid not in killed # supervisor-owned gateway spared (no pidfile!)- assert bootstrap_pid not in killed # its bootstrap spared too+ assert marked_pids == [orphan_pid] # only the genuine orphan is asked to drain+ assert killed_pids == [] # no Windows SIGTERM before the drain waitdef test_macos_orphan_reparented_to_launchd_is_still_reaped(self, monkeypatch):"""POSIX inertness guard: a genuine macOS orphan is reparented directly@@ -932,9 +984,10 @@ class TestReaperCandidateIsSupervisorOwned:)killed_pids = []+ marked_pids = []monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)- monkeypatch.setattr("gateway.status.write_planned_stop_marker", lambda pid: None)+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)monkeypatch.setattr("time.sleep", lambda _: None)monkeypatch.setattr("time.monotonic", lambda: 1.0)@@ -1068,16 +1121,18 @@ class TestWindowsScheduledTaskSupervisorGuard:],)killed_pids = []+ marked_pids = []monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)- monkeypatch.setattr("gateway.status.write_planned_stop_marker", lambda pid: None)+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)monkeypatch.setattr("time.sleep", lambda _: None)monkeypatch.setattr("time.monotonic", lambda: 1.0)result = gateway._reap_unsupervised_gateway_orphans()assert result is True- assert orphan_pid in [pid for pid, _ in killed_pids]+ assert marked_pids == [orphan_pid]+ assert killed_pids == []def test_windows_scheduled_task_running_returns_false_off_windows(self, monkeypatch):"""The state helper is inert on POSIX (no subprocess spawned)."""