DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(partners): retain failed channel deliveries for retry
dajiaohuangf04641750036
diff --git a/deeptutor/partners/channels/dingtalk.py b/deeptutor/partners/channels/dingtalk.pyindex 8c5028395..3a631af01 100644--- a/deeptutor/partners/channels/dingtalk.py+++ b/deeptutor/partners/channels/dingtalk.py@@ -499,10 +499,11 @@ class DingTalkChannel(BaseChannel):"""Send a message through DingTalk."""token = await self._get_access_token()if not token:- return+ raise RuntimeError("DingTalk access token unavailable")if msg.content and msg.content.strip():- await self._send_markdown_text(token, msg.chat_id, msg.content.strip())+ if not await self._send_markdown_text(token, msg.chat_id, msg.content.strip()):+ raise RuntimeError(f"DingTalk text delivery failed for chat {msg.chat_id}")for media_ref in msg.media or []:ok = await self._send_media_ref(token, msg.chat_id, media_ref)@@ -511,11 +512,12 @@ class DingTalkChannel(BaseChannel):logger.error("DingTalk media send failed for {}", media_ref)# Send visible fallback so failures are observable by the user.filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))- await self._send_markdown_text(+ if not await self._send_markdown_text(token,msg.chat_id,f"[Attachment send failed: {filename}]",- )+ ):+ raise RuntimeError(f"DingTalk attachment notice failed for chat {msg.chat_id}")async def _on_message(self,diff --git a/deeptutor/partners/channels/matrix.py b/deeptutor/partners/channels/matrix.pyindex b1db432d5..e235aa224 100644--- a/deeptutor/partners/channels/matrix.py+++ b/deeptutor/partners/channels/matrix.py@@ -364,7 +364,9 @@ class MatrixChannel(BaseChannel):}if self.config.e2ee_enabled:kwargs["ignore_unverified_devices"] = True- await self.client.room_send(**kwargs)+ response = await self.client.room_send(**kwargs)+ if isinstance(response, RoomSendError):+ raise RuntimeError(f"Matrix message delivery failed: {response}")async def _resolve_server_upload_limit_bytes(self) -> int | None:"""Query homeserver upload limit once per channel lifecycle."""diff --git a/deeptutor/partners/channels/mochat.py b/deeptutor/partners/channels/mochat.pyindex 05976f24e..2836f017d 100644--- a/deeptutor/partners/channels/mochat.py+++ b/deeptutor/partners/channels/mochat.py@@ -408,6 +408,7 @@ class MochatChannel(BaseChannel):)except Exception as e:logger.error("Failed to send Mochat message: {}", e)+ raise# ---- config / init helpers ---------------------------------------------diff --git a/tests/services/partners/test_dingtalk_delivery_retry.py b/tests/services/partners/test_dingtalk_delivery_retry.pynew file mode 100644index 000000000..aa9aec940--- /dev/null+++ b/tests/services/partners/test_dingtalk_delivery_retry.py@@ -0,0 +1,51 @@+"""DingTalk delivery failures must reach the shared retry boundary."""++import json++import httpx+import pytest++from deeptutor.partners.bus.events import OutboundMessage+from deeptutor.partners.bus.queue import MessageBus+from deeptutor.partners.channels.dingtalk import DingTalkChannel+from deeptutor.partners.channels.manager import send_with_retry++[email protected]("failure", ["token", "http", "api"])+async def test_transient_text_failure_is_retried(failure: str) -> None:+ """Use the native HTTP client and public sender, without external accounts."""+ token_requests = 0+ messages: list[dict] = []+ delivered: list[str] = []++ def respond(request: httpx.Request) -> httpx.Response:+ nonlocal token_requests+ if request.url.path.endswith("accessToken"):+ token_requests += 1+ if failure == "token" and token_requests == 1:+ return httpx.Response(503)+ return httpx.Response(200, json={"accessToken": "test-token", "expireIn": 7200})+ payload = json.loads(request.content)+ messages.append(payload)+ if len(messages) == 1 and failure == "http":+ return httpx.Response(503)+ if len(messages) == 1 and failure == "api":+ return httpx.Response(200, json={"errcode": 500, "errmsg": "temporarily unavailable"})+ delivered.append(json.loads(payload["msgParam"])["text"])+ return httpx.Response(200, json={"processQueryKey": "test-delivery"})++ channel = DingTalkChannel(+ {"client_id": "test-id", "client_secret": "test-secret"}, MessageBus()+ )+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:+ channel._http = client+ await send_with_retry(+ channel,+ OutboundMessage(channel="dingtalk", chat_id="test-recipient", content="学习回复"),+ max_attempts=2,+ retry_delays=(0,),+ )+ assert delivered == ["学习回复"]+ assert token_requests == (2 if failure == "token" else 1)+ assert len(messages) == (1 if failure == "token" else 2)diff --git a/tests/services/partners/test_matrix_delivery_retry.py b/tests/services/partners/test_matrix_delivery_retry.pynew file mode 100644index 000000000..2da6308ff--- /dev/null+++ b/tests/services/partners/test_matrix_delivery_retry.py@@ -0,0 +1,55 @@+"""Native Matrix SDK error responses must reach the shared retry boundary."""++from aiohttp import web+from nio import AsyncClient, AsyncClientConfig+import pytest++from deeptutor.partners.bus.events import OutboundMessage+from deeptutor.partners.bus.queue import MessageBus+from deeptutor.partners.channels.manager import send_with_retry+from deeptutor.partners.channels.matrix import MatrixChannel+++async def test_matrix_error_response_is_retried() -> None:+ """Exercise the native SDK against a local server, without a Matrix account."""+ requests = 0+ delivered: list[str] = []++ async def send(request: web.Request) -> web.Response:+ nonlocal requests+ if "/send/" not in request.path:+ return web.json_response({})+ requests += 1+ if requests == 1:+ return web.json_response({"errcode": "M_UNKNOWN", "error": "try again"}, status=400)+ delivered.append((await request.json())["body"])+ return web.json_response({"event_id": "$test-delivery"})++ app = web.Application()+ app.router.add_put("/{path:.*}", send)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ port = site._server.sockets[0].getsockname()[1]+ client = AsyncClient(+ f"http://127.0.0.1:{port}",+ user="@test:localhost",+ config=AsyncClientConfig(max_limit_exceeded=0, max_timeouts=0),+ )+ client.access_token = "test-token"+ channel = MatrixChannel({}, MessageBus())+ channel.client = client+ try:+ await send_with_retry(+ channel,+ OutboundMessage(channel="matrix", chat_id="!test:localhost", content="学习回复"),+ max_attempts=2,+ retry_delays=(0,),+ )+ assert delivered == ["学习回复"]+ assert requests == 2+ finally:+ await client.close()+ await runner.cleanup()diff --git a/tests/services/partners/test_mochat_delivery_retry.py b/tests/services/partners/test_mochat_delivery_retry.pynew file mode 100644index 000000000..822fe4dd7--- /dev/null+++ b/tests/services/partners/test_mochat_delivery_retry.py@@ -0,0 +1,41 @@+"""Mochat delivery errors must propagate to the public retry boundary."""++import json++import httpx+import pytest++from deeptutor.partners.bus.events import OutboundMessage+from deeptutor.partners.bus.queue import MessageBus+from deeptutor.partners.channels.manager import send_with_retry+from deeptutor.partners.channels.mochat import MochatChannel++[email protected]("failure", ["http", "api"])+async def test_mochat_delivery_is_retried(failure: str) -> None:+ """Use actual HTTP response parsing and the channel's session send path."""+ requests = 0+ delivered: list[str] = []++ def respond(request: httpx.Request) -> httpx.Response:+ nonlocal requests+ requests += 1+ if requests == 1:+ if failure == "http":+ return httpx.Response(503)+ return httpx.Response(200, json={"code": 503, "message": "try again"})+ delivered.append(json.loads(request.content)["content"])+ return httpx.Response(200, json={"code": 200, "data": {"messageId": "test-delivery"}})++ channel = MochatChannel({"claw_token": "test-token"}, MessageBus())+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:+ channel._http = client+ await send_with_retry(+ channel,+ OutboundMessage(channel="mochat", chat_id="session_test", content="学习回复"),+ max_attempts=2,+ retry_delays=(0,),+ )+ assert delivered == ["学习回复"]+ assert requests == 2