Skip to content

The agent that grows with you

fix(cron): establish suspend baseline before worker startup

unsupportedpastels266f11c5c5d6
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 9b210bfd701..7a9b08ff541 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -1208,7 +1208,7 @@ def _consume_interrupted_flag(job_id: str, token: Optional[object] = None) -> bo
def _inactivity_watchdog_loop(
*, get_idle_seconds: Callable[[], float], limit_s: float, poll_s: float, stop: threading.Event,
- future_done: Callable[[], bool],
+ future_done: Callable[[], bool], meter: Optional[AwakeIdleMeter] = None,
) -> bool:
"""Poll idle time until limit (-> True), stop, or the future completes (-> False). Uses
``threading.Event.wait``, not asyncio, so a blocked event loop cannot disable the watchdog.
@@ -1219,7 +1219,8 @@ def _inactivity_watchdog_loop(
observed.
"""
# A sleeping host freezes the job with it, so time asleep never counts as inactivity.
- meter = AwakeIdleMeter()
+ if meter is None:
+ meter = AwakeIdleMeter()
while not stop.wait(poll_s):
if future_done():
return False
@@ -2006,6 +2007,8 @@ def _run_agent_with_watchdog(
except Exception:
logger.debug("Job '%s': run_claim heartbeat failed", job_name, exc_info=True)
+ # Establish suspend accounting before the worker can stamp its first activity.
+ _awake_idle = AwakeIdleMeter()
_cron_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
# Carry scheduler-scoped ContextVar state (e.g. env passthrough) into the worker thread.
_cron_context = contextvars.copy_context()
@@ -2031,7 +2034,7 @@ def _run_agent_with_watchdog(
return
if _inactivity_watchdog_loop(
get_idle_seconds=_idle_seconds, limit_s=_cron_inactivity_limit, poll_s=_POLL_INTERVAL,
- stop=_watch_stop, future_done=_cron_future.done):
+ stop=_watch_stop, future_done=_cron_future.done, meter=_awake_idle):
_inactivity_timeout = True
_watch_thread = threading.Thread(
diff --git a/tests/cron/test_cron_inactivity_timeout.py b/tests/cron/test_cron_inactivity_timeout.py
index 567d949be62..a5df678cef2 100644
--- a/tests/cron/test_cron_inactivity_timeout.py
+++ b/tests/cron/test_cron_inactivity_timeout.py
@@ -119,3 +119,59 @@ class TestHostSleep:
assert fired is True
awake_idle = clock.mono - start_mono
assert 600.0 <= awake_idle < 605.0
+
+
+def test_sleep_before_watchdog_thread_starts(monkeypatch):
+ """The worker can record activity before the watchdog gets its first timeslice."""
+ from agent import activity_tracking, session_activity
+ from cron import scheduler
+
+ clock = SimpleNamespace(wall=1000.0, mono=1000.0)
+ timer = SimpleNamespace(time=lambda: clock.wall, monotonic=lambda: clock.mono)
+ started, finish = threading.Event(), threading.Event()
+ interrupted_at = []
+
+ class Agent(activity_tracking.ActivityTrackingMixin):
+ def run_conversation(self, *args, **kwargs):
+ self._touch_activity("starting new turn")
+ started.set()
+ finish.wait(20)
+ return {"final_response": "finished"}
+
+ def get_activity_summary(self):
+ return session_activity.build_activity_snapshot(
+ last_activity_at=self._last_activity_ts,
+ last_activity_description=self._last_activity_desc)
+
+ def interrupt(self, message, **kwargs):
+ interrupted_at.append(clock.mono - 1000.0)
+ finish.set()
+
+ original_start, original_wait = threading.Thread.start, threading.Event.wait
+
+ def start(thread):
+ if thread.name.startswith("cron-inactivity-"):
+ assert started.wait(5), "worker did not start"
+ clock.wall += 900
+ return original_start(thread)
+
+ def wait(event, timeout=None):
+ if threading.current_thread().name.startswith("cron-inactivity-") and timeout == 5.0:
+ clock.wall += timeout
+ clock.mono += timeout
+ return event.is_set()
+ return original_wait(event, timeout)
+
+ for module in (activity_tracking, session_activity, scheduler):
+ monkeypatch.setattr(module, "time", timer)
+ monkeypatch.setattr(threading.Thread, "start", start)
+ monkeypatch.setattr(threading.Event, "wait", wait)
+ monkeypatch.setattr(scheduler, "_cron_inactivity_seconds", lambda: 600.0)
+ try:
+ with pytest.raises(TimeoutError):
+ scheduler._run_agent_with_watchdog(
+ Agent(), "probe", {"schedule": {"kind": "every"}},
+ "probe", "probe", "probe", None)
+ finally:
+ finish.set()
+ assert interrupted_at and min(interrupted_at) >= 600.0