Skip to content

The agent that grows with you

refactor(gateway): read cgroup pids once and skip the gateway.status import when empty

kshitijk4poor0687c5e17159
diff --git a/gateway/cgroup_cleanup.py b/gateway/cgroup_cleanup.py
index 01e03f69e8d..1230969e51a 100644
--- a/gateway/cgroup_cleanup.py
+++ b/gateway/cgroup_cleanup.py
@@ -43,17 +43,11 @@ def _read_cgroup_pids(cgroup_path: str) -> list[int]:
def _parent_is_systemd() -> bool:
"""True when this process was spawned by a systemd manager (ExecStopPost etc.).
- The reaper is safe only in that context: the gateway's main process is
- already gone, and the cgroup holds orphans. Any other parent (an agent
- terminal tool, a shell, a test) shares a *live* process's cgroup, so
- reaping there SIGKILLs that process. Refuse loudly instead (issue:
- 2026-09-29 engineering-gateway self-kill incident).
-
- No PID-1 shortcut: in a plain container the gateway itself can be PID 1
- (or the init can be ``tini``/``launchd``), and an orphan reparented to
- PID 1 shares the live gateway's cgroup. PID 1 must present as systemd
- like any other parent, and an unreadable ``/proc/<ppid>/comm`` fails
- closed.
+ Any other parent (an agent terminal tool, a shell) shares a *live*
+ process's cgroup, so reaping there would SIGKILL that process. No PID-1
+ shortcut: in a container the gateway itself can be PID 1 (or init can be
+ ``tini``), so PID 1 must present as systemd too; an unreadable
+ ``/proc/<ppid>/comm`` fails closed.
"""
ppid = os.getppid()
try:
@@ -62,47 +56,38 @@ def _parent_is_systemd() -> bool:
return False
-def _live_gateway_in_cgroup(cgroup_path: str) -> bool:
- """True when a live Hermes gateway process still sits in the cgroup.
-
- The reaper's hard precondition is that the gateway's main process is
- gone: ExecStopPost runs after it, and the cgroup then holds orphans. A
- live gateway in the cgroup (a container where the gateway is PID 1, a
- targeted reap of a still-running service) would be SIGKILLed by the
- reap, so it must be detected and the reap refused. A PID whose command
- line can no longer be read has already exited (or is a zombie) — exactly
- what the reaper exists to clear — so only a readable, gateway-shaped
- command line blocks.
-
- Uses the *runtime* matcher (``run`` **or** ``restart``): on a host
- without a service manager, ``hermes gateway restart`` runs
- ``run_gateway()`` in-process, so the restart process is itself the live
- runtime and must block a reap too. The strict ``run``-only matcher is
- for lifecycle decisions (stop/replace); this cleanup scan is exactly
- the use case its docstring carves out.
+def _live_gateway_among(pids: list[int]) -> bool:
+ """True when one of ``pids`` is a live Hermes gateway runtime.
+
+ A PID whose command line can't be read has already exited (or is a
+ zombie) — exactly what the reaper clears — so only a readable,
+ gateway-shaped command line blocks. Uses the *runtime* matcher (``run``
+ or ``restart``): without a service manager, ``gateway restart`` runs the
+ gateway in-process and is itself the live runtime.
"""
from gateway.status import _read_process_cmdline, looks_like_gateway_runtime_command_line
- for pid in _read_cgroup_pids(cgroup_path):
- if pid == os.getpid():
- continue
+ for pid in pids:
cmdline = _read_process_cmdline(pid)
if cmdline and looks_like_gateway_runtime_command_line(cmdline):
return True
return False
-def reap_cgroup(cgroup_path: str | None = None) -> int:
+def reap_cgroup(cgroup_path: str | None = None) -> int | None:
"""SIGKILL every PID in the cgroup other than the caller. Returns the count killed.
- Refuses (returns -1, no signals) when a live gateway process is still in
- the cgroup — the reaper must never signal the live gateway, no matter
- how it was invoked.
+ Returns None (no signals) when a live gateway process is still in the
+ cgroup — the reaper must never signal the live gateway, however invoked.
"""
cgroup_path = _own_cgroup_path() if cgroup_path is None else cgroup_path
if not cgroup_path:
return 0
- if _live_gateway_in_cgroup(cgroup_path):
+ me = os.getpid()
+ others = [pid for pid in _read_cgroup_pids(cgroup_path) if pid != me]
+ if not others:
+ return 0
+ if _live_gateway_among(others):
print(
"cgroup_cleanup: refusing — a live gateway process is still in the "
"cgroup; reaping would SIGKILL it. Stop the service first (then "
@@ -110,11 +95,9 @@ def reap_cgroup(cgroup_path: str | None = None) -> int:
"the gateway process has exited.",
file=sys.stderr,
)
- return -1
+ return None
killed = 0
- for pid in _read_cgroup_pids(cgroup_path):
- if pid == os.getpid():
- continue
+ for pid in others:
try:
os.kill(pid, signal.SIGKILL) # windows-footgun: ok — Linux-only (reads /proc, /sys/fs/cgroup; runs from a systemd unit)
killed += 1
@@ -133,7 +116,7 @@ def main() -> int:
file=sys.stderr,
)
return 1
- return 1 if reap_cgroup() < 0 else 0
+ return 1 if reap_cgroup() is None else 0
if __name__ == "__main__":
diff --git a/tests/gateway/test_cgroup_cleanup.py b/tests/gateway/test_cgroup_cleanup.py
index 86bd570ffc6..18180b34b3c 100644
--- a/tests/gateway/test_cgroup_cleanup.py
+++ b/tests/gateway/test_cgroup_cleanup.py
@@ -24,8 +24,6 @@ class TestOwnCgroupPath:
class TestReapCgroup:
-
-
def test_noop_when_procs_file_missing(self, tmp_path, monkeypatch):
cgroup_path = "/missing.slice/hermes-gateway.service"
monkeypatch.setattr(
@@ -42,7 +40,6 @@ class TestReapCgroup:
class TestMain:
-
def test_main_refuses_when_pid1_parent_is_not_systemd(self, tmp_path, monkeypatch):
# Regression: a container where the gateway itself is PID 1 (or init
# is tini/launchd) must NOT be authorized by "ppid == 1". PID 1 has to
@@ -60,12 +57,10 @@ class TestMain:
pytest.fail("os.kill must not be called for a non-systemd PID 1 parent")
monkeypatch.setattr(cgroup_cleanup.os, "kill", _explode)
- assert cgroup_cleanup._parent_is_systemd() is False
assert cgroup_cleanup.main() == 1
class TestLiveGatewayGuard:
-
@pytest.mark.parametrize("verb", ["run", "restart"])
def test_reap_refuses_when_live_gateway_in_cgroup(self, monkeypatch, verb):
# Regression: a live gateway PID still in cgroup.procs (gateway is PID 1
@@ -90,27 +85,20 @@ class TestLiveGatewayGuard:
pytest.fail("os.kill must not signal a cgroup holding a live gateway")
monkeypatch.setattr(cgroup_cleanup.os, "kill", _explode)
- assert cgroup_cleanup.reap_cgroup(cgroup_path) == -1
+ assert cgroup_cleanup.reap_cgroup(cgroup_path) is None
monkeypatch.setattr(cgroup_cleanup, "_parent_is_systemd", lambda: True)
monkeypatch.setattr(cgroup_cleanup, "_own_cgroup_path", lambda: cgroup_path)
assert cgroup_cleanup.main() == 1
- def test_reap_proceeds_when_only_orphans_in_cgroup(self, monkeypatch):
- # Allow-path contract: orphans with non-gateway command lines must
- # still be reaped — the guard must not destroy the feature it secures.
- import gateway.status
-
- monkeypatch.setattr(
- cgroup_cleanup, "_read_cgroup_pids", lambda _p: [777, os.getpid()]
- )
+ # Allow-path: once the gateway is gone, a non-gateway orphan in the
+ # same cgroup must still be reaped — the guard must not destroy the
+ # feature it secures.
monkeypatch.setattr(
gateway.status,
"_read_process_cmdline",
lambda pid: "bash -c adb forward tcp:8888 tcp:8889" if pid == 777 else None,
)
killed: list[int] = []
- monkeypatch.setattr(
- cgroup_cleanup.os, "kill", lambda pid, sig: killed.append(pid)
- )
- assert cgroup_cleanup.reap_cgroup("/some.slice/some-gateway.service") == 1
+ monkeypatch.setattr(cgroup_cleanup.os, "kill", lambda pid, sig: killed.append(pid))
+ assert cgroup_cleanup.reap_cgroup(cgroup_path) == 1
assert killed == [777]