The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): hold fires through a provider's closed usage window instead of re-firing every tick
teknium1b680dcd5d48d
diff --git a/cron/jobs.py b/cron/jobs.pyindex e2bfa0c97a5..bdad9916310 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -944,6 +944,9 @@ def _job_is_stale_error_recurring("""if job.get("last_status") != "error":return False+ from cron.quota_hold import hold_active+ if hold_active(job, now):+ return False # deliberately parked past a provider usage window, not wedged (#89376)if _job_running_in_this_process(str(job.get("id") or "")):return False# A fresh fire_claim means the job is running in ANOTHER process sharing this@@ -2457,6 +2460,7 @@ def mark_job_run(*,expected_fire_owner: Optional[str] = None,model_unreachable: bool = False,+ quota_hold_seconds: Optional[float] = None,) -> bool:"""Mark a job as run: update last_run_at/last_status, bump completed, recompute next_run_at,and retire the record as a terminal completion when the repeat limit is reached.@@ -2470,6 +2474,10 @@ def mark_job_run(zero API calls). Recurring jobs then get a bounded automatic re-run — ``next_run_at`` is pulledearlier per ``cron.unreachable_retry.RETRY_DELAYS_SECONDS`` — instead of waiting a full period(Cowork-style; see cron/unreachable_retry.py).++ ``quota_hold_seconds``: the provider said it stays closed for this long (a quota 429 with+ ``retry after <N>s``). Recurring jobs are parked at their first occurrence after the window+ instead of re-firing into it on every tick (cron/quota_hold.py, #89376)."""def apply(jobs, _i, job):if expected_fire_owner is not None:@@ -2482,6 +2490,7 @@ def mark_job_run(now = _hermes_now().isoformat()_record_run_outcome(job, success, error, delivery_error, status, now)_advance_after_run(job, now)+ from cron import quota_holdfrom cron.unreachable_retry import clear_state, plan_retryif not success and model_unreachable and not is_terminal_job(job):@@ -2489,6 +2498,10 @@ def mark_job_run(else:# Any run that reached the model (either outcome) resets the re-run ladder.clear_state(job)+ if not success and quota_hold_seconds and not is_terminal_job(job):+ quota_hold.plan_hold(job, quota_hold_seconds)+ else:+ quota_hold.clear_state(job)save_jobs(jobs)return Truediff --git a/cron/quota_hold.py b/cron/quota_hold.pynew file mode 100644index 00000000000..0d031a4e761--- /dev/null+++ b/cron/quota_hold.py@@ -0,0 +1,109 @@+"""Hold a job's fires while a provider's usage window is known to be closed (#89376).++A quota-exhausted provider answers with an explicit ``retry after <N>s`` (Codex 429: the+``AuthError`` from ``hermes_cli.auth_codex._codex_quota_exhausted_error``). When the whole+fallback chain is unavailable, re-firing on cadence is guaranteed to fail identically until+the window reopens — every fire is a usage probe plus a delivered failure alert. The failing+run's alert says the job is held; ``mark_job_run`` then parks ``next_run_at`` at the first+scheduled occurrence after the window and stamps ``quota_hold_until`` so the stale-error+re-arm (``cron.jobs._job_is_stale_error_recurring``) does not pull the job back early.++Mirror of ``cron/unreachable_retry.py`` (which pulls ``next_run_at`` EARLIER); this one pushes+it LATER. Any run that reaches the model clears the marker.+"""++from __future__ import annotations++import logging+import re+from datetime import datetime, timedelta+from typing import Any, Dict, Optional++from hermes_time import now as _hermes_now++logger = logging.getLogger("cron.scheduler")++# Persisted while a hold is active: ISO instant the job was parked at.+STATE_KEY = "quota_hold_until"++# The provider's remaining seconds were measured when the probe ran; by the time the run is+# recorded a little wall clock has passed, so land clearly past the boundary.+HOLD_SLACK_SECONDS = 60++_RETRY_AFTER_RE = re.compile(r"retry after (\d+)s", re.IGNORECASE)+++def hold_seconds_from_failure(exc: BaseException) -> Optional[float]:+ """Seconds the provider said it will stay closed, or None when *exc* (or anything in its+ cause chain) is not a rate-limited ``AuthError`` carrying a wait hint. Anchored on the+ AuthError itself, never on arbitrary text, so an unrelated "retry after" in an agent's+ output cannot park a job."""+ from hermes_cli.auth import AuthError, is_rate_limited_auth_error++ seen: set[int] = set()+ cur: Optional[BaseException] = exc+ while cur is not None and id(cur) not in seen:+ seen.add(id(cur))+ if isinstance(cur, AuthError) and is_rate_limited_auth_error(cur):+ hint = getattr(cur, "retry_after", None)+ if hint is None:+ m = _RETRY_AFTER_RE.search(str(cur))+ hint = float(m.group(1)) if m else None+ return float(hint) if hint is not None and float(hint) > 0 else None+ cur = cur.__cause__ or cur.__context__+ return None+++def hold_active(job: Dict[str, Any], now: Optional[datetime] = None) -> bool:+ """True while the job is parked inside a provider window (an expired marker is inert)."""+ from cron.jobs import _parse_aware # late: jobs imports this module's helpers++ until = _parse_aware(job.get(STATE_KEY)) if job.get(STATE_KEY) else None+ return until is not None and until > (now or _hermes_now())+++def clear_state(job: Dict[str, Any]) -> None:+ job.pop(STATE_KEY, None)+++def plan_hold(job: Dict[str, Any], hold_seconds: float) -> bool:+ """Called under the jobs lock AFTER ``_advance_after_run`` computed the schedule's natural+ ``next_run_at`` for a failed run. Parks a recurring job at its first occurrence after the+ provider window when that is later than the natural one. Returns True when parked."""+ from cron.jobs import _parse_aware, compute_next_run++ schedule = job.get("schedule") or {}+ if schedule.get("kind") not in {"cron", "interval"} or job.get("state") == "paused":+ clear_state(job)+ return False+ window_end = _hermes_now() + timedelta(seconds=float(hold_seconds) + HOLD_SLACK_SECONDS)+ natural_next = _parse_aware(job.get("next_run_at"))+ if natural_next is not None and natural_next >= window_end:+ clear_state(job)+ return False+ if schedule.get("kind") == "interval":+ parked = window_end.isoformat()+ else:+ # First LEGAL cron occurrence after the window; parking at the boundary would fire at a+ # time the expression excludes.+ parked = compute_next_run(schedule, window_end.isoformat()) or window_end.isoformat()+ job["next_run_at"] = parked+ job[STATE_KEY] = parked+ logger.warning(+ "Job '%s': provider usage window closed for %.0fs — holding fires until %s instead of "+ "failing on every cadence tick",+ job.get("name", job.get("id", "?")), float(hold_seconds), parked)+ return True+++def hold_notice(job: Dict[str, Any], hold_seconds: Optional[float]) -> str:+ """Line appended to the ONE failure alert delivered on entering the hold, else ""."""+ if not hold_seconds or (job.get("schedule") or {}).get("kind") not in {"cron", "interval"}:+ return ""+ window_end = _hermes_now() + timedelta(seconds=float(hold_seconds) + HOLD_SLACK_SECONDS)+ hours = float(hold_seconds) / 3600.0+ return (+ f"\nThe provider's usage window is closed for about {hours:.1f}h. This job is held "+ f"until its first scheduled run after {window_end.strftime('%Y-%m-%d %H:%M %Z')} — "+ "no further alerts until then."+ )diff --git a/cron/scheduler.py b/cron/scheduler.pyindex a38c17bc93a..3b0f065b15e 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -2351,6 +2351,12 @@ def run_job(from cron.unreachable_retry import is_model_unreachable_failureif is_model_unreachable_failure(e, agent):job["_model_unreachable"] = True+ # Provider usage window closed for a known duration (cron/quota_hold.py): flag it so the+ # bookkeeping tail parks the job past the window instead of re-firing into it (#89376).+ from cron.quota_hold import hold_seconds_from_failure+ _hold_s = hold_seconds_from_failure(e)+ if _hold_s:+ job["_quota_hold_seconds"] = _hold_sexcept Exception: # classification must never mask the real failurelogger.debug("Job '%s': unreachable-failure classification failed", job_id)# No audit row when we failed before the agent existed; the audit write must never raise.@@ -2648,8 +2654,11 @@ def _compose_run_delivery(job.get("name") or job["id"], job["id"], err.strip().rstrip("."),) + _failure_streak_nudge(job)else:+ from cron.quota_hold import hold_noticedeliver_content = (_summarize_cron_failure_for_delivery(job, error) + _failure_streak_nudge(job)+ # The one alert on entering a provider-window hold says so (#89376).+ + hold_notice(job, job.get("_quota_hold_seconds")))return deliver_content, blocked_config, blocked_config_silent, incident_acked, failure_incident_id@@ -2846,6 +2855,10 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_# Never-reached-the-model failure: schedule the Cowork-style bounded re-run# (cron/unreachable_retry.py) inside the same fenced store write.mark_kwargs["model_unreachable"] = True+ _hold_s = job.pop("_quota_hold_seconds", None)+ if not d.success and _hold_s:+ # Provider window closed for a known duration: park past it (cron/quota_hold.py, #89376).+ mark_kwargs["quota_hold_seconds"] = _hold_sif d.success and not d.delivery_error and d.should_deliver and job.get("last_delivery_queued"):mark_kwargs["status"] = "delivery_queued"if fire_owner is not None:diff --git a/cron/scheduler_preflight.py b/cron/scheduler_preflight.pyindex 96c5d1a3e2c..5aa058c31c9 100644--- a/cron/scheduler_preflight.py+++ b/cron/scheduler_preflight.py@@ -98,7 +98,7 @@ def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]:job.get("provider") or str((_cron_cfg or {}).get("model_provider") or "").strip() or None)model = job.get("model") or cron_env_setting("HERMES_MODEL") or ""- from hermes_cli.auth import AuthError+ from hermes_cli.auth import AuthError, is_rate_limited_auth_errortry:from hermes_cli.runtime_provider import resolve_runtime_providerkwargs = {"requested": requested, "target_model": model}@@ -106,6 +106,10 @@ def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]:kwargs["explicit_base_url"] = job.get("base_url")resolve_runtime_provider(**kwargs)except AuthError as exc:+ if is_rate_limited_auth_error(exc):+ # Quota/rate-limit is not a missing credential: let the real path report it and hold+ # the job through the provider's window (cron/quota_hold.py, #89376).+ return Nonereturn (f"provider credential missing: {exc}. ""Set the provider API key in .env (or `hermes setup`), or pin a "diff --git a/tests/cron/test_quota_hold.py b/tests/cron/test_quota_hold.pynew file mode 100644index 00000000000..8fea77ebcd3--- /dev/null+++ b/tests/cron/test_quota_hold.py@@ -0,0 +1,78 @@+"""Provider quota windows park a cron job instead of re-firing into them (#89376).++Contract (cron/quota_hold.py): a failed run whose cause is a rate-limited ``AuthError`` with a+``retry after <N>s`` hint parks a recurring job's ``next_run_at`` past the window and stamps+``quota_hold_until``; the stale-error re-arm leaves a held job alone; a run that reaches the+model clears the marker. The hint is read only from the AuthError in the cause chain, never from+arbitrary failure text.+"""++from datetime import datetime, timedelta, timezone++import pytest++from cron import quota_hold as qh+from cron.jobs import (+ _job_is_stale_error_recurring, create_job, get_due_jobs, get_job, mark_job_run, update_job,+)+from hermes_cli.auth import CODEX_RATE_LIMITED_CODE, AuthError++QUOTA_MSG = "Codex provider quota exhausted (429); retry after 123518s. Credentials are still valid."+++def tmp_cron_home(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home+++def _quota_error() -> AuthError:+ return AuthError(QUOTA_MSG, provider="openai-codex", code=CODEX_RATE_LIMITED_CODE)+++def test_hold_seconds_only_from_rate_limited_auth_error_in_cause_chain():+ """The scheduler wraps the resolve failure in a RuntimeError ``from`` the AuthError; the+ hint survives through the cause chain, and text alone (or a re-login AuthError) never+ parks a job."""+ try:+ raise RuntimeError(QUOTA_MSG) from _quota_error()+ except RuntimeError as wrapped:+ assert qh.hold_seconds_from_failure(wrapped) == 123518.0++ assert qh.hold_seconds_from_failure(RuntimeError(QUOTA_MSG)) is None+ assert qh.hold_seconds_from_failure(RuntimeError("HTTP 429: retry after 60s")) is None+ relogin = AuthError(QUOTA_MSG, provider="openai-codex", code="expired", relogin_required=True)+ assert qh.hold_seconds_from_failure(relogin) is None+ structured = AuthError("quota", code=CODEX_RATE_LIMITED_CODE, retry_after=900)+ assert qh.hold_seconds_from_failure(structured) == 900.0+++def test_quota_hold_parks_past_window_survives_stale_rearm_and_clears_on_model_reach(tmp_cron_home):+ """A 30-minute job told 'retry after 123518s' does not fire again inside the window (not+ even after the stale-error re-arm's cadence+grace), and the marker clears once a run+ reaches the model."""+ job = create_job("portfolio triage", "every 30m")+ job_id = job["id"]+ now = datetime.now(timezone.utc)++ assert mark_job_run(job_id, False, QUOTA_MSG, quota_hold_seconds=123518)+ j = get_job(job_id)+ parked = datetime.fromisoformat(j["next_run_at"])+ assert parked - now >= timedelta(seconds=123518), "next_run_at must land past the window"+ assert j[qh.STATE_KEY] == j["next_run_at"]++ # Two hours later the job looks like a wedged stale-error record (#62002) — the hold says+ # it is parked on purpose, so it is neither re-armed nor due.+ update_job(job_id, {"last_run_at": (now - timedelta(hours=2)).isoformat()})+ j = get_job(job_id)+ assert not _job_is_stale_error_recurring(j, j["schedule"], now)+ assert all(d["id"] != job_id for d in get_due_jobs())+ assert datetime.fromisoformat(get_job(job_id)["next_run_at"]) == parked++ # A run that reached the model (either outcome) clears the marker.+ assert mark_job_run(job_id, False, "RuntimeError: model said no")+ j = get_job(job_id)+ assert qh.STATE_KEY not in j+ assert datetime.fromisoformat(j["next_run_at"]) - now < timedelta(hours=1)diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex d04444a480b..bf16096d155 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -447,6 +447,20 @@ cron:retry_unreachable: false # default true; disables the automatic re-runs```+### Holding a job through a closed provider usage window++The mirror case: the provider says exactly how long it will stay closed. A+subscription provider whose usage limit is exhausted rejects every request+with a 429 and a `retry after <N>s` hint (often many hours). When the whole+fallback chain is unavailable, re-firing a sub-hourly job into that window is+guaranteed to fail identically on every tick — and to alert every time.++Instead, the scheduler **parks the job**: the one failure alert says the+window is closed and that the job is held, `next_run_at` moves to the first+scheduled occurrence after the window (`quota_hold_until` on the job record),+and nothing fires or alerts until then. Any run that reaches the model clears+the hold. One-shot jobs are not held.+### Failure incidents: alert once, remind on a cooldown, acknowledgeA recurring job that keeps failing with the *same* error alerts you **once**,