Skip to content

The agent that grows with you

fix(gateway): spare pidfile-less Scheduled-Task gateways from the orphan reaper on Windows (#83683)

EvanProgramming30c469b15313
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index e8634ea12da..b9df20436bb 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1525,6 +1525,54 @@ def kill_gateway_processes(
return killed
+_REAPER_SUPERVISOR_WALK_LIMIT = 12
+
+
+def _reaper_candidate_is_supervisor_owned(pid: int) -> bool:
+ """True when ``pid`` is a gateway process owned by the Windows Task Scheduler.
+
+ Windows-only backstop for the orphan reaper: ``_get_service_pids()`` is
+ empty on Windows (no systemd/launchd query), so a Scheduled-Task gateway
+ whose ``gateway.pid`` record is missing or stale is invisible to both the
+ service-PID and recorded-PID exclusions — yet it is alive and supervised.
+ Scheduled Tasks run under the services tree, so a candidate whose parent
+ chain reaches ``services.exe`` is spared even with no pidfile (#83683,
+ #86098).
+
+ This check is deliberately NOT applied on POSIX: there, every process has
+ PID 1 (launchd / init / systemd) in its ancestry — and a genuine orphan is
+ *reparented directly to PID 1* — so supervisor-name ancestry carries zero
+ signal and would spare every orphan the reaper exists to kill (#51325,
+ #75936). POSIX supervised gateways are already covered pidfile-
+ independently by the ``_get_service_pids()`` exclusion.
+
+ Known limitation (fail-open): if the Task-launched bootstrap parent has
+ already exited, Windows does not reparent the gateway, the chain breaks
+ before ``services.exe``, and the gateway is treated as an orphan. Any
+ error (process gone, psutil unavailable) is likewise treated as "not
+ owned" so a genuine orphan is still reaped.
+ """
+ if not is_windows():
+ return False
+ try:
+ import psutil # type: ignore
+
+ parent = psutil.Process(pid).parent()
+ for _ in range(_REAPER_SUPERVISOR_WALK_LIMIT):
+ if parent is None:
+ break
+ try:
+ name = (parent.name() or "").lower()
+ except Exception:
+ name = ""
+ if name == "services.exe":
+ return True
+ parent = parent.parent()
+ except Exception:
+ pass
+ return False
+
+
def _reap_unsupervised_gateway_orphans(extra_exclude: set | None = None) -> bool:
"""Kill no-supervisor gateway orphans the pidfile/runtime record can't see.
@@ -1595,8 +1643,14 @@ def _reap_unsupervised_gateway_orphans(extra_exclude: set | None = None) -> bool
pass
try:
# find_gateway_pids() includes no-supervisor `gateway restart` runtimes
- # for the current profile when no systemd supervisor is present.
- orphans = [p for p in find_gateway_pids(exclude_pids=own) if p and p > 0]
+ # for the current profile when no systemd supervisor is present. On
+ # Windows, additionally drop any candidate the Task Scheduler owns —
+ # the pidfile-less gap neither exclusion above can see (#83683, #86098).
+ orphans = [
+ p
+ for p in find_gateway_pids(exclude_pids=own)
+ if p and p > 0 and not _reaper_candidate_is_supervisor_owned(p)
+ ]
except Exception:
return False
if not orphans:
diff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.py
index d47c647506b..d050f307fc2 100644
--- a/tests/hermes_cli/test_gateway.py
+++ b/tests/hermes_cli/test_gateway.py
@@ -604,6 +604,135 @@ class TestReapUnsupervisedGatewayOrphansWindows:
assert killed_pids == [] # nothing was killed
+class TestReaperCandidateIsSupervisorOwned:
+ """Regression for the Windows pidfile-less supervisor-owned case (#83683).
+
+ On Windows ``_get_service_pids()`` is empty and a Scheduled-Task gateway
+ that lost ``gateway.pid`` is invisible to both the service-PID and
+ recorded-PID exclusions — the backstop spares it via services.exe
+ ancestry. On POSIX the backstop must be inert: every process (and
+ especially a genuine orphan, which is reparented to PID 1) has
+ launchd/init in its ancestry, so ancestry carries no supervision signal
+ there (#51325, #75936).
+ """
+
+ @staticmethod
+ def _install_fake_psutil(monkeypatch, by_pid):
+ fake_psutil = SimpleNamespace(Process=lambda pid: by_pid[pid])
+ monkeypatch.setitem(sys.modules, "psutil", fake_psutil)
+
+ def test_windows_scheduled_task_gateway_spared_without_pidfile(self, monkeypatch):
+ """A Windows gateway launched by the Scheduled Task is spared even when
+ gateway.pid is missing — the supervisor-owned backstop catches it."""
+ gateway_pid = 52615
+ bootstrap_pid = 52616 # Task-launched `hermes gateway run` bootstrap
+ orphan_pid = 99998 # a genuine orphan that SHOULD be reaped
+
+ monkeypatch.setattr(gateway, "is_windows", lambda: True)
+ monkeypatch.setattr(gateway, "is_macos", lambda: False)
+ monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
+ # No pidfile => get_running_pid() returns None.
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
+ # _get_service_pids() is empty on Windows.
+ monkeypatch.setattr(gateway, "_get_service_pids", lambda: set())
+
+ # Parent chain: gateway -> bootstrap -> services.exe (Task Scheduler).
+ services = SimpleNamespace(pid=4, parent=lambda: None, name=lambda: "services.exe")
+ bootstrap = SimpleNamespace(
+ pid=bootstrap_pid, parent=lambda: services, name=lambda: "hermes-gateway.exe"
+ )
+ gw = SimpleNamespace(
+ pid=gateway_pid, parent=lambda: bootstrap, name=lambda: "hermes-gateway.exe"
+ )
+ # Genuine Windows orphan: its parent exited; Windows does NOT reparent,
+ # so psutil reports parent() is None — the chain never reaches
+ # services.exe and the orphan is reaped.
+ orphan = SimpleNamespace(pid=orphan_pid, parent=lambda: None, name=lambda: "hermes-gateway.exe")
+ by_pid = {gateway_pid: gw, bootstrap_pid: bootstrap, orphan_pid: orphan}
+ self._install_fake_psutil(monkeypatch, by_pid)
+
+ monkeypatch.setattr(
+ gateway,
+ "find_gateway_pids",
+ lambda exclude_pids=None: [
+ p for p in [gateway_pid, bootstrap_pid, orphan_pid]
+ if p not in (exclude_pids or set())
+ ],
+ )
+
+ killed_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("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
+
+ def test_macos_orphan_reparented_to_launchd_is_still_reaped(self, monkeypatch):
+ """POSIX inertness guard: a genuine macOS orphan is reparented directly
+ to launchd (PID 1) — supervisor-name ancestry must NOT spare it, or the
+ reaper becomes a permanent no-op on macOS/WSL (#51325, #75936)."""
+ orphan_pid = 99998
+
+ monkeypatch.setattr(gateway, "is_macos", lambda: True)
+ monkeypatch.setattr(gateway, "is_windows", lambda: False)
+ monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
+ monkeypatch.setattr(gateway, "_get_service_pids", lambda: set())
+
+ # Realistic macOS topology: the orphan's parent IS launchd (PID 1).
+ launchd = SimpleNamespace(pid=1, parent=lambda: None, name=lambda: "launchd")
+ orphan = SimpleNamespace(pid=orphan_pid, parent=lambda: launchd, name=lambda: "Python")
+ self._install_fake_psutil(monkeypatch, {orphan_pid: orphan, 1: launchd})
+
+ monkeypatch.setattr(
+ gateway,
+ "find_gateway_pids",
+ lambda exclude_pids=None: [
+ p for p in [orphan_pid] if p not in (exclude_pids or set())
+ ],
+ )
+
+ killed_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("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]
+
+ def test_backstop_is_inert_on_posix(self, monkeypatch):
+ """Direct unit guard: on non-Windows the backstop returns False without
+ touching psutil, even for a launchd/init-ancestored process."""
+ monkeypatch.setattr(gateway, "is_windows", lambda: False)
+
+ def _boom(_pid):
+ raise AssertionError("psutil must not be consulted on POSIX")
+
+ monkeypatch.setitem(sys.modules, "psutil", SimpleNamespace(Process=_boom))
+ assert gateway._reaper_candidate_is_supervisor_owned(12345) is False
+
+ def test_windows_backstop_fails_open_when_bootstrap_exited(self, monkeypatch):
+ """Documented limitation: if the Task bootstrap already exited, the
+ chain breaks before services.exe (Windows does not reparent) and the
+ candidate is treated as a reapable orphan."""
+ monkeypatch.setattr(gateway, "is_windows", lambda: True)
+ stranded = SimpleNamespace(pid=4242, parent=lambda: None, name=lambda: "hermes-gateway.exe")
+ self._install_fake_psutil(monkeypatch, {4242: stranded})
+ assert gateway._reaper_candidate_is_supervisor_owned(4242) is False
+
+
def test_module_has_logger():
"""Verify module has a logger instance (regression guard for #27154)."""
assert hasattr(gateway, "logger")