Skip to content

The agent that grows with you

fix(cron): live-owner stale-claim reclaim measures silence, not run length

Tekniumed2dd0b35ced
diff --git a/cron/executions.py b/cron/executions.py
index 32a5ce4728d..5b8585d41dc 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -91,6 +91,7 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
)
add_column_if_missing(conn, "executions", "delivery_outcome", "delivery_outcome TEXT")
add_column_if_missing(conn, "executions", "scheduled_instant", "scheduled_instant TEXT")
+ add_column_if_missing(conn, "executions", "progress_at", "progress_at TEXT")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_executions_occurrence "
"ON executions(job_id, scheduled_instant) WHERE status='completed'"
@@ -174,6 +175,29 @@ def _claim_age_seconds(claimed_at: str) -> float:
return (_hermes_now() - datetime.fromisoformat(claimed_at)).total_seconds()
+def _stale_age_seconds(claimed_at: str, progress_at: Optional[str]) -> float:
+ """Seconds since the owner last proved it was making progress.
+
+ A wedged worker (#115692) stops stamping ``progress_at``; a long but healthy run keeps
+ stamping it, so the derived stale bound measures silence, not run length. Rows written
+ before the column existed have no stamp and fall back to claim age.
+ """
+ return _claim_age_seconds(progress_at or claimed_at)
+
+
+def touch_execution_progress(execution_id: str) -> bool:
+ """Stamp ``progress_at`` on a running attempt this process owns. Returns False when the row
+ is no longer ours or no longer running (the caller treats that as informational only)."""
+ now = _hermes_now().isoformat()
+ with _transaction() as conn:
+ cur = conn.execute(
+ """UPDATE executions SET progress_at=?
+ WHERE id=? AND status IN ('claimed','running') AND process_id=? AND pid=?""",
+ (now, execution_id, _PROCESS_ID, os.getpid()),
+ )
+ return cur.rowcount == 1
+
+
def _prune_unlocked(conn: sqlite3.Connection) -> None:
conn.execute(
"""DELETE FROM executions WHERE id IN (
@@ -346,7 +370,7 @@ def recover_interrupted_executions() -> int:
with _transaction() as conn:
rows = conn.execute(
"""SELECT id, status, process_id, pid, process_started_at,
- handoff_pending, handoff_started_at, claimed_at
+ handoff_pending, handoff_started_at, claimed_at, progress_at
FROM executions
WHERE status IN ('claimed','running')"""
).fetchall()
@@ -357,16 +381,21 @@ def recover_interrupted_executions() -> int:
if _owner_is_live(int(row["pid"]), row["process_started_at"]):
# A live owner is normally a legitimately running job. A worker permanently
# deadlocked (e.g. futex_wait behind a route/proxy flip, #115692) also passes
- # this check, so a claim older than the derived bound is treated as wedged
- # and released — the external-worker wait loop polls this ledger for a
- # terminal status, so the job can fire again. The wedged worker PROCESS is
- # NOT terminated here (leaked until host restart); rows owned by this process
- # (process_id == _PROCESS_ID, in-process runs) are skipped above and remain
- # out of scope.
+ # this check, so a claim SILENT for longer than the derived bound is treated
+ # as wedged and released — the external-worker wait loop polls this ledger
+ # for a terminal status, so the job can fire again. Silence is measured from
+ # the owner's last ``progress_at`` stamp (the run monitor refreshes it while
+ # the agent is active), so a healthy multi-hour run is never reclaimed while
+ # it is still working. The wedged worker PROCESS is NOT terminated here
+ # (leaked until host restart); rows owned by this process (process_id ==
+ # _PROCESS_ID, in-process runs) are skipped above and remain out of scope.
if not stale_after_resolved:
stale_after = _live_owner_stale_after_seconds()
stale_after_resolved = True
- if stale_after is None or _claim_age_seconds(row["claimed_at"]) <= stale_after:
+ if (
+ stale_after is None
+ or _stale_age_seconds(row["claimed_at"], row["progress_at"]) <= stale_after
+ ):
continue
reason = _OWNER_WEDGED_REASON
handoff_started_at = row["handoff_started_at"]
diff --git a/cron/scheduler.py b/cron/scheduler.py
index c126e57bd72..ad55899d6a4 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -520,6 +520,7 @@ from cron.executions import (
_TERMINAL_STATES, HANDOFF_ADOPTION_GRACE_SECONDS, create_execution, finish_execution,
get_execution, mark_execution_handoff_pending, mark_execution_running,
recover_interrupted_executions, settle_unstarted_execution, terminalize_dead_owner)
+from cron.scheduler_liveness import ExecutionProgressStamper, _inactivity_watchdog_loop
# Response marker that suppresses delivery (output is still saved locally for audit).
SILENT_MARKER = "[SILENT]"
@@ -1192,33 +1193,6 @@ def _consume_interrupted_flag(job_id: str, token: Optional[object] = None) -> bo
return hit
-def _inactivity_watchdog_loop(
- *, get_idle_seconds: Callable[[], float], limit_s: float, poll_s: float, stop: threading.Event,
- 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.
-
- Driven by ``threading.Event.wait`` (a kernel timeout), not asyncio, so a blocked event-loop /
- ``run_job`` thread cannot disable this watchdog the way ``asyncio.sleep`` / ``wait_for`` would (family A
- of #94285 — the 4118s-idle-on-a-600s-limit cron hang). Returns True when *limit_s* of inactivity was
- observed.
- """
- # A sleeping host freezes the job with it, so time asleep never counts as inactivity.
- if meter is None:
- meter = AwakeIdleMeter()
- while not stop.wait(poll_s):
- if future_done():
- return False
- try:
- idle = float(get_idle_seconds() or 0.0)
- except Exception:
- idle = 0.0
- if meter.measure(idle) >= limit_s:
- return True
- return False
-
-
def _cron_inactivity_seconds() -> float:
"""Parse HERMES_CRON_TIMEOUT (seconds). 0 = unlimited; bad input = 600. Shared by the
inactivity monitor and the cwd-lock bound so they can't drift: the lock bound must stay >= the
@@ -2026,6 +2000,10 @@ def _run_agent_with_watchdog(
_watch_thread = threading.Thread(
target=_watch_inactivity, name=f"cron-inactivity-{str(job_id)[:8]}", daemon=True)
+ # Ledger progress stamps: the stale-claim sweep measures silence since the last stamp.
+ _progress = ExecutionProgressStamper(
+ str(job.get("execution_id") or ""), job_name, idle_seconds=_idle_seconds,
+ every_seconds=_RUN_CLAIM_HEARTBEAT_SECONDS)
try:
if _cron_inactivity_limit is not None:
# Separate daemon thread so a hung get_activity_summary can't stop the limit firing.
@@ -2047,6 +2025,7 @@ def _run_agent_with_watchdog(
break
_abort_if_fire_claim_lost()
_heartbeat_run_claim_if_due()
+ _progress.tick()
except Exception:
_cron_pool.shutdown(wait=False, cancel_futures=True)
raise
diff --git a/cron/scheduler_liveness.py b/cron/scheduler_liveness.py
new file mode 100644
index 00000000000..9602f5253c4
--- /dev/null
+++ b/cron/scheduler_liveness.py
@@ -0,0 +1,77 @@
+"""Liveness side of a running cron job: the inactivity watchdog loop and the execution-ledger
+progress stamps.
+
+Both read the same signal (the agent's idle time) and act on opposite edges of it. The
+watchdog interrupts the run once idle time crosses the configured limit. The stamper refreshes
+``progress_at`` while idle time stays short, so the live-owner stale-claim sweep (#115692)
+measures silence since the last stamp rather than run length: a busy multi-hour job keeps
+stamping and is never reclaimed under a healthy owner, while a wedged worker reports growing
+idle time, stops stamping, and is still released once the derived bound passes.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+from typing import Callable, Optional
+
+from agent.session_activity import AwakeIdleMeter
+from cron.executions import touch_execution_progress
+
+logger = logging.getLogger(__name__)
+
+
+def _inactivity_watchdog_loop(
+ *, get_idle_seconds: Callable[[], float], limit_s: float, poll_s: float, stop: threading.Event,
+ 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.
+
+ Driven by ``threading.Event.wait`` (a kernel timeout), not asyncio, so a blocked event-loop /
+ ``run_job`` thread cannot disable this watchdog the way ``asyncio.sleep`` / ``wait_for`` would (family A
+ of #94285 — the 4118s-idle-on-a-600s-limit cron hang). Returns True when *limit_s* of inactivity was
+ observed.
+ """
+ # A sleeping host freezes the job with it, so time asleep never counts as inactivity.
+ if meter is None:
+ meter = AwakeIdleMeter()
+ while not stop.wait(poll_s):
+ if future_done():
+ return False
+ try:
+ idle = float(get_idle_seconds() or 0.0)
+ except Exception:
+ idle = 0.0
+ if meter.measure(idle) >= limit_s:
+ return True
+ return False
+
+
+class ExecutionProgressStamper:
+ def __init__(
+ self, execution_id: str, job_name: str, *, idle_seconds: Callable[[], float],
+ every_seconds: float,
+ ):
+ self._execution_id = execution_id
+ self._job_name = job_name
+ self._idle_seconds = idle_seconds
+ self._every = every_seconds
+ self._last = time.monotonic()
+
+ def tick(self) -> None:
+ if not self._execution_id:
+ return
+ now = time.monotonic()
+ if now - self._last < self._every:
+ return
+ # Idle past the cadence means the agent itself stopped: no stamp, so the ledger goes
+ # quiet exactly when the watchdog would.
+ if self._idle_seconds() >= self._every:
+ return
+ self._last = now
+ try:
+ touch_execution_progress(self._execution_id)
+ except Exception:
+ logger.debug("Job '%s': execution progress stamp failed", self._job_name, exc_info=True)
diff --git a/tests/cron/test_cron_inactivity_timeout.py b/tests/cron/test_cron_inactivity_timeout.py
index a5df678cef2..11fe6f619b2 100644
--- a/tests/cron/test_cron_inactivity_timeout.py
+++ b/tests/cron/test_cron_inactivity_timeout.py
@@ -11,7 +11,7 @@ class TestInactivityWatchdogLoop:
"""The daemon-thread inactivity helper must not depend on the caller thread."""
def test_fires_when_idle_crosses_limit(self):
- from cron.scheduler import _inactivity_watchdog_loop
+ from cron.scheduler_liveness import _inactivity_watchdog_loop
stop = threading.Event()
idle = {"s": 0.0}
@@ -38,7 +38,7 @@ class TestInactivityWatchdogLoop:
assert not watcher.is_alive()
def test_stops_when_future_completes_before_idle_limit(self):
- from cron.scheduler import _inactivity_watchdog_loop
+ from cron.scheduler_liveness import _inactivity_watchdog_loop
stop = threading.Event()
fired = _inactivity_watchdog_loop(
@@ -52,7 +52,7 @@ class TestInactivityWatchdogLoop:
def test_fires_while_caller_thread_is_blocked(self):
"""#94285: a blocked run_job thread must not disable the watchdog."""
- from cron.scheduler import _inactivity_watchdog_loop
+ from cron.scheduler_liveness import _inactivity_watchdog_loop
stop = threading.Event()
idle = {"s": 1.0}
@@ -84,7 +84,7 @@ class TestHostSleep:
@pytest.mark.parametrize("during_sample", [False, True])
def test_sleep_is_not_idle_time_but_awake_idle_still_fires(self, monkeypatch, during_sample):
from agent import session_activity
- from cron.scheduler import _inactivity_watchdog_loop
+ from cron.scheduler_liveness 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)
diff --git a/tests/cron/test_execution_progress_stamp.py b/tests/cron/test_execution_progress_stamp.py
new file mode 100644
index 00000000000..d0c8a3f712f
--- /dev/null
+++ b/tests/cron/test_execution_progress_stamp.py
@@ -0,0 +1,77 @@
+"""The run monitor stamps ``progress_at`` on the execution row while the agent is active.
+
+The live-owner stale-claim sweep (#115692) reclaims a running row once it has been silent
+for the derived bound. Before this stamp existed the bound was measured from ``claimed_at``,
+so any healthy job that simply ran longer than ~2 h was reclaimed mid-run, its fire claim
+yanked and the run aborted with "lost its durable fire claim ownership".
+"""
+
+from __future__ import annotations
+
+import threading
+
+import pytest
+
+import cron.executions as executions_mod
+from cron import scheduler
+from cron.executions import _transaction, create_execution, mark_execution_running
+
+
[email protected](autouse=True)
+def _ledger(monkeypatch, tmp_path):
+ monkeypatch.setattr(executions_mod, "EXECUTIONS_FILE", tmp_path / "cron" / "executions.db")
+
+
+def _progress_at(execution_id: str):
+ with _transaction() as conn:
+ return conn.execute(
+ "SELECT progress_at FROM executions WHERE id=?", (execution_id,)
+ ).fetchone()["progress_at"]
+
+
+def test_active_run_stamps_progress_and_idle_run_does_not(monkeypatch):
+ stamp_every = 0.05
+ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", stamp_every)
+ monkeypatch.setattr(scheduler, "_cron_inactivity_seconds", lambda: 3600.0)
+ # The monitor polls concurrent.futures.wait(timeout=_POLL_INTERVAL); shorten the local
+ # constant so the stamp cadence is observable within the test.
+ monkeypatch.setattr(
+ scheduler.concurrent.futures, "wait",
+ lambda fs, timeout=None: scheduler.concurrent.futures._base.wait(fs, timeout=0.01),
+ )
+
+ finish = threading.Event()
+
+ class Agent:
+ def __init__(self, idle):
+ self._idle = idle
+
+ def get_activity_summary(self):
+ return {"seconds_since_activity": self._idle}
+
+ def run_conversation(self, *a, **k):
+ finish.wait(2)
+ return {"final_response": "ok"}
+
+ def interrupt(self, *a, **k):
+ finish.set()
+
+ def run(idle_seconds):
+ finish.clear()
+ execution = create_execution("job-progress", source="cron")
+ mark_execution_running(execution["id"])
+ job = {"id": "job-progress", "execution_id": execution["id"], "schedule": {"kind": "every"}}
+ timer = threading.Timer(0.4, finish.set)
+ timer.start()
+ try:
+ scheduler._run_agent_with_watchdog(
+ Agent(idle_seconds), "probe", job, "job-progress", "job-progress", "task", None)
+ finally:
+ timer.cancel()
+ return _progress_at(execution["id"])
+
+ # Active agent (idle 0s): the row is stamped.
+ assert run(idle_seconds=0.0) is not None
+ # An agent that reports idleness past the stamp cadence is silent in the ledger too: a wedged
+ # worker must not keep refreshing its own liveness.
+ assert run(idle_seconds=stamp_every * 10) is None
diff --git a/tests/cron/test_stale_running_recovery.py b/tests/cron/test_stale_running_recovery.py
index 0616088d23c..63fd97d6641 100644
--- a/tests/cron/test_stale_running_recovery.py
+++ b/tests/cron/test_stale_running_recovery.py
@@ -56,6 +56,25 @@ def test_live_owner_stale_claim_gets_recovered(monkeypatch):
assert recover_interrupted_executions() == 1
assert _status(eid) == "unknown"
+ # A claim older than the bound whose owner stamped progress recently is a long healthy
+ # run, not a wedge: the bound measures silence since ``progress_at``, not run length.
+ busy = _seed_running("job-busy", age_seconds=bound + 60, pid=66666)
+ with _transaction() as conn:
+ conn.execute(
+ "UPDATE executions SET progress_at=? WHERE id=?",
+ ((_hermes_now() - timedelta(seconds=120)).isoformat(), busy),
+ )
+ assert recover_interrupted_executions() == 0
+ assert _status(busy) == "running"
+ # Once the stamps stop for longer than the bound, the same row is reclaimed.
+ with _transaction() as conn:
+ conn.execute(
+ "UPDATE executions SET progress_at=? WHERE id=?",
+ ((_hermes_now() - timedelta(seconds=bound + 1)).isoformat(), busy),
+ )
+ assert recover_interrupted_executions() == 1
+ assert _status(busy) == "unknown"
+
# A larger inactivity timeout widens the bound: the same age is no longer stale.
monkeypatch.setenv("HERMES_CRON_TIMEOUT", "3600")
assert executions_mod._live_owner_stale_after_seconds() == pytest.approx(10800.0)
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index 6e5723b78c3..77c87df1424 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -399,7 +399,12 @@ move through `claimed`, `running`, and one immutable terminal state:
`hermes cron run` / `/cron run`, so a one-shot invocation with no scheduler
running heals the ledger too — Hermes marks an abandoned attempt `unknown` only
when the original PID and process-start fingerprint prove that its owner is
-gone. Unknown attempts are audit records and are never automatically rerun.
+gone, or when a live owner has been **silent** for longer than the derived
+stale bound (`max(3 × HERMES_CRON_TIMEOUT, script timeout, 2 h)`): the run
+monitor stamps `progress_at` on the attempt while the agent is still calling
+tools or streaming, so a healthy multi-hour job is never reclaimed mid-run, while
+a worker deadlocked on a lock stops stamping and is released once the bound
+passes. Unknown attempts are audit records and are never automatically rerun.
Inspect recent attempts with `hermes cron runs [job-id] --limit 20` (alias:
`history`). Terminal history is bounded; active attempts are never pruned. The