The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): inactivity watchdogs do not count host sleep as idle
Maciej Lisiewski07f9e8e654cc
diff --git a/gateway/run.py b/gateway/run.pyindex 2ae94196dc9..42c8243c453 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -42,7 +42,7 @@ from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIXfrom agent.interrupt_compat import request_hard_interruptfrom agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, copy_identity_fieldsfrom agent.turn_context import compression_made_progress-from agent.session_activity import ActivityProvenance+from agent.session_activity import ActivityProvenance, AwakeIdleMeterfrom hermes_cli.config import _is_ssh_remote_tilde_cwd, cfg_getfrom hermes_cli.fallback_config import pre_agent_fallback_noticefrom gateway.turn_executor import _UnboundedThreadExecutor@@ -2746,6 +2746,7 @@ def _watch_gateway_turn_inactivity(retain the session turn lease forever because every watchdog poll just skips it."""activity_origin = time.monotonic()+ awake_idle = AwakeIdleMeter() # host sleep is not idlenesswhile not worker_done.wait(max(0.01, poll_interval)):now = time.monotonic()idle_seconds = now - activity_origin@@ -2754,7 +2755,7 @@ def _watch_gateway_turn_inactivity(try:reported_idle = agent.get_activity_summary().get("seconds_since_activity")if reported_idle is not None:- idle_seconds = max(0.0, float(reported_idle))+ idle_seconds = awake_idle.measure(max(0.0, float(reported_idle)))# Preserve the most recent usable activity clock as the fallback if# a later provider-side diagnostic read raises or returns None.activity_origin = now - idle_secondsdiff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex b6c1dc22135..28a16f9fe5e 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -490,6 +490,10 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)if _resolved_idle is not None:_stale_idle = _resolved_idle_activity_summary_valid = True+ # Host sleep is not idleness: share the turn poll loop's meter (same event loop).+ _awake_idle = getattr(_quick_state.turn.ctx, "awake_idle", None)+ if _awake_idle is not None:+ _stale_idle = _awake_idle.measure(_stale_idle)_stale_detail = (f" | last_activity={_sa_d.get('last_activity_desc', 'unknown')} "f"({_stale_idle:.0f}s ago) "diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 8ca7e00944c..683e61e8db2 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1647,7 +1647,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewayif worker.agent_timeout is not None:if worker.timeout_fired.is_set():break- _idle_secs = self._agent_activity_summary(agent_holder[0]).get("seconds_since_activity", 0.0)+ _idle_secs = turn_ctx.awake_idle.measure(self._agent_activity_summary(agent_holder[0]).get("seconds_since_activity", 0.0))if not _warning_fired and worker.agent_warning is not None and _idle_secs >= worker.agent_warning:_warning_fired = Trueawait self._run_agent_inactivity_warning(worker, turn_ctx.source, turn_ctx._status_thread_metadata)diff --git a/gateway/turn_context.py b/gateway/turn_context.pyindex d0f781bd04b..13bb65776cf 100644--- a/gateway/turn_context.py+++ b/gateway/turn_context.py@@ -10,6 +10,8 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom typing import Any, Callable, List, Optional+from agent.session_activity import AwakeIdleMeter+@dataclassclass TurnContext:@@ -35,6 +37,8 @@ class TurnContext:repeat_count: list = field(default_factory=lambda: [0])long_tool_hint_fired: list = field(default_factory=lambda: [False])agent_holder: list = field(default_factory=lambda: [None])+ # Turn-scoped so the poll loop and stale-agent eviction both discount host sleep from idle.+ awake_idle: AwakeIdleMeter = field(default_factory=AwakeIdleMeter)_LONG_TOOL_THRESHOLD_S: float = 30.0_cleanup_progress: bool = False_cleanup_msg_ids: list[str] = field(default_factory=list)diff --git a/tests/gateway/test_gateway_watchdog_host_sleep.py b/tests/gateway/test_gateway_watchdog_host_sleep.pynew file mode 100644index 00000000000..b4055b1e057--- /dev/null+++ b/tests/gateway/test_gateway_watchdog_host_sleep.py@@ -0,0 +1,140 @@+"""Gateway inactivity watchdogs must not charge host sleep (laptop lid closed) as turn idleness.++The agent's ``seconds_since_activity`` is wall-clock; after resume the first watchdog poll reads+the whole sleep as idle and killed / warned / evicted a turn that never had a chance to run.+Sleep is simulated by advancing the wall clock while ``time.monotonic()`` stays put, which is+what ``CLOCK_MONOTONIC`` / ``mach_absolute_time`` do across suspend.+"""++import asyncio+import threading+from types import SimpleNamespace++import pytest++from agent import session_activity+import gateway.run as gateway_run+from gateway.run import GatewayRunner, _watch_gateway_turn_inactivity+from gateway.session_state import TurnState+from gateway.turn_context import TurnContext++TIMEOUT_S = 1800.0+SLEEP_S = 2000.0+++class _Clock:+ def __init__(self):+ self.wall = 1_000_000.0+ self.mono = 500.0++ def time(self):+ return self.wall++ def monotonic(self):+ return self.mono++ def sleep(self, seconds):+ self.wall += seconds++ def awake(self, seconds):+ self.wall += seconds+ self.mono += seconds+++def clock(monkeypatch):+ fake = _Clock()+ monkeypatch.setattr(session_activity, "time", fake)+ return fake+++class _ScriptedAgent:+ """Each activity read applies the next clock step, then reports wall-clock idle since the+ agent's last activity (stamped at clock creation)."""++ def __init__(self, clock, steps):+ self._clock = clock+ self._origin = clock.wall+ self._steps = list(steps)+ self.reads = 0++ def get_activity_summary(self):+ if self._steps:+ self._steps.pop(0)(self._clock)+ self.reads += 1+ return {"seconds_since_activity": self._clock.wall - self._origin}+++def _resume_then_idle_steps():+ return [lambda c: c.awake(1.0), lambda c: c.sleep(SLEEP_S), lambda c: c.awake(TIMEOUT_S)]+++def test_turn_watchdog_thread_ignores_host_sleep(clock, monkeypatch):+ agent = _ScriptedAgent(clock, _resume_then_idle_steps())+ fired_at_read = []+ monkeypatch.setattr(+ gateway_run, "_abandon_timed_out_gateway_turn", lambda **_kw: fired_at_read.append(agent.reads))++ _watch_gateway_turn_inactivity(+ agent_holder=[agent], task_id="t", process_baseline=None, timeout=TIMEOUT_S,+ worker_done=threading.Event(), timeout_fired=threading.Event(),+ cleanup_lock=threading.Lock(), poll_interval=0.01)++ # Read 2 is the first poll after resume (2001 s wall idle, 1 s awake): it must not fire.+ assert fired_at_read == [3]+++async def test_turn_poll_loop_ignores_host_sleep(clock, monkeypatch):+ turn_ctx = TurnContext()+ agent = _ScriptedAgent(clock, [lambda c: c.sleep(SLEEP_S), lambda c: c.awake(TIMEOUT_S)])+ turn_ctx.agent_holder[0] = agent+ runner = object.__new__(GatewayRunner)+ runner._agent_activity_summary = lambda a: a.get_activity_summary()+ warned_at_read = []+ fired_at_read = []++ async def _warn(*_args):+ warned_at_read.append(agent.reads)++ async def _no_backup_check(*_args):+ return None++ async def _poll_without_waiting(_fs, timeout=None):+ await asyncio.sleep(0)+ return set(), set()++ runner._run_agent_inactivity_warning = _warn+ runner._run_agent_backup_interrupt_check = _no_backup_check+ runner._run_agent_timeout_result = lambda _worker, _ctx: "timed out"+ monkeypatch.setattr(asyncio, "wait", _poll_without_waiting)+ monkeypatch.setattr(+ gateway_run, "_abandon_timed_out_gateway_turn", lambda **_kw: fired_at_read.append(agent.reads))+ worker = GatewayRunner._RunAgentWorker(+ agent_timeout=TIMEOUT_S, agent_warning=900.0, task_id="t", process_baseline=None,+ worker_done=threading.Event(), timeout_fired=threading.Event(),+ cleanup_lock=threading.Lock(), is_current=lambda: True)+ worker.executor_task = object()++ result = await runner._run_agent_await_turn_worker(worker, turn_ctx, asyncio.Event(), None)++ assert result == "timed out"+ assert warned_at_read == [2]+ assert agent.reads == 2+++def test_stale_agent_eviction_ignores_host_sleep(clock, monkeypatch):+ monkeypatch.setenv("HERMES_AGENT_TIMEOUT", str(TIMEOUT_S))+ turn = TurnState(ctx=TurnContext(), started_ts=clock.wall)+ agent = _ScriptedAgent(clock, [lambda c: c.sleep(SLEEP_S), lambda c: c.awake(TIMEOUT_S)])+ turn.agent = agent+ runner = object.__new__(GatewayRunner)+ runner._peek_session_state = lambda _key: SimpleNamespace(turn=turn)+ evicted_at_read = []+ runner._hm_evict_running_agent = lambda _key, _reason: evicted_at_read.append(agent.reads)++ runner._hm_evict_idle_stale_agent("k")+ assert evicted_at_read == []++ runner._hm_evict_idle_stale_agent("k")+ assert evicted_at_read == [2]