The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): exclude wedged turns from the restart after-turn wait
Tekniumafe09c794267
diff --git a/gateway/run.py b/gateway/run.pyindex 00d0d22d295..70950a11c55 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -10876,6 +10876,50 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewexcept Exception as e:logger.debug("Failed to launch systemd planned-restart helper: %s", e)+ def _wedged_agent_count(self) -> int:+ """Count running chat agents already past the inactivity timeout.++ A turn whose agent has recorded no activity (no API bytes, no tool+ progress) for longer than ``agent.gateway_timeout`` is wedged — the+ same threshold at which the turn reaper gives up on it. The restart+ after-turn wait must not treat such turns as work worth waiting for:+ a wedged agent pinned ``hermes update`` in "draining" for the full+ ``restart_after_turn_timeout`` cap because the drain counted it as+ active while its own inactivity watchdog had already declared it dead+ (Aug 2026, WhatsApp turn idle 30+ min, drain waited on it anyway).++ Returns 0 when the inactivity timeout is disabled (``gateway_timeout``+ 0/unset ⇒ the operator opted into unbounded turns; the after-turn cap+ still bounds the wait). Cron/API-server work has no per-turn activity+ clock and is never counted as wedged. Pending sentinels are brand-new+ turns, never wedged. Fail-open per agent: an unreadable activity+ summary means "not wedged".+ """+ timeout = _float_env("HERMES_AGENT_TIMEOUT", 1800)+ if timeout <= 0:+ return 0+ wedged = 0+ for agent in list((getattr(self, "_running_agents", None) or {}).values()):+ if agent is None or agent is _AGENT_PENDING_SENTINEL:+ continue+ summary_fn = getattr(agent, "get_activity_summary", None)+ if not callable(summary_fn):+ continue+ try:+ summary = summary_fn()+ if not isinstance(summary, dict):+ continue+ idle = float(summary.get("seconds_since_activity", 0.0))+ except Exception:+ continue+ if idle >= timeout:+ wedged += 1+ return wedged++ def _awaitable_work_count(self) -> int:+ """Active work minus wedged turns — what the restart wait waits on."""+ return max(0, self._active_work_count() - self._wedged_agent_count())+async def _await_active_work_before_restart(self) -> bool:"""Wait for in-flight work to finish before entering ``stop()``.@@ -10885,14 +10929,31 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewwait here for active agents/cron/api work to reach zero, then let``stop()`` run against an idle gateway (drain is instant).+ Turns already past the inactivity timeout are excluded from the wait+ (``_wedged_agent_count``): restart is usually the *remedy* for a+ wedged turn, so deferring it behind one inverts the point of the+ graceful path. ``stop()``'s drain interrupts them under+ ``restart_drain_timeout`` instead.+Returns True when work drained to zero, False when the safety cap- elapsed with work still active (caller proceeds to ``stop()``, which- may then interrupt remaining runs under ``restart_drain_timeout``).+ elapsed with work still active — or when only wedged work remains —+ (caller proceeds to ``stop()``, which may then interrupt remaining+ runs under ``restart_drain_timeout``)."""active = self._active_work_count()if active <= 0:return True+ awaitable = self._awaitable_work_count()+ if awaitable <= 0:+ logger.warning(+ "Restart requested with %d active work unit(s), all wedged "+ "past the inactivity timeout; skipping the after-turn wait "+ "and proceeding to stop()/drain which will interrupt them",+ active,+ )+ return False+timeout = float(getattr(self, "_restart_after_turn_timeout", 0.0) or 0.0)if timeout <= 0:logger.info(@@ -10917,7 +10978,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewloop = asyncio.get_running_loop()deadline = loop.time() + timeoutlast_status_at = 0.0- while self._active_work_count() > 0:+ while self._awaitable_work_count() > 0:now = loop.time()if now >= deadline:logger.warning(@@ -10931,8 +10992,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif (now - last_status_at) >= 30.0:logger.info("Restart deferred: waiting on %d active work unit(s) "- "(%.0fs remaining before force drain)",- self._active_work_count(),+ "(%d wedged and excluded; %.0fs remaining before force drain)",+ self._awaitable_work_count(),+ self._wedged_agent_count(),deadline - now,)try:@@ -10942,6 +11004,14 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewlast_status_at = nowawait asyncio.sleep(0.1)+ if self._active_work_count() > 0:+ logger.warning(+ "Restart deferred wait: %d wedged work unit(s) remain; "+ "proceeding to stop()/drain which will interrupt them",+ self._active_work_count(),+ )+ return False+logger.info("Restart deferred wait complete — active work drained; ""proceeding to stop()"diff --git a/tests/gateway/test_restart_drain.py b/tests/gateway/test_restart_drain.pyindex 7304f93581c..590223f51c4 100644--- a/tests/gateway/test_restart_drain.py+++ b/tests/gateway/test_restart_drain.py@@ -375,3 +375,96 @@ async def test_drain_suppress_skips_home_channel_keeps_session_ping(tmp_path, moassert "shutting down" in adapter.sent[0]+++def _wedged_agent(idle_seconds: float = 4000.0) -> MagicMock:+ """Agent double whose activity summary reports it idle past the timeout."""+ agent = MagicMock()+ agent.get_activity_summary = MagicMock(+ return_value={"seconds_since_activity": idle_seconds}+ )+ return agent+++def _live_agent(idle_seconds: float = 1.0) -> MagicMock:+ agent = MagicMock()+ agent.get_activity_summary = MagicMock(+ return_value={"seconds_since_activity": idle_seconds}+ )+ return agent+++async def test_request_restart_skips_wait_when_only_wedged_turns(monkeypatch):+ """A turn idle past agent.gateway_timeout must not defer the restart.++ Regression: a WhatsApp turn wedged for 30+ min pinned `hermes update`+ in "draining" for the full restart_after_turn_timeout cap — the+ after-turn wait counted the wedged agent as active work even though+ the inactivity watchdog had already declared it dead (Aug 2026).+ """+ monkeypatch.delenv("HERMES_AGENT_TIMEOUT", raising=False)+ runner, _adapter = make_restart_runner()+ runner.stop = AsyncMock()+ # A cap long enough that the test would hang without the wedge bypass.+ runner._restart_after_turn_timeout = 300.0+ runner._running_agents["agent:main:whatsapp:dm:1"] = _wedged_agent()++ assert runner.request_restart(detached=False, via_service=True) is True+ await asyncio.wait_for(runner._restart_task, timeout=5.0)++ runner.stop.assert_awaited_once_with(+ restart=True, detached_restart=False, service_restart=True+ )+ # Wedged agent stays in the map — stop() owns the interrupt from here.+ assert runner._running_agents+++async def test_request_restart_still_waits_for_live_turn_alongside_wedged(monkeypatch):+ """Mixed live + wedged: the live turn is honored, the wedged one ignored."""+ monkeypatch.delenv("HERMES_AGENT_TIMEOUT", raising=False)+ runner, _adapter = make_restart_runner()+ runner.stop = AsyncMock()+ runner._launch_detached_restart_command = AsyncMock()+ runner._restart_after_turn_timeout = 300.0+ live_key = "agent:main:telegram:dm:2"+ runner._running_agents["agent:main:whatsapp:dm:1"] = _wedged_agent()+ runner._running_agents[live_key] = _live_agent()++ assert runner.request_restart(detached=False, via_service=True) is True++ # Live turn active → stop() must not run yet, wedged turn notwithstanding.+ await asyncio.sleep(0.25)+ runner.stop.assert_not_awaited()++ # Live turn finishes → restart proceeds without waiting on the wedged one.+ del runner._running_agents[live_key]+ await asyncio.wait_for(runner._restart_task, timeout=5.0)+ runner.stop.assert_awaited_once()+++def test_wedged_agent_count_disabled_timeout_counts_nothing(monkeypatch):+ """gateway_timeout=0 (unbounded turns) disables wedge detection."""+ monkeypatch.setenv("HERMES_AGENT_TIMEOUT", "0")+ runner, _adapter = make_restart_runner()+ runner._running_agents["agent:main:telegram:dm:1"] = _wedged_agent(10**6)+ assert runner._wedged_agent_count() == 0+++def test_wedged_agent_count_ignores_sentinels_and_bad_summaries(monkeypatch):+ monkeypatch.delenv("HERMES_AGENT_TIMEOUT", raising=False)+ runner, _adapter = make_restart_runner()+ broken = MagicMock()+ broken.get_activity_summary = MagicMock(side_effect=RuntimeError("boom"))+ non_dict = MagicMock() # auto-attr summary returns a MagicMock, not a dict+ runner._running_agents.update(+ {+ "pending": gateway_run._AGENT_PENDING_SENTINEL,+ "broken": broken,+ "non_dict": non_dict,+ "wedged": _wedged_agent(),+ "live": _live_agent(),+ }+ )+ assert runner._wedged_agent_count() == 1