Skip to content

The agent that grows with you

fix(cron): unreachable-model re-runs no longer use up repeat slots

FroRautc84ef163844e
diff --git a/cron/jobs.py b/cron/jobs.py
index b3321f21f57..9bfc25fc34c 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -2412,7 +2412,7 @@ def _record_run_outcome(
job["run_claim"] = None
-def _advance_after_run(job: Dict[str, Any], now: str) -> None:
+def _advance_after_run(job: Dict[str, Any], now: str, *, count_run: bool = True) -> None:
"""Bump ``repeat.completed`` and recompute ``next_run_at``; retire the record as a terminal
completion when the repeat limit is reached or a one-shot has no further run."""
# If no next run, decide whether this is terminal completion (one-shot) or a transient failure
@@ -2430,7 +2430,7 @@ def _advance_after_run(job: Dict[str, Any], now: str) -> None:
completed = repeat.get("completed", 0)
# Finite one-shots were pre-claimed by claim_dispatch() (completed already incremented) —
# do not double-count; recurring jobs and direct callers still get the increment.
- if not (kind == "once" and finite and completed > 0):
+ if count_run and not (kind == "once" and finite and completed > 0):
completed += 1
repeat["completed"] = completed
if finite and completed >= times:
@@ -2468,6 +2468,7 @@ def mark_job_run(
*,
expected_fire_owner: Optional[str] = None,
model_unreachable: bool = False,
+ ladder_rung: bool = False,
quota_hold_seconds: Optional[float] = None,
recover_consumed_fire: bool = False,
) -> bool:
@@ -2482,7 +2483,9 @@ def mark_job_run(
``model_unreachable``: this failed run never reached the model (transient network/DNS error,
zero API calls). Recurring jobs then get a bounded automatic re-run — ``next_run_at`` is pulled
earlier per ``cron.unreachable_retry.RETRY_DELAYS_SECONDS`` — instead of waiting a full period
- (Cowork-style; see cron/unreachable_retry.py).
+ (Cowork-style; see cron/unreachable_retry.py). ``ladder_rung``: this run IS one of those
+ re-runs (``is_retry_run``); its occurrence already counted, so ``repeat.completed`` is not
+ bumped again.
``quota_hold_seconds``: the provider said it stays closed for this long (a quota 429 with
``retry after <N>s``). Recurring jobs are parked through the window instead of re-firing into
@@ -2500,7 +2503,7 @@ def mark_job_run(
return False
now = _hermes_now().isoformat()
_record_run_outcome(job, success, error, delivery_error, status, now)
- _advance_after_run(job, now)
+ _advance_after_run(job, now, count_run=not ladder_rung)
from cron import quota_hold
from cron.unreachable_retry import clear_state, plan_retry
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 86d0482ec8f..f6c65deb089 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -3172,6 +3172,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
+ from cron.unreachable_retry import is_retry_run
+ if is_retry_run(job):
+ # A re-run of an occurrence that already counted: must not spend another repeat slot.
+ mark_kwargs["ladder_rung"] = 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).
diff --git a/cron/unreachable_retry.py b/cron/unreachable_retry.py
index 7c0298d4d1d..6fe27b6fdf6 100644
--- a/cron/unreachable_retry.py
+++ b/cron/unreachable_retry.py
@@ -96,7 +96,8 @@ def will_retry(job: Dict[str, Any]) -> bool:
may hold the interim notice. Called before ``mark_job_run``."""
repeat = job.get("repeat") or {}
times = repeat.get("times")
- if times is not None and times > 0 and int(repeat.get("completed") or 0) + 1 >= times:
+ counted = 0 if is_retry_run(job) else 1 # a ladder re-run does not count (``ladder_rung``)
+ if times is not None and times > 0 and int(repeat.get("completed") or 0) + counted >= times:
return False # _advance_after_run completes the job; plan_retry never runs
from cron.jobs import _parse_aware, compute_next_run
@@ -124,6 +125,16 @@ def is_retry_fire(job: Dict[str, Any], next_run: str) -> bool:
return state.get("at") == next_run and state.get("expr") == (job.get("schedule") or {}).get("expr")
+def is_retry_run(job: Dict[str, Any]) -> bool:
+ """True when this dispatch snapshot fired the ladder instant parked by ``plan_retry``: a
+ re-run of an occurrence that already counted toward ``repeat``, so it must not count again.
+ Manual runs carry no ``_scheduled_instant`` and always count."""
+ from cron.occurrences import scheduled_instant
+
+ instant = job.get("_scheduled_instant")
+ return instant is not None and scheduled_instant((job.get(STATE_KEY) or {}).get("at")) == instant
+
+
def plan_retry(job: Dict[str, Any]) -> bool:
"""Called under the jobs lock AFTER ``_advance_after_run`` computed the schedule's
natural ``next_run_at`` for a failed, flagged run. Pulls ``next_run_at`` earlier to
diff --git a/tests/cron/test_unreachable_retry.py b/tests/cron/test_unreachable_retry.py
index f82744ee12a..5bce93f8b5e 100644
--- a/tests/cron/test_unreachable_retry.py
+++ b/tests/cron/test_unreachable_retry.py
@@ -10,6 +10,7 @@ from datetime import datetime, timedelta, timezone
import pytest
+import cron.scheduler as sched
from cron import unreachable_retry as ur
from cron.jobs import create_job, get_due_jobs, get_job, load_jobs, mark_job_run, save_jobs
@@ -126,3 +127,39 @@ def test_reaching_the_model_resets_ladder_and_oneshots_never_retry(tmp_cron_home
assert mark_job_run(once["id"], False, "ConnectError: dns", model_unreachable=True)
remaining = get_job(once["id"])
assert remaining is None or remaining.get(ur.STATE_KEY) is None
+
+
+def test_ladder_reruns_do_not_spend_extra_repeat_budget(tmp_cron_home, monkeypatch):
+ """A ladder re-run repeats an occurrence that already counted toward ``repeat``, so it must
+ not count again. Otherwise an outage that outlasts the ladder retires a finite job with zero
+ model calls, where the same outage with the ladder off costs it one run (#109990 fixed only
+ the final-run notice). Drives the tick's claim hand-off and bookkeeping tail: the claimed
+ snapshot's ``next_run_at`` has already moved to the natural slot when the run is recorded."""
+ clock = [datetime.now(timezone.utc)]
+ monkeypatch.setattr("cron.jobs._hermes_now", lambda: clock[0])
+ monkeypatch.setattr(ur, "_hermes_now", lambda: clock[0])
+ monkeypatch.setattr(sched, "finish_execution", lambda *_a, **_kw: None)
+ runs = []
+ monkeypatch.setattr(sched, "run_one_job", lambda job, **_kw: runs.append(job) or True)
+ job_id = create_job("digest", "every 24h", repeat=2)["id"]
+
+ held = []
+ for _ in range(1 + len(ur.RETRY_DELAYS_SECONDS)): # the occurrence, then every rung
+ clock[0] = datetime.fromisoformat(get_job(job_id)["next_run_at"]) + timedelta(seconds=1)
+ due = next(d for d in get_due_jobs() if d["id"] == job_id)
+ assert sched._process_due_job(dict(due, execution_id="exec"), None, None, False)
+ run = runs[-1]
+ run["_model_unreachable"] = True
+ held.append(ur.will_retry(run))
+ assert sched._finish_completed_run(
+ sched._RunDelivery(job=run, success=False, error="ConnectError: dns"),
+ run["fire_claim"]["by"], "exec")
+ assert get_job(job_id)["repeat"]["completed"] == 1, "only the occurrence itself counts"
+
+ j = get_job(job_id)
+ assert j["state"] == "scheduled" and j.get(ur.STATE_KEY) is None
+ assert datetime.fromisoformat(j["next_run_at"]) - clock[0] > timedelta(hours=23)
+ # A rung on the last slot no longer completes the job, so its notice is held as well.
+ assert held == [True, True, True, False]
+ # But a rung whose limit was edited down to the count does retire the job: send its notice.
+ assert not ur.will_retry(dict(runs[1], repeat={"times": 1, "completed": 1}))
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index 42bf085f118..bdd21427247 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -432,7 +432,8 @@ computer wakes, while the VPN or Wi-Fi is still reconnecting — does not sit
out a whole period. The scheduler re-runs it automatically after **5, 15, and
30 minutes** (inspired by Claude Cowork's scheduled-task re-runs), then falls
back to the normal schedule. Because zero API calls were made, the re-run is
-spend-neutral and cannot duplicate any side effect.
+spend-neutral and cannot duplicate any side effect. Re-runs also do not count
+toward a job's `repeat` limit: the occurrence they repeat already counted once.
While a re-run is pending, the interim failure notice is suppressed — you get
the real result when a re-run succeeds, or a normal failure alert once the