feat(cron): doctor flags overdue next_run_at as silent non-firing

Widens the salvaged cron doctor with the highest-value fleet check:
an active job whose next_run_at is parked >15min in the past is not
firing (dead ticker, downed gateway, wedged fire-claim). Also registers
doctor in the docs (cron guide + CLI reference) and resolves the salvage
onto current main alongside runs/incidents/notepad.
This commit is contained in:
Teknium
2026-08-31 08:16:15 -07:00
parent b028fe632e
commit f2f7a3bf15
4 changed files with 92 additions and 2 deletions
+32 -1
View File
@@ -582,6 +582,32 @@ def _script_health_issue(script: str) -> Optional[str]:
return None
# Grace period before an overdue ``next_run_at`` is reported. The ticker runs
# once a minute and a busy tick can push dispatch a few minutes late; only a
# next_run_at parked well in the past means the job is silently not firing
# (ticker dead, gateway down, or a wedged fire-claim).
_OVERDUE_GRACE_SECONDS = 15 * 60
def _next_run_overdue_issue(next_run: str) -> Optional[str]:
"""Return an issue string when ``next_run_at`` is parked in the past."""
from datetime import datetime, timezone
try:
dt = datetime.fromisoformat(next_run.replace("Z", "+00:00"))
except ValueError:
return f"next_run_at is not a valid timestamp: {next_run!r}"
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
overdue_s = (datetime.now(timezone.utc) - dt).total_seconds()
if overdue_s > _OVERDUE_GRACE_SECONDS:
hours = overdue_s / 3600
if hours >= 1:
return f"next_run_at is {hours:.1f}h overdue — job is not firing (is the scheduler running?)"
return f"next_run_at is {overdue_s / 60:.0f}m overdue — job is not firing (is the scheduler running?)"
return None
def _cron_doctor_issues_for_job(job: Dict[str, Any]) -> List[str]:
issues: List[str] = []
@@ -595,8 +621,13 @@ def _cron_doctor_issues_for_job(job: Dict[str, Any]) -> List[str]:
issues.append(f"last delivery failed: {delivery_err}")
if job.get("enabled", True) and job.get("state") not in {"paused", "completed"}:
if not job.get("next_run_at"):
next_run = str(job.get("next_run_at") or "").strip()
if not next_run:
issues.append("active job has no next_run_at")
else:
overdue = _next_run_overdue_issue(next_run)
if overdue:
issues.append(overdue)
script = str(job.get("script") or "").strip()
if job.get("no_agent") and not script:
+32
View File
@@ -160,6 +160,38 @@ class TestCronDoctor:
assert rc == 0
assert "✓ Cron doctor found no issues" in out
def test_doctor_flags_overdue_next_run(self, tmp_cron_dir, capsys):
from datetime import datetime, timedelta, timezone
create_job(prompt="Hourly ping", schedule="every 1h")
jobs = load_jobs()
stale = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()
jobs[0]["next_run_at"] = stale
save_jobs(jobs)
rc = cron_command(Namespace(cron_command="doctor"))
out = capsys.readouterr().out
assert rc == 1
assert "overdue" in out
assert "not firing" in out
def test_doctor_tolerates_slightly_late_next_run(self, tmp_cron_dir, capsys):
from datetime import datetime, timedelta, timezone
create_job(prompt="Hourly ping", schedule="every 1h")
jobs = load_jobs()
# 5 minutes late is within the ticker grace window — healthy.
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
jobs[0]["next_run_at"] = recent
save_jobs(jobs)
rc = cron_command(Namespace(cron_command="doctor"))
out = capsys.readouterr().out
assert rc == 0
assert "✓ Cron doctor found no issues" in out
class TestGatewayNotRunningWarning:
"""`cron create` / `cron list` must warn when the gateway (and thus the
+2 -1
View File
@@ -604,7 +604,7 @@ hermes status [--all] [--deep]
## `hermes cron`
```bash
hermes cron <list|create|edit|pause|resume|run|remove|status|tick>
hermes cron <list|create|edit|pause|resume|run|remove|status|runs|incidents|doctor|tick>
```
| Subcommand | Description |
@@ -617,6 +617,7 @@ hermes cron <list|create|edit|pause|resume|run|remove|status|tick>
| `run` | Trigger a job on the next scheduler tick. |
| `remove` | Delete a scheduled job. |
| `status` | Check whether the cron scheduler is running. |
| `doctor` | Read-only fleet health check: failed runs, failed deliveries, overdue/missing `next_run_at`, missing scripts or workdirs. Exits non-zero when issues are found. |
| `tick` | Run due jobs once and exit. |
The cron **trigger** is pluggable via the `cron.provider` config key. Empty
+26
View File
@@ -379,6 +379,32 @@ written.
Recording is always on and costs nothing to ignore — no ping is ever
suppressed until you explicitly `ack`.
### Fleet health check: `hermes cron doctor`
`hermes cron doctor` is a read-only health check over every active job. It
prints grouped, per-job issues and exits `1` when anything actionable is
found (`0` when healthy), so it works from a terminal, a watchdog script, or
a CI-style smoke check:
```bash
hermes cron doctor
```
Checks per active job:
- last run failed (`last_status` not ok, with the recorded error),
- last delivery failed (the output was produced but never reached you),
- `next_run_at` missing, or parked in the past beyond a 15-minute ticker
grace window — the "job is silently not firing" signal (scheduler dead,
gateway down, or a wedged fire-claim),
- script missing, not a file, or resolving outside `HERMES_HOME/scripts`,
- `no_agent` job with no script,
- configured `workdir` that no longer exists.
Doctor never mutates jobs or state — it only reports. Pair it with
`hermes cron incidents` (durable failure records) and `hermes cron runs`
(attempt ledger) when digging into a flagged job.
## Delivery options
When scheduling jobs, you specify where the output goes: