Skip to content

The agent that grows with you

fix(cron): derive the live-owner stale-claim bound from the configured timeouts

kshitijk4poorb552dc9a8c4b
diff --git a/cron/executions.py b/cron/executions.py
index 9c793bf66d5..5a15946f77d 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -7,6 +7,7 @@ immutable.
from __future__ import annotations
+import math
import os
import sqlite3
import threading
@@ -26,12 +27,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
+# Floor for the live-owner stale-claim bound (#115692); see _live_owner_stale_after_seconds.
+LIVE_OWNER_STALE_CLAIM_FLOOR_SECONDS = 7200.0
+# Headroom over the inactivity timeout, mirroring cron/jobs.py::_oneshot_run_claim_ttl_seconds:
+# HERMES_CRON_TIMEOUT is an *inactivity* limit, not a wall-clock cap, so healthy runs may
+# legitimately exceed it.
+_LIVE_OWNER_STALE_CLAIM_HEADROOM = 3
_TERMINAL_STATES = ("completed", "failed", "unknown")
_lock = threading.RLock()
_PROCESS_ID = uuid.uuid4().hex
@@ -141,6 +142,35 @@ def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:
return current is not None and current == started_at
+def _live_owner_stale_after_seconds() -> Optional[float]:
+ """Age past which a claimed/running row with a LIVE owner is treated as wedged.
+
+ Derived from the existing knobs, never a bare wall-clock constant:
+ ``max(3 × HERMES_CRON_TIMEOUT, cron script timeout, 7200)``. Returns ``None`` (never reclaim
+ live owners — today's behaviour) when the inactivity timeout is 0/unlimited or not a finite
+ positive number: with no bound to derive from, fail closed.
+ """
+ from cron.scheduler import _cron_inactivity_seconds
+ from cron.scheduler_script import _get_script_timeout
+
+ inactivity = float(_cron_inactivity_seconds())
+ if not math.isfinite(inactivity) or inactivity <= 0:
+ return None
+ return max(
+ inactivity * _LIVE_OWNER_STALE_CLAIM_HEADROOM,
+ float(_get_script_timeout()),
+ LIVE_OWNER_STALE_CLAIM_FLOOR_SECONDS,
+ )
+
+
+def _claim_age_seconds(claimed_at: str) -> float:
+ """Seconds since ``claimed_at`` (aware ISO from hermes_time.now; naive is read as UTC)."""
+ claimed_dt = datetime.fromisoformat(claimed_at)
+ if claimed_dt.tzinfo is None:
+ claimed_dt = claimed_dt.replace(tzinfo=timezone.utc)
+ return (datetime.now(timezone.utc) - claimed_dt).total_seconds()
+
+
def _prune_unlocked(conn: sqlite3.Connection) -> None:
conn.execute(
"""DELETE FROM executions WHERE id IN (
@@ -276,14 +306,26 @@ def finish_execution(
return record
+_OWNER_GONE_REASON = (
+ "Scheduler restarted after this execution's owner exited before a durable "
+ "terminal state; whether side effects ran is unknown."
+)
+_OWNER_WEDGED_REASON = (
+ "Owner process is still alive but the claim outlived the derived stale bound; "
+ "treated as wedged (#115692). The process was not terminated; whether side effects "
+ "ran is unknown."
+)
+
+
def recover_interrupted_executions() -> int:
"""Mark provably abandoned attempts unknown without scheduling retries."""
now = _hermes_now().isoformat()
changed = 0
recovered: List[Dict[str, Any]] = []
+ stale_after = _live_owner_stale_after_seconds()
with _transaction() as conn:
rows = conn.execute(
- """ SELECT id, status, process_id, pid, process_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')"""
@@ -291,27 +333,19 @@ def recover_interrupted_executions() -> int:
for row in rows:
if row["process_id"] == _PROCESS_ID:
continue
+ reason = _OWNER_GONE_REASON
if _owner_is_live(int(row["pid"]), row["process_started_at"]):
- # 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:
+ # 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.
+ if stale_after is None or _claim_age_seconds(row["claimed_at"]) <= stale_after:
continue
+ reason = _OWNER_WEDGED_REASON
handoff_started_at = row["handoff_started_at"]
if (
row["handoff_pending"]
@@ -327,10 +361,7 @@ def recover_interrupted_executions() -> int:
WHERE id=? AND status=? AND process_id=? AND pid=?
AND handoff_pending=?
AND handoff_started_at IS ?""",
- (now,
- "Scheduler restarted after this execution's owner exited before a durable "
- "terminal state; whether side effects ran is unknown.",
- row["id"], row["status"], row["process_id"], row["pid"],
+ (now, reason, row["id"], row["status"], row["process_id"], row["pid"],
row["handoff_pending"], row["handoff_started_at"]),
)
changed += cur.rowcount