The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): probe the store the way a save writes it; print the store warning before job reads
kshitijk4poorb476fb107e5c
diff --git a/cron/store_health.py b/cron/store_health.pyindex c59dd2f9e67..c8a13b0416f 100644--- a/cron/store_health.py+++ b/cron/store_health.py@@ -10,11 +10,11 @@ another process, so they cannot read this record or trust markers in a directoryfrom __future__ import annotations+import contextlibimport errnoimport loggingimport osimport shutil-import tempfileimport threadingimport timefrom dataclasses import dataclass, field@@ -27,8 +27,6 @@ logger = logging.getLogger("cron.jobs")PROBE_INTERVAL_SECONDS = 60.0# Store-write failures that degrade the store (the tick keeps running) instead of failing the tick.UNWRITABLE_ERRNOS = frozenset({errno.EROFS, errno.EACCES, errno.EPERM, errno.ENOSPC, errno.EDQUOT})-# 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 << 20FIX_HINT = "free disk space, remount it read-write, or fix permissions on {store}"@@ -245,17 +243,32 @@ def free_bytes(path: Path) -> Optional[int]: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."""+ """Write probe mirroring a jobs.json save: ``None`` when it would land (or the store does not+ exist yet), else the OSError it would hit. Stages a payload the size of the current jobs.json+ (plus a page) where the save stages it (beside a symlinked file's real target), so a full,+ over-quota or read-only target fails here the way the save would."""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))+ from utils import mkstemp_beside+ jobs_file = cron_dir / "jobs.json"try:- fd, tmp = tempfile.mkstemp(dir=cron_dir, prefix=".probe_")- os.close(fd)- os.unlink(tmp)+ size = jobs_file.stat().st_size + 4096+ except OSError:+ size = 4096+ target = os.path.realpath(jobs_file)+ if os.path.exists(target) and not os.access(target, os.W_OK): # e.g. a read-only symlink target+ return OSError(errno.EACCES, os.strerror(errno.EACCES), target)+ tmp = None+ try:+ fd, tmp = mkstemp_beside(jobs_file, prefix=".probe_")+ with os.fdopen(fd, "wb") as f:+ f.write(b"\0" * size)+ f.flush()+ os.fsync(f.fileno())except OSError as exc:return exc+ finally:+ if tmp is not None:+ with contextlib.suppress(OSError):+ os.unlink(tmp)return Nonediff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex 97cb1fc31c3..2ccaf46342e 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -177,8 +177,14 @@ _STATE_BADGES = {"paused": ("[paused]", Colors.YELLOW), "completed": ("[completedef cron_list(show_all: bool = False):"""List all scheduled jobs."""from cron.jobs import effective_job_state, list_jobs- store_report = _store_unwritable_report()- jobs = list_jobs(include_disabled=True)+ 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+ returnif not show_all:jobs = [job for job in jobs@@ -192,8 +198,6 @@ def cron_list(show_all: bool = False):return_print_banner(f"Scheduled Jobs (profile: {get_active_profile_name()})")- if store_report is not None:- _print_store_unwritable(store_report, brief=True)for job in jobs:# effective_job_state honours the scheduler flag — never [paused] when enabled=true.@@ -427,8 +431,7 @@ def _print_store_unwritable(report: dict, *, brief: bool = False) -> None:f"are being skipped; {report['fix']}. See `hermes cron status`.", Colors.RED))returnprint(color("⚠ Cron store is NOT writable — scheduled jobs are being skipped", Colors.RED))- print(color(f" {report['store']}: {report['error']} (last successful write {report['since']}; "- f"{report['skipped']} due run(s) not fired)", Colors.RED))+ print(color(f" {report['store']}: {report['error']} (last successful write {report['since']})", Colors.RED))print(color(f" Fix: {report['fix']}. Each due job then fires once on the next tick.", Colors.YELLOW))@@ -502,12 +505,19 @@ def cron_status():from hermes_cli.profiles import get_active_profile_nameprint()- 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)+ # 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 = []+ 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))print()provider = _active_cron_provider_name()if provider != "builtin":diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.pyindex 234bdb9cdbf..23ae5cb5e64 100644--- a/tests/cron/test_due_scan_save_failure.py+++ b/tests/cron/test_due_scan_save_failure.py@@ -325,12 +325,31 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,os.chmod(cron_dir, 0o500)try:cron_cli.cron_status()+ os.chmod(cron_dir, 0o700)+ (cron_dir / "output").rmdir()+ os.chmod(cron_dir, 0o500)+ cron_cli.cron_list() # the job read would create cron/output and fail: the banner comes firstfinally:os.chmod(cron_dir, 0o700)out = capsys.readouterr().outassert out.lstrip().startswith("⚠ Cron store is NOT writable — scheduled jobs are being skipped")assert f"{cron_dir}: EACCES" in out and "1 due run(s) not fired" in outassert f"fix permissions on {cron_dir}" in out+ assert f"⚠ Cron store {cron_dir} is NOT writable (EACCES" in out+ store_health._degraded.clear()++ target = cron_store / "ro" / "jobs.json" # the save follows a symlinked jobs.json to its target+ target.parent.mkdir()+ target.write_text((cron_dir / "jobs.json").read_text())+ (cron_dir / "jobs.json").unlink()+ (cron_dir / "jobs.json").symlink_to(target)+ os.chmod(target, 0o400)+ os.chmod(target.parent, 0o500)+ try:+ assert store_health.probe_store(cron_dir) is not None+ finally:+ os.chmod(target.parent, 0o700)+ os.chmod(target, 0o600)sent = []