Skip to content

The agent that grows with you

fix(gateway): stamp the clean exit before the bounded metrics flush

Teknium9810951353e5
diff --git a/gateway/run.py b/gateway/run.py
index 3d85ef0d9c9..efda43e498c 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -5183,7 +5183,7 @@ def main():
def _exit_after_graceful_shutdown(exit_code: int) -> None:
- """Flush stdio and opt-in shared metrics, release the PID file + runtime lock, then hard-exit.
+ """Flush stdio, release the PID file + lock, stamp the clean exit, flush opt-in metrics, 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 the metrics flush,
PID/lock release and the bounded log drain (file handlers sit behind a ``QueueListener`` thread)
@@ -5198,10 +5198,6 @@ def _exit_after_graceful_shutdown(exit_code: int) -> None:
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
@@ -5216,13 +5212,17 @@ def _exit_after_graceful_shutdown(exit_code: int) -> None:
from gateway.lifecycle_ledger import mark_exited
mark_exited(exit_code, reason="graceful_shutdown")
+ def _flush_metrics() -> None: # after the clean stamp: a supervisor kill mid-flush is no unclean death
+ 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 (bounded)
+
def _drain_logs() -> None:
# os._exit bypasses the listener's atexit drain. Bounded, no restart — NOT flush_log_queue():
# a listener wedged on the rotation lock would re-freeze shutdown in an unbounded stop() join.
from hermes_logging import drain_log_queue
drain_log_queue(timeout=1.0)
- for _step in (_flush_metrics, _release_locks, _mark_exited, _drain_logs):
+ for _step in (_release_locks, _mark_exited, _flush_metrics, _drain_logs):
_best_effort(_step)
os._exit(exit_code)
diff --git a/tests/hermes_cli/test_shared_metrics_exit_flush.py b/tests/hermes_cli/test_shared_metrics_exit_flush.py
index f8b0df6bd74..de0362be091 100644
--- a/tests/hermes_cli/test_shared_metrics_exit_flush.py
+++ b/tests/hermes_cli/test_shared_metrics_exit_flush.py
@@ -9,6 +9,7 @@ own consent (a multiplex gateway exits from the launch profile's scope).
from __future__ import annotations
+import functools
import json
import os
import sqlite3
@@ -227,12 +228,46 @@ def test_exit_flush_applies_each_profiles_own_consent(tmp_path, monkeypatch):
relay_runtime._reset_for_tests()
-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))
+def test_a_wedged_exit_flush_is_bounded_and_runs_after_the_clean_exit_stamp(metrics_home, monkeypatch):
+ """A managed tool call still in flight holds the Relay flush barrier (#53107): the exit still
+ leaves within the flush bound, and the clean-exit sentinel is already written, so a supervisor
+ killing the process during the flush never records a graceful stop as an unclean death."""
+ import gateway.run as gateway_run
+ from agent import relay_tools
+ from gateway.lifecycle_ledger import get_lifecycle_sentinel_path
+
+ home, _ = metrics_home
+ _finished_task_in_open_session()
+ _wait_for(home, "hermes.task_run.finished")
+ entered, release = threading.Event(), threading.Event()
+
+ def wedged_tool(_args):
+ entered.set()
+ release.wait(30)
+ return "late"
+
+ threading.Thread(
+ target=relay_tools.execute, args=("terminal", {"command": "x"}, wedged_tool),
+ kwargs={"session_id": "other-session"}, daemon=True,
+ ).start()
+ assert entered.wait(10)
+ phase_at_flush, finished_in_time = [], []
+ bounded_flush = functools.partial(process_metrics.flush_before_hard_exit, timeout_s=0.5)
+
+ def observed_flush():
+ sentinel = get_lifecycle_sentinel_path()
+ phase_at_flush.append(json.loads(sentinel.read_text()).get("phase") if sentinel.exists() else None)
+ finished_in_time.append(bounded_flush())
+
+ monkeypatch.setattr(process_metrics, "flush_before_hard_exit", observed_flush)
+ monkeypatch.setattr(gateway_run.os, "_exit", _fake_exit)
started = time.monotonic()
try:
- assert process_metrics.flush_before_hard_exit(timeout_s=0.2) is False
+ with pytest.raises(_Exited):
+ gateway_run._exit_after_graceful_shutdown(0)
finally:
release.set()
+
+ assert finished_in_time == [False] # the barrier really was wedged
+ assert phase_at_flush == ["exited"]
assert time.monotonic() - started < 5