The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): recover sparse fires after quota cooldown
Marko Niskalaac10d34f61be
diff --git a/cron/jobs.py b/cron/jobs.pyindex 20e3ae5a8f6..730716bd6b8 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -2378,6 +2378,7 @@ def mark_job_run(expected_fire_owner: Optional[str] = None,model_unreachable: bool = False,quota_hold_seconds: Optional[float] = None,+ quota_recover_occurrence: bool = False,) -> 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.@@ -2393,8 +2394,10 @@ def mark_job_run((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).+ ``retry after <N>s``). Recurring jobs are parked through the window instead of re-firing into+ it on every tick. ``quota_recover_occurrence`` lets a scheduled sparse cron recover its+ consumed fire when the provider reopens; manual runs retain the natural schedule+ (cron/quota_hold.py, #89376)."""def apply(jobs, _i, job):if expected_fire_owner is not None:@@ -2416,7 +2419,8 @@ def mark_job_run(# 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)+ quota_hold.plan_hold(+ job, quota_hold_seconds, recover_consumed_fire=quota_recover_occurrence)else:quota_hold.clear_state(job)save_jobs(jobs)@@ -2985,13 +2989,20 @@ def _reanchor_stale_cron(d: _DueJob) -> bool:"""Stale-schedule guard for a due cron instant; True when re-anchored without firing.A direct edit of schedule.expr leaves next_run_at on the old lattice, so re-anchor first (from- the current expr, so this converges). An offset-representation migration also moves a legacy- instant off the lattice, and re-anchoring THAT swallowed a due occurrence — so classify, and- let- the migration case fall through to fire ONCE (at-most-once holds: nothing re-reads the legacy- instant after advance/mark_job_run rewrites it)."""+ the current expr, so this converges). Two cases intentionally authorize one off-lattice fire+ instead: an offset-representation migration that would otherwise swallow a never-fired+ occurrence, and a quota recovery before a sparse cron's next natural occurrence.+ Both fall through to fire ONCE (at-most-once holds: completion rewrites the instant)."""stale_class = _classify_stale_cron_next_run(d.schedule, d.raw_next_run_dt, d.next_run_dt)if stale_class == STALE_CRON_EXPR_EDIT:+ from cron.quota_hold import is_recovery_fire+ if is_recovery_fire(d.job, d.next_run):+ # plan_hold deliberately creates one off-lattice recovery fire when a provider+ # reopens before a sparse cron's next natural occurrence.+ logger.info(+ "cron.quota_hold.recovery_fire job='%s' id=%s expr=%r at=%s",+ d.label, d.job.get("id"), d.schedule.get("expr"), d.next_run)+ return Falsenew_next = d.recompute_next()logger.info("Job '%s' next_run_at %s does not match its current "diff --git a/cron/quota_hold.py b/cron/quota_hold.pyindex 6069cc1328b..9ef52ce9f57 100644--- a/cron/quota_hold.py+++ b/cron/quota_hold.py@@ -4,12 +4,13 @@ A quota-exhausted provider answers with an explicit ``retry after <N>s`` (Codex``AuthError`` from ``hermes_cli.auth_codex._codex_quota_exhausted_error``). When the wholefallback chain is unavailable, re-firing on cadence is guaranteed to fail identically untilthe 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.+run's alert says the job is held; ``mark_job_run`` then parks ``next_run_at`` at the recovery+boundary (or the first legal occurrence after it, when several fall inside 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.+Complement to ``cron/unreachable_retry.py``: this one moves ``next_run_at`` out of a known+closed provider window. Any run that reaches the model clears the marker."""from __future__ import annotations@@ -25,6 +26,7 @@ logger = logging.getLogger("cron.scheduler")# Persisted while a hold is active: ISO instant the job was parked at.STATE_KEY = "quota_hold_until"+SCHEDULE_EXPR_KEY = "quota_hold_cron_expr"# 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.@@ -64,6 +66,21 @@ def hold_active(job: Dict[str, Any], now: Optional[datetime] = None) -> bool:def clear_state(job: Dict[str, Any]) -> None:job.pop(STATE_KEY, None)+ job.pop(SCHEDULE_EXPR_KEY, None)+++def is_recovery_fire(job: Dict[str, Any], next_run: str) -> bool:+ """True for the exact off-lattice cron fire parked by ``plan_hold``.++ The expression fingerprint keeps a direct ``jobs.json`` schedule edit from inheriting the+ exception: edited schedules must still re-anchor without firing.+ """+ schedule = job.get("schedule") or {}+ return (+ schedule.get("kind") == "cron"+ and job.get(STATE_KEY) == next_run+ and job.get(SCHEDULE_EXPR_KEY) == schedule.get("expr")+ )def _window_end(hold_seconds: float) -> datetime:@@ -72,27 +89,40 @@ def _window_end(hold_seconds: float) -> datetime:return _seconds_after(_hermes_now(), float(hold_seconds) + HOLD_SLACK_SECONDS)-def plan_hold(job: Dict[str, Any], hold_seconds: float) -> bool:+def plan_hold(+ job: Dict[str, Any], hold_seconds: float, *, recover_consumed_fire: bool = False,+) -> 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."""+ ``next_run_at`` for a failed run. A scheduled sparse cron may retry its consumed fire at the+ recovery boundary; manual runs keep the natural schedule. Otherwise coalesce fires through+ the closed window. Returns True when parked."""from cron.jobs import _instant_before, _parse_aware, compute_next_runschedule = job.get("schedule") or {}- if schedule.get("kind") not in {"cron", "interval"} or job.get("state") == "paused":+ kind = schedule.get("kind")+ if kind not in {"cron", "interval"} or job.get("state") == "paused":clear_state(job)return Falsewindow_end = _window_end(hold_seconds)natural_next = _parse_aware(job.get("next_run_at"))- if natural_next is not None and not _instant_before(natural_next, window_end):- clear_state(job)- return False- if schedule.get("kind") == "interval":+ blocked = natural_next is None or _instant_before(natural_next, window_end)+ if kind == "interval":+ if not blocked:+ # No interval occurrence is blocked: its natural next run is already after recovery.+ clear_state(job)+ return Falseparked = window_end.isoformat()+ job.pop(SCHEDULE_EXPR_KEY, None)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()+ if not blocked:+ if not recover_consumed_fire:+ clear_state(job)+ return False+ parked = window_end.isoformat()+ else:+ # Coalesce cron occurrences inside the closed window to the first legal instant after it.+ parked = compute_next_run(schedule, window_end.isoformat()) or window_end.isoformat()+ job[SCHEDULE_EXPR_KEY] = schedule.get("expr")job["next_run_at"] = parkedjob[STATE_KEY] = parkedlogger.warning(@@ -110,6 +140,6 @@ def hold_notice(job: Dict[str, Any], hold_seconds: Optional[float]) -> str:hours = float(hold_seconds) / 3600.0return (f"\nThe provider's usage window is closed for about {hours:.1f}h. This job is held "- f"until its first scheduled run after {safe_strftime(window_end, '%Y-%m-%d %H:%M %Z')} — "- "no further alerts until then."+ f"through {safe_strftime(window_end, '%Y-%m-%d %H:%M %Z')} and resumes at the first safe "+ "opportunity afterwards; no further alerts are sent while the provider is unavailable.")diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 9e16f57c955..b1711d75159 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -3059,6 +3059,7 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_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_s+ mark_kwargs["quota_recover_occurrence"] = bool(job.get("_scheduled_instant"))if 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/tests/cron/test_quota_hold.py b/tests/cron/test_quota_hold.pyindex dc730c709d6..d0f6a20218c 100644--- a/tests/cron/test_quota_hold.py+++ b/tests/cron/test_quota_hold.py@@ -1,4 +1,5 @@-"""Provider quota windows park a cron job instead of re-firing into them (#89376).+"""Provider quota windows park a cron job instead of re-firing into them (#89376;+ai-velho-oy/chairman#3).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@@ -51,6 +52,64 @@ def test_hold_seconds_only_from_rate_limited_auth_error_in_cause_chain():assert qh.hold_seconds_from_failure(structured) == 900.0+def test_weekly_cron_retries_when_quota_recovers_before_next_occurrence(+ tmp_cron_home, monkeypatch,+):+ """A weekly fire blocked by a shorter quota window retries when the provider reopens;+ it is not silently deferred until the following week's natural occurrence."""+ now = datetime(2026, 9, 18, 12, 1, tzinfo=timezone.utc)+ natural_next = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)+ monkeypatch.setattr("cron.jobs._hermes_now", lambda: now)+ monkeypatch.setattr(qh, "_hermes_now", lambda: now)+ job = create_job("weekly digest", "0 12 * * 5")+ assert datetime.fromisoformat(job["next_run_at"]) == natural_next++ assert mark_job_run(+ job["id"], False, QUOTA_MSG, quota_hold_seconds=20 * 60 * 60,+ quota_recover_occurrence=True,+ )++ held = get_job(job["id"])+ assert held is not None+ retry_at = datetime.fromisoformat(held["next_run_at"])+ assert retry_at == now + timedelta(hours=20, seconds=qh.HOLD_SLACK_SECONDS) < natural_next+ assert qh.is_recovery_fire(held, held["next_run_at"])+ edited = {**held, "schedule": {"kind": "cron", "expr": "0 9 * * *"}}+ assert not qh.is_recovery_fire(edited, edited["next_run_at"])++ monkeypatch.setattr("cron.jobs._hermes_now", lambda: retry_at + timedelta(seconds=1))+ assert job["id"] in {due["id"] for due in get_due_jobs()}+++def test_hold_policy_coalesces_dense_cron_without_accelerating_sparse_interval(monkeypatch):+ now = datetime(2026, 9, 18, 12, 1, tzinfo=timezone.utc)+ window_end = now + timedelta(hours=20, seconds=qh.HOLD_SLACK_SECONDS)+ monkeypatch.setattr(qh, "_hermes_now", lambda: now)++ dense_cron = {+ "schedule": {"kind": "cron", "expr": "0 * * * *"},+ "next_run_at": (now + timedelta(hours=1)).isoformat(),+ }+ assert qh.plan_hold(dense_cron, hold_seconds=20 * 60 * 60)+ assert datetime.fromisoformat(dense_cron["next_run_at"]) > window_end++ sparse_interval = {+ "schedule": {"kind": "interval", "minutes": 7 * 24 * 60},+ "next_run_at": (now + timedelta(days=7)).isoformat(),+ }+ original_next = sparse_interval["next_run_at"]+ assert not qh.plan_hold(sparse_interval, hold_seconds=20 * 60 * 60)+ assert sparse_interval["next_run_at"] == original_next+ assert qh.STATE_KEY not in sparse_interval++ manual_sparse_cron = {+ "schedule": {"kind": "cron", "expr": "0 12 * * 5"},+ "next_run_at": (now + timedelta(days=7)).isoformat(),+ }+ assert not qh.plan_hold(manual_sparse_cron, hold_seconds=20 * 60 * 60)+ assert qh.STATE_KEY not in manual_sparse_cron++def _raise_quota(**_kw):raise _quota_error()diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex 1aaf1da3de3..42cd6b8de8f 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -457,10 +457,13 @@ identically on every tick — and to alert every time. A 429 the model APIreturns mid-run is not held this way; it is retried on the normal cadence.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.+window is closed and that the job is held. If the provider reopens before a+cron job's next natural occurrence, a blocked scheduled occurrence retries+once at that recovery boundary; manual runs and interval jobs retain their+natural next run. Otherwise, missed occurrences are coalesced and+`next_run_at` moves to the first scheduled occurrence after the window. The+parked instant is stored as `quota_hold_until`; nothing fires or alerts before+it. Any run that reaches the model clears the hold. One-shot jobs are not held.### Failure incidents: alert once, remind on a cooldown, acknowledge