Skip to content

The agent that grows with you

feat(cron): automatic bounded re-runs when a fire never reached the model

Tekniumec58e08a353a
diff --git a/cron/jobs.py b/cron/jobs.py
index 3892b35c75b..c41e65da44d 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -2370,6 +2370,7 @@ def mark_job_run(
status: Optional[str] = None,
*,
expected_fire_owner: Optional[str] = None,
+ model_unreachable: 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.
@@ -2378,6 +2379,11 @@ def mark_job_run(
``last_status = "delivery_failed"`` (never "ok") while ``failure_streak`` is left alone. An
explicit ``status`` (e.g. "blocked_config") overrides the derived value. False when the fence
can't be taken, the job is missing, or ``expected_fire_owner`` no longer holds the fire claim.
+
+ ``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).
"""
def apply(jobs, _i, job):
if expected_fire_owner is not None:
@@ -2390,6 +2396,13 @@ 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.unreachable_retry import clear_state, plan_retry
+
+ if not success and model_unreachable and not is_terminal_job(job):
+ plan_retry(job)
+ else:
+ # Any run that reached the model (either outcome) resets the re-run ladder.
+ clear_state(job)
save_jobs(jobs)
return True
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 043d86a7fe1..be4b10ab0e5 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -2288,6 +2288,15 @@ def run_job(
except Exception as e:
error_msg = f"{type(e).__name__}: {str(e)}"
logger.exception("Job '%s' failed: %s", job_name, error_msg)
+ # Cowork-style unreachable-model re-run (cron/unreachable_retry.py): flag failures where
+ # the model was never reached (transient network/DNS, zero API calls) so the bookkeeping
+ # tail can schedule a bounded automatic re-run instead of waiting a full period.
+ try:
+ from cron.unreachable_retry import is_model_unreachable_failure
+ if is_model_unreachable_failure(e, agent):
+ job["_model_unreachable"] = True
+ except Exception: # classification must never mask the real failure
+ logger.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.
if _audit is not None:
_audit.write({}, error_msg)
@@ -2652,6 +2661,16 @@ def _save_compose_deliver(
output_file=output_file)
# Whitespace-only == empty: skip delivery; the guard below marks it a soft failure.
d.should_deliver = bool(deliver_content.strip()) and not _silent_alert
+ if d.should_deliver and not d.success and job.get("_model_unreachable"):
+ # The model was never reached and a bounded automatic re-run will be scheduled
+ # (cron/unreachable_retry.py): hold the failure notice — the re-run either
+ # delivers the real result or, once the ladder is exhausted, the next failure
+ # alerts normally. Mirrors Cowork's silent 5/15/30-minute re-runs.
+ from cron.unreachable_retry import will_retry
+ if will_retry(job):
+ d.should_deliver = False
+ logger.info(
+ "Job '%s': suppressing failure notice — automatic re-run pending", job["id"])
# Not a substring check: bare "SILENT"/"NO_REPLY" or a report quoting "[SILENT]" must
# not be swallowed; bracketed-prefix / trailing-line tolerance is kept.
if d.should_deliver and d.success and _is_cron_silence_response(deliver_content):
@@ -2719,7 +2738,11 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_
from cron.jobs import update_job
update_job(job["id"], {"last_delivery_queued": None})
job["last_delivery_queued"] = None
- mark_kwargs = {"delivery_error": d.delivery_error}
+ mark_kwargs: dict = {"delivery_error": d.delivery_error}
+ if not d.success and job.pop("_model_unreachable", False):
+ # 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
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/cron/unreachable_retry.py b/cron/unreachable_retry.py
new file mode 100644
index 00000000000..924a826a521
--- /dev/null
+++ b/cron/unreachable_retry.py
@@ -0,0 +1,125 @@
+"""Automatic bounded re-runs for scheduled fires that never reached the model.
+
+Inspired by Claude Cowork (desktop changelog v1.46388.1, 2026-09-04): "automatic re-runs
+(after 5, 15, and 30 minutes) for a scheduled task that could not reach the model at all,
+for example right after the computer wakes behind a VPN."
+
+The class is deliberately narrow: the run must have FAILED with a transient network /
+DNS error (``cron.scheduler_preflight._is_transient_provider_resolve_error``) AND the
+agent must have completed zero API calls. Nothing was executed and nothing was spent, so
+re-running cannot double a side effect — unlike a generic failure retry (see PR #16512),
+which has to answer for one-shot dispatch accounting and mid-run side effects. Recurring
+jobs only: finite one-shots are pre-claimed by ``claim_dispatch`` (at-most-times, #38758)
+and must not regain a consumed dispatch here.
+
+While a retry is pending the failure notice is suppressed (Cowork re-runs silently); a
+run that reaches the model — success or not — resets the ladder. Disable with
+``cron.retry_unreachable: false`` in config.yaml.
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import timedelta
+from typing import Any, Dict, Optional
+
+from hermes_time import now as _hermes_now
+
+logger = logging.getLogger("cron.scheduler")
+
+# Cowork's ladder: re-run after 5, 15, then 30 minutes; then give up until the
+# schedule's own next occurrence.
+RETRY_DELAYS_SECONDS: tuple[int, ...] = (300, 900, 1800)
+
+# Persisted on the job while a retry cycle is active: {"attempt": <1-based count of
+# retries already scheduled>}. Cleared by any run that reached the model.
+STATE_KEY = "unreachable_retry"
+
+
+def retry_enabled(cfg: Optional[dict] = None) -> bool:
+ """``cron.retry_unreachable`` — default ON (spend-neutral: only fires when zero
+ model calls were made)."""
+ if cfg is None:
+ try:
+ from hermes_cli.config import load_config
+
+ cfg = load_config() or {}
+ except Exception: # config unreadable — keep the reliability default
+ return True
+ cron_cfg = (cfg or {}).get("cron")
+ if not isinstance(cron_cfg, dict):
+ return True
+ return cron_cfg.get("retry_unreachable") is not False
+
+
+def is_model_unreachable_failure(exc: BaseException, agent: Any = None) -> bool:
+ """True when *exc* is a transient network/DNS failure and *agent* (may be ``None``)
+ never completed a model call — the run consumed nothing and executed nothing."""
+ if int(getattr(agent, "session_api_calls", 0) or 0) > 0:
+ return False
+ from cron.scheduler_preflight import _is_transient_provider_resolve_error
+
+ return _is_transient_provider_resolve_error(exc)
+
+
+def _is_recurring(job: Dict[str, Any]) -> bool:
+ return job.get("schedule", {}).get("kind") in {"cron", "interval"}
+
+
+def will_retry(job: Dict[str, Any]) -> bool:
+ """Predict whether ``plan_retry`` will schedule a re-run for this flagged failure —
+ used by the scheduler to suppress the interim failure notice."""
+ if not _is_recurring(job) or job.get("state") == "paused":
+ return False
+ state = job.get(STATE_KEY) or {}
+ if int(state.get("attempt") or 0) >= len(RETRY_DELAYS_SECONDS):
+ return False
+ return retry_enabled()
+
+
+def clear_state(job: Dict[str, Any]) -> None:
+ """A run reached the model (any outcome): the ladder resets."""
+ job.pop(STATE_KEY, None)
+
+
+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
+ the ladder instant when that is sooner than the natural occurrence; exhausted or
+ inapplicable cycles clear state and leave the schedule untouched. Returns True when
+ a retry was scheduled."""
+ if not _is_recurring(job) or job.get("state") == "paused" or not retry_enabled():
+ clear_state(job)
+ return False
+ state = job.get(STATE_KEY) or {}
+ attempt = int(state.get("attempt") or 0)
+ if attempt >= len(RETRY_DELAYS_SECONDS):
+ # Ladder exhausted: fall back to the natural schedule and reset so the NEXT
+ # occurrence gets a fresh ladder if the network is still down.
+ clear_state(job)
+ logger.warning(
+ "Job '%s': model unreachable after %d automatic re-runs — waiting for the "
+ "scheduled occurrence at %s",
+ job.get("name", job.get("id", "?")), attempt, job.get("next_run_at"))
+ return False
+ delay = RETRY_DELAYS_SECONDS[attempt]
+ retry_dt = _hermes_now() + timedelta(seconds=delay)
+ from cron.jobs import _parse_aware # late: jobs imports this module's helpers
+
+ natural_next = _parse_aware(job.get("next_run_at"))
+ if natural_next is not None and natural_next <= retry_dt:
+ # The schedule fires again sooner than the ladder would — no point consuming an
+ # attempt; the natural occurrence IS the retry.
+ clear_state(job)
+ return False
+ retry_at = retry_dt.isoformat()
+ job[STATE_KEY] = {"attempt": attempt + 1}
+ job["next_run_at"] = retry_at
+ if job.get("state") != "paused":
+ job["state"] = "scheduled"
+ logger.info(
+ "Job '%s': model unreachable with zero API calls — automatic re-run %d/%d in %ds "
+ "(at %s)",
+ job.get("name", job.get("id", "?")), attempt + 1, len(RETRY_DELAYS_SECONDS),
+ delay, retry_at)
+ return True
diff --git a/tests/cron/test_unreachable_retry.py b/tests/cron/test_unreachable_retry.py
new file mode 100644
index 00000000000..bce50f4c0dd
--- /dev/null
+++ b/tests/cron/test_unreachable_retry.py
@@ -0,0 +1,71 @@
+"""Cowork-inspired bounded automatic re-runs for cron fires that never reached the model.
+
+Contract (cron/unreachable_retry.py): a recurring job whose run fails with a transient
+network/DNS error before ANY model call gets its ``next_run_at`` pulled earlier along a
+bounded ladder (5/15/30 min); a run that reaches the model resets the ladder, and the
+ladder never fires past its last rung.
+"""
+
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+from cron import unreachable_retry as ur
+from cron.jobs import create_job, get_job, mark_job_run
+
+
+def tmp_cron_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return home
+
+
+def _iso(dt: datetime) -> str:
+ return dt.isoformat()
+
+
+def test_unreachable_failure_pulls_next_run_earlier_then_ladder_exhausts(tmp_cron_home):
+ """Failed-unreachable runs re-fire on the 5/15/30-minute ladder instead of waiting a
+ full period, and the ladder stops after its last rung (falls back to the schedule)."""
+ job = create_job("nightly report", "0 3 * * *") # daily — natural gap is hours
+ job_id = job["id"]
+
+ now = datetime.now(timezone.utc)
+ for i, delay in enumerate(ur.RETRY_DELAYS_SECONDS):
+ assert mark_job_run(job_id, False, "ConnectError: dns", model_unreachable=True)
+ j = get_job(job_id)
+ nxt = datetime.fromisoformat(j["next_run_at"])
+ # Pulled to roughly now + ladder delay, far before the daily occurrence.
+ assert timedelta(0) < nxt - now <= timedelta(seconds=delay + 120), (
+ f"attempt {i}: expected retry ~{delay}s out, got {nxt - now}")
+ assert j[ur.STATE_KEY]["attempt"] == i + 1
+
+ # Ladder exhausted: the next unreachable failure keeps the natural schedule.
+ assert mark_job_run(job_id, False, "ConnectError: dns", model_unreachable=True)
+ j = get_job(job_id)
+ assert j.get(ur.STATE_KEY) is None
+ assert datetime.fromisoformat(j["next_run_at"]) - now > timedelta(hours=1)
+
+
+def test_reaching_the_model_resets_ladder_and_oneshots_never_retry(tmp_cron_home):
+ """Any run that reached the model clears retry state; one-shots (pre-claimed
+ dispatch, at-most-times #38758) never enter the ladder."""
+ job = create_job("hourly sync", "every 12h")
+ job_id = job["id"]
+ assert mark_job_run(job_id, False, "ConnectError: dns", model_unreachable=True)
+ assert get_job(job_id)[ur.STATE_KEY]["attempt"] == 1
+
+ # A normal failed run (model reached) resets the ladder and stays on schedule.
+ assert mark_job_run(job_id, False, "agent error")
+ j = get_job(job_id)
+ assert j.get(ur.STATE_KEY) is None
+ now = datetime.now(timezone.utc)
+ assert datetime.fromisoformat(j["next_run_at"]) - now > timedelta(hours=11)
+
+ # One-shot: flag is ignored, no retry state, no resurrection.
+ once = create_job("one shot", _iso(datetime.now(timezone.utc) + timedelta(minutes=1)))
+ 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
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index 84927502b00..f53001f17e0 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -397,6 +397,28 @@ cron:
failure_nudge_threshold: 3 # default; 0 disables the nudge
```
+### Automatic re-runs when the model was unreachable
+
+A recurring job whose run fails with a transient network or DNS error before
+a single model call was made — the classic case is a fire right after the
+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.
+
+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
+ladder is exhausted. Any run that reaches the model (success or failure)
+resets the ladder. One-shot jobs are excluded: their dispatch accounting is
+at-most-times and a consumed dispatch is never resurrected. Retries never
+fire past the schedule's own next occurrence when that comes sooner.
+
+```yaml
+cron:
+ retry_unreachable: false # default true; disables the automatic re-runs
+```
+
### Failure incidents: acknowledge a known failure
A recurring job that keeps failing with the *same* error pings you on every