Skip to content

The agent that grows with you

fix(cron): keep one degraded state per unwritable store and stop burning ticks on it

kshitijk4poor759b1c34adb5
diff --git a/cron/jobs.py b/cron/jobs.py
index 29dcfe6e54c..be201ea7084 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1248,24 +1248,12 @@ def _write_marker(name: str, text: str, tmp_prefix: str) -> None:
pass
-# One WARNING per (store, errno, site) per window: an unwritable store fails every 60s tick until fixed;
-# the site keeps the scan's warning from silencing the tick's "skipped jobs" one.
-_STORE_WARN_INTERVAL_SECONDS = 900.0
-_last_store_warning: dict = {}
-
-
-def warn_store_unwritable(exc: OSError, consequence: str, site: 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."""
- cron_dir = str(_current_cron_store().cron_dir) # multi-profile gateway: one key per store
- now, key = time.monotonic(), (cron_dir, exc.errno, site)
- 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 %s is unwritable (%s); %s. Jobs stay due and fire once the store accepts writes "
- "again.", cron_dir, exc, consequence)
+def warn_store_unwritable(exc: OSError, consequence: str, site: str, skipped_jobs=()) -> None:
+ """Record a failed cron store write (ENOSPC/EROFS/EACCES) in the store's degraded state, which
+ warns once per outage. Callers skip the dispatch that needed the write: no job runs without a
+ durable advance/fire claim."""
+ from cron.store_health import note_unwritable
+ note_unwritable(_current_cron_store().cron_dir, exc, consequence, site, skipped_jobs)
def record_ticker_heartbeat(success: bool = False) -> None:
@@ -1616,6 +1604,8 @@ def _save_jobs_unlocked(
# Invalidate (never refresh) the stamp: a refresh would let a nested save certify disk
# against an OUTER caller's stale payload. Later saves take the full merge (fail-safe).
_record_load_stamp(None)
+ from cron.store_health import note_writable
+ note_writable(jobs_file.parent)
return
except BaseException:
_unlink_quiet(tmp_path)
diff --git a/cron/scheduler.py b/cron/scheduler.py
index b2e9434c187..edd39dfab81 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -4265,7 +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:
- warn_store_unwritable(exc, f"skipped job '{job.get('name') or job['id']}'", "claim")
+ warn_store_unwritable(exc, f"skipped job '{job.get('name') or job['id']}'", "claim", [job])
settle_unstarted_execution(
job["execution_id"], job["id"], f"Cron store unwritable; not started: {exc}")
return False
diff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.py
index c9f6cd69427..121fb5aec12 100644
--- a/cron/scheduler_tick.py
+++ b/cron/scheduler_tick.py
@@ -5,6 +5,7 @@ import contextlib
import logging
import time
+from cron import store_health
from cron.jobs import warn_store_unwritable
logger = logging.getLogger("cron.scheduler")
@@ -99,6 +100,12 @@ def _tick_admitted(
_sched._sweep_mcp_orphans()
return 0
+ if store_health.dispatch_blocked(due_jobs):
+ # Known-unwritable store, re-probed at most once a minute: every advance/claim would
+ # fail, so skip them (the skip is recorded) and keep the tick's housekeeping alive.
+ _sched._sweep_mcp_orphans()
+ return 0
+
if verbose:
_sched.logger.info("%s - %s job(s) due", _sched._hermes_now().strftime('%H:%M:%S'), len(due_jobs))
@@ -110,9 +117,10 @@ def _tick_admitted(
except OSError as exc:
# 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.
- n = len(due_jobs)
- due_jobs = [j for j in due_jobs if j.get("schedule", {}).get("kind") not in {"cron", "interval"}]
- warn_store_unwritable(exc, f"skipped {n - len(due_jobs)} recurring job(s)", "advance")
+ recurring = [j.get("schedule", {}).get("kind") in {"cron", "interval"} for j in due_jobs]
+ skipped = [j for j, r in zip(due_jobs, recurring) if r]
+ due_jobs = [j for j, r in zip(due_jobs, recurring) if not r]
+ warn_store_unwritable(exc, f"skipped {len(skipped)} recurring job(s)", "advance", skipped)
if not due_jobs:
_sched._sweep_mcp_orphans()
return 0
diff --git a/cron/store_health.py b/cron/store_health.py
new file mode 100644
index 00000000000..65fc69cd7f4
--- /dev/null
+++ b/cron/store_health.py
@@ -0,0 +1,205 @@
+"""Degraded state for an unwritable cron store (ENOSPC, EROFS, EACCES).
+
+A full disk or read-only mount fails every store write on every 60s tick. Instead of one warning
+per failing call site, each store directory gets ONE in-memory record: set by the first failed
+write, updated by later ones, cleared by the first jobs.json save that lands. While it is set,
+the tick skips the advance/claim work that can only fail and re-probes the store at most once a
+minute. ``probe_store`` is also what ``hermes cron status`` and ``hermes doctor`` use: they run in
+another process, so they cannot read this record or trust markers in a directory nobody can write.
+"""
+
+from __future__ import annotations
+
+import errno
+import logging
+import os
+import shutil
+import tempfile
+import threading
+import time
+from dataclasses import dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Callable, Iterable, Optional
+
+logger = logging.getLogger("cron.jobs")
+
+PROBE_INTERVAL_SECONDS = 60.0
+# Below this the probe reports ENOSPC: an empty temp file can still be created on a full disk.
+_PROBE_MIN_FREE_BYTES = 1 << 20
+# `hermes doctor` warns below this, before the store actually starts failing.
+LOW_FREE_BYTES = 100 << 20
+FIX_HINT = "free disk space, remount it read-write, or fix permissions on {store}"
+
+
+def describe_error(exc: OSError) -> str:
+ code = errno.errorcode.get(exc.errno or 0, "")
+ text = exc.strerror or str(exc)
+ return f"{code}: {text}" if code else text
+
+
+@dataclass
+class StoreDegraded:
+ store: str
+ since: float # epoch seconds of the first failed write
+ error: str
+ sites: set = field(default_factory=set)
+ skipped: set = field(default_factory=set) # distinct (job id, scheduled instant) not run
+ # Monotonic time of the last failed dispatch write or re-probe. None until a dispatch write
+ # fails, so a due one-shot reaches its claim and settles its ``failed`` row once per probe.
+ last_probe: Optional[float] = None
+
+ @property
+ def skipped_runs(self) -> int:
+ return len(self.skipped)
+
+ def notice_fields(self) -> dict:
+ since = datetime.fromtimestamp(self.since).astimezone().isoformat(timespec="seconds")
+ return {"store": self.store, "error": self.error, "since": since, "skipped": self.skipped_runs,
+ "fix": FIX_HINT.format(store=self.store)}
+
+
+_DISPATCH_SITES = frozenset({"advance", "claim"})
+_degraded: dict[str, StoreDegraded] = {}
+_lock = threading.Lock()
+# The gateway consumes transitions; ``fn(event, record)`` with event "unwritable" or "recovered".
+_listener: Optional[Callable[[str, StoreDegraded], None]] = None
+
+
+def set_transition_listener(fn: Optional[Callable[[str, StoreDegraded], None]]) -> None:
+ global _listener
+ _listener = fn
+
+
+def _notify(event: str, record: StoreDegraded) -> None:
+ listener = _listener
+ if listener is None:
+ return
+ try: # a notice must never break the cron tick that reported the transition
+ listener(event, record)
+ except Exception:
+ logger.debug("Cron store %s transition listener failed", event, exc_info=True)
+
+
+def _active_cron_dir() -> Path:
+ from cron.jobs import _current_cron_store
+ return _current_cron_store().cron_dir
+
+
+def _run_keys(jobs: Iterable[dict]) -> set:
+ return {(job.get("id"), job.get("next_run_at")) for job in jobs}
+
+
+def note_unwritable(cron_dir: Path, exc: OSError, consequence: str, site: str,
+ skipped_jobs: Iterable[dict] = ()) -> None:
+ """Record a failed store write; WARN once, when the store enters the degraded state."""
+ store = str(cron_dir)
+ with _lock:
+ record = _degraded.get(store)
+ entered = record is None
+ if entered:
+ record = _degraded[store] = StoreDegraded(store, time.time(), describe_error(exc))
+ new_site = site not in record.sites
+ record.sites.add(site)
+ if site in _DISPATCH_SITES: # a dispatch write failed: throttle the next attempt from here
+ record.last_probe = time.monotonic()
+ record.error = describe_error(exc)
+ record.skipped |= _run_keys(skipped_jobs)
+ if entered:
+ logger.warning(
+ "Cron store %s is unwritable (%s); %s. Scheduled jobs are skipped until it accepts writes "
+ "again, then each due job fires once. Fix: %s.", store, exc, consequence,
+ FIX_HINT.format(store=store))
+ _notify("unwritable", record)
+ elif new_site:
+ logger.info("Cron store %s still unwritable (%s); %s", store, exc, consequence)
+
+
+def note_writable(cron_dir: Path) -> None:
+ """A jobs.json save landed: clear the degraded state for that store."""
+ if not _degraded:
+ return
+ with _lock:
+ record = _degraded.pop(str(cron_dir), None)
+ if record is None:
+ return
+ logger.warning("Cron store %s is writable again; %d skipped run(s), catching up once per job",
+ record.store, record.skipped_runs)
+ _notify("recovered", record)
+
+
+def degraded_record(cron_dir: Optional[Path] = None) -> Optional[StoreDegraded]:
+ return _degraded.get(str(cron_dir if cron_dir is not None else _active_cron_dir()))
+
+
+def degraded_records() -> list:
+ with _lock:
+ return list(_degraded.values())
+
+
+def degraded_since(cron_dir: Path) -> Optional[float]:
+ record = _degraded.get(str(cron_dir))
+ return record.since if record is not None else None
+
+
+def dispatch_blocked(due_jobs: list) -> bool:
+ """Whether this tick skips advance/claim for ``due_jobs``: the active store is known
+ unwritable and the minute-throttled re-probe has not seen it accept a write. Skipped runs are
+ recorded; once the probe passes, the dispatch's own save confirms recovery (or re-degrades)."""
+ cron_dir = _active_cron_dir()
+ record = _degraded.get(str(cron_dir))
+ if record is None:
+ return False
+ now = time.monotonic()
+ if record.last_probe is None: # entered in load/scan: dispatch has not been tried yet
+ return False
+ error = None
+ if now - record.last_probe < PROBE_INTERVAL_SECONDS or (error := probe_store(cron_dir)) is not None:
+ with _lock:
+ if error is not None:
+ record.last_probe, record.error = now, describe_error(error)
+ record.skipped |= _run_keys(due_jobs)
+ return True
+ record.last_probe = now
+ return False
+
+
+def probe_report(cron_dir: Path) -> Optional[dict]:
+ """Cross-process view for `cron status` / `doctor`: ``None`` when the store accepts writes,
+ else the notice fields. ``since`` is jobs.json's mtime (the last write that landed);
+ ``skipped`` is left to the caller, which counts the due jobs that have not fired."""
+ error = probe_store(cron_dir)
+ if error is None:
+ return None
+ try:
+ since = datetime.fromtimestamp((cron_dir / "jobs.json").stat().st_mtime).astimezone()
+ since_text = since.isoformat(timespec="seconds")
+ except OSError:
+ since_text = "unknown"
+ store = str(cron_dir)
+ return {"store": store, "error": describe_error(error), "since": since_text,
+ "fix": FIX_HINT.format(store=store)}
+
+
+def free_bytes(path: Path) -> Optional[int]:
+ try:
+ return shutil.disk_usage(path).free
+ except OSError:
+ return None
+
+
+def probe_store(cron_dir: Path) -> Optional[OSError]:
+ """Cheap write probe: ``None`` when ``cron_dir`` accepts a new file (or does not exist yet),
+ else the OSError a store write would hit."""
+ if not cron_dir.is_dir():
+ return None
+ free = free_bytes(cron_dir)
+ if free is not None and free < _PROBE_MIN_FREE_BYTES:
+ return OSError(errno.ENOSPC, os.strerror(errno.ENOSPC), str(cron_dir))
+ try:
+ fd, tmp = tempfile.mkstemp(dir=cron_dir, prefix=".probe_")
+ os.close(fd)
+ os.unlink(tmp)
+ except OSError as exc:
+ return exc
+ return None
diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.py
index d5469c2497c..5ea99ccd26f 100644
--- a/tests/cron/test_due_scan_save_failure.py
+++ b/tests/cron/test_due_scan_save_failure.py
@@ -22,6 +22,7 @@ import pytest
from datetime import datetime, timezone
from cron import jobs as cronjobs
+from cron import store_health
from cron.jobs import get_due_jobs, load_jobs, save_jobs
FIXED_NOW = datetime(2026, 6, 22, 12, 0, 0, tzinfo=timezone.utc)
@@ -29,7 +30,9 @@ FIXED_NOW = datetime(2026, 6, 22, 12, 0, 0, tzinfo=timezone.utc)
@pytest.fixture()
def cron_store(tmp_path, monkeypatch):
- """Redirect cron storage to a temp dir and pin the clock."""
+ """Redirect cron storage to a temp dir, pin the clock, start with no degraded store."""
+ monkeypatch.setattr(store_health, "_degraded", {})
+ monkeypatch.setattr(store_health, "_listener", None)
monkeypatch.setattr("cron.jobs.CRON_DIR", tmp_path / "cron")
monkeypatch.setattr("cron.jobs.JOBS_FILE", tmp_path / "cron" / "jobs.json")
monkeypatch.setattr("cron.jobs.OUTPUT_DIR", tmp_path / "cron" / "output")
@@ -75,7 +78,6 @@ def full_disk(monkeypatch):
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", {})
with caplog.at_level(logging.WARNING, logger="cron.jobs"):
assert [d["id"] for d in get_due_jobs()] == ["due-job"]
@@ -84,7 +86,7 @@ def test_due_jobs_are_returned_when_the_store_cannot_be_saved(cron_store, full_d
with cronjobs.use_cron_store(cron_store / "other-profile"): # a second profile's store
cronjobs.warn_store_unwritable(OSError(errno.ENOSPC, "No space left on device"), "x", "scan")
- # Rate-limited per store: one WARNING per outage per profile, not one per 60s scan, and a
+ # One WARNING per outage per store (its degraded state), not one per 60s scan, and a
# sibling profile on the same errno is not silenced; each names its store.
warnings = [r.getMessage() for r in caplog.records if r.name == "cron.jobs" and r.levelno == logging.WARNING]
assert len(warnings) == 2 and "due-scan repairs not persisted" in warnings[0]
@@ -112,14 +114,14 @@ def test_tick_on_unwritable_store_returns_cleanly_without_dispatch(cron_store, m
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, "_sweep_mcp_orphans", lambda: sweeps.append(1))
- monkeypatch.setattr(cronjobs, "_last_store_warning", {})
monkeypatch.setattr(cronjobs, "_stage_jobs_payload", _enospc)
- with caplog.at_level(logging.WARNING):
+ with caplog.at_level(logging.INFO):
assert scheduler.tick(verbose=False, sync=True) == 0
assert ran == [] and sweeps == [1]
assert f"Cron store {cron_store / 'cron'} is unwritable" in caplog.text
assert "skipped 1 recurring job(s)" in caplog.text # not silenced by the scan's earlier warning
+ assert store_health.degraded_record(cron_store / "cron").skipped_runs == 1 + with_once
assert executions.latest_execution("due-job") is None # skipped before its fire claim
assert load_jobs() == before
row = executions.latest_execution("once")
@@ -164,3 +166,4 @@ def test_dispatch_failure_after_receipt_never_leaves_it_claimed(
assert row is not None and row["status"] == "failed"
if site == "note_cron_execution": # the receipt exists, so creation did not fail
assert "dispatch preparation failed" in caplog.text
+