The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): stop counting host sleep as job inactivity
KJH2f267112ce5d
diff --git a/agent/session_activity.py b/agent/session_activity.pyindex 0a06b9e5e7d..079a4a461ac 100644--- a/agent/session_activity.py+++ b/agent/session_activity.py@@ -116,3 +116,27 @@ def build_activity_snapshot("last_activity_ts": when, "last_activity_desc": desc, "description": desc, "provenance": prov,**(extra or {}),}+++class AwakeIdleMeter:+ """Removes host sleep from a polling watchdog's idle readings.++ Idle time is measured on the wall clock, which keeps running while the host sleeps, so a laptop+ that sleeps 15 minutes mid-turn wakes up "idle" for 15 minutes and the first poll after resume+ kills a turn that never had a chance to run. ``time.monotonic()`` pauses during sleep on macOS+ (``mach_absolute_time``) and Linux (``CLOCK_MONOTONIC``), so the two clocks drift apart by the+ time spent asleep. Call :meth:`measure` once per poll with the wall-clock idle seconds.+ """++ def __init__(self) -> None:+ self._wall, self._mono = time.time(), time.monotonic()+ self._asleep_s = 0.0++ def measure(self, idle_s: float) -> float:+ """Return *idle_s* minus the sleep observed since the agent's last activity."""+ wall, mono = time.time(), time.monotonic()+ self._asleep_s += max(0.0, (wall - self._wall) - (mono - self._mono))+ self._wall, self._mono = wall, mono+ # New activity pulls idle below the credit, which then drops with it (to within one poll).+ self._asleep_s = max(0.0, min(self._asleep_s, idle_s))+ return idle_s - self._asleep_sdiff --git a/agent/turn_liveness.py b/agent/turn_liveness.pyindex db5da80f429..c0b00c0cc0c 100644--- a/agent/turn_liveness.py+++ b/agent/turn_liveness.py@@ -16,6 +16,8 @@ import threadingimport timefrom typing import Any, Callable, Dict, NamedTuple, Optional, Tuple+from agent.session_activity import AwakeIdleMeter+logger = logging.getLogger(__name__)DEFAULT_TURN_LIVENESS_TIMEOUT_S = 600.0@@ -108,6 +110,8 @@ class TurnLivenessWatchdog:self._is_turn_active = is_turn_activeself._commit_abort = commit_abortself._deactivate_turn = deactivate_turn+ # A sleeping host is not a stalled turn: time asleep never counts toward the bound.+ self._awake_idle = AwakeIdleMeter()def schedule(self):"""Start polling via the shared periodic scheduler; returns the cancel handle.@@ -123,7 +127,7 @@ class TurnLivenessWatchdog:snapshot = self._sample()if snapshot is None:return False # turn no longer active- if snapshot.idle_seconds < self._timeout_s:+ if self._awake_idle.measure(snapshot.idle_seconds) < self._timeout_s:return None# Observational only: the commit below can still veto the abort if progress# resumed; the definitive settlement is _surface_committed_abort.diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..e6b578dfec4--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1 @@+kohjunhaodiff --git a/cron/scheduler.py b/cron/scheduler.pyindex 8365a8dc02e..9b210bfd701 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -48,6 +48,7 @@ from agent.interrupt_compat import request_hard_interruptfrom agent.delegation_context import (enter_non_dispatcher_owned_context, exit_non_dispatcher_owned_context)from agent.memory_provider import ctx_bound+from agent.session_activity import AwakeIdleMeterfrom agent.turn_failure_copy import is_max_iteration_handofflogger = logging.getLogger(__name__)@@ -1217,6 +1218,8 @@ def _inactivity_watchdog_loop(of #94285 — the 4118s-idle-on-a-600s-limit cron hang). Returns True when *limit_s* of inactivity wasobserved."""+ # A sleeping host freezes the job with it, so time asleep never counts as inactivity.+ meter = AwakeIdleMeter()while not stop.wait(poll_s):if future_done():return False@@ -1224,7 +1227,7 @@ def _inactivity_watchdog_loop(idle = float(get_idle_seconds() or 0.0)except Exception:idle = 0.0- if idle >= limit_s:+ if meter.measure(idle) >= limit_s:return Truereturn Falsediff --git a/tests/agent/test_turn_liveness_watchdog.py b/tests/agent/test_turn_liveness_watchdog.pyindex 4a1c02ca71d..cd19ba7fb42 100644--- a/tests/agent/test_turn_liveness_watchdog.py+++ b/tests/agent/test_turn_liveness_watchdog.py@@ -753,3 +753,39 @@ def test_declined_abort_does_not_cancel_pending_compression_commit():"cancelled: begin_commit() refused")fence.finish_commit()+++def test_host_sleep_is_not_a_stalled_turn(monkeypatch):+ """A host that sleeps mid-turn wakes with a wall-clock activity stamp as old as the nap.+ The nap is not a stall; awake silence after it still aborts at the bound."""+ from types import SimpleNamespace+ from unittest.mock import MagicMock++ from agent import activity_tracking, session_activity, turn_liveness++ # Wall time keeps running while the host sleeps; monotonic time pauses (macOS, Linux).+ clock = SimpleNamespace(wall=1000.0, mono=1000.0)+ timer = SimpleNamespace(time=lambda: clock.wall, monotonic=lambda: clock.mono)+ for module in (activity_tracking, session_activity, turn_liveness):+ monkeypatch.setattr(module, "time", timer)+ agent = activity_tracking.ActivityTrackingMixin()+ agent._touch_activity("starting new turn")+ abort = MagicMock(return_value=True)+ watchdog = turn_liveness.TurnLivenessWatchdog(+ agent, session_id="test", timeout_s=600, poll_s=15,+ stop_event=threading.Event(), activity_lock=agent._liveness_activity_lock(),+ is_turn_active=lambda: True, commit_abort=abort, deactivate_turn=MagicMock(),+ )++ def poll(asleep=0.0):+ clock.mono += 15+ clock.wall += 15 + asleep+ return watchdog._tick()++ poll()+ poll(asleep=900.0) # 30s awake, then 15 minutes asleep: 930s of wall-clock silence+ abort.assert_not_called()+ while abort.call_count == 0 and clock.mono < 3000:+ poll()+ abort.assert_called_once()+ assert clock.mono - 1000.0 == 600.0diff --git a/tests/cron/test_cron_inactivity_timeout.py b/tests/cron/test_cron_inactivity_timeout.pyindex 47edcdc74b2..b3a6ac03153 100644--- a/tests/cron/test_cron_inactivity_timeout.py+++ b/tests/cron/test_cron_inactivity_timeout.py@@ -2,6 +2,7 @@import threadingimport time+from types import SimpleNamespaceclass TestInactivityWatchdogLoop:@@ -73,3 +74,39 @@ class TestInactivityWatchdogLoop:assert result["fired"] is Trueassert not watcher.is_alive()+++class TestHostSleep:+ """A sleeping host freezes the whole job, so the nap is not job inactivity."""++ def test_sleep_is_not_idle_time_but_awake_idle_still_fires(self, monkeypatch):+ from agent import session_activity+ from cron.scheduler import _inactivity_watchdog_loop++ # Wall time keeps running while the host sleeps; monotonic time pauses (macOS, Linux).+ clock = SimpleNamespace(wall=1_000_000.0, mono=50.0)+ monkeypatch.setattr(+ session_activity, "time", SimpleNamespace(time=lambda: clock.wall, monotonic=lambda: clock.mono))+ last_activity_wall, start_mono = clock.wall, clock.mono+ polls = []++ class _Stop:+ def wait(self, timeout):+ polls.append(timeout)+ clock.wall += timeout+ clock.mono += timeout+ if len(polls) == 3:+ clock.wall += 900.0 # the laptop sleeps for 15 minutes mid-job+ return len(polls) > 1000++ fired = _inactivity_watchdog_loop(+ get_idle_seconds=lambda: clock.wall - last_activity_wall,+ limit_s=600.0,+ poll_s=5.0,+ stop=_Stop(),+ future_done=lambda: False,+ )++ assert fired is True+ awake_idle = clock.mono - start_mono+ assert 600.0 <= awake_idle < 605.0diff --git a/website/docs/developer-guide/cron-internals.md b/website/docs/developer-guide/cron-internals.mdindex d0ddd4175ef..610f6f26642 100644--- a/website/docs/developer-guide/cron-internals.md+++ b/website/docs/developer-guide/cron-internals.md@@ -306,7 +306,7 @@ The script timeout defaults to 3600 seconds (1 hour). `_get_script_timeout()` re3. **Config** — `cron.script_timeout_seconds` in `config.yaml` (read via `load_config()`)4. **Default** — 3600 seconds (1 hour)-This timeout bounds the **pre-run script only**, not the agent. Skill-based / LLM-driven jobs run on a separate *inactivity*-based budget (`HERMES_CRON_TIMEOUT`, default 600s of idle time, `0` = unlimited) — they can run for hours as long as they keep calling tools or streaming tokens, and are only killed after the configured idle period with no activity. Scripts are dispatched to a persistent thread pool (not held under the tick lock), so a long-running script does not block other due jobs from firing.+This timeout bounds the **pre-run script only**, not the agent. Skill-based / LLM-driven jobs run on a separate *inactivity*-based budget (`HERMES_CRON_TIMEOUT`, default 600s of idle time, `0` = unlimited) — they can run for hours as long as they keep calling tools or streaming tokens, and are only killed after the configured idle period with no activity. Time the host spends asleep does not count toward that idle period. Scripts are dispatched to a persistent thread pool (not held under the tick lock), so a long-running script does not block other due jobs from firing.On timeout or ownership cancellation, `cron.scheduler_script` uses the shared`agent.deadline.kill_process_tree` hard-kill path. On POSIX it briefly stops and