The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): key store state by resolved path, never swallow a flapped outage notice
kshitijk4poor152aa695bbbc
diff --git a/cron/store_health.py b/cron/store_health.pyindex 603d6960ebd..a0e92bddeb1 100644--- a/cron/store_health.py+++ b/cron/store_health.py@@ -95,6 +95,12 @@ def _active_cron_dir() -> Path:return _current_cron_store().cron_dir+def _key(cron_dir: Optional[Path]) -> str:+ """Record key for a store: its resolved path (default: the active store). Callers pass both+ resolved (cron store) and unresolved (tick-lock dir, profile homes) paths for one store."""+ return os.path.realpath(cron_dir if cron_dir is not None else _active_cron_dir())++def _run_keys(jobs: Iterable[dict]) -> set:return {(job.get("id"), job.get("next_run_at")) for job in jobs}@@ -104,7 +110,7 @@ def note_unwritable(exc: OSError, consequence: str, site: str, skipped_jobs: Ite"""Record a failed write to ``cron_dir`` (default: the active store); WARN once, when the storeenters the degraded state. Callers skip the dispatch that needed the write: no job runswithout a durable advance/fire claim."""- store = str(cron_dir if cron_dir is not None else _active_cron_dir())+ store = _key(cron_dir)with _lock:record = _degraded.get(store)entered = record is None@@ -135,7 +141,7 @@ def note_writable(cron_dir: Path) -> None:if not _degraded:returnwith _lock:- record = _degraded.pop(str(cron_dir), None)+ record = _degraded.pop(_key(cron_dir), None)if record is not None:record.recovered_at = time.time()_recovered[record.store] = record@@ -147,13 +153,13 @@ def note_writable(cron_dir: Path) -> None: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()))+ return _degraded.get(_key(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 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))))+ for r in (_degraded.get(_key(cron_dir)), _recovered.get(_key(cron_dir))))def forget_homes(home_keys) -> None:@@ -177,7 +183,7 @@ def dispatch_blocked(due_jobs: list) -> bool:unwritable and the minute-throttled re-probe has not seen it accept a write. Skipped runs arerecorded; once the probe passes, the dispatch's own save confirms recovery (or re-degrades)."""cron_dir = _active_cron_dir()- record = _degraded.get(str(cron_dir))+ record = _degraded.get(_key(cron_dir))# Entered in load/scan (last_probe None): dispatch has not been tried yet, so let it try.if record is None or record.last_probe is None:return False@@ -199,7 +205,7 @@ def end_recovery_window(cron_dir: Path) -> None:"""A due scan's save landed after the outage ended: normal grace applies again."""if _recovered:with _lock:- _recovered.pop(str(cron_dir), None)+ _recovered.pop(_key(cron_dir), None)def recheck_idle() -> None:@@ -210,7 +216,7 @@ def recheck_idle() -> None:if not _degraded:returncron_dir = _active_cron_dir()- record = _degraded.get(str(cron_dir))+ record = _degraded.get(_key(cron_dir))now = time.monotonic()if record is None or (record.last_probe is not None and now - record.last_probe < PROBE_INTERVAL_SECONDS):returndiff --git a/gateway/cron_store_notices.py b/gateway/cron_store_notices.pyindex ab48adc0dc0..d88936f1b81 100644--- a/gateway/cron_store_notices.py+++ b/gateway/cron_store_notices.py@@ -37,11 +37,15 @@ def install_cron_store_notices(runner, loop: asyncio.AbstractEventLoop) -> None:async with sending.setdefault(record.store, asyncio.Lock()):# Re-check at delivery: a send can wait on profile loading or its transport, and the# store may have flipped meanwhile; a stale notice must never be the last word.- if (degraded_record(Path(record.store)) is None) != (event == "recovered"):- if event == "unwritable":- announced.discard(record.store) # never announced: no "recovered" owed either- return # a dropped "recovered" leaves the outage announced: its notice still stands+ degraded = degraded_record(Path(record.store)) is not None+ if event == "unwritable" and not degraded: # never announced: nothing owed, next entry announces+ announced.discard(record.store)+ if (handle := pending.pop(record.store, None)) is not None:+ handle.cancel()+ returnif event == "recovered":+ if degraded or record.store not in announced: # outage goes on / was never announced+ returnannounced.discard(record.store)await send_cron_store_notice(runner, event, record)diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex 8f70e75ab0c..57399fd8f49 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -516,10 +516,12 @@ def cron_status():print()store_report, active_jobs = _probe_then_list_jobs(include_disabled=False)- active_jobs = active_jobs or []- if store_report is not None:+ if active_jobs is None:+ print(color(" Jobs could not be read from the unwritable store.", Colors.RED))+ elif 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))+ if store_report is not None: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 21045203a75..242e825e15e 100644--- a/tests/cron/test_due_scan_save_failure.py+++ b/tests/cron/test_due_scan_save_failure.py@@ -321,6 +321,14 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,assert scheduler.tick(verbose=False, sync=True) == 0 # degrade, do not raiseassert "lock" in store_health.degraded_record(cron_dir).sitesstore_health._degraded.clear()+ link = cron_store / "home-link" # the tick lock is built from the unresolved profile home+ link.symlink_to(cron_store, target_is_directory=True)+ with monkeypatch.context() as m:+ m.setattr(scheduler, "_acquire_tick_lock", read_only_lock)+ m.setattr(scheduler, "_get_lock_paths", lambda: (link / "cron", link / "cron" / ".tick.lock"))+ scheduler.tick(verbose=False, sync=True)+ save_jobs([_due_job()]) # a save of the (resolved) store ends that outage too+ assert store_health.degraded_records() == []os.chmod(cron_dir, 0o500)try:cron_cli.cron_status()@@ -363,16 +371,23 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,runner = SimpleNamespace(_send_home_channel_message=send, _served_profile_homes={"p": cron_store},_served_home_channel_transports=lambda: iter([("p", "telegram", None, home, object())]))monkeypatch.setattr("hermes_constants.get_routing_process_hermes_home", lambda: cron_store / "launch")- # Zero repeat window: the deferred "recovered" is due on the loop's next pass, after every- # transition already queued, so the flap cases below are decided by event order, not timing.- monkeypatch.setattr(cron_store_notices, "NOTICE_REPEAT_SECONDS", 0)+ # A manual loop clock: the real one-hour "recovered" window only elapses when the test says+ # so, so every case below is decided by event order, never by wall-clock timing.loop = asyncio.new_event_loop()+ clock = [loop.time()]+ loop.time = lambda: clock[0]- async def drain(): # until no timer or notice send is left- while loop._scheduled or len(asyncio.all_tasks()) > 1:+ async def drain(): # until no due timer and no notice send is left+ while len(asyncio.all_tasks()) > 1 or any(+ not h.cancelled() and h.when() <= clock[0] for h in loop._scheduled):await asyncio.sleep(0)- settle = lambda: loop.run_until_complete(drain())+ def settle(): # process queued transitions, let the window elapse, deliver what is due+ loop.run_until_complete(drain())+ clock[0] += cron_store_notices.NOTICE_REPEAT_SECONDS+ loop.run_until_complete(drain())++ spin = lambda: [loop.run_until_complete(asyncio.sleep(0)) for _ in range(5)]try:install_cron_store_notices(runner, loop)enospc = OSError(errno.ENOSPC, "No space left on device")@@ -390,12 +405,21 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,store_health.note_unwritable(enospc, "x", "scan", [_due_job()]) # already writable when the loop runs:save_jobs([_due_job()]) # nothing announced, so no lone "recovered" eithersettle()- spin = lambda: [loop.run_until_complete(asyncio.sleep(0)) for _ in range(5)]- gate.clear() # the 3rd notice ("unwritable") is slow to deliver ...+ store_health.note_unwritable(enospc, "x", "scan", [_due_job()])+ save_jobs([_due_job()]) # recovers before that notice is delivered ...+ spin()+ store_health.note_unwritable(enospc, "x", "scan", [_due_job()]) # ... and fails again+ settle() # the dropped first notice must not swallow this outage: announced once+ assert [m[0] for _, m in sent][-1] == "⚠"+ save_jobs([_due_job()])+ settle()+ gate.clear() # the next "unwritable" is slow to deliver ...store_health.note_unwritable(enospc, "x", "scan", [_due_job()])spin()save_jobs([_due_job()]) # ... "recovered" fires and queues behind it ...spin()+ clock[0] += cron_store_notices.NOTICE_REPEAT_SECONDS+ spin()store_health.note_unwritable(enospc, "x", "scan", [_due_job()]) # ... and the store fails againgate.set()settle() # in order: the outage notice lands, the stale "recovered" is dropped, no duplicate@@ -407,7 +431,7 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,settle()finally:loop.close()- assert [m[0] for _, m in sent] == ["⚠", "✅", "⚠", "✅"] and {chat for chat, _ in sent} == {"c1"}+ assert [m[0] for _, m in sent] == ["⚠", "✅", "⚠", "✅", "⚠", "✅"] and {chat for chat, _ in sent} == {"c1"}assert str(cron_dir) in sent[0][1] and "ENOSPC: No space left on device" in sent[0][1] and "since " in sent[0][1]assert f"fix permissions on {cron_dir}" in sent[0][1]assert "writable again; 1 skipped run(s), catching up once per job" in sent[1][1]