The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): keep PTY teardown inside the shutdown budget and the save grace
kshitijk4poor9236c9c63d04
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex baff8e4ef40..33b361d33e8 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -451,7 +451,7 @@ def _kill_pids_windows(pids: list[int], killed: list[int], failed: list[tuple[in# SIGTERM → SIGKILL grace for the dashboard/serve backend. Must outlast the lifespan teardown in# hermes_cli/web_server.py::_lifespan: stop_hosted_room_service(timeout=5.0) + the startup-thread-# join(1.0) + PTY_REGISTRY.close_all() (≤1.5s per attached Chat PTY, serial). A SIGKILL inside+# join(1.0) + PTY_REGISTRY.close_all() (concurrent; ≤ ~4.5s with the default helper grace). A SIGKILL inside# that window skips close_all(), so the ui-tui / tui_gateway.entry children outlive the backend# and keep the deleted state.db-wal inode open — the next hermes start refuses with a FATAL# DeletedWalGenerationError (#111912). The orphan reaper's 1.5s (`_reap_orphaned_desktop_local_serves`)diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.pyindex b50a9e1a470..246ea4cbf98 100644--- a/hermes_cli/pty_bridge.py+++ b/hermes_cli/pty_bridge.py@@ -61,11 +61,20 @@ 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.+# Longer than the TUI gateway's own SIGHUP shutdown grace, so a helper that is saving state on+# SIGHUP finishes before it is SIGKILLed._HELPER_SHUTDOWN_GRACE_S = 1.5+def _helper_shutdown_grace() -> float:+ # The gateway's grace is 1.0 s unless HERMES_TUI_GATEWAY_SHUTDOWN_GRACE_S raises it+ # (tui_gateway/entry.py); the PTY child inherits that env. Read it here rather than import+ # tui_gateway.entry, which installs signal handlers.+ from utils import env_float++ return max(_HELPER_SHUTDOWN_GRACE_S, env_float("HERMES_TUI_GATEWAY_SHUTDOWN_GRACE_S", 1.0) + 0.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)@@ -74,10 +83,6 @@ def _process_group_exists(pgid: int) -> bool: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:@@ -245,9 +250,27 @@ class PtyBridge:except OSError:pass+ def _discard_output(self, timeout: float) -> None:+ # Exiting children flush their pending terminal output first; on macOS a process stays in+ # exit (and a SIGHUP save outlasts the grace) until someone drains the master. The drain+ # task has stopped reading by now, so read and drop while waiting.+ try:+ readable, _, _ = select.select([self._fd], [], [], timeout)+ if readable:+ os.read(self._fd, 65536)+ except OSError:+ time.sleep(timeout)++ def _wait_for_group_exit(self, pgid: int, timeout: float) -> None:+ deadline = time.monotonic() + timeout+ while _process_group_exists(pgid) and time.monotonic() < deadline:+ self._discard_output(0.02)+def close(self) -> None:- """Terminate the child (SIGHUP → SIGTERM → SIGKILL, 0.5s grace each), reap it so the- dashboard process never leaks zombies, and close fds. Idempotent.+ """Terminate the child's process group (SIGHUP → SIGTERM → SIGKILL, 0.5s grace each while+ the leader lives, then up to the helper grace for the rest of the group), reap the leader so+ the dashboard never leaks zombies, and close fds. Idempotent; blocks, so call it off the+ event loop."""if self._closed:return@@ -270,22 +293,26 @@ class PtyBridge:passdeadline = time.monotonic() + 0.5while self._proc.isalive() and time.monotonic() < deadline:- time.sleep(0.02)+ self._discard_output(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.+ # The group id cannot be reused while any member is alive; if the group emptied after the+ # leader was reaped, a pid wrap inside that window could hand it to a new group (killpg+ # then hits that group). The reaper closes a dead session within one tick, so the window is short.if pgid is not None:+ grace = _helper_shutdown_grace()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)+ self._wait_for_group_exit(pgid, grace)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)+ self._wait_for_group_exit(pgid, grace)try:self._proc.close(force=True)diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.pyindex 5fbc403acd7..092d0151758 100644--- a/hermes_cli/pty_session.py+++ b/hermes_cli/pty_session.py@@ -191,8 +191,10 @@ class PtySessionRegistry:if existing is not None and existing.alive:return existing, Falseif existing is not None: # dead remnant- await existing.close()+ # Close in the background: ending a dead leader's helpers can take the helper+ # grace, and this lock serializes every new chat.self._sessions.pop(key, None)+ asyncio.create_task(existing.close())if len(self._sessions) >= self._max:self._reap_one_idle_or_raise()# PTY spawn does blocking fork/exec work — keep it off the event loop.@@ -257,9 +259,7 @@ class PtySessionRegistry:asyncio.create_task(oldest.close())async def close_all(self) -> None:- for key in list(self._sessions):- # Same overlap window as reap_idle: an in-flight reap may have popped- # a snapshot key while we awaited an earlier close().- session = self._sessions.pop(key, None)- if session is not None:- await session.close()+ # Close concurrently: each close() may wait out its helpers' SIGHUP grace, and shutdown runs+ # under the backend's SIGTERM -> SIGKILL budget (dashboard_procs._POSIX_TERM_GRACE_SECONDS).+ sessions = [self._sessions.pop(key) for key in list(self._sessions)]+ await asyncio.gather(*(s.close() for s in sessions), return_exceptions=True)diff --git a/tests/hermes_cli/test_pty_bridge.py b/tests/hermes_cli/test_pty_bridge.pyindex d3a66b2ac18..42ca2cd15ed 100644--- a/tests/hermes_cli/test_pty_bridge.py+++ b/tests/hermes_cli/test_pty_bridge.py@@ -306,10 +306,16 @@ class TestPtyBridgeClose:# 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+ # The trap ignores further SIGHUPs (the kernel may re-send one when the session leader+ # exits), so only an early SIGKILL from close() can stop the save.+ script = tmp_path / "helper.sh"+ script.write_text(+ f"trap 'trap \"\" HUP; sleep 0.6; echo ok > {marker}; exit 0' HUP\n"+ "echo armed\n"+ "while :; do sleep 0.05; done\n"+ )+ bridge = PtyBridge.spawn(["/bin/sh", "-c", f"/bin/sh {script} & exec sleep 60"])+ _read_until(bridge, b"armed", timeout=10.0) # the helper's trap is installedbridge.close()diff --git a/tests/hermes_cli/test_pty_session.py b/tests/hermes_cli/test_pty_session.pyindex 4198bab6a82..008f447edd5 100644--- a/tests/hermes_cli/test_pty_session.py+++ b/tests/hermes_cli/test_pty_session.py@@ -433,6 +433,25 @@ async def test_close_all_survives_key_popped_by_concurrent_reap():assert all(b.closed for b in bridges)+async def test_close_all_does_not_wait_on_one_slow_close_before_the_next():+ """Each close() can wait out its helpers' SIGHUP grace, and the backend's teardown runs under+ a SIGKILL budget, so sessions close concurrently rather than one after another."""+ reg = make_registry(ttl=60.0)+ bridges, entered, release = await _two_idle_sessions_first_close_gated(reg)++ closer = asyncio.create_task(reg.close_all())+ await entered.wait() # k0's close() is parked+ for _ in range(50):+ if bridges[1].closed:+ break+ await asyncio.sleep(0.01)+ assert bridges[1].closed # k1 closed while k0 still waits+ release.set()+ await closer+ assert all(b.closed for b in bridges)++@pytest.mark.asyncioasync def test_close_other_sessions_removes_old_profile_session():from hermes_cli.pty_session import WS_CLOSE_SUPERSEDED, PtySession