Skip to content

The agent that grows with you

fix(cron): wall-clock stale-claim guard for live-but-deadlocked workers (#115692)

holny086da1e0727e
diff --git a/cron/executions.py b/cron/executions.py
index 35dd8b5b607..9c793bf66d5 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -13,6 +13,7 @@ import threading
import time
import uuid
from contextlib import contextmanager
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional
@@ -25,6 +26,12 @@ from hermes_time import now as _hermes_now
EXECUTIONS_FILE: Optional[Path] = None
MAX_TERMINAL_EXECUTIONS = 1000
HANDOFF_ADOPTION_GRACE_SECONDS = 30.0
+# Wall-clock bound on a ``running`` execution whose owner process is still alive:
+# cron jobs are bounded by the inactivity watchdog (600 s) and the script timeout
+# (3600 s), so a run exceeding this ceiling is permanently wedged (e.g. deadlocked
+# on a futex behind a route flip, #115692) — never going to reach a terminal state
+# on its own. Generous enough that a legitimate long-running job is never cut off.
+STALE_RUNNING_CLAIM_TIMEOUT_SECONDS = 7200.0
_TERMINAL_STATES = ("completed", "failed", "unknown")
_lock = threading.RLock()
_PROCESS_ID = uuid.uuid4().hex
@@ -276,8 +283,8 @@ def recover_interrupted_executions() -> int:
recovered: List[Dict[str, Any]] = []
with _transaction() as conn:
rows = conn.execute(
- """SELECT id, status, process_id, pid, process_started_at,
- handoff_pending, handoff_started_at
+ """ SELECT id, status, process_id, pid, process_started_at,
+ handoff_pending, handoff_started_at, claimed_at
FROM executions
WHERE status IN ('claimed','running')"""
).fetchall()
@@ -285,7 +292,26 @@ def recover_interrupted_executions() -> int:
if row["process_id"] == _PROCESS_ID:
continue
if _owner_is_live(int(row["pid"]), row["process_started_at"]):
- continue
+ # Owner process is alive. In the vast majority of cases the job is
+ # still running legitimately. But a worker permanently deadlocked
+ # on a lock (e.g. futex_wait after a route/proxy flip, #115692)
+ # also passes this check — the bounded wall-clock guard below
+ # catches that class: a cron job cannot legitimately outlast the
+ # script timeout (3600 s) plus the inactivity watchdog (600 s).
+ stale_claim = False
+ claimed_at_str = row["claimed_at"]
+ if claimed_at_str:
+ try:
+ claimed_dt = datetime.fromisoformat(claimed_at_str)
+ if claimed_dt.tzinfo is None:
+ claimed_dt = claimed_dt.replace(tzinfo=timezone.utc)
+ elapsed = (datetime.now(timezone.utc) - claimed_dt).total_seconds()
+ if elapsed > STALE_RUNNING_CLAIM_TIMEOUT_SECONDS:
+ stale_claim = True
+ except (ValueError, TypeError):
+ pass
+ if not stale_claim:
+ continue
handoff_started_at = row["handoff_started_at"]
if (
row["handoff_pending"]
diff --git a/tests/cron/test_stale_running_recovery_115692.py b/tests/cron/test_stale_running_recovery_115692.py
new file mode 100644
index 00000000000..729fd25fd63
--- /dev/null
+++ b/tests/cron/test_stale_running_recovery_115692.py
@@ -0,0 +1,63 @@
+"""A live-but-deadlocked worker passes ``_owner_is_live()`` and never gets
+reclaimed. The wall-clock guard catches that: a claimed/running execution
+older than ``STALE_RUNNING_CLAIM_TIMEOUT_SECONDS`` is marked unknown even
+though the owner PID exists (#115692)."""
+import os
+import sqlite3
+import time
+import uuid
+
+import pytest
+
+from cron.executions import (
+ create_execution,
+ recover_interrupted_executions,
+ _transaction,
+)
+
+
+def _seed_running(job_id, claimed_at, pid=99999, proc="ext-proc"):
+ with _transaction() as conn:
+ eid = uuid.uuid4().hex
+ conn.execute(
+ """INSERT INTO executions
+ (id, job_id, status, source, process_id, pid, process_started_at, claimed_at)
+ VALUES (?, ?, 'running', 'cron', ?, ?, ?, ?)""",
+ (eid, job_id, proc, pid, int(time.time()), claimed_at),
+ )
+ return eid
+
+
+def test_live_owner_stale_claim_gets_recovered(tmp_path, monkeypatch):
+ """A claimed/running row whose owner is alive but stale past the wall-clock
+ guard must be marked unknown — a live-but-deadlocked worker otherwise
+ blocks every future fire forever (#115692)."""
+ monkeypatch.setattr("cron.executions._owner_is_live", lambda pid, sat: True)
+
+ # claimed_at = 3h ago (well past the 2h stale-claim timeout)
+ old = "2026-09-17T00:00:00"
+ eid = _seed_running("job-stale", claimed_at=old, pid=99999)
+
+ assert recover_interrupted_executions() >= 1
+
+ with _transaction() as conn:
+ row = conn.execute(
+ "SELECT status FROM executions WHERE id=?", (eid,)
+ ).fetchone()
+ assert row["status"] == "unknown"
+
+
+def test_live_owner_recent_claim_not_recovered(tmp_path, monkeypatch):
+ """A live owner with a recent claim must NOT be recovered (normal running)."""
+ monkeypatch.setattr("cron.executions._owner_is_live", lambda pid, sat: True)
+
+ now = time.strftime("%Y-%m-%dT%H:%M:%S")
+ eid = _seed_running("job-recent", claimed_at=now, pid=88888)
+
+ assert recover_interrupted_executions() == 0
+
+ with _transaction() as conn:
+ row = conn.execute(
+ "SELECT status FROM executions WHERE id=?", (eid,)
+ ).fetchone()
+ assert row["status"] == "running"