Skip to content

The agent that grows with you

refactor(cron): drop the warn_store_unwritable wrapper and two getattr hacks

kshitijk4poor4453800b82e8
diff --git a/agent/monitoring/cron_health.py b/agent/monitoring/cron_health.py
index b271f562f1a..c8029a70497 100644
--- a/agent/monitoring/cron_health.py
+++ b/agent/monitoring/cron_health.py
@@ -153,7 +153,7 @@ _METRIC_GROUPS: tuple[tuple[Callable[[list[GatewayMetric]], None], str], ...] =
(_job_metrics, "cron job metrics unavailable"),
(_single_metric("hermes.cron.jobs.running", lambda: len(get_running_job_ids())), "cron running-job metric unavailable"),
(_single_metric("hermes.cron.store.writable", lambda: int(degraded_record() is None)), "cron store metric unavailable"),
- (_single_metric("hermes.cron.store.skipped_runs", lambda: getattr(degraded_record(), "skipped_runs", 0)),
+ (_single_metric("hermes.cron.store.skipped_runs", lambda: (r.skipped_runs if (r := degraded_record()) else 0)),
"cron store metric unavailable"),
)
diff --git a/cron/jobs.py b/cron/jobs.py
index 81d09d00e19..18aabae12cc 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1249,13 +1249,6 @@ def _write_marker(name: str, text: str, tmp_prefix: str) -> None:
pass
-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."""
- store_health.note_unwritable(_current_cron_store().cron_dir, exc, consequence, site, skipped_jobs)
-
-
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.
@@ -1450,7 +1443,7 @@ def load_jobs() -> List[Dict[str, Any]]:
save_jobs(jobs, replace=unmergeable and _peek_jobs_unlocked() is None)
logger.warning("Auto-repaired jobs.json (%s)", repair)
except OSError as exc: # repaired in memory; the next load retries the persist
- warn_store_unwritable(exc, f"jobs.json repair ({repair}) not persisted", "load")
+ store_health.note_unwritable(exc, f"jobs.json repair ({repair}) not persisted", "load")
_record_load_stamp(pre_read_stamp)
return jobs
@@ -3357,7 +3350,7 @@ def _get_due_jobs_locked() -> List[Dict[str, Any]]:
try:
save_jobs(raw_jobs, removed_ids=scan.removed or None)
except OSError as exc: # repairs live in memory; the next tick retries the persist
- warn_store_unwritable(exc, "due-scan repairs not persisted", "scan")
+ store_health.note_unwritable(exc, "due-scan repairs not persisted", "scan")
return due
diff --git a/cron/scheduler.py b/cron/scheduler.py
index edd39dfab81..3fa0365a4a5 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -513,8 +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,
- warn_store_unwritable)
+ save_job_output, self_removal_delivery_allowed, self_removal_delivery_scope, use_cron_store)
+from cron import store_health
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,
@@ -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", [job])
+ store_health.note_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 fc761fbba52..7e8d301299d 100644
--- a/cron/scheduler_tick.py
+++ b/cron/scheduler_tick.py
@@ -6,7 +6,6 @@ import logging
import time
from cron import store_health
-from cron.jobs import warn_store_unwritable
logger = logging.getLogger("cron.scheduler")
@@ -118,10 +117,9 @@ 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.
- 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)
+ skipped = [j for j in due_jobs if (j.get("schedule") or {}).get("kind") in {"cron", "interval"}]
+ due_jobs = [j for j in due_jobs if j not in skipped]
+ store_health.note_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
index 4610093789d..38e6ad5da7c 100644
--- a/cron/store_health.py
+++ b/cron/store_health.py
@@ -95,10 +95,12 @@ 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)
+def note_unwritable(exc: OSError, consequence: str, site: str, skipped_jobs: Iterable[dict] = (),
+ cron_dir: Optional[Path] = None) -> None:
+ """Record a failed write to ``cron_dir`` (default: the active store); WARN once, when the store
+ enters the degraded state. Callers skip the dispatch that needed the write: no job runs
+ without a durable advance/fire claim."""
+ store = str(cron_dir if cron_dir is not None else _active_cron_dir())
with _lock:
record = _degraded.get(store)
entered = record is None
diff --git a/gateway/cron_store_notices.py b/gateway/cron_store_notices.py
index 3ea79b1b455..02ad91b2196 100644
--- a/gateway/cron_store_notices.py
+++ b/gateway/cron_store_notices.py
@@ -81,7 +81,7 @@ async def send_cron_store_notice(runner, event: str, record) -> None:
key = "gateway.cron_store.unwritable" if event == "unwritable" else "gateway.cron_store.recovered"
message = t(key, **fields)
store_home = hermes_home_key(Path(record.store).parent)
- served_homes = getattr(runner, "_served_profile_homes", None) or {}
+ served_homes = runner._served_profile_homes or {}
logger.info("Broadcasting cron store %s notice for %s", event, record.store)
for profile, platform, _cfg, home, transport in list(runner._served_home_channel_transports()):
served_home = served_homes.get(profile) if profile is not None else None
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index 78ee266e618..97cb1fc31c3 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -502,8 +502,10 @@ def cron_status():
from hermes_cli.profiles import get_active_profile_name
print()
- if (store_report := _store_unwritable_report()) is not None:
- store_report["skipped"] = sum(1 for j in list_jobs(include_disabled=False)
+ store_report = _store_unwritable_report() # before list_jobs: loading re-secures the dir mode
+ active_jobs = list_jobs(include_disabled=False)
+ if store_report is not None:
+ store_report["skipped"] = sum(1 for j in active_jobs
if (_next_run_overdue_seconds(j.get("next_run_at")) or 0) > 0)
_print_store_unwritable(store_report)
print()
@@ -594,7 +596,7 @@ def cron_status():
" Check: hermes cron status from this profile should show its ticker heartbeat.\n")
print()
- _print_active_jobs_summary(list_jobs(include_disabled=False))
+ _print_active_jobs_summary(active_jobs)
print()
diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.py
index 7b84f02d237..ee898209e76 100644
--- a/tests/cron/test_due_scan_save_failure.py
+++ b/tests/cron/test_due_scan_save_failure.py
@@ -88,7 +88,7 @@ def test_due_jobs_are_returned_when_the_store_cannot_be_saved(cron_store, full_d
assert [d["id"] for d in get_due_jobs()] == ["due-job"]
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")
+ store_health.note_unwritable(OSError(errno.ENOSPC, "No space left on device"), "x", "scan")
# 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.
@@ -239,7 +239,7 @@ def test_skipped_oneshot_survives_recovery_by_any_save(cron_store, monkeypatch):
repeat={"times": 1, "completed": 0})
save_jobs([once])
enospc = OSError(errno.ENOSPC, "No space left on device")
- cronjobs.warn_store_unwritable(enospc, "x", "claim", [once])
+ store_health.note_unwritable(enospc, "x", "claim", [once])
clock["now"] = FIXED_NOW + timedelta(minutes=10)
save_jobs(load_jobs() + [dict(_due_job("other"), next_run_at=(clock["now"] + timedelta(hours=1)).isoformat())])
assert store_health.degraded_record(cron_store / "cron") is None
@@ -266,7 +266,7 @@ def test_idle_tick_reprobes_a_degraded_store_and_clears_it(cron_store, monkeypat
probe_result = [enospc]
monkeypatch.setattr(store_health, "probe_store", lambda _d: probe_result[0])
save_jobs([])
- cronjobs.warn_store_unwritable(enospc, "x", "scan")
+ store_health.note_unwritable(enospc, "x", "scan")
assert scheduler.tick(verbose=False, sync=True) == 0 # idle and still full: stays degraded
probe_result[0] = None
clock["mono"] += 30.0
@@ -325,21 +325,21 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,
install_cron_store_notices(runner, loop)
enospc = OSError(errno.ENOSPC, "No space left on device")
for site in ("scan", "advance", "claim"): # one outage, many failing sites
- cronjobs.warn_store_unwritable(enospc, "x", site, [_due_job()])
+ store_health.note_unwritable(enospc, "x", site, [_due_job()])
save_jobs([_due_job()])
save_jobs([_due_job()])
- cronjobs.warn_store_unwritable(enospc, "x", "scan", [_due_job()]) # flaps back within the window
+ store_health.note_unwritable(enospc, "x", "scan", [_due_job()]) # flaps back within the window
settle()
assert [m[:2] for _, m in sent] == ["⚠️"] # still down: no "writable again", ever
save_jobs([_due_job()])
- cronjobs.warn_store_unwritable(enospc, "x", "scan", [_due_job()]) # re-entry cancels the pending recovery
+ store_health.note_unwritable(enospc, "x", "scan", [_due_job()]) # re-entry cancels the pending recovery
save_jobs([_due_job()])
settle()
- cronjobs.warn_store_unwritable(enospc, "x", "scan", [_due_job()]) # already writable when the loop runs:
+ store_health.note_unwritable(enospc, "x", "scan", [_due_job()]) # already writable when the loop runs:
save_jobs([_due_job()]) # nothing announced, so no lone "recovered" either
settle()
install_cron_store_notices(SimpleNamespace(), loop) # a send that raises is logged, not lost
- cronjobs.warn_store_unwritable(enospc, "x", "scan", [_due_job()])
+ store_health.note_unwritable(enospc, "x", "scan", [_due_job()])
settle()
finally:
loop.close()
diff --git a/tests/monitoring/test_cron_health_export.py b/tests/monitoring/test_cron_health_export.py
index 77d960be64c..e190c22d84f 100644
--- a/tests/monitoring/test_cron_health_export.py
+++ b/tests/monitoring/test_cron_health_export.py
@@ -39,11 +39,9 @@ def test_cron_store_writability_is_exported(monkeypatch):
import errno
from agent.monitoring.cron_health import build_cron_health_snapshot
from cron import store_health
- from cron.jobs import _current_cron_store
-
monkeypatch.setattr(store_health, "_degraded", {})
monkeypatch.setattr(store_health, "_listener", None)
- store_health.note_unwritable(_current_cron_store().cron_dir, OSError(errno.ENOSPC, "full"), "x", "advance",
+ store_health.note_unwritable(OSError(errno.ENOSPC, "full"), "x", "advance",
[{"id": "job", "next_run_at": "2026-06-22T12:00:00+00:00"}])
degraded = build_cron_health_snapshot()
assert (_metric(degraded, "hermes.cron.store.writable").value,