The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): confirm idle recovery with a real save, count misses only when persisted, close the recovery window
kshitijk4poorf6a27e91ef99
diff --git a/cron/jobs.py b/cron/jobs.pyindex 18aabae12cc..24420971d37 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -2897,6 +2897,9 @@ class _DueScan:now: datetimeneeds_save: bool = Falseremoved: Set[str] = field(default_factory=set)+ # Miss/catch-up metrics, emitted once the save that persists the scan's repairs lands: an+ # unwritable store re-finds the same miss every tick, so counting before the save over-counts.+ on_saved: List[Callable[[], None]] = field(default_factory=list)def find(self, job_id: Any) -> Optional[Dict[str, Any]]:return next((rj for rj in self.raw_jobs if rj["id"] == job_id), None)@@ -3127,23 +3130,20 @@ def _fast_forward_missed_recurring(d: _DueJob, grace: int) -> bool:if not new_next:return Falsed.scan.persist(d.job["id"], next_run_at=new_next)- counted = store_health.first_report(_current_cron_store().cron_dir, d.job)if (_instant_after(_ensure_aware(datetime.fromisoformat(new_next)), d.scan.now)and not _cron_config_number("catch_up_missed", True, lambda value: value is not False)):logger.info("Job '%s' missed its scheduled time (%s, grace=%ds). ""Skipping missed occurrence because cron.catch_up_missed is false; next run: %s",d.label, d.next_run, grace, new_next)- if counted:- record_cron_missed(d.job)+ d.scan.on_saved.append(lambda job=d.job: record_cron_missed(job))return Truelogger.info("Job '%s' missed its scheduled time (%s, grace=%ds). ""Running now; next run provisionally set to: %s (re-anchored on completion)",d.label, d.next_run, grace, new_next)- if counted:- from cron.occurrences import record_catch_up_occurrence- record_catch_up_occurrence()+ from cron.occurrences import record_catch_up_occurrence+ d.scan.on_saved.append(record_catch_up_occurrence)return False@@ -3162,7 +3162,7 @@ def _retire_expired_oneshot(d: _DueJob) -> bool:if not (d.job.get("run_claim") or d.job.get("fire_claim")):_write_missed_oneshot_diagnostic(d.job, d.next_run)d.scan.retire(d.job["id"])- record_cron_missed(d.job)+ d.scan.on_saved.append(lambda job=d.job: record_cron_missed(job))return True@@ -3346,11 +3346,15 @@ def _get_due_jobs_locked() -> List[Dict[str, Any]]:"Skipping malformed cron job %r during due scan",job.get("name") or job.get("id") or "?")+ store_health.end_recovery_window(_current_cron_store().cron_dir)if scan.needs_save:try:save_jobs(raw_jobs, removed_ids=scan.removed or None)except OSError as exc: # repairs live in memory; the next tick retries the persiststore_health.note_unwritable(exc, "due-scan repairs not persisted", "scan")+ return due+ for emit in scan.on_saved:+ emit()return duediff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.pyindex 7e8d301299d..051aa956b35 100644--- a/cron/scheduler_tick.py+++ b/cron/scheduler_tick.py@@ -118,7 +118,7 @@ def _tick_admitted(# 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.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]+ due_jobs = [j for j in due_jobs if (j.get("schedule") or {}).get("kind") not in {"cron", "interval"}]store_health.note_unwritable(exc, f"skipped {len(skipped)} recurring job(s)", "advance", skipped)if not due_jobs:_sched._sweep_mcp_orphans()diff --git a/cron/store_health.py b/cron/store_health.pyindex 38e6ad5da7c..a5349a388dd 100644--- a/cron/store_health.py+++ b/cron/store_health.py@@ -46,7 +46,6 @@ class StoreDegraded:recovered_at: Optional[float] = None # epoch seconds of the first write that landed againsites: set = field(default_factory=set)skipped: set = field(default_factory=set) # distinct (job id, scheduled instant) not run- reported: set = field(default_factory=set) # misses already counted this outage (first_report)# 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@@ -63,8 +62,9 @@ class StoreDegraded:_DISPATCH_SITES = frozenset({"advance", "claim"})_degraded: dict[str, StoreDegraded] = {}-# Each store's last ended outage (``outage_covers``): the save that ends an outage is often another-# job's heartbeat, landing before the scan that fires the one-shots the outage skipped.+# Each store's just-ended outage, kept until the next due scan (``outage_covers``): the save that+# ends an outage is often another job's heartbeat, landing before the scan that fires the+# one-shots the outage skipped._recovered: dict[str, StoreDegraded] = {}_lock = threading.Lock()# The gateway consumes transitions; ``fn(event, record)`` with event "unwritable" or "recovered".@@ -145,7 +145,7 @@ def degraded_record(cron_dir: Optional[Path] = None) -> Optional[StoreDegraded]:def outage_covers(cron_dir: Path, due_at: float, grace: float) -> bool:- """Whether a run due at ``due_at`` fell inside this store's current or last ended outage."""+ """Whether a run due at ``due_at`` fell inside this store's current or just-ended outage."""return any(r is not None and r.since <= due_at + grace and (r.recovered_at is None or due_at <= r.recovered_at)for r in (_degraded.get(str(cron_dir)), _recovered.get(str(cron_dir))))@@ -178,34 +178,37 @@ def dispatch_blocked(due_jobs: list) -> bool:return blocked-def first_report(cron_dir: Path, job: dict) -> bool:- """Whether a missed run should be counted now. An unwritable store cannot persist the scan's- fast-forward, so the scan re-finds the same miss every tick: count it once per outage."""- record = _degraded.get(str(cron_dir))- if record is None:- return True- key = (job.get("id"), job.get("next_run_at"))- with _lock:- fresh = key not in record.reported- record.reported.add(key)- return fresh+def end_recovery_window(cron_dir: Path) -> None:+ """A due scan ran after the outage ended: later scans apply the normal grace window again."""+ if _recovered:+ with _lock:+ _recovered.pop(str(cron_dir), None)def recheck_idle() -> None:"""Idle tick (nothing due, so no save will land): re-probe a degraded store at most once a- minute and clear it when it accepts writes, so metrics, notices and the one-shot grace gate- do not stay on a store that has already recovered."""+ minute. The probe only creates an empty file, so a passing probe is confirmed by a real+ jobs.json save, whose ``note_writable`` ends the outage; metrics, notices and the one-shot+ grace gate then stop treating a recovered store as degraded."""+ if not _degraded:+ returncron_dir = _active_cron_dir()record = _degraded.get(str(cron_dir))now = time.monotonic()if record is None or (record.last_probe is not None and now - record.last_probe < PROBE_INTERVAL_SECONDS):return+ record.last_probe = nowerror = probe_store(cron_dir)if error is None:- note_writable(cron_dir)- return+ from cron.jobs import _jobs_lock, load_jobs, save_jobs+ try:+ with _jobs_lock():+ save_jobs(load_jobs())+ return+ except OSError as exc: # e.g. EDQUOT or a read-only jobs.json in a writable dir+ error = excwith _lock:- record.last_probe, record.error = now, describe_error(error)+ record.error = describe_error(error)def probe_report(cron_dir: Path) -> Optional[dict]:diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.pyindex ee898209e76..1d34d3fe2ea 100644--- a/tests/cron/test_due_scan_save_failure.py+++ b/tests/cron/test_due_scan_save_failure.py@@ -217,12 +217,13 @@ def test_unwritable_store_degrades_once_throttles_and_catches_up_once(cron_store# Distinct (job, due instant): the unpersisted fast-forward keeps both on one instant each.assert store_health.degraded_record(cron_store / "cron").skipped_runs == 2from cron.occurrences import get_catch_up_occurrence_count- assert get_catch_up_occurrence_count() == 1 # the unpersisted fast-forward is counted once, not per tick+ assert get_catch_up_occurrence_count() == 0 # the fast-forward did not persist: not counted yetoutage = Falseclock["now"], clock["mono"] = FIXED_NOW + timedelta(minutes=5), 180.0assert scheduler.tick(verbose=False, sync=True) == 2assert sorted(ran) == ["due-job", "once"] and events[-1][0] == "recovered" and len(events) == 2assert store_health.degraded_record(cron_store / "cron") is None+ assert get_catch_up_occurrence_count() == 1 # counted once, when the fast-forward persistedonce_rows = executions.list_executions(job_id="once")assert [r["status"] for r in once_rows].count("failed") == 1@@ -244,6 +245,9 @@ def test_skipped_oneshot_survives_recovery_by_any_save(cron_store, monkeypatch):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 Noneassert [d["id"] for d in get_due_jobs()] == ["once"]+ stale = dict(once, id="stale") # due during the outage, first scanned after the recovery scan+ save_jobs(load_jobs() + [stale])+ assert "stale" not in [d["id"] for d in get_due_jobs()]late = dict(once, id="late", next_run_at=(clock["now"] + timedelta(minutes=1)).isoformat())save_jobs(load_jobs() + [late])@@ -254,7 +258,8 @@ def test_skipped_oneshot_survives_recovery_by_any_save(cron_store, monkeypatch):def test_idle_tick_reprobes_a_degraded_store_and_clears_it(cron_store, monkeypatch):"""With nothing due no save lands, so only a re-probe can end the outage; without it the- store stays degraded (writable=0, no "recovered" notice) after the disk is fixed."""+ store stays degraded (writable=0, no "recovered" notice) after the disk is fixed. The probe+ only creates an empty file, so recovery is confirmed by a real jobs.json save."""from cron import schedulerclock = {"mono": 0.0}@@ -272,6 +277,12 @@ def test_idle_tick_reprobes_a_degraded_store_and_clears_it(cron_store, monkeypatclock["mono"] += 30.0scheduler.tick(verbose=False, sync=True) # re-probe throttled to once a minuteassert store_health.degraded_record(cron_store / "cron") is not None+ real_stage = cronjobs._stage_jobs_payload+ monkeypatch.setattr(cronjobs, "_stage_jobs_payload", _enospc) # probe passes, real save fails (EDQUOT-like)+ clock["mono"] += 60.0+ scheduler.tick(verbose=False, sync=True)+ assert store_health.degraded_record(cron_store / "cron") is not None+ monkeypatch.setattr(cronjobs, "_stage_jobs_payload", real_stage)clock["mono"] += 60.0scheduler.tick(verbose=False, sync=True)assert store_health.degraded_record(cron_store / "cron") is None