Skip to content

The agent that grows with you

fix: re-arm wedged cron jobs to next legal occurrence, cache cadence

kshitij8a4b28f43946
diff --git a/cron/jobs.py b/cron/jobs.py
index a5427d53273..1aee6fff68d 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -966,7 +966,13 @@ def _schedule_cadence_seconds(schedule: Dict[str, Any]) -> Optional[float]:
Interval jobs use ``minutes * 60``. Cron jobs measure the gap between the
next two fire times with croniter (falling back to None when croniter is
- missing or the expr is malformed).
+ missing or the expr is malformed). Cron results are cached per expr —
+ this runs inside ``_jobs_lock`` on every tick for every stale-errored
+ job, and two croniter evaluations per call add up (the same reason
+ ``scheduler.py`` caches ``_cron_interval_minutes``). The measured gap
+ can vary with the base time for irregular exprs; the cache trades that
+ precision for not re-evaluating croniter under the lock, which is fine
+ for a staleness *threshold*.
"""
if not isinstance(schedule, dict):
return None
@@ -983,18 +989,26 @@ def _schedule_cadence_seconds(schedule: Dict[str, Any]) -> Optional[float]:
expr = schedule.get("expr")
if not expr:
return None
+ if expr in _cron_cadence_cache:
+ return _cron_cadence_cache[expr]
try:
base = _hermes_now()
it = croniter(expr, base)
first = it.get_next(datetime)
second = it.get_next(datetime)
gap = (second - first).total_seconds()
- return gap if gap > 0 else None
+ result = gap if gap > 0 else None
except Exception:
- return None
+ result = None
+ _cron_cadence_cache[expr] = result
+ return result
return None
+# Per-expr cache for _schedule_cadence_seconds' croniter measurements.
+_cron_cadence_cache: Dict[str, Optional[float]] = {}
+
+
def _record_persisted_error_recovery(job: Dict[str, Any], previous_next_run: str) -> None:
"""Persist a countable, probe-visible signal for one stale-error re-arm."""
global _persisted_error_recoveries
@@ -3228,30 +3242,54 @@ def _get_due_jobs_locked() -> List[Dict[str, Any]]:
# (errored once, next_run_at re-armed into the future by
# mark_job_run, but never re-dispatched — the restart-surviving
# half of the 2026-08-14 incident, invisible to the in-memory
- # in-flight sweep). Re-arm next_run_at to now so the next tick
- # returns it as due and re-dispatches it WITHOUT force-run/resume.
+ # in-flight sweep). Re-arm so the job re-dispatches WITHOUT
+ # force-run/resume:
+ # * interval jobs re-arm to now — interval schedules have no
+ # excluded times, so an immediate catch-up retry is always a
+ # legal fire (the 2026-08-14 incident jobs were intervals);
+ # * cron jobs re-arm to the next LEGAL occurrence from now —
+ # re-arming to now would fire at times the expression
+ # explicitly excludes (e.g. a weekday-only 9am job whose
+ # Friday run errored must fire Monday 9am, not Saturday).
+ # This still repairs values parked beyond the next legal
+ # occurrence; a correctly-parked cron value is left as-is.
if (
kind in ("cron", "interval")
and next_run_dt > now
and _job_is_stale_error_recurring(job, schedule, now)
):
jid = job.get("id")
- logger.warning(
- "cron.persisted_error.recovered job='%s' id=%s — recurring "
- "job wedged in stale last_status=error without re-firing for "
- "a full cadence; re-arming next_run_at to now so it "
- "re-dispatches without force-run/resume",
- job.get("name", jid),
- jid,
- )
- _record_persisted_error_recovery(job, next_run)
- job["next_run_at"] = now.isoformat()
- next_run_dt = now
- for rj in raw_jobs:
- if rj["id"] == jid:
- rj["next_run_at"] = now.isoformat()
- needs_save = True
- break
+ if kind == "interval":
+ recovered_next = now.isoformat()
+ recovered_next_dt = now
+ else:
+ recovered_next = compute_next_run(schedule, now.isoformat())
+ try:
+ recovered_next_dt = (
+ _ensure_aware(datetime.fromisoformat(recovered_next))
+ if recovered_next
+ else None
+ )
+ except (ValueError, TypeError):
+ recovered_next_dt = None
+ if recovered_next and recovered_next_dt is not None and recovered_next_dt < next_run_dt:
+ logger.warning(
+ "cron.persisted_error.recovered job='%s' id=%s — recurring "
+ "job wedged in stale last_status=error without re-firing for "
+ "a full cadence; re-arming next_run_at to %s so it "
+ "re-dispatches without force-run/resume",
+ job.get("name", jid),
+ jid,
+ recovered_next,
+ )
+ _record_persisted_error_recovery(job, next_run)
+ job["next_run_at"] = recovered_next
+ next_run_dt = recovered_next_dt
+ for rj in raw_jobs:
+ if rj["id"] == jid:
+ rj["next_run_at"] = recovered_next
+ needs_save = True
+ break
if next_run_dt <= now:
diff --git a/tests/cron/test_persisted_error_rearm_legality.py b/tests/cron/test_persisted_error_rearm_legality.py
new file mode 100644
index 00000000000..74370df3ce8
--- /dev/null
+++ b/tests/cron/test_persisted_error_rearm_legality.py
@@ -0,0 +1,106 @@
+"""The persisted-error re-arm must respect cron schedule legality.
+
+Salvage follow-up on PR #87261: re-arming a wedged CRON job to ``now`` would
+fire it at times the expression explicitly excludes (a weekday-only 9am job
+whose Friday run errored would fire on SATURDAY). Cron jobs re-arm to the
+next LEGAL occurrence instead; interval jobs (the 2026-08-14 incident class)
+still re-arm to now — an immediate catch-up is always legal for intervals.
+"""
+from __future__ import annotations
+
+import sys
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from unittest import mock
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+pytest.importorskip("croniter")
+
+import cron.jobs as J
+
+
+def cron_store(tmp_path, monkeypatch):
+ hermes_home = tmp_path / ".hermes"
+ (hermes_home / "cron").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setattr(J, "HERMES_DIR", hermes_home)
+ monkeypatch.setattr(J, "CRON_DIR", hermes_home / "cron")
+ monkeypatch.setattr(J, "JOBS_FILE", hermes_home / "cron" / "jobs.json")
+ monkeypatch.setattr(J, "OUTPUT_DIR", hermes_home / "cron" / "output")
+ J._cron_cadence_cache.clear()
+ monkeypatch.setattr(J, "_persisted_error_recoveries", 0)
+ monkeypatch.setattr(J, "_persisted_error_recoveries_recent", [])
+ return hermes_home
+
+
+def _wedge(job_id: str, *, next_run_at: datetime, last_run_at: datetime) -> None:
+ J.update_job(
+ job_id,
+ {
+ "next_run_at": next_run_at.isoformat(),
+ "last_status": "error",
+ "last_error": "EAGAIN [Errno 11] Resource temporarily unavailable",
+ "last_run_at": last_run_at.isoformat(),
+ },
+ )
+
+
+class TestCronRearmRespectsScheduleLegality:
+ def test_weekday_job_errored_friday_does_not_fire_on_saturday(self, cron_store):
+ """A '0 9 * * 1-5' job whose Friday 9am run errored must re-arm to
+ Monday 9am (the next legal occurrence), NOT to Saturday-now."""
+ job = J.create_job(prompt="weekday report", schedule="0 9 * * 1-5")
+ # Saturday 2026-08-22 12:00 UTC; Friday's run errored at 9am.
+ now = datetime(2026, 8, 22, 12, 0, tzinfo=timezone.utc)
+ _wedge(
+ job["id"],
+ # parked well past Monday (the wedge shape: stale error + future park)
+ next_run_at=datetime(2026, 8, 26, 9, 0, tzinfo=timezone.utc),
+ last_run_at=datetime(2026, 8, 21, 9, 0, tzinfo=timezone.utc),
+ )
+ with mock.patch.object(J, "_hermes_now", lambda: now):
+ due = J.get_due_jobs()
+ assert due == [], "Saturday must not fire a weekday-only job"
+ rearmed = J.get_job(job["id"])
+ next_dt = datetime.fromisoformat(rearmed["next_run_at"])
+ assert next_dt == datetime(2026, 8, 24, 9, 0, tzinfo=timezone.utc), (
+ f"expected re-arm to Monday 9am, got {rearmed['next_run_at']}"
+ )
+ # The recovery is still counted (the wedge WAS repaired).
+ assert J.get_persisted_error_recovery_stats()["persisted_error_recoveries"] >= 1
+
+ def test_cron_value_parked_at_next_legal_occurrence_left_alone(self, cron_store):
+ """A wedged-looking job whose next_run_at already IS the next legal
+ occurrence needs no repair — re-arm must be a no-op."""
+ job = J.create_job(prompt="daily", schedule="30 14 * * *")
+ now = datetime(2026, 8, 22, 12, 0, tzinfo=timezone.utc)
+ legal_next = datetime(2026, 8, 22, 14, 30, tzinfo=timezone.utc)
+ _wedge(
+ job["id"],
+ next_run_at=legal_next,
+ last_run_at=now - timedelta(hours=27),
+ )
+ with mock.patch.object(J, "_hermes_now", lambda: now):
+ J.get_due_jobs()
+ assert datetime.fromisoformat(J.get_job(job["id"])["next_run_at"]) == legal_next
+ assert J.get_persisted_error_recovery_stats()["persisted_error_recoveries"] == 0
+
+ def test_interval_job_still_rearms_to_now(self, cron_store):
+ """Interval jobs (the 2026-08-14 incident class) keep the immediate
+ catch-up: re-armed to now, due on this same scan."""
+ job = J.create_job(prompt="probe", schedule="every 10m", no_agent=True, script="p.py")
+ now = datetime(2026, 8, 22, 12, 0, tzinfo=timezone.utc)
+ _wedge(
+ job["id"],
+ next_run_at=now + timedelta(minutes=5),
+ last_run_at=now - timedelta(minutes=110),
+ )
+ with mock.patch.object(J, "_hermes_now", lambda: now):
+ due = J.get_due_jobs()
+ assert any(j["id"] == job["id"] for j in due), (
+ "wedged interval job must become due immediately after re-arm"
+ )