The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): offload remaining atomic_json_write calls on platform-adapter hot paths
pierrenodecf6547da47f4
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.pyindex 73b8dcad55d..58f9d401bae 100644--- a/gateway/platforms/weixin.py+++ b/gateway/platforms/weixin.py@@ -329,9 +329,13 @@ class ContextTokenStore:def get(self, account_id: str, user_id: str) -> Optional[str]:return self._cache.get(self._key(account_id, user_id))- def set(self, account_id: str, user_id: str, token: str) -> None:+ async def set(self, account_id: str, user_id: str, token: str) -> None:self._cache[self._key(account_id, user_id)] = token- self._persist(account_id)+ # atomic_json_write() calls os.fsync(), which blocks until the write+ # reaches stable storage. _process_message runs on the event loop for+ # every inbound message, so offload the flush the same way #83906 did+ # for the other gateway persist paths.+ await asyncio.to_thread(self._persist, account_id)def _persist(self, account_id: str) -> None:prefix = f"{account_id}:"@@ -1501,7 +1505,7 @@ class WeixinAdapter(BasePlatformAdapter):context_token = str(message.get("context_token") or "").strip()if context_token:- self._token_store.set(self._account_id, sender_id, context_token)+ await self._token_store.set(self._account_id, sender_id, context_token)asyncio.create_task(self._maybe_fetch_typing_ticket(sender_id, context_token or None))media_paths: List[str] = []diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 2b53778d015..802b685f217 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -414,7 +414,7 @@ class _DiscordNonConversationalMessageTracker:except Exception:logger.debug("[%s] Failed to save non-conversational Discord IDs", "Discord", exc_info=True)- def mark_many(self, message_ids: List[str]) -> None:+ async def mark_many(self, message_ids: List[str]) -> None:changed = Falsefor message_id in message_ids:key = str(message_id or "").strip()@@ -422,7 +422,11 @@ class _DiscordNonConversationalMessageTracker:self._ids[key] = Nonechanged = Trueif changed:- self._save()+ # atomic_json_write() calls os.fsync(), which blocks until the+ # write reaches stable storage. Both callers of mark_many() run+ # on the event loop, so offload the flush the same way #83906+ # did for the other gateway persist paths.+ await asyncio.to_thread(self._save)def __contains__(self, message_id: str) -> bool:return str(message_id or "") in self._ids@@ -3611,7 +3615,7 @@ class DiscordAdapter(BasePlatformAdapter):if message_ids:_target_id = thread_id or chat_idif nonconversational:- self._nonconversational_messages.mark_many(message_ids)+ await self._nonconversational_messages.mark_many(message_ids)elif not _looks_like_nonconversational_history_message(content):self._last_self_message_id[_target_id] = message_ids[-1]@@ -7872,7 +7876,7 @@ class DiscordAdapter(BasePlatformAdapter):msg = await channel.send(content=content, embed=embed, view=view)view._message = msg # store for on_timeout expiration editingif _metadata_marks_nonconversational(metadata):- self._nonconversational_messages.mark_many([str(msg.id)])+ await self._nonconversational_messages.mark_many([str(msg.id)])return SendResult(success=True, message_id=str(msg.id))except Exception as e:return SendResult(success=False, error=str(e))diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex 0c7bb89039a..87207fcbc04 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -2740,7 +2740,7 @@ class FeishuAdapter(BasePlatformAdapter):returnmessage_id = getattr(message, "message_id", None)- if not message_id or self._is_duplicate(message_id):+ if not message_id or await self._is_duplicate(message_id):logger.debug("[Feishu] Dropping duplicate/missing message_id: %s", message_id)return@@ -4738,14 +4738,15 @@ class FeishuAdapter(BasePlatformAdapter):def _persist_seen_message_ids(self) -> None:try:self._dedup_state_path.parent.mkdir(parents=True, exist_ok=True)- recent = self._seen_message_order[-self._dedup_cache_size:]- # Save as {msg_id: timestamp} so TTL filtering works across restarts.- payload = {"message_ids": {k: self._seen_message_ids[k] for k in recent if k in self._seen_message_ids}}+ with self._dedup_lock:+ recent = self._seen_message_order[-self._dedup_cache_size:]+ # Save as {msg_id: timestamp} so TTL filtering works across restarts.+ payload = {"message_ids": {k: self._seen_message_ids[k] for k in recent if k in self._seen_message_ids}}atomic_json_write(self._dedup_state_path, payload, indent=None)except OSError:logger.warning("[Feishu] Failed to persist dedup state to %s", self._dedup_state_path, exc_info=True)- def _is_duplicate(self, message_id: str) -> bool:+ async def _is_duplicate(self, message_id: str) -> bool:now = time.time()ttl = _FEISHU_DEDUP_TTL_SECONDSwith self._dedup_lock:@@ -4758,8 +4759,12 @@ class FeishuAdapter(BasePlatformAdapter):while len(self._seen_message_order) > self._dedup_cache_size:stale = self._seen_message_order.pop(0)self._seen_message_ids.pop(stale, None)- self._persist_seen_message_ids()- return False+ # atomic_json_write() calls os.fsync(), which blocks until the write+ # reaches stable storage. _handle_message_event_data runs on the+ # event loop for every inbound message, so offload the flush the+ # same way #83906 did for the other gateway persist paths.+ await asyncio.to_thread(self._persist_seen_message_ids)+ return False# =========================================================================# Outbound payload construction and send pipelinediff --git a/plugins/platforms/feishu/feishu_meeting_invite.py b/plugins/platforms/feishu/feishu_meeting_invite.pyindex 69a487c0291..0648d6fca9d 100644--- a/plugins/platforms/feishu/feishu_meeting_invite.py+++ b/plugins/platforms/feishu/feishu_meeting_invite.py@@ -173,7 +173,7 @@ async def handle_meeting_invited_event(adapter: Any, data: Any) -> None:dedup_key = _dedup_key(payload)is_duplicate = getattr(adapter, "_is_duplicate", None)- if callable(is_duplicate) and is_duplicate(dedup_key):+ if callable(is_duplicate) and await is_duplicate(dedup_key):logger.debug("[Feishu-MeetingInvite] Dropping duplicate event: %s", dedup_key)returndiff --git a/tests/gateway/test_discord_free_response.py b/tests/gateway/test_discord_free_response.pyindex fdba6fea2ab..75ee52ea19e 100644--- a/tests/gateway/test_discord_free_response.py+++ b/tests/gateway/test_discord_free_response.py@@ -2,7 +2,7 @@from datetime import datetime, timezonefrom types import SimpleNamespace-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMock, MagicMock, patchimport sysimport pytest@@ -378,7 +378,7 @@ async def test_fetch_channel_context_skips_self_improvement_boundary_message(ada],channel_id=123,)- adapter._nonconversational_messages.mark_many(["9"])+ await adapter._nonconversational_messages.mark_many(["9"])result = await adapter._fetch_channel_context(channel, before=make_message(channel=channel, content="trigger"))@@ -827,3 +827,31 @@ async def test_discord_reply_in_free_channel_triggers_backfill(adapter, monkeypa)+class TestNonConversationalTrackerOffload:+ """atomic_json_write() calls os.fsync(), which blocks until the write+ reaches stable storage. mark_many() runs on the event loop from both+ DiscordAdapter.send() and send_update_prompt(), so the persist step+ must be offloaded to a thread — mirrors+ test_directory_write_runs_off_event_loop_thread in+ test_channel_directory.py for the same #83906 bug class.+ """++ @pytest.mark.asyncio+ async def test_mark_many_persist_runs_off_event_loop_thread(self):+ import threading++ tracker = discord_platform._DiscordNonConversationalMessageTracker()+ loop_thread = threading.get_ident()+ write_threads = []++ def fake_write(path, data, *args, **kwargs):+ write_threads.append(threading.get_ident())++ with patch.object(discord_platform, "atomic_json_write", side_effect=fake_write):+ await tracker.mark_many(["999"])++ assert "999" in tracker+ assert write_threads+ assert all(tid != loop_thread for tid in write_threads)++diff --git a/tests/gateway/test_feishu.py b/tests/gateway/test_feishu.pyindex d25c5ad5749..c41a4ab0d59 100644--- a/tests/gateway/test_feishu.py+++ b/tests/gateway/test_feishu.py@@ -1186,9 +1186,9 @@ class TestAdapterBehavior(unittest.TestCase):with tempfile.TemporaryDirectory() as temp_home:with patch.dict(os.environ, {"HERMES_HOME": temp_home}, clear=False):first = FeishuAdapter(PlatformConfig())- self.assertFalse(first._is_duplicate("om_same"))+ self.assertFalse(asyncio.run(first._is_duplicate("om_same")))second = FeishuAdapter(PlatformConfig())- self.assertTrue(second._is_duplicate("om_same"))+ self.assertTrue(asyncio.run(second._is_duplicate("om_same")))@patch.dict(os.environ, {}, clear=True)@@ -1622,7 +1622,7 @@ class TestDedupTTL(unittest.TestCase):with patch.object(adapter, "_persist_seen_message_ids"):adapter._seen_message_ids = {"om_dup": time.time()}adapter._seen_message_order = ["om_dup"]- self.assertTrue(adapter._is_duplicate("om_dup"))+ self.assertTrue(asyncio.run(adapter._is_duplicate("om_dup")))@patch.dict(os.environ, {}, clear=True)@@ -1656,6 +1656,32 @@ class TestDedupTTL(unittest.TestCase):assert "om_bad_str" not in adapter._seen_message_idsassert "om_bad_null" not in adapter._seen_message_ids+ @patch.dict(os.environ, {}, clear=True)+ def test_persist_on_new_message_runs_off_event_loop_thread(self):+ """atomic_json_write() calls os.fsync(), which blocks until the write+ reaches stable storage. _is_duplicate() runs on the event loop for+ every inbound message (_handle_message_event_data), so the persist+ step must be offloaded to a thread — mirrors+ test_directory_write_runs_off_event_loop_thread in+ test_channel_directory.py for the same #83906 bug class."""+ import threading+ from gateway.config import PlatformConfig+ from plugins.platforms.feishu.adapter import FeishuAdapter++ adapter = FeishuAdapter(PlatformConfig())+ loop_thread = threading.get_ident()+ write_threads = []++ def fake_write(path, data, *args, **kwargs):+ write_threads.append(threading.get_ident())++ with patch("plugins.platforms.feishu.adapter.atomic_json_write", side_effect=fake_write):+ is_dup = asyncio.run(adapter._is_duplicate("om_new"))++ self.assertFalse(is_dup)+ self.assertTrue(write_threads)+ self.assertTrue(all(tid != loop_thread for tid in write_threads))+class TestGroupMentionAtAll(unittest.TestCase):"""Tests for @_all (Feishu @everyone) group mention routing."""diff --git a/tests/gateway/test_feishu_meeting_invite.py b/tests/gateway/test_feishu_meeting_invite.pyindex 47ce7472d00..d8e4725a646 100644--- a/tests/gateway/test_feishu_meeting_invite.py+++ b/tests/gateway/test_feishu_meeting_invite.py@@ -76,7 +76,7 @@ class _Adapter:self.dedup_keys = []self.profile_requests = []- def _is_duplicate(self, key):+ async def _is_duplicate(self, key):self.dedup_keys.append(key)return self.duplicate@@ -166,6 +166,19 @@ class TestMeetingInviteHandler(unittest.TestCase):self.assertIn("You have been invited to join a meeting: 赵磊的视频会议", event.text)self.assertNotIn("{'open_id'", event.text)+ def test_duplicate_event_is_dropped_without_routing(self):+ """_is_duplicate() is async on the real FeishuAdapter (dedup persist+ is offloaded off the event loop); the dedup check here must await+ it — a missing await would leave an un-awaited coroutine, which is+ always truthy, and drop every event as a false duplicate."""+ adapter = _Adapter(duplicate=True)++ self._run(handle_meeting_invited_event(adapter, _make_payload()))++ self.assertEqual(adapter.dedup_keys, ["vc_invite:evt_1"])+ self.assertEqual(adapter.events, [])+ self.assertEqual(adapter.profile_requests, [])+class TestMeetingInviteSendRouting(unittest.TestCase):def _run(self, coro):diff --git a/tests/gateway/test_weixin.py b/tests/gateway/test_weixin.pyindex ed9c5e58045..1c44b1c204e 100644--- a/tests/gateway/test_weixin.py+++ b/tests/gateway/test_weixin.py@@ -167,6 +167,30 @@ class TestWeixinStatePersistence:assert json.loads(account_path.read_text(encoding="utf-8")) == original+ @pytest.mark.asyncio+ async def test_context_token_persist_runs_off_event_loop_thread(self, tmp_path):+ """atomic_json_write() calls os.fsync(), which blocks until the write+ reaches stable storage. ContextTokenStore.set() runs on the event+ loop for every inbound message carrying a context_token+ (_process_message), so the persist step must be offloaded to a+ thread — mirrors test_directory_write_runs_off_event_loop_thread in+ test_channel_directory.py for the same #83906 bug class."""+ import threading++ store = ContextTokenStore(str(tmp_path))+ loop_thread = threading.get_ident()+ write_threads = []++ def fake_write(path, data, *args, **kwargs):+ write_threads.append(threading.get_ident())++ with patch("gateway.platforms.weixin.atomic_json_write", side_effect=fake_write):+ await store.set("acct-1", "user-1", "ctx-token-abc")++ assert store.get("acct-1", "user-1") == "ctx-token-abc"+ assert write_threads+ assert all(tid != loop_thread for tid in write_threads)+class TestWeixinQrLogin:@pytest.mark.asyncio