The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): rich_sent_store writes run off the event loop
kshitijk4poor7dd6bee33bdd
diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.pyindex 96e3871efe5..7194cedd169 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@ -372,7 +372,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):# Index (chat_id, wamid) → text: Meta's inbound ``context`` carries only the# quoted message's id, so this is how replies to our messages resolve text.if last_message_id:- rich_sent_store.record(chat_id, last_message_id, formatted)+ await rich_sent_store.record_async(chat_id, last_message_id, formatted)return SendResult(success=True, message_id=last_message_id)# ------------------------------------------------------------------ typing indicator + read receipts@@ -562,9 +562,9 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):result = await self._send_media(chat_id, media_kind, caption=caption, filename=filename, reply_to=reply_to, **ref)if result.success and result.message_id and "media_id" in ref:mime = mime_type or mimetypes.guess_type(source)[0] or _DEFAULT_MIME.get(media_kind, "application/octet-stream")- rich_sent_store.record_media(chat_id, result.message_id, [(source, mime)])+ await rich_sent_store.record_media_async(chat_id, result.message_id, [(source, mime)])if caption:- rich_sent_store.record(chat_id, result.message_id, caption)+ await rich_sent_store.record_async(chat_id, result.message_id, caption)return result# ``**kwargs`` absorbs base-class args (e.g. ``metadata``) the Cloud API has no use for.@@ -1001,9 +1001,9 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):# Done AFTER gating so filtered messages don't leak typing/read receipts.bounded_put(self._last_inbound_wamid_by_chat, chat_id, wamid, INTERACTIVE_STATE_CACHE_SIZE)if body:- rich_sent_store.record(chat_id, wamid, body)+ await rich_sent_store.record_async(chat_id, wamid, body)if msg_type_str in _INBOUND_MEDIA_KINDS and media_urls:- rich_sent_store.record_media(chat_id, wamid, list(zip(media_urls, media_types)))+ await rich_sent_store.record_media_async(chat_id, wamid, list(zip(media_urls, media_types)))if reply_to_id:for path, mime in rich_sent_store.lookup_media(chat_id, reply_to_id):if path not in media_urls:diff --git a/gateway/rich_sent_store.py b/gateway/rich_sent_store.pyindex 145e755b6ab..73327626a29 100644--- a/gateway/rich_sent_store.py+++ b/gateway/rich_sent_store.py@@ -11,6 +11,7 @@ inbound. Best-effort and dependency-free: every operation swallows errors and defrom __future__ import annotations+import asyncioimport jsonimport osimport time@@ -67,6 +68,17 @@ def record_media(chat_id, message_id, media: list[tuple[str, str]]) -> None:_update(chat_id, message_id, {"m": [[str(p), str(mt or "")] for p, mt in media if p]})+async def record_async(chat_id, message_id, text: Optional[str]) -> None:+ """``record`` for coroutine callers: the read-modify-write + ``os.replace``+ runs on a worker thread so the event loop is not stalled by the filesystem."""+ await asyncio.to_thread(record, chat_id, message_id, text)+++async def record_media_async(chat_id, message_id, media: list[tuple[str, str]]) -> None:+ """``record_media`` for coroutine callers; see ``record_async``."""+ await asyncio.to_thread(record_media, chat_id, message_id, media)++def _entry(chat_id, message_id) -> dict:if message_id is None or chat_id is None:return {}diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 5eac463db0b..c6c68ae3056 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -1520,11 +1520,13 @@ class TelegramAdapter(BasePlatformAdapter):retryable=(self._looks_like_connect_timeout(exc) or not self._is_timed_out(exc)), retry_after=retry_after)@staticmethod- def _record_rich_sent(chat_id: Any, message_id: Any, content: str) -> None:- """Index rich content we sent: Telegram won't echo it back in reply_to_message."""+ async def _record_rich_sent(chat_id: Any, message_id: Any, content: str) -> None:+ """Index rich content we sent: Telegram won't echo it back in reply_to_message.++ Awaited so the store's read-modify-write + ``os.replace`` runs off the loop."""try:from gateway import rich_sent_store- rich_sent_store.record(str(chat_id), str(message_id), content)+ await rich_sent_store.record_async(str(chat_id), str(message_id), content)except Exception:pass@@ -1567,7 +1569,7 @@ class TelegramAdapter(BasePlatformAdapter):else:message_id = getattr(msg, "message_id", None)if message_id is not None:- self._record_rich_sent(chat_id, message_id, content)+ await self._record_rich_sent(chat_id, message_id, content)return SendResult(success=True, message_id=str(message_id) if message_id is not None else None)def _rich_payload_base(self, chat_id: str, content: str) -> Dict[str, Any]:@@ -1606,7 +1608,7 @@ class TelegramAdapter(BasePlatformAdapter):return Nonereturn self._rich_transient_result(exc, "rich editMessageText")# Mirror the fresh-send index: a streamed final finalized via edit is otherwise never recorded.- self._record_rich_sent(chat_id, message_id, content)+ await self._record_rich_sent(chat_id, message_id, content)return SendResult(success=True, message_id=message_id)def _should_attempt_rich_draft(self, content: str) -> bool:diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex c390a40543b..6fde9bf8cfa 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -633,7 +633,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):# knows inbound media only, so index our own sends (the cron-delivered image case).from gateway import rich_sent_storemime = mimetypes.guess_type(file_path)[0] or _MEDIA_INFO.get(_MEDIA_TYPE_BY_BRIDGE_KIND.get(media_type), ("", ""))[1]- rich_sent_store.record_media(jid, result.message_id, [(file_path, mime or "application/octet-stream")])+ await rich_sent_store.record_media_async(jid, result.message_id, [(file_path, mime or "application/octet-stream")])return result@_needs_bridgediff --git a/tests/gateway/test_rich_sent_store_off_loop.py b/tests/gateway/test_rich_sent_store_off_loop.pynew file mode 100644index 00000000000..1595b21362e--- /dev/null+++ b/tests/gateway/test_rich_sent_store_off_loop.py@@ -0,0 +1,32 @@+"""The rich-sent index write runs off the event loop for coroutine callers."""++import asyncio+import threading++import pytest++from gateway import rich_sent_store+++def isolated_store(tmp_path, monkeypatch):+ monkeypatch.setattr(rich_sent_store, "_store_path", lambda: str(tmp_path / "rich_sent.json"))+++def test_record_async_runs_off_the_loop_thread(isolated_store, monkeypatch):+ writer_thread: list[int] = []+ real_update = rich_sent_store._update++ def spy_update(chat_id, message_id, fields):+ writer_thread.append(threading.get_ident())+ real_update(chat_id, message_id, fields)++ monkeypatch.setattr(rich_sent_store, "_update", spy_update)++ async def go():+ await rich_sent_store.record_async("chat", "42", "hello")+ return threading.get_ident()++ loop_thread = asyncio.run(go())+ assert writer_thread and writer_thread[0] != loop_thread+ assert rich_sent_store.lookup("chat", "42") == "hello"