Skip to content

The agent that grows with you

fix(gateway): flush opt-in shared metrics before the graceful os._exit

Teknium6e5ebd7a7634
diff --git a/gateway/run.py b/gateway/run.py
index c063e4f4140..3d85ef0d9c9 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -5183,26 +5183,25 @@ def main():
def _exit_after_graceful_shutdown(exit_code: int) -> None:
- """Flush stdio, release the PID file + runtime lock, then hard-exit.
+ """Flush stdio and opt-in shared metrics, release the PID file + runtime lock, then hard-exit.
``os._exit`` (not ``sys.exit``): SystemExit runs ``Py_FinalizeEx``, which joins every non-daemon
- thread — exactly the hang a wedged worker causes. It bypasses ``atexit``, so PID/lock release and the
- bounded log drain (file handlers sit behind a ``QueueListener`` thread) are done here explicitly.
-
- Graceful teardown is already complete by the time this runs, so there is nothing left that needs a clean
- interpreter shutdown. See #53107.
- ``os._exit`` bypasses ``atexit`` handlers, so we cannot rely on the ``atexit``-registered
- ``remove_pid_file`` / ``release_gateway_runtime_lock`` (registered in ``start_gateway``) to run. The
- full-shutdown path releases both explicitly in ``_stop_impl``, but the EARLY exit paths —
- clean-fatal-config (#51228) and startup-aborted-before-running — raise ``SystemExit`` right after
- ``runner.start()`` without going through ``_stop_impl``, so on those paths ``atexit`` was the only thing
- releasing them. Now that those paths are routed through this backstop (#53107), release both here
- explicitly. Both calls are idempotent — ``remove_pid_file`` only unlinks a PID file that belongs to this
- process, and ``release_gateway_runtime_lock`` no-ops when the lock is already released — so this is a
- no-op on the normal shutdown path and the actual cleanup on the early-exit paths.
+ thread — exactly the hang a wedged worker causes. It bypasses ``atexit``, so the metrics flush,
+ PID/lock release and the bounded log drain (file handlers sit behind a ``QueueListener`` thread)
+ are done here explicitly; graceful teardown is already complete by the time this runs. See #53107.
+ The atexit-registered ``remove_pid_file`` / ``release_gateway_runtime_lock`` (``start_gateway``) never
+ run either. ``_stop_impl`` releases both on the full shutdown, but the EARLY exits — clean-fatal-config
+ (#51228) and startup-aborted-before-running — raise ``SystemExit`` right after ``runner.start()``
+ without ``_stop_impl``, so atexit was all that released them there; this backstop does now (#53107).
+ Both are idempotent (``remove_pid_file`` only unlinks this process's PID file; the lock release no-ops
+ once released): a no-op on the normal shutdown, the actual cleanup on the early exits.
"""
for stream in (sys.stdout, sys.stderr):
with suppress(Exception):
stream.flush()
+ def _flush_metrics() -> None: # first, so its rows land before the PID/lock release (bounded)
+ from hermes_cli.observability.shared_metrics_process import flush_before_hard_exit
+ flush_before_hard_exit() # the runtimes' atexit flush: open sessions + queued opt-in rows
+
def _release_locks() -> None:
# BEFORE the log drain (bounded, but could take its full timeout on a wedged disk); idempotent.
from gateway.status import remove_pid_file, release_gateway_runtime_lock
@@ -5223,7 +5222,7 @@ def _exit_after_graceful_shutdown(exit_code: int) -> None:
from hermes_logging import drain_log_queue
drain_log_queue(timeout=1.0)
- for _step in (_release_locks, _mark_exited, _drain_logs):
+ for _step in (_flush_metrics, _release_locks, _mark_exited, _drain_logs):
_best_effort(_step)
os._exit(exit_code)
diff --git a/hermes_cli/observability/shared_metrics_process.py b/hermes_cli/observability/shared_metrics_process.py
index 95c94e5ec5e..96db965fbd7 100644
--- a/hermes_cli/observability/shared_metrics_process.py
+++ b/hermes_cli/observability/shared_metrics_process.py
@@ -11,6 +11,7 @@ runtime; a claimed-but-unreported marker (the reporter died mid-way) is reclaime
from __future__ import annotations
import atexit
+import contextvars
import json
import logging
import os
@@ -29,6 +30,8 @@ _CRASH_CLASSES = (
(MemoryError, "memory_error"), (ImportError, "import_error"), (OSError, "os_error"),
(RuntimeError, "runtime_error"),
)
+#: Ceiling on ``flush_before_hard_exit``: a wedged flush costs its pending rows, never the exit.
+EXIT_FLUSH_TIMEOUT_S = 3.0
_STATE: dict[str, Any] = {}
_STATE_LOCK = threading.Lock()
@@ -62,6 +65,33 @@ def stamp_exit(exit_kind: str, crash: str = "none") -> None:
logger.debug("Process exit marker not stamped", exc_info=True)
+def flush_before_hard_exit(timeout_s: float = EXIT_FLUSH_TIMEOUT_S) -> bool:
+ """For a graceful stop about to ``os._exit``: run the shared-metrics exit flush its skipped atexit
+ hook would have run (close each live runtime's sessions, write queued rows to the local store).
+
+ Joined for at most ``timeout_s`` on a daemon thread, because the Relay flush waits on every managed
+ call still in flight and a wedged one must not hold the exit. Never imports the runtime module:
+ collection off (or never started) means nothing to flush and nothing created. Never raises; True
+ when the flush finished in time."""
+ runtimes = sys.modules.get("hermes_cli.observability.relay_shared_metrics")
+ if runtimes is None:
+ return True
+ try:
+ # The caller's context, as the atexit hook would have had: the export reads profile config.
+ worker = threading.Thread(
+ target=contextvars.copy_context().run, args=(runtimes.shutdown_runtimes,),
+ name="hermes-shared-metrics-exit-flush", daemon=True)
+ worker.start()
+ worker.join(max(0.0, timeout_s))
+ except Exception:
+ logger.debug("Shared-metrics exit flush not started", exc_info=True)
+ return False
+ if worker.is_alive():
+ logger.warning("Shared-metrics exit flush still running after %.1fs; exiting without it", timeout_s)
+ return False
+ return True
+
+
def _excepthook(previous: Any) -> Any:
def hook(exc_type: type[BaseException], exc: BaseException, tb: Any) -> None:
if not issubclass(exc_type, (KeyboardInterrupt, SystemExit)):
diff --git a/tests/gateway/test_graceful_exit_metrics_flush.py b/tests/gateway/test_graceful_exit_metrics_flush.py
new file mode 100644
index 00000000000..6411404e81e
--- /dev/null
+++ b/tests/gateway/test_graceful_exit_metrics_flush.py
@@ -0,0 +1,120 @@
+"""Graceful ``os._exit`` paths run the shared-metrics exit flush their skipped atexit hook would have run.
+
+The gateway (SIGTERM, update restart, idle exit all funnel through ``_exit_after_graceful_shutdown``)
+and the compute host leave via ``os._exit``, so a session still open at the stop never wrote its
+summary rows to the opt-in local store. The flush is bounded and creates nothing when collection is off.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from agent import relay_runtime
+from hermes_cli import lifecycle, plugins
+from hermes_cli.observability import relay_shared_metrics
+from hermes_cli.observability import shared_metrics_process as process_metrics
+from hermes_cli.plugins import PluginManager
+
+
+class _Exited(Exception):
+ pass
+
+
+def _fake_exit(code):
+ raise _Exited(code)
+
+
+def _store(home: Path) -> Path:
+ return home / "telemetry" / "shared_metrics" / "metrics.sqlite3"
+
+
+def _metric_names(home: Path) -> set[str]:
+ database = _store(home)
+ if not database.exists():
+ return set()
+ with sqlite3.connect(database.as_uri() + "?mode=ro", uri=True) as conn:
+ return {name for (name,) in conn.execute("SELECT metric_name FROM counter_aggregates")}
+
+
+def metrics_home(tmp_path, monkeypatch):
+ """Real NeMo Relay runtime over a temp HERMES_HOME; ``policy['on']`` is the opt-in answer."""
+ relay = pytest.importorskip("nemo_relay")
+ if getattr(relay, "_native", None) is None:
+ pytest.skip("NeMo Relay native binding is unavailable on this platform")
+ home = tmp_path / "hermes-home"
+ policy = {"on": True}
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(
+ "hermes_cli.config.read_raw_config_readonly",
+ lambda: {"telemetry": {"shared_metrics": {"enabled": policy["on"], "send": False}}},
+ )
+ relay_shared_metrics._reset_for_tests()
+ relay_runtime._reset_for_tests()
+ manager = PluginManager()
+ manager._discovered = True # a runtime with zero plugins (#64178)
+ monkeypatch.setattr(plugins, "_plugin_manager", manager)
+ yield home, policy
+ relay_shared_metrics._reset_for_tests()
+ relay_runtime._reset_for_tests()
+
+
+def _finished_task_in_open_session() -> None:
+ """One completed task in a session that stays open, as a messaging or Desktop chat does."""
+ event = {"session_id": "open-session", "task_id": "task-1", "platform": "cli"}
+ lifecycle.invoke_hook("on_session_start", **event, turn_id="turn-1")
+ relay_shared_metrics.start_task_run(**event)
+ lifecycle.invoke_hook("pre_llm_call", **event, turn_id="turn-1", messages=["hello"]) # a user turn
+ relay_shared_metrics.finish_task_run(**event, result={"completed": True, "final_response": "ok"})
+
+
+def _wait_for(home: Path, metric: str, deadline_s: float = 10.0) -> None:
+ deadline = time.monotonic() + deadline_s
+ while metric not in _metric_names(home):
+ assert time.monotonic() < deadline, f"{metric} never reached the store"
+ time.sleep(0.05)
+
+
+def test_graceful_gateway_exit_writes_the_open_sessions_summary(metrics_home, monkeypatch):
+ import gateway.run as gateway_run
+
+ home, _ = metrics_home
+ _finished_task_in_open_session()
+ _wait_for(home, "hermes.task_run.finished") # the task flush runs on its own worker
+ assert "hermes.session.count" not in _metric_names(home)
+
+ monkeypatch.setattr(gateway_run.os, "_exit", _fake_exit)
+ with pytest.raises(_Exited):
+ gateway_run._exit_after_graceful_shutdown(1)
+
+ assert "hermes.session.count" in _metric_names(home)
+
+
+def test_graceful_exit_with_collection_off_creates_no_store(metrics_home, monkeypatch):
+ import gateway.run as gateway_run
+
+ home, policy = metrics_home
+ policy["on"] = False
+ _finished_task_in_open_session()
+
+ monkeypatch.setattr(gateway_run.os, "_exit", _fake_exit)
+ with pytest.raises(_Exited):
+ gateway_run._exit_after_graceful_shutdown(0)
+
+ assert not (home / "telemetry").exists()
+
+
+def test_a_wedged_exit_flush_never_holds_the_exit(monkeypatch):
+ release = threading.Event()
+ monkeypatch.setattr(relay_shared_metrics, "shutdown_runtimes", lambda: release.wait(30))
+ started = time.monotonic()
+ try:
+ assert process_metrics.flush_before_hard_exit(timeout_s=0.2) is False
+ finally:
+ release.set()
+ assert time.monotonic() - started < 5