Skip to content

The agent that grows with you

fix(serve): shut down gracefully on parent death instead of os._exit

Vadim Comanescu1b64a72e251e
diff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.py
index e51196af244..535fc636a80 100644
--- a/hermes_cli/web_server_lifecycle.py
+++ b/hermes_cli/web_server_lifecycle.py
@@ -5,6 +5,7 @@ import asyncio
import logging
import ipaddress
import os
+import signal
import subprocess
import sys
import threading
@@ -291,6 +292,35 @@ def _is_serve_orphaned(
return False
+#: Ceiling on the post-orphan graceful unwind before the hard exit takes over.
+#: The desktop is already gone, so nothing escalates for us and this is the
+#: whole budget: comfortably past the 5s exit-flush budget
+#: (``HERMES_TUI_EXIT_FLUSH_BUDGET_S``), still short enough to keep the reap prompt.
+_ORPHAN_EXIT_CEILING_S = 10.0
+
+
+def _request_orphan_shutdown() -> threading.Timer:
+ """Ask this backend to shut itself down, with a hard-exit backstop.
+
+ ``os._exit`` here skipped the flush-on-kill handlers this same process
+ installs before serving (#96095, ``install_exit_flush_signal_handlers``)
+ and every ``atexit`` hook, so an unclean desktop exit dropped the in-memory
+ transcripts that a SIGTERM from a live desktop persists to ``state.db``.
+ Raise SIGTERM instead, and keep the reap guaranteed the way ``cli.py``'s
+ ``_arm_exit_watchdog`` does: a daemon timer that ``os._exit``\\ s if the
+ unwind stalls (it survives ``Py_FinalizeEx``'s non-daemon thread joins).
+ ``raise_signal`` reaches Python's handler on Windows too, where
+ ``os.kill(pid, SIGTERM)`` would terminate the process without running it.
+
+ Returns the armed ceiling timer.
+ """
+ ceiling = threading.Timer(_ORPHAN_EXIT_CEILING_S, os._exit, args=(0,))
+ ceiling.daemon = True
+ ceiling.start()
+ signal.raise_signal(signal.SIGTERM)
+ return ceiling
+
+
def _start_parent_death_watchdog() -> None:
"""Exit when the exact desktop parent that spawned this backend dies.
@@ -334,26 +364,13 @@ def _start_parent_death_watchdog() -> None:
time.sleep(poll)
try:
_log.warning(
- "Parent-death watchdog: desktop PID %s appears orphaned (expected_start_marker=%r); exiting.",
+ "Parent-death watchdog: desktop PID %s appears orphaned (expected_start_marker=%r); shutting down.",
desktop_pid,
start_marker,
)
except Exception:
pass
- # Reaping ourselves when the owning Desktop is gone is the designed stop, not a kill; os._exit
- # skips the atexit stamp that would otherwise say so.
- try:
- from hermes_cli.observability.shared_metrics_process import stamp_exit
- stamp_exit("clean")
- except Exception:
- pass
- # os._exit skips every cleanup: a foreground command in its own process group would outlive us.
- try:
- from tools.environments.base import kill_live_foreground_processes
- kill_live_foreground_processes(now=True)
- except Exception:
- pass
- os._exit(0)
+ _request_orphan_shutdown()
threading.Thread(target=_loop, daemon=True, name="serve-parent-watchdog").start()
diff --git a/tests/hermes_cli/test_serve_parent_watchdog.py b/tests/hermes_cli/test_serve_parent_watchdog.py
index b2fd384919f..b44d54ef703 100644
--- a/tests/hermes_cli/test_serve_parent_watchdog.py
+++ b/tests/hermes_cli/test_serve_parent_watchdog.py
@@ -219,3 +219,77 @@ def test_ps_marker_probe_classifies_missing_process_vs_other_ps_failures(monkeyp
with pytest.raises(OSError) as excinfo:
web_server_lifecycle._process_start_marker(4242)
assert not isinstance(excinfo.value, ProcessLookupError)
+
+
+def test_parent_watchdog_shuts_down_through_the_signal_path_not_os_exit(monkeypatch):
+ """#96095's flush-on-kill handlers only persist transcripts if a signal is raised.
+
+ ``os._exit`` skips signal handlers and ``atexit``, so an unclean desktop exit used
+ to drop exactly the in-memory state a SIGTERM from a live desktop would have saved.
+ """
+ import signal
+ import threading
+
+ from hermes_cli import web_server_lifecycle
+
+ monkeypatch.setenv("HERMES_PARENT_PID", "4242")
+ monkeypatch.delenv("HERMES_PARENT_START_MARKER", raising=False)
+ monkeypatch.delenv("HERMES_PARENT_NONCE", raising=False)
+ monkeypatch.setattr(web_server_lifecycle, "_is_serve_orphaned", lambda *_args: True)
+
+ hard_exits = []
+ monkeypatch.setattr(web_server_lifecycle.os, "_exit", lambda code: hard_exits.append(code))
+
+ timers = []
+
+ class _FakeThreading:
+ """Run the watchdog loop inline and keep its ceiling timer cancellable."""
+
+ @staticmethod
+ def Thread(target, **_kw):
+ class _Inline:
+ def start(self):
+ target()
+
+ return _Inline()
+
+ @staticmethod
+ def Timer(*args, **kwargs):
+ timer = threading.Timer(*args, **kwargs)
+ timers.append(timer)
+ return timer
+
+ monkeypatch.setattr(web_server_lifecycle, "threading", _FakeThreading)
+
+ handled = []
+ previous = signal.signal(signal.SIGTERM, lambda *_a: handled.append("sigterm"))
+ try:
+ web_server_lifecycle._start_parent_death_watchdog()
+ finally:
+ for timer in timers:
+ timer.cancel()
+ signal.signal(signal.SIGTERM, previous)
+
+ assert handled == ["sigterm"], "parent loss must run this process's shutdown handlers"
+ assert hard_exits == [], "the watchdog must not bypass those handlers with os._exit"
+
+
+def test_parent_watchdog_arms_a_daemon_hard_exit_ceiling(monkeypatch):
+ """A stalled unwind must still reap the orphan, and the timer must outlive teardown joins."""
+ import os
+ import signal
+
+ from hermes_cli import web_server_lifecycle
+
+ raised = []
+ monkeypatch.setattr(web_server_lifecycle.signal, "raise_signal", raised.append)
+
+ ceiling = web_server_lifecycle._request_orphan_shutdown()
+ try:
+ assert raised == [signal.SIGTERM]
+ assert ceiling.function is os._exit
+ assert ceiling.daemon is True
+ assert ceiling.is_alive()
+ assert 0 < ceiling.interval <= 30
+ finally:
+ ceiling.cancel()