Skip to content

The agent that grows with you

fix(cron): fire a skipped one-shot once even when another save ends the outage

kshitijk4poor71ff3820923f
diff --git a/cron/jobs.py b/cron/jobs.py
index 2ef3b025039..d6ee32470d6 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -3160,9 +3160,8 @@ def _retire_expired_oneshot(d: _DueJob) -> bool:
still in flight elsewhere — skip but keep the record so its mark_job_run can land."""
if _elapsed_seconds(d.scan.now, d.next_run_dt) <= ONESHOT_GRACE_SECONDS:
return False
- # Due before/while the store went unwritable: it was skipped, not missed; fire it once on recovery.
- degraded = store_health.degraded_record(_current_cron_store().cron_dir)
- if degraded is not None and degraded.since <= d.next_run_dt.timestamp() + ONESHOT_GRACE_SECONDS:
+ # Due during an outage of its store: it was skipped, not missed; fire it once on recovery.
+ if store_health.outage_covers(_current_cron_store().cron_dir, d.next_run_dt.timestamp(), ONESHOT_GRACE_SECONDS):
return False
if not (d.job.get("run_claim") or d.job.get("fire_claim")):
_write_missed_oneshot_diagnostic(d.job, d.next_run)
diff --git a/cron/store_health.py b/cron/store_health.py
index 3eefcb5c0f5..7e51c7a9eed 100644
--- a/cron/store_health.py
+++ b/cron/store_health.py
@@ -43,6 +43,7 @@ class StoreDegraded:
store: str
since: float # epoch seconds of the first failed write
error: str
+ recovered_at: Optional[float] = None # epoch seconds of the first write that landed again
sites: set = field(default_factory=set)
skipped: set = field(default_factory=set) # distinct (job id, scheduled instant) not run
# Monotonic time of the last failed dispatch write or re-probe. None until a dispatch write
@@ -61,6 +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.
+_recovered: dict[str, StoreDegraded] = {}
_lock = threading.Lock()
# The gateway consumes transitions; ``fn(event, record)`` with event "unwritable" or "recovered".
_listener: Optional[Callable[[str, StoreDegraded], None]] = None
@@ -123,6 +127,9 @@ def note_writable(cron_dir: Path) -> None:
return
with _lock:
record = _degraded.pop(str(cron_dir), None)
+ if record is not None:
+ record.recovered_at = time.time()
+ _recovered[record.store] = record
if record is None:
return
logger.warning("Cron store %s is writable again; %d skipped run(s), catching up once per job",
@@ -134,6 +141,12 @@ def degraded_record(cron_dir: Optional[Path] = None) -> Optional[StoreDegraded]:
return _degraded.get(str(cron_dir if cron_dir is not None else _active_cron_dir()))
+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."""
+ 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))))
+
+
def degraded_records() -> list:
with _lock:
return list(_degraded.values())
diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.py
index 897f4dafc67..7eb64499bb8 100644
--- a/tests/cron/test_due_scan_save_failure.py
+++ b/tests/cron/test_due_scan_save_failure.py
@@ -36,6 +36,7 @@ def cron_store(tmp_path, monkeypatch):
"""Redirect cron storage to a temp dir, pin the clock, start with no degraded store."""
monkeypatch.setattr(store_health, "_degraded", {})
monkeypatch.setattr(store_health, "_listener", None)
+ monkeypatch.setattr(store_health, "_recovered", {})
monkeypatch.setattr("cron.jobs.CRON_DIR", tmp_path / "cron")
monkeypatch.setattr("cron.jobs.JOBS_FILE", tmp_path / "cron" / "jobs.json")
monkeypatch.setattr("cron.jobs.OUTPUT_DIR", tmp_path / "cron" / "output")
@@ -224,6 +225,31 @@ def test_unwritable_store_degrades_once_throttles_and_catches_up_once(cron_store
assert [r["status"] for r in once_rows].count("failed") == 1
+def test_skipped_oneshot_survives_recovery_by_any_save(cron_store, monkeypatch):
+ """The outage window outlives the save that ends it: another job's save (a heartbeat, a
+ create) usually lands before the due scan, and the one-shot the outage skipped must still
+ fire once, not be retired as missed. A one-shot due after the store recovered and missed
+ later is retired as on main."""
+ clock = {"now": FIXED_NOW}
+ monkeypatch.setattr(cronjobs, "_hermes_now", lambda: clock["now"])
+ monkeypatch.setattr(store_health.time, "time", lambda: clock["now"].timestamp())
+ once = dict(_due_job("once"), schedule={"kind": "once", "run_at": FIXED_NOW.isoformat(), "display": "once"},
+ 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])
+ 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
+ assert [d["id"] for d in get_due_jobs()] == ["once"]
+
+ late = dict(once, id="late", next_run_at=(clock["now"] + timedelta(minutes=1)).isoformat())
+ save_jobs(load_jobs() + [late])
+ clock["now"] += timedelta(minutes=10) # missed while the store was writable: retired
+ assert "late" not in [d["id"] for d in get_due_jobs()]
+ assert "late" not in [j["id"] for j in load_jobs()]
+
+
@pytest.mark.platforms("posix") # POSIX mode bits; root ignores them
@pytest.mark.skipif(hasattr(os, "geteuid") and os.geteuid() == 0, reason="root bypasses directory modes")
def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store, monkeypatch, capsys, caplog):