Skip to content

The agent that grows with you

fix(dashboard): end a PTY session's helpers after its leader dies

kshitijk4poorc047f354800e
diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.py
index 9abbe0f7876..b50a9e1a470 100644
--- a/hermes_cli/pty_bridge.py
+++ b/hermes_cli/pty_bridge.py
@@ -61,6 +61,25 @@ class PtyUnavailableError(RuntimeError):
"""
+# Longer than the TUI gateway's own SIGHUP shutdown grace (tui_gateway/entry.py, 1.0 s by default),
+# so a helper that is saving state on SIGHUP finishes before it is SIGKILLed.
+_HELPER_SHUTDOWN_GRACE_S = 1.5
+
+
+def _process_group_exists(pgid: int) -> bool:
+ try:
+ os.killpg(pgid, 0) # windows-footgun: ok — POSIX-only module (imports fcntl/termios/ptyprocess at top)
+ except OSError:
+ return False
+ return True
+
+
+def _wait_for_group_exit(pgid: int, timeout: float) -> None:
+ deadline = time.monotonic() + timeout
+ while _process_group_exists(pgid) and time.monotonic() < deadline:
+ time.sleep(0.02)
+
+
class PtyBridge:
"""Thin wrapper around ``ptyprocess.PtyProcess`` for byte streaming. Not thread-safe: owned by
the WebSocket handler that spawned it; reads run in an executor thread, writes are awaited on
@@ -72,6 +91,12 @@ class PtyBridge:
self._proc = proc
self._fd: int = proc.fd
self._closed = False
+ # Recorded at spawn: once the leader is reaped getpgid() can no longer find its group,
+ # but the helpers it started still belong to it.
+ try:
+ self._pgid: Optional[int] = os.getpgid(proc.pid) # windows-footgun: ok — POSIX-only module (imports fcntl/termios/ptyprocess at top)
+ except OSError:
+ self._pgid = None
os.set_blocking(self._fd, False)
@classmethod
@@ -228,10 +253,8 @@ class PtyBridge:
return
self._closed = True
- try:
- pgid = os.getpgid(self._proc.pid) # windows-footgun: ok — POSIX-only module (imports fcntl/termios/ptyprocess at top)
- except Exception:
- pgid = None
+ pgid = self._pgid
+ leader_was_alive = self._proc.isalive()
# Signal the whole process group, not just the PTY leader: the dashboard TUI starts helper
# children (e.g. the Python slash worker) and killing only the leader strands them.
@@ -249,6 +272,21 @@ class PtyBridge:
while self._proc.isalive() and time.monotonic() < deadline:
time.sleep(0.02)
+ # Helpers can outlive the leader and keep the PTY slave open, so no EOF ever arrives (#76759):
+ # one that ignores SIGHUP, or any helper of a leader that died first (crash, OOM kill). When
+ # the group already got SIGHUP above, only wait: the TUI gateway saves its sessions on SIGHUP
+ # within its shutdown grace, and a second SIGHUP or an early SIGKILL would cut that short.
+ if pgid is not None:
+ sweep = (signal.SIGKILL,) if leader_was_alive else (signal.SIGHUP, signal.SIGKILL) # windows-footgun: ok — POSIX-only module (imports fcntl/termios/ptyprocess at top)
+ if leader_was_alive:
+ _wait_for_group_exit(pgid, _HELPER_SHUTDOWN_GRACE_S)
+ for sig in sweep:
+ try:
+ os.killpg(pgid, sig) # windows-footgun: ok — POSIX-only module (imports fcntl/termios/ptyprocess at top)
+ except OSError:
+ break # ESRCH: the group is empty
+ _wait_for_group_exit(pgid, _HELPER_SHUTDOWN_GRACE_S)
+
try:
self._proc.close(force=True)
except Exception:
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.py
index cc62f2f4c27..5fbc403acd7 100644
--- a/hermes_cli/pty_session.py
+++ b/hermes_cli/pty_session.py
@@ -156,22 +156,6 @@ class RegistryFull(Exception):
super().__init__(message)
-def _bridge_alive(s: "PtySession") -> bool:
- """True when the session's child process is still running.
-
- Duck-typed: fake bridges used in tests may not implement ``is_alive``;
- when the bridge doesn't expose it we conservatively treat the session as
- alive and rely on the EOF path (``alive = False``) instead.
- """
- is_alive = getattr(s.bridge, "is_alive", None)
- if is_alive is None:
- return True
- try:
- return bool(is_alive())
- except Exception:
- return False
-
-
async def run_reaper(registry: "PtySessionRegistry", *, interval: float = 60.0) -> None:
"""Periodically reap idle/dead keep-alive sessions. Cancelled on shutdown."""
while True:
@@ -252,15 +236,9 @@ class PtySessionRegistry:
key for key, s in self._sessions.items()
if not s.alive
or (not s.attached and s.last_detached_at is not None and (now - s.last_detached_at) > self._ttl)
- # The drain task sets ``alive = False`` only when it observes
- # EOF on the PTY master. If the child was killed externally
- # (OOM killer, cgroup SIGKILL, manual kill) while a grandchild
- # still holds the PTY slave, or the drain task itself died, EOF
- # never arrives and the session would pin its bridge (fds) and
- # registry slot forever — each leaked TUI subprocess costs
- # ~150-250 MB RSS in the dashboard's cgroup (#76759).
- # Ask the bridge directly; the check is a cheap WNOHANG waitpid.
- or not _bridge_alive(s)
+ # EOF never arrives if a helper still holds the PTY slave after the child died (#76759);
+ # ask the process itself (a WNOHANG waitpid).
+ or not s.bridge.is_alive()
]
for key in doomed:
# Reaps overlap (attach_or_spawn and the background reaper) and close()
diff --git a/tests/hermes_cli/test_pty_bridge.py b/tests/hermes_cli/test_pty_bridge.py
index 353aea61766..d3a66b2ac18 100644
--- a/tests/hermes_cli/test_pty_bridge.py
+++ b/tests/hermes_cli/test_pty_bridge.py
@@ -261,15 +261,17 @@ class TestPtyBridgeClose:
fake = _FakeProc()
def fake_killpg(pgid, sig):
+ if not fake.alive:
+ raise ProcessLookupError # the whole group exited with its leader
sent.append((pgid, sig))
fake.alive = False
- monkeypatch.setattr(os, "getpgid", lambda pid: 67890)
monkeypatch.setattr(os, "killpg", fake_killpg)
bridge = PtyBridge.__new__(PtyBridge)
bridge._proc = fake
bridge._fd = -1
+ bridge._pgid = 67890
bridge._closed = False
bridge.close()
@@ -277,6 +279,42 @@ class TestPtyBridgeClose:
assert sent == [(67890, signal.SIGHUP)]
assert bridge._closed is True
+ def test_close_ends_helpers_that_outlive_a_dead_leader(self):
+ # #76759: the helper ignores SIGHUP and keeps the PTY slave open, so the leader's death
+ # never produces EOF. close() must still end it.
+ bridge = PtyBridge.spawn(["/bin/sh", "-c", "trap '' HUP; sleep 60 & echo helper=$!; exec sleep 60"])
+ out = _read_until(bridge, b"\n", timeout=5.0)
+ helper = int(out.split(b"helper=")[1].split()[0])
+ os.kill(bridge.pid, signal.SIGKILL)
+ deadline = time.monotonic() + 3.0
+ while bridge.is_alive() and time.monotonic() < deadline:
+ time.sleep(0.02)
+
+ bridge.close()
+
+ deadline = time.monotonic() + 3.0
+ while time.monotonic() < deadline:
+ try:
+ os.kill(helper, 0)
+ except ProcessLookupError:
+ return
+ time.sleep(0.05)
+ os.kill(helper, signal.SIGKILL)
+ pytest.fail(f"helper pid {helper} survived close() after its leader died")
+
+ def test_close_lets_a_helper_finish_its_sighup_shutdown(self, tmp_path):
+ # The TUI gateway saves its sessions on SIGHUP within a 1 s grace. Once the group got
+ # SIGHUP, close() must wait for it, not re-signal or SIGKILL it early.
+ marker = tmp_path / "saved"
+ helper = f"trap 'sleep 0.8; echo ok > {marker}; exit 0' HUP; while :; do sleep 0.05; done"
+ bridge = PtyBridge.spawn(["/bin/sh", "-c", f"/bin/sh -c \"{helper}\" & echo up; exec sleep 60"])
+ _read_until(bridge, b"up", timeout=5.0)
+ time.sleep(0.2) # let the helper install its trap
+
+ bridge.close()
+
+ assert marker.read_text().strip() == "ok"
+
@skip_on_windows
class TestPtyBridgeEnv:
def test_cwd_is_respected(self, tmp_path):
diff --git a/tests/hermes_cli/test_pty_keepalive_ws.py b/tests/hermes_cli/test_pty_keepalive_ws.py
index 47ca9c284c3..f73b5f6c426 100644
--- a/tests/hermes_cli/test_pty_keepalive_ws.py
+++ b/tests/hermes_cli/test_pty_keepalive_ws.py
@@ -24,6 +24,9 @@ class FakeBridge:
def resize(self, cols, rows):
pass
+ def is_alive(self):
+ return self.alive
+
def close(self):
self.alive = False