Skip to content

The agent that grows with you

fix(cron): rate-limit the due-scan save warning through the store-unwritable helper

kshitijk4poorf204976a6236
diff --git a/cron/jobs.py b/cron/jobs.py
index 2124340ba85..16535140e21 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1247,6 +1247,24 @@ def _write_marker(name: str, text: str, tmp_prefix: str) -> None:
pass
+# One WARNING per errno per window: an unwritable store fails every 60s tick until fixed.
+_STORE_WARN_INTERVAL_SECONDS = 900.0
+_last_store_warning: dict = {}
+
+
+def warn_store_unwritable(exc: OSError, consequence: str) -> None:
+ """Rate-limited WARNING for a failed cron store write (ENOSPC/EROFS/EACCES). Callers skip the
+ dispatch that needed the write: no job runs without a durable advance/fire claim."""
+ now, key = time.monotonic(), exc.errno
+ last = _last_store_warning.get(key)
+ if last is not None and now - last < _STORE_WARN_INTERVAL_SECONDS:
+ return
+ _last_store_warning[key] = now
+ logger.warning(
+ "Cron store is unwritable (%s); %s. Jobs stay due and fire once the store accepts writes "
+ "again.", exc, consequence)
+
+
def record_ticker_heartbeat(success: bool = False) -> None:
"""Record ticker liveness (+ last-success marker when ``success``) so `cron status` can tell
"alive but failing" from "firing"; scoped per profile store.
@@ -3338,15 +3356,8 @@ def _get_due_jobs_locked() -> List[Dict[str, Any]]:
if scan.needs_save:
try:
save_jobs(raw_jobs, removed_ids=scan.removed or None)
- except OSError as exc:
- # The repairs above are already applied in memory — that is what the scan keys off — so a
- # store that cannot be written right now (full disk, read-only mount, permissions) must
- # not take the whole tick down with it: every job on the profile would stop firing until
- # a write succeeds, the exact fast-forward freeze the normalization above prevents.
- # Persisting is retried by the next tick.
- logger.warning(
- "Cron store repairs could not be persisted (%s); due jobs still dispatched",
- exc)
+ except OSError as exc: # repairs live in memory; the next tick retries the persist
+ warn_store_unwritable(exc, "due-scan repairs not persisted")
return due
diff --git a/cron/scheduler.py b/cron/scheduler.py
index cdf62ebe612..e982386d8b8 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -513,7 +513,8 @@ def _resolve_job_reasoning_config(job: dict, cfg: dict, model: str) -> dict | No
from cron.jobs import (
_ensure_cron_dir, advance_next_runs, claim_dispatch, claim_job_for_fire, fire_claim_fence,
clear_run_claim, get_due_jobs, heartbeat_fire_claim, heartbeat_run_claim, mark_job_run,
- save_job_output, self_removal_delivery_allowed, self_removal_delivery_scope, use_cron_store)
+ save_job_output, self_removal_delivery_allowed, self_removal_delivery_scope, use_cron_store,
+ warn_store_unwritable)
from cron.execution_identity import enter_cron_execution, exit_cron_execution
from cron.executions import (
_TERMINAL_STATES, HANDOFF_ADOPTION_GRACE_SECONDS, create_execution, finish_execution,
@@ -4264,8 +4265,7 @@ def _process_due_job(job: dict, adapters, loop, verbose: bool) -> bool:
try:
claimed = claim_job_for_fire(job["id"], return_job=True)
except OSError as exc:
- from cron.scheduler_tick import warn_store_unwritable
- warn_store_unwritable(exc, f"job '{job.get('name') or job['id']}'")
+ warn_store_unwritable(exc, f"skipped job '{job.get('name') or job['id']}'")
finish_execution(
job["execution_id"], success=False, error=f"Cron store unwritable; not started: {exc}")
return False
diff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.py
index cd342fbc9c9..f3b086c2e64 100644
--- a/cron/scheduler_tick.py
+++ b/cron/scheduler_tick.py
@@ -5,12 +5,9 @@ import contextlib
import logging
import time
-logger = logging.getLogger("cron.scheduler")
-
-# One WARNING per errno per window: an unwritable store fails every 60s tick until fixed.
-_STORE_WARN_INTERVAL_SECONDS = 900.0
-_last_store_warning: dict = {}
+from cron.jobs import warn_store_unwritable
+logger = logging.getLogger("cron.scheduler")
# Log the yield at most once per episode (reset when the skew changes) to avoid per-interval spam.
_YIELD_LOG_INTERVAL_SECONDS = 3600.0
@@ -33,19 +30,6 @@ def _log_tick_yield_once(reason: str) -> None:
-def warn_store_unwritable(exc: OSError, skipped: str) -> None:
- """Rate-limited WARNING for a cron store write that failed (ENOSPC/EROFS/EACCES). The caller
- skips the dispatch that needed the write: no job runs without a durable advance/fire claim."""
- now = time.monotonic()
- last = _last_store_warning.get(exc.errno)
- if last is not None and now - last < _STORE_WARN_INTERVAL_SECONDS:
- return
- _last_store_warning[exc.errno] = now
- logger.warning(
- "Cron store is unwritable (%s); skipped %s. Jobs stay due and fire once the store "
- "accepts writes again.", exc, skipped)
-
-
def tick(verbose=True, adapters=None, loop=None, sync=True, *, can_dispatch=None):
from hermes_cli.backend_retirement import retirement
@@ -128,7 +112,7 @@ def _tick_admitted(
# No durable advance -> a crash mid-run would re-fire recurring jobs; skipping is the
# at-most-once side. One-shots still go through their own fire claim.
recurring = [j for j in due_jobs if j.get("schedule", {}).get("kind") in {"cron", "interval"}]
- warn_store_unwritable(exc, f"{len(recurring)} recurring job(s)")
+ warn_store_unwritable(exc, f"skipped {len(recurring)} recurring job(s)")
due_jobs = [j for j in due_jobs if j not in recurring]
if not due_jobs:
return 0
diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.py
index 6d6f4260376..b898979c131 100644
--- a/tests/cron/test_due_scan_save_failure.py
+++ b/tests/cron/test_due_scan_save_failure.py
@@ -72,17 +72,24 @@ def full_disk(monkeypatch):
return _raise
-def test_due_jobs_are_returned_when_the_store_cannot_be_saved(cron_store, full_disk):
+def test_due_jobs_are_returned_when_the_store_cannot_be_saved(cron_store, full_disk, monkeypatch, caplog):
save_jobs([_due_job(), _half_paused_job()])
+ monkeypatch.setattr(cronjobs, "_last_store_warning", {})
- assert [d["id"] for d in get_due_jobs()] == ["due-job"]
+ with caplog.at_level(logging.WARNING, logger="cron.jobs"):
+ assert [d["id"] for d in get_due_jobs()] == ["due-job"]
+ assert [d["id"] for d in get_due_jobs()] == ["due-job"]
+
+ # Rate-limited like the tick-level skips: one WARNING per outage, not one per 60s scan.
+ warnings = [r.getMessage() for r in caplog.records if r.name == "cron.jobs" and r.levelno == logging.WARNING]
+ assert len(warnings) == 1 and "due-scan repairs not persisted" in warnings[0]
def test_tick_on_unwritable_store_returns_cleanly_without_dispatch(cron_store, monkeypatch, caplog):
"""Real tick(): the advance cannot be persisted, so the recurring job is NOT run (at-most-once);
the one-shot still reaches its fire claim, which fails closed with a ``failed`` execution row.
The tick neither raises nor alters the store; a WARNING names the unwritable store."""
- from cron import executions, scheduler, scheduler_tick
+ from cron import executions, scheduler
once = dict(_due_job("once"), schedule={"kind": "once", "run_at": FIXED_NOW.isoformat(), "display": "once"},
repeat={"times": 1, "completed": 0})
@@ -92,7 +99,7 @@ def test_tick_on_unwritable_store_returns_cleanly_without_dispatch(cron_store, m
monkeypatch.setattr(executions, "EXECUTIONS_FILE", cron_store / "cron" / "executions.db")
monkeypatch.setattr(scheduler, "run_one_job", lambda job, **k: ran.append(job["id"]) or True)
monkeypatch.setattr(scheduler, "_should_yield_tick_to_fresh_gateway", lambda: None)
- monkeypatch.setattr(scheduler_tick, "_last_store_warning", {})
+ monkeypatch.setattr(cronjobs, "_last_store_warning", {})
def _enospc(*_args, **_kwargs):
raise OSError(errno.ENOSPC, "No space left on device")