The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): bound signal interrupt grace
embwl0x221312834ea7
diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 5b670b57b7b..b2d09dc5ddd 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -1160,6 +1160,15 @@ agent:# tone: "direct"# style: "terse"+# =============================================================================+# Gateway Lifecycle+# =============================================================================+gateway:+ # Post-interrupt grace for running agents during an unexpected SIGTERM.+ # Adapter, bridge, and database teardown starts after this many seconds even+ # if an agent has not unwound. Keep it below the service-manager stop budget.+ # signal_interrupt_grace_timeout: 1+# =============================================================================# Toolsets# =============================================================================diff --git a/gateway/restart.py b/gateway/restart.pyindex 7190e5a7f42..986b5a4fee3 100644--- a/gateway/restart.py+++ b/gateway/restart.py@@ -1,5 +1,6 @@"""Shared gateway restart constants and supervisor detection helpers."""+import mathimport osfrom collections.abc import Mapping@@ -23,6 +24,10 @@ EXTERNAL_GATEWAY_SUPERVISOR_ENV = "HERMES_GATEWAY_EXTERNAL_SUPERVISOR"DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT = float(DEFAULT_CONFIG["agent"]["restart_drain_timeout"])+DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT = float(+ DEFAULT_CONFIG["gateway"]["signal_interrupt_grace_timeout"]+)+DEFAULT_GATEWAY_POST_INTERRUPT_GRACE_TIMEOUT = 5.0# In-band restart (``/restart``, SIGUSR1, self-restart from a child CLI)# waits for active turns to finish *before* ``stop()`` begins. Distinct@@ -238,3 +243,17 @@ def resolve_restart_exit_wait_budget(except (TypeError, ValueError):margin = 0.0return drain + after_turn + margin+++def parse_signal_interrupt_grace_timeout(raw: object) -> float:+ """Parse the unexpected-signal post-interrupt grace timeout."""+ try:+ if raw is None or (isinstance(raw, str) and not raw.strip()):+ value = DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT+ else:+ value = float(raw)+ except (TypeError, ValueError):+ return DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT+ if not math.isfinite(value):+ return DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT+ return max(0.0, value)diff --git a/gateway/run.py b/gateway/run.pyindex 56086ec6ce0..45533f0bb1c 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -3033,13 +3033,16 @@ from gateway.shutdown_watchdog import ()from gateway.restart import (DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT,+ DEFAULT_GATEWAY_POST_INTERRUPT_GRACE_TIMEOUT,DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUT,DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT,+ DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT,GATEWAY_FATAL_CONFIG_EXIT_CODE,GATEWAY_SERVICE_RESTART_EXIT_CODE,parse_cron_drain_timeout,parse_restart_after_turn_timeout,parse_restart_drain_timeout,+ parse_signal_interrupt_grace_timeout,resolve_cron_drain_budget,)@@ -7298,6 +7301,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_restart_drain_timeout: float = DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT_restart_after_turn_timeout: float = DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUT_cron_drain_timeout: float = DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT+ _signal_interrupt_grace_timeout: float = (+ DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT+ )_exit_code: Optional[int] = None_draining: bool = False_external_drain_active: bool = False@@ -7447,6 +7453,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself._restart_drain_timeout = self._load_restart_drain_timeout()self._restart_after_turn_timeout = self._load_restart_after_turn_timeout()self._cron_drain_timeout = self._load_cron_drain_timeout()+ self._signal_interrupt_grace_timeout = (+ self._load_signal_interrupt_grace_timeout()+ )self._provider_routing = self._load_provider_routing()self._fallback_model = self._load_fallback_model()@@ -10419,6 +10428,46 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew)return value+ @staticmethod+ def _load_signal_interrupt_grace_timeout() -> float:+ """Load the unexpected-signal post-interrupt grace in seconds."""+ cfg = _load_gateway_runtime_config()+ raw = cfg_get(+ cfg,+ "gateway",+ "signal_interrupt_grace_timeout",+ default=None,+ )+ value = parse_signal_interrupt_grace_timeout(raw)+ if raw is not None and raw != "":+ try:+ float(raw)+ except (TypeError, ValueError):+ logger.warning(+ "Invalid signal_interrupt_grace_timeout '%s', using default %.0fs",+ raw,+ DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT,+ )+ return value++ def _post_interrupt_grace_timeout(self) -> float:+ """Return the grace before teardown after forcibly interrupting agents."""+ if (+ getattr(self, "_signal_initiated_shutdown", False)+ and not getattr(self, "_restart_requested", False)+ ):+ return max(+ 0.0,+ float(+ getattr(+ self,+ "_signal_interrupt_grace_timeout",+ DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT,+ )+ ),+ )+ return DEFAULT_GATEWAY_POST_INTERRUPT_GRACE_TIMEOUT+@staticmethoddef _load_background_notifications_mode() -> str:"""Load background process notification mode from config or env var.@@ -16173,7 +16222,16 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself._interrupt_running_agents(_INTERRUPT_REASON_GATEWAY_RESTART if self._restart_requested else _INTERRUPT_REASON_GATEWAY_SHUTDOWN)- interrupt_deadline = asyncio.get_running_loop().time() + 5.0+ interrupt_grace_timeout = (+ GatewayRunner._post_interrupt_grace_timeout(self)+ )+ interrupt_deadline = (+ asyncio.get_running_loop().time() + interrupt_grace_timeout+ )+ logger.info(+ "Shutdown phase: allowing %.1fs for interrupted agents to unwind",+ interrupt_grace_timeout,+ )# Wait on API-server work too. The interrupt is cooperative:# without this the settle window closes the instant# _running_agents is empty, and an API turn that was just askeddiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex d403047f6e0..f0af27e8ca7 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -3170,6 +3170,12 @@ DEFAULT_CONFIG = {# the historical serve-all behavior; [] serves only the default."multiplex_profile_allowlist": None,+ # After an unexpected SIGTERM interrupts a running gateway agent,+ # wait this many seconds for it to unwind before adapter and database+ # teardown proceeds. Keep this short so service-manager shutdowns do+ # not exhaust their stop budget before resource cleanup begins.+ "signal_interrupt_grace_timeout": 1,+# Durable delivery-obligation ledger: final agent responses are# recorded in state.db around the platform send, and a gateway that# died between finalize and platform ACK redelivers the storeddiff --git a/tests/gateway/restart_test_helpers.py b/tests/gateway/restart_test_helpers.pyindex 589cdca1d82..134267be169 100644--- a/tests/gateway/restart_test_helpers.py+++ b/tests/gateway/restart_test_helpers.py@@ -8,6 +8,7 @@ from gateway.restart import (DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT,DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUT,DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT,+ DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT,)from gateway.run import GatewayRunnerfrom gateway.session import SessionSource@@ -79,6 +80,9 @@ def make_restart_runner(runner._restart_drain_timeout = DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUTrunner._restart_after_turn_timeout = DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUTrunner._cron_drain_timeout = DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT+ runner._signal_interrupt_grace_timeout = (+ DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT+ )runner._stop_task = Nonerunner._busy_input_mode = "interrupt"runner._update_prompt_pending = {}diff --git a/tests/gateway/test_gateway_shutdown.py b/tests/gateway/test_gateway_shutdown.pyindex eb7ae47090e..f83310485a2 100644--- a/tests/gateway/test_gateway_shutdown.py+++ b/tests/gateway/test_gateway_shutdown.py@@ -168,6 +168,58 @@ async def test_planned_service_exit_issues_no_restart_of_its_own(monkeypatch):assert runner._exit_code == GATEWAY_SERVICE_RESTART_EXIT_CODE+async def test_unexpected_signal_starts_teardown_after_bounded_interrupt_grace():+ runner, adapter = make_restart_runner()+ runner._restart_drain_timeout = 0.0+ runner._signal_initiated_shutdown = True+ runner._signal_interrupt_grace_timeout = 0.01+ runner._running_agents = {"session": MagicMock()}++ disconnect_started = asyncio.Event()++ async def disconnect():+ disconnect_started.set()++ adapter.disconnect = disconnect++ with patch("gateway.status.remove_pid_file"), patch(+ "gateway.status.write_runtime_status"+ ):+ stop_task = asyncio.create_task(runner.stop())+ await asyncio.wait_for(disconnect_started.wait(), timeout=0.75)+ await stop_task++ assert runner._shutdown_event.is_set() is True+++ ("signal_initiated", "restart_requested", "expected"),+ [+ (True, False, 0.25),+ (False, False, 5.0),+ (True, True, 5.0),+ ],+)+def test_post_interrupt_grace_only_shortens_unexpected_signal_shutdown(+ signal_initiated, restart_requested, expected+):+ runner, _adapter = make_restart_runner()+ runner._signal_initiated_shutdown = signal_initiated+ runner._restart_requested = restart_requested+ runner._signal_interrupt_grace_timeout = 0.25++ assert runner._post_interrupt_grace_timeout() == expected+++def test_post_interrupt_grace_tolerates_duck_typed_runner():+ runner = MagicMock(spec=[])++ assert (+ gateway_run.GatewayRunner._post_interrupt_grace_timeout(runner)+ == gateway_run.DEFAULT_GATEWAY_POST_INTERRUPT_GRACE_TIMEOUT+ )+@pytest.mark.asyncioasync def test_in_chat_restart_skips_home_shutdown_even_with_active_session():runner, adapter = make_restart_runner()@@ -343,5 +395,3 @@ def test_pid_exists_zombie_via_psutil_returns_false(monkeypatch):monkeypatch.setitem(sys.modules, "psutil", fake_psutil)assert status._pid_exists(4242) is False--diff --git a/tests/gateway/test_restart_drain.py b/tests/gateway/test_restart_drain.pyindex 590223f51c4..0d643e65719 100644--- a/tests/gateway/test_restart_drain.py+++ b/tests/gateway/test_restart_drain.py@@ -9,7 +9,10 @@ import pytestimport gateway.run as gateway_runfrom agent.i18n import tfrom gateway.platforms.base import MessageEvent, MessageType-from gateway.restart import DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT+from gateway.restart import (+ DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT,+ DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT,+)from gateway.session import SessionEntry, build_session_keyfrom tests.gateway.restart_test_helpers import make_restart_runner, make_restart_source@@ -89,6 +92,48 @@ def test_load_busy_text_mode_follows_input_mode_and_honors_legacy(tmp_path, monkassert gateway_run.GatewayRunner._load_busy_text_mode() == "interrupt"+def test_load_signal_interrupt_grace_timeout_from_typed_config(+ tmp_path, monkeypatch, caplog+):+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)++ assert (+ gateway_run.GatewayRunner._load_signal_interrupt_grace_timeout()+ == DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT+ )++ (tmp_path / "config.yaml").write_text(+ "gateway:\n signal_interrupt_grace_timeout: 0.25\n",+ encoding="utf-8",+ )+ assert gateway_run.GatewayRunner._load_signal_interrupt_grace_timeout() == 0.25++ (tmp_path / "config.yaml").write_text(+ "gateway:\n signal_interrupt_grace_timeout: 0\n",+ encoding="utf-8",+ )+ assert gateway_run.GatewayRunner._load_signal_interrupt_grace_timeout() == 0.0++ (tmp_path / "config.yaml").write_text(+ "gateway:\n signal_interrupt_grace_timeout: .inf\n",+ encoding="utf-8",+ )+ assert (+ gateway_run.GatewayRunner._load_signal_interrupt_grace_timeout()+ == DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT+ )++ (tmp_path / "config.yaml").write_text(+ "gateway:\n signal_interrupt_grace_timeout: invalid\n",+ encoding="utf-8",+ )+ assert (+ gateway_run.GatewayRunner._load_signal_interrupt_grace_timeout()+ == DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT+ )+ assert "Invalid signal_interrupt_grace_timeout" in caplog.text++@pytest.mark.asyncioasync def test_request_restart_is_idempotent():runner, _adapter = make_restart_runner()