Skip to content

The agent that grows with you

refactor(cron): share is_recurring, the CLI probe-then-read and the report fields

kshitijk4poor6f88751a7e90
diff --git a/cron/constants.py b/cron/constants.py
index 0e4649f0817..2c612890c1c 100644
--- a/cron/constants.py
+++ b/cron/constants.py
@@ -15,3 +15,8 @@ FIRE_CLAIM_SKEW_SECONDS = 60
# wall-clock cap, so healthy runs may legitimately exceed it and a TTL of exactly the timeout
# would expire live claims.
CLAIM_TTL_INACTIVITY_HEADROOM = 3
+
+
+def is_recurring(job: dict) -> bool:
+ """A cron/interval job (vs a one-shot); a null ``schedule`` counts as not recurring."""
+ return (job.get("schedule") or {}).get("kind") in {"cron", "interval"}
diff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.py
index 266f8f90699..68d3b183a8c 100644
--- a/cron/scheduler_tick.py
+++ b/cron/scheduler_tick.py
@@ -6,6 +6,7 @@ import logging
import time
from cron import store_health
+from cron.constants import is_recurring
logger = logging.getLogger("cron.scheduler")
@@ -40,10 +41,6 @@ def tick(verbose=True, adapters=None, loop=None, sync=True, *, can_dispatch=None
return _tick_admitted(verbose, adapters, loop, sync, can_dispatch=can_dispatch)
-def _is_recurring(job: dict) -> bool:
- return (job.get("schedule") or {}).get("kind") in {"cron", "interval"}
-
-
def _acquire_tick_lock_or_degrade(_sched):
"""The tick lock fd, or None when this tick must not run: another ticker holds the lock, or
the store cannot be written (read-only/full/denied: the lock file cannot even be created), in
@@ -68,9 +65,9 @@ def _advance_or_drop_recurring(_sched, due_jobs: list) -> list:
_sched.advance_next_runs([job["id"] for job in due_jobs])
return due_jobs
except OSError as exc:
- skipped = [j for j in due_jobs if _is_recurring(j)]
+ skipped = [j for j in due_jobs if is_recurring(j)]
store_health.note_unwritable(exc, f"skipped {len(skipped)} recurring job(s)", "advance", skipped)
- return [j for j in due_jobs if not _is_recurring(j)]
+ return [j for j in due_jobs if not is_recurring(j)]
def _tick_admitted(
diff --git a/cron/store_health.py b/cron/store_health.py
index b0d4d4e2e50..603d6960ebd 100644
--- a/cron/store_health.py
+++ b/cron/store_health.py
@@ -38,6 +38,12 @@ def describe_error(exc: OSError) -> str:
return f"{code}: {text}" if code else text
+def _report_fields(store: str, error: str, since: Optional[float]) -> dict:
+ """The fields `cron status`, doctor and the home-channel notices print for an unwritable store."""
+ since_text = "unknown" if since is None else datetime.fromtimestamp(since).astimezone().isoformat(timespec="seconds")
+ return {"store": store, "error": error, "since": since_text, "fix": FIX_HINT.format(store=store)}
+
+
@dataclass
class StoreDegraded:
store: str
@@ -55,9 +61,7 @@ class StoreDegraded:
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)}
+ return dict(_report_fields(self.store, self.error, self.since), skipped=self.skipped_runs)
_DISPATCH_SITES = frozenset({"advance", "claim"})
@@ -232,13 +236,10 @@ def probe_report(cron_dir: Path) -> Optional[dict]:
if error is None:
return None
try:
- since = datetime.fromtimestamp((cron_dir / "jobs.json").stat().st_mtime).astimezone()
- since_text = since.isoformat(timespec="seconds")
+ since = (cron_dir / "jobs.json").stat().st_mtime
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)}
+ since = None
+ return _report_fields(str(cron_dir), describe_error(error), since)
def free_bytes(path: Path) -> Optional[int]:
diff --git a/cron/unreachable_retry.py b/cron/unreachable_retry.py
index 6fe27b6fdf6..be418ed5b18 100644
--- a/cron/unreachable_retry.py
+++ b/cron/unreachable_retry.py
@@ -23,6 +23,7 @@ import logging
from datetime import datetime
from typing import Any, Dict, Optional
+from cron.constants import is_recurring
from hermes_time import now as _hermes_now
logger = logging.getLogger("cron.scheduler")
@@ -64,13 +65,9 @@ def is_model_unreachable_failure(exc: BaseException, agent: Any = None) -> bool:
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 _ladder_applies(job: Dict[str, Any]) -> bool:
"""The ladder's applicability gate: recurring, not paused, and enabled in config."""
- return _is_recurring(job) and job.get("state") != "paused" and retry_enabled()
+ return is_recurring(job) and job.get("state") != "paused" and retry_enabled()
def _ladder_instant(job: Dict[str, Any], natural_next: Optional[datetime],
diff --git a/gateway/cron_store_notices.py b/gateway/cron_store_notices.py
index 8eae5cce1e7..ab48adc0dc0 100644
--- a/gateway/cron_store_notices.py
+++ b/gateway/cron_store_notices.py
@@ -51,16 +51,16 @@ def install_cron_store_notices(runner, loop: asyncio.AbstractEventLoop) -> None:
def send_recovered(record) -> None:
pending.pop(record.store, None)
- if record.store in announced and degraded_record(Path(record.store)) is None:
- send("recovered", record) # else it degraded again (outage goes on) or was never told
+ if record.store in announced: # deliver() drops it if the store degraded again meanwhile
+ send("recovered", record)
def on_loop(event, record) -> None:
store = record.store
if event == "unwritable":
if (handle := pending.pop(store, None)) is not None:
handle.cancel() # never told it recovered: the outage notice still stands
- elif store not in announced and degraded_record(Path(store)) is not None:
- announced.add(store) # recheck: a boot replay can land after the store recovered
+ elif store not in announced: # deliver() drops a boot replay of a since-recovered store
+ announced.add(store)
send(event, record)
elif store in announced and store not in pending: # no lone "recovered"
pending[store] = loop.call_later(NOTICE_REPEAT_SECONDS, send_recovered, record)
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index 2ccaf46342e..8f70e75ab0c 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -176,14 +176,9 @@ _STATE_BADGES = {"paused": ("[paused]", Colors.YELLOW), "completed": ("[complete
def cron_list(show_all: bool = False):
"""List all scheduled jobs."""
- from cron.jobs import effective_job_state, list_jobs
- if (store_report := _store_unwritable_report()) is not None:
- _print_store_unwritable(store_report, brief=True) # before the read, which can fail too
- try:
- jobs = list_jobs(include_disabled=True)
- except OSError:
- if store_report is None:
- raise
+ from cron.jobs import effective_job_state
+ _store_report, jobs = _probe_then_list_jobs(include_disabled=True, brief=True)
+ if jobs is None:
return
if not show_all:
jobs = [
@@ -425,6 +420,22 @@ def _store_unwritable_report() -> Optional[dict]:
return probe_report(_current_cron_store().cron_dir)
+def _probe_then_list_jobs(*, include_disabled: bool, brief: bool = False):
+ """``(store report or None, jobs or None)``. Probes and prints the unwritable-store warning
+ BEFORE reading jobs: loading re-secures the dir mode (masking a mode problem), and on an
+ unwritable store the read itself can fail (it creates cron/output). Jobs is ``None`` only
+ when that read failed on a store already reported unwritable."""
+ from cron.jobs import list_jobs
+ if (report := _store_unwritable_report()) is not None:
+ _print_store_unwritable(report, brief=brief)
+ try:
+ return report, list_jobs(include_disabled=include_disabled)
+ except OSError:
+ if report is None:
+ raise
+ return report, None
+
+
def _print_store_unwritable(report: dict, *, brief: bool = False) -> None:
if brief: # `cron list`: one line
print(color(f"⚠ Cron store {report['store']} is NOT writable ({report['error']}) — scheduled jobs "
@@ -500,21 +511,12 @@ def _print_ticker_health(pids: list, restart_command: str = "hermes gateway rest
def cron_status():
"""Show cron execution status."""
- from cron.jobs import list_jobs
from hermes_cli.gateway import find_gateway_pids, named_profile_served_by_running_multiplexer
from hermes_cli.profiles import get_active_profile_name
print()
- # Probe before list_jobs (loading re-secures the dir mode) and print before it too: on an
- # unwritable store the read itself can fail (it creates cron/output).
- if (store_report := _store_unwritable_report()) is not None:
- _print_store_unwritable(store_report)
- try:
- active_jobs = list_jobs(include_disabled=False)
- except OSError:
- if store_report is None:
- raise
- active_jobs = []
+ store_report, active_jobs = _probe_then_list_jobs(include_disabled=False)
+ active_jobs = active_jobs or []
if store_report is not None:
overdue = sum(1 for j in active_jobs if (_next_run_overdue_seconds(j.get("next_run_at")) or 0) > 0)
print(color(f" {overdue} due run(s) not fired", Colors.RED))