The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): defer the cron store "recovered" notice instead of dropping a re-entry
kshitijk4poor33530d12075f
diff --git a/gateway/cron_store_notices.py b/gateway/cron_store_notices.pyindex b41c45dcb48..10066e00b05 100644--- a/gateway/cron_store_notices.py+++ b/gateway/cron_store_notices.py@@ -12,42 +12,51 @@ import asyncioimport concurrent.futuresimport contextlibimport logging-import threading-import timefrom pathlib import Pathfrom agent.i18n import tlogger = logging.getLogger(__name__)-# A store flapping across the disk-full line must not post a notice pair every tick.+# A store flapping across the disk-full line must not post a notice pair every tick: "recovered"+# waits this long and is dropped if the store degrades again meanwhile.NOTICE_REPEAT_SECONDS = 3600.0def install_cron_store_notices(runner, loop: asyncio.AbstractEventLoop) -> None:"""Route store transitions from the ticker thread onto the gateway loop. Installed once the- adapters are connected, so a store that degraded during boot is announced then."""- from cron.store_health import degraded_records, set_transition_listener+ adapters are connected, so a store that degraded during boot is announced then. The last+ notice a home channel sees always matches the store's real state."""+ from cron.store_health import degraded_record, degraded_records, set_transition_listener- last_sent: dict[str, float] = {} # store -> monotonic time of its last notice+ # Loop-only state (mutated in loop callbacks, never on the ticker thread).announced: set[str] = set() # stores whose current outage got an "unwritable" notice- lock = threading.Lock()-- def on_transition(event, record) -> None:- store, now = record.store, time.monotonic()- with lock:- if event == "unwritable":- last = last_sent.get(store)- if last is not None and now - last < NOTICE_REPEAT_SECONDS:- return # the logs still carry every transition+ pending: dict[str, asyncio.TimerHandle] = {} # store -> its deferred "recovered" notice++ def send(event, record) -> None:+ task = loop.create_task(send_cron_store_notice(runner, event, record))+ task.add_done_callback(lambda done: _log_notice_failure(done, event, record.store))++ def send_recovered(record) -> None:+ pending.pop(record.store, None)+ if degraded_record(Path(record.store)) is None: # else it degraded again: outage goes on+ announced.discard(record.store)+ send("recovered", record)++ def on_loop(event, record) -> None:+ store = record.store+ if event == "unwritable":+ if (handle := pending.pop(store, None)) is not None:+ handle.cancel() # never told it recovered: the outage notice still stands+ elif store not in announced:announced.add(store)- elif store in announced:- announced.discard(store)- else:- return # its outage was never announced: no lone "recovered"- last_sent[store] = now- future = asyncio.run_coroutine_threadsafe(send_cron_store_notice(runner, event, record), loop)- future.add_done_callback(lambda done: _log_notice_failure(done, event, store))+ send(event, record)+ elif store in announced and store not in pending: # no lone "recovered"+ pending[store] = loop.call_later(NOTICE_REPEAT_SECONDS, send_recovered, record)++ def on_transition(event, record) -> None: # the ticker thread+ # A closed loop raises before any coroutine exists; store_health._notify logs and swallows it.+ loop.call_soon_threadsafe(on_loop, event, record)set_transition_listener(on_transition)for record in degraded_records():diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.pyindex 0ab54257304..1d4e4317e13 100644--- a/tests/cron/test_due_scan_save_failure.py+++ b/tests/cron/test_due_scan_save_failure.py@@ -228,10 +228,12 @@ def test_unwritable_store_degrades_once_throttles_and_catches_up_once(cron_store@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):"""`hermes cron status` probes the store itself (a real 0500 dir) and leads with the red- headline + fix; the gateway posts ONE home-channel notice on entry and ONE on recovery,- each naming the store, the error, since-when and the skipped runs; re-entry within the hour- posts nothing."""+ headline + fix; the gateway posts ONE home-channel notice on entry, naming the store, the+ error and since-when. "recovered" waits out the repeat+ window and is dropped if the store degrades again meanwhile, so the last notice always matches+ the store's real state."""from types import SimpleNamespace+ from gateway import cron_store_noticesfrom gateway.cron_store_notices import install_cron_store_noticesfrom hermes_cli import cron as cron_cli@@ -251,14 +253,21 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,sent = []async def send(platform, home, transport, message, failure_fmt):- sent.append(message)+ sent.append((home.chat_id, message))return Truehome = SimpleNamespace(chat_id="c1", thread_id=None)runner = SimpleNamespace(_send_home_channel_message=send, _served_home_channel_transports=lambda: iter([(None, "telegram", None, home, object())]))monkeypatch.setattr("hermes_constants.get_routing_process_hermes_home", lambda: cron_store)+ monkeypatch.setattr(cron_store_notices, "NOTICE_REPEAT_SECONDS", 0.05)loop = asyncio.new_event_loop()++ async def drain(): # past the repeat window, then until every notice send has finished+ await asyncio.sleep(0.2)+ await asyncio.gather(*(asyncio.all_tasks() - {asyncio.current_task()}), return_exceptions=True)++ settle = lambda: loop.run_until_complete(drain())try:install_cron_store_notices(runner, loop)enospc = OSError(errno.ENOSPC, "No space left on device")@@ -266,14 +275,18 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,cronjobs.warn_store_unwritable(enospc, "x", site, [_due_job()])save_jobs([_due_job()])save_jobs([_due_job()])- cronjobs.warn_store_unwritable(enospc, "x", "scan", [_due_job()]) # flaps back within the hour- loop.run_until_complete(asyncio.sleep(0.05))+ cronjobs.warn_store_unwritable(enospc, "x", "scan", [_due_job()]) # flaps back within the window+ settle()+ assert [m[:2] for _, m in sent] == ["⚠️"] # still down: no "writable again", ever+ save_jobs([_due_job()])+ settle()install_cron_store_notices(SimpleNamespace(), loop) # a send that raises is logged, not lost- loop.run_until_complete(asyncio.sleep(0.05))+ cronjobs.warn_store_unwritable(enospc, "x", "scan", [_due_job()])+ settle()finally:loop.close()assert len(sent) == 2- assert str(cron_dir) in sent[0] and "ENOSPC: No space left on device" in sent[0] and "since " in sent[0]- assert f"fix permissions on {cron_dir}" in sent[0]- assert "writable again; 1 skipped run(s), catching up once per job" in sent[1]+ 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]assert any(r.levelname == "WARNING" and "unwritable notice for" in r.getMessage() for r in caplog.records)diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex dfc365436f5..a7a0113654b 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -356,7 +356,7 @@ When the cron store (`~/.hermes/cron/`, or the profile's own `cron/` directory)- `hermes cron status` probes the store itself and leads with `⚠ Cron store is NOT writable — scheduled jobs are being skipped`. Below that it shows the store path, the OS error, the last successful write and how many due runs have not fired. `hermes cron list` prints a one-line banner.- `hermes doctor` warns when the store is not writable, or when its filesystem has less than 100 MB free.-- The gateway posts one notice to the profile's home channels when the store becomes unwritable and one when it recovers. Both respect `display.suppress_warning_notifications`.+- The gateway posts one notice to the profile's home channels when the store becomes unwritable and one when it has stayed writable for an hour (a store that fails again within that hour posts nothing more, so the last notice always matches its state). Both respect `display.suppress_warning_notifications`.- Monitoring exports `hermes.cron.store.writable` (0/1) and `hermes.cron.store.skipped_runs`.To fix it, free disk space on the filesystem holding the store, remount it read-write, or fix the ownership and permissions of the store directory so the gateway user can write it. You don't need to restart anything. On the next tick that can write, each job that stayed due fires **once** under the normal [misfire catch-up](#misfire-catch-up) rules, not once per missed tick. A one-shot that came due during the outage fires once instead of expiring (unless the gateway restarts while the store is unwritable).