The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): deliver cron store notices in order, in the owner's language
kshitijk4poor3192c530031d
diff --git a/gateway/cron_store_notices.py b/gateway/cron_store_notices.pyindex 02ad91b2196..8eae5cce1e7 100644--- a/gateway/cron_store_notices.py+++ b/gateway/cron_store_notices.py@@ -31,16 +31,28 @@ def install_cron_store_notices(runner, loop: asyncio.AbstractEventLoop) -> None:# Loop-only state (mutated in loop callbacks, never on the ticker thread).announced: set[str] = set() # stores whose current outage got an "unwritable" noticepending: dict[str, asyncio.TimerHandle] = {} # store -> its deferred "recovered" notice+ sending: dict[str, asyncio.Lock] = {} # store -> serializes its notices, in transition order++ async def deliver(event, record) -> 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+ if event == "recovered":+ announced.discard(record.store)+ await send_cron_store_notice(runner, event, record)def send(event, record) -> None:- task = loop.create_task(send_cron_store_notice(runner, event, record))+ task = loop.create_task(deliver(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)+ if record.store in announced and degraded_record(Path(record.store)) is None:+ send("recovered", record) # else it degraded again (outage goes on) or was never tolddef on_loop(event, record) -> None:store = record.store@@ -79,7 +91,6 @@ async def send_cron_store_notice(runner, event: str, record) -> None:fields = record.notice_fields()key = "gateway.cron_store.unwritable" if event == "unwritable" else "gateway.cron_store.recovered"- message = t(key, **fields)store_home = hermes_home_key(Path(record.store).parent)served_homes = runner._served_profile_homes or {}logger.info("Broadcasting cron store %s notice for %s", event, record.store)@@ -90,6 +101,7 @@ async def send_cron_store_notice(runner, event: str, record) -> None:# The opt-out is the owning profile's; the launch profile needs no extra scope.scope = _async_profile_runtime_scope(Path(served_home)) if served_home else contextlib.nullcontext()async with scope:+ message = t(key, **fields) # inside the owning profile's scope: its display.languageawait present_notification(lambda: runner._send_home_channel_message(platform, home, transport, message, "Cron store notice failed for %s:%s: %s"),diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.pyindex 23ae5cb5e64..21045203a75 100644--- a/tests/cron/test_due_scan_save_failure.py+++ b/tests/cron/test_due_scan_save_failure.py@@ -312,7 +312,6 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,monkeypatch.setattr(cron_cli, "_active_cron_provider_name", lambda: "chronos")monkeypatch.setattr(scheduler, "_should_yield_tick_to_fresh_gateway", lambda: None)monkeypatch.setattr(scheduler, "_sweep_mcp_orphans", lambda: None)-def read_only_lock(_path):raise OSError(errno.EROFS, "Read-only file system")@@ -352,8 +351,11 @@ def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store,os.chmod(target, 0o600)sent = []+ gate = asyncio.Event()+ gate.set()async def send(platform, home, transport, message, failure_fmt):+ await gate.wait() # cleared below to hold a delivery open while the store flipssent.append((home.chat_id, message))return True@@ -361,12 +363,14 @@ 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")- monkeypatch.setattr(cron_store_notices, "NOTICE_REPEAT_SECONDS", 0.05)+ # 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)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)+ async def drain(): # until no timer or notice send is left+ while loop._scheduled or len(asyncio.all_tasks()) > 1:+ await asyncio.sleep(0)settle = lambda: loop.run_until_complete(drain())try:@@ -386,12 +390,24 @@ 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()])+ spin()+ save_jobs([_due_job()]) # ... "recovered" fires and queues behind it ...+ spin()+ store_health.note_unwritable(enospc, "x", "scan", [_due_job()]) # ... and the store fails again+ gate.set()+ settle() # in order: the outage notice lands, the stale "recovered" is dropped, no duplicate+ assert [m[0] for _, m in sent][-1] == "⚠" # store still down: the outage notice is the last word+ save_jobs([_due_job()])+ settle() # 4th notice: recoveredinstall_cron_store_notices(SimpleNamespace(), loop) # a send that raises is logged, not loststore_health.note_unwritable(enospc, "x", "scan", [_due_job()])settle()finally:loop.close()- assert len(sent) == 2 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]