Skip to content

The agent that grows with you

fix(gateway): drop PID-1 trust in cgroup_cleanup; refuse reap when a live gateway is still in the cgroup

jcjc8134e3cd0e541f
diff --git a/gateway/cgroup_cleanup.py b/gateway/cgroup_cleanup.py
index 28dfe4971a9..5757bc44529 100644
--- a/gateway/cgroup_cleanup.py
+++ b/gateway/cgroup_cleanup.py
@@ -48,21 +48,62 @@ def _parent_is_systemd() -> bool:
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.
"""
ppid = os.getppid()
- if ppid == 1:
- return True
try:
return Path(f"/proc/{ppid}/comm").read_text(encoding="utf-8").strip() == "systemd"
except OSError:
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.
+ """
+ from gateway.status import _read_process_cmdline, looks_like_gateway_command_line
+
+ for pid in _read_cgroup_pids(cgroup_path):
+ if pid == os.getpid():
+ continue
+ cmdline = _read_process_cmdline(pid)
+ if cmdline and looks_like_gateway_command_line(cmdline):
+ return True
+ return False
+
+
def reap_cgroup(cgroup_path: str | None = None) -> int:
- """SIGKILL every PID in the cgroup other than the caller. Returns the count killed."""
+ """SIGKILL every PID in the cgroup other than the caller. Returns the count killed.
+
+ Refuses (returns 0, 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.
+ """
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):
+ print(
+ "cgroup_cleanup: refusing — a live gateway process is still in the "
+ "cgroup; reaping would SIGKILL it. Stop the service first (then "
+ "ExecStopPost reaps its orphans), or call reap_cgroup(path) once "
+ "the gateway process has exited.",
+ file=sys.stderr,
+ )
+ return 0
killed = 0
for pid in _read_cgroup_pids(cgroup_path):
if pid == os.getpid():
diff --git a/tests/gateway/test_cgroup_cleanup.py b/tests/gateway/test_cgroup_cleanup.py
index 0163939fa4c..9650e92494d 100644
--- a/tests/gateway/test_cgroup_cleanup.py
+++ b/tests/gateway/test_cgroup_cleanup.py
@@ -103,3 +103,68 @@ class TestMain:
)
assert cgroup_cleanup.main() == 0
assert len(calls) == 1
+
+ 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
+ # present as systemd in /proc/1/comm like any other parent.
+ comm = tmp_path / "comm"
+ comm.write_text("tini\n")
+ monkeypatch.setattr(cgroup_cleanup.os, "getppid", lambda: 1)
+ monkeypatch.setattr(
+ cgroup_cleanup,
+ "Path",
+ lambda p: comm if p == "/proc/1/comm" else Path(p),
+ )
+
+ def _explode(*_a, **_kw):
+ 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:
+
+ def test_reap_refuses_when_live_gateway_in_cgroup(self, monkeypatch):
+ # Regression: a live gateway PID still in cgroup.procs (e.g. the
+ # gateway is PID 1 in a plain container, or a targeted reap of a
+ # still-running service) must abort the reap before any signal.
+ import gateway.status
+
+ gateway_cmdline = "/opt/hermes/venv/bin/python -m hermes_cli.main gateway run"
+ monkeypatch.setattr(
+ cgroup_cleanup, "_read_cgroup_pids", lambda _p: [777, os.getpid()]
+ )
+ monkeypatch.setattr(
+ gateway.status,
+ "_read_process_cmdline",
+ lambda pid: gateway_cmdline if pid == 777 else None,
+ )
+
+ def _explode(*_a, **_kw):
+ 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("/some.slice/some-gateway.service") == 0
+
+ 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()]
+ )
+ 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
+ assert killed == [777]