Skip to content

The agent that grows with you

fix(gateway): a split send that fails mid-way is never re-sent whole

teknium1c8cde58273a1
diff --git a/gateway/platforms/helpers.py b/gateway/platforms/helpers.py
index aa0ea7ac409..0635334e98c 100644
--- a/gateway/platforms/helpers.py
+++ b/gateway/platforms/helpers.py
@@ -242,6 +242,26 @@ class ThreadParticipationTracker:
self._threads.clear()
+async def send_chunks(chunks: list, send_one) -> Any:
+ """Send ``chunks`` in order through ``send_one(chunk) -> SendResult``, stopping at the first failure.
+
+ A failure after earlier chunks landed carries the ``partial_overflow`` contract that
+ ``BasePlatformAdapter._is_partial_delivery`` reads, so no caller (send retry, plain-text
+ fallback, cron standalone fallback) re-sends the head the recipient already has.
+ """
+ from gateway.platforms.base import SendResult
+ result = SendResult(success=False, error="nothing to send")
+ for delivered, chunk in enumerate(chunks):
+ result = await send_one(chunk)
+ if not result.success:
+ if delivered:
+ raw = dict(result.raw_response) if isinstance(result.raw_response, dict) else {}
+ raw.update(partial_overflow=True, delivered_chunks=delivered, total_chunks=len(chunks))
+ result.raw_response = raw
+ break
+ return result
+
+
def redact_phone(phone: str) -> str:
"""Redact a phone number for logging, preserving country code and last 4."""
if not phone:
diff --git a/plugins/platforms/sms/adapter.py b/plugins/platforms/sms/adapter.py
index 0c6cfb91e1f..c7027a24b82 100644
--- a/plugins/platforms/sms/adapter.py
+++ b/plugins/platforms/sms/adapter.py
@@ -23,7 +23,7 @@ from typing import Any, Dict, Optional
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, SendResult
from gateway.platforms.event import MessageEvent, MessageType
-from gateway.platforms.helpers import redact_phone, strip_markdown
+from gateway.platforms.helpers import redact_phone, send_chunks, strip_markdown
from gateway.platforms._shared import (
env_is_connected as _env_is_connected, get_scoped_secret as _get_scoped_secret, send_error
)
@@ -161,29 +161,27 @@ class SmsAdapter(BasePlatformAdapter):
async def send(
self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- last_result = SendResult(success=True)
url, headers = _messages_endpoint(self._account_sid, self._auth_token)
session = self._http_session or _new_session(trust_env=gateway_trust_env())
+
+ async def _send_one(chunk: str) -> SendResult:
+ try:
+ async with session.post(url, data=_twilio_form(self._from_number, chat_id, chunk), headers=headers) as resp:
+ body = await resp.json()
+ if resp.status >= 400:
+ error_msg = body.get("message", str(body))
+ logger.error("[sms] send failed to %s: %s %s", redact_phone(chat_id), resp.status, error_msg)
+ return SendResult(success=False, error=f"Twilio {resp.status}: {error_msg}")
+ return SendResult(success=True, message_id=body.get("sid", ""))
+ except Exception as e:
+ logger.error("[sms] send error to %s: %s", redact_phone(chat_id), e)
+ return SendResult(success=False, error=str(e))
+
try:
- for chunk in self.truncate_message(self.format_message(content), self.MAX_MESSAGE_LENGTH):
- form_data = _twilio_form(self._from_number, chat_id, chunk)
- try:
- async with session.post(url, data=form_data, headers=headers) as resp:
- body = await resp.json()
- if resp.status >= 400:
- error_msg = body.get("message", str(body))
- logger.error(
- "[sms] send failed to %s: %s %s", redact_phone(chat_id), resp.status, error_msg,
- )
- return SendResult(success=False, error=f"Twilio {resp.status}: {error_msg}")
- last_result = SendResult(success=True, message_id=body.get("sid", ""))
- except Exception as e:
- logger.error("[sms] send error to %s: %s", redact_phone(chat_id), e)
- return SendResult(success=False, error=str(e))
+ return await send_chunks(self.truncate_message(self.format_message(content), self.MAX_MESSAGE_LENGTH), _send_one)
finally:
if not self._http_session and session: # close only a fallback session we created
await session.close()
- return last_result
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
return {"name": chat_id, "type": "dm"}
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index 7d45e6500d1..742b2e4458b 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -28,7 +28,7 @@ AIOHTTP_AVAILABLE = aiohttp is not None
HTTPX_AVAILABLE = httpx is not None
from gateway.config import Platform, PlatformConfig
-from gateway.platforms.helpers import MessageDeduplicator, bounded_put
+from gateway.platforms.helpers import MessageDeduplicator, bounded_put, send_chunks
from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, SendResult
from gateway.platforms.event import MessageEvent, MessageType
@@ -600,12 +600,8 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAcc
# Approval *confirmations* must not consume the req_id the stream consumer still needs.
force_proactive = bool(metadata.pop("force_proactive_send", False))
# One queued send per chunk so each one draws a token from the 30 msgs/min bucket.
- result = SendResult(success=False, error="nothing to send")
- for chunk in self.truncate_message(content, self.MAX_MESSAGE_LENGTH):
- result = await self._enqueue_chat_send(chat_id, lambda c=chunk: self._send_inner(chat_id, c, reply_to, force_proactive=force_proactive), is_control=is_control)
- if not result.success:
- break
- return result
+ return await send_chunks(self.truncate_message(content, self.MAX_MESSAGE_LENGTH), lambda chunk: self._enqueue_chat_send(
+ chat_id, lambda: self._send_inner(chat_id, chunk, reply_to, force_proactive=force_proactive), is_control=is_control))
async def _send_inner(self, chat_id: str, content: str, reply_to: Optional[str] = None, *, force_proactive: bool = False) -> SendResult:
"""Send under the per-chat queue; force_proactive skips passive reply except in groups."""
diff --git a/plugins/platforms/wecom/callback_adapter.py b/plugins/platforms/wecom/callback_adapter.py
index 7dafb76baeb..dd21b28d7d3 100644
--- a/plugins/platforms/wecom/callback_adapter.py
+++ b/plugins/platforms/wecom/callback_adapter.py
@@ -34,7 +34,7 @@ except ImportError:
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import BasePlatformAdapter, SendResult
from gateway.platforms.event import MessageEvent, MessageType
-from gateway.platforms.helpers import MessageDeduplicator
+from gateway.platforms.helpers import MessageDeduplicator, send_chunks
from plugins.platforms.wecom.wecom_crypto import WXBizMsgCrypt, WeComCryptoError
logger = logging.getLogger(__name__)
@@ -190,12 +190,8 @@ class WecomCallbackAdapter(BasePlatformAdapter):
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:
"""One text message per MAX_MESSAGE_LENGTH-byte chunk; stops at the first failure."""
app = self._resolve_app_for_chat(chat_id)
- result = SendResult(success=False, error="nothing to send")
- for chunk in self.truncate_message(content, self.MAX_MESSAGE_LENGTH, len_fn=_utf8_len):
- result = await self._send_text(app, chat_id, chunk)
- if not result.success:
- break
- return result
+ chunks = self.truncate_message(content, self.MAX_MESSAGE_LENGTH, len_fn=_utf8_len)
+ return await send_chunks(chunks, lambda chunk: self._send_text(app, chat_id, chunk))
async def _send_text(self, app: Dict[str, Any], chat_id: str, content: str) -> SendResult:
try:
diff --git a/tests/gateway/test_sms.py b/tests/gateway/test_sms.py
index bf24747df04..c49611ce187 100644
--- a/tests/gateway/test_sms.py
+++ b/tests/gateway/test_sms.py
@@ -348,3 +348,38 @@ async def test_oversized_cron_output_reaches_twilio_in_1600_char_chunks():
assert result.success
assert len(bodies) > 1 and max(map(len, bodies)) <= 1600
assert "line 39 " in bodies[-1]
+
+
+async def test_failure_after_delivered_chunks_is_never_resent_whole():
+ """Twilio rejects chunk 3 of a long reply. The chunks already on the phone must not arrive again
+ via the retry/plain-text fallback, which would also drop the tail (it resends content[:3500])."""
+ from plugins.platforms.sms.adapter import SmsAdapter
+
+ with patch.dict(os.environ, {"TWILIO_ACCOUNT_SID": "ACtest", "TWILIO_AUTH_TOKEN": "tok",
+ "TWILIO_PHONE_NUMBER": "+15550001111"}):
+ adapter = SmsAdapter(PlatformConfig(enabled=True, api_key="tok"))
+ bodies = []
+
+ class _Resp:
+ def __init__(self, status):
+ self.status = status
+ async def json(self):
+ return {"sid": f"SM{len(bodies)}"} if self.status < 400 else {"message": "rejected"}
+ async def __aenter__(self):
+ return self
+ async def __aexit__(self, *exc):
+ return False
+
+ class _Session:
+ def post(self, url, data, headers):
+ bodies.append(next(value for opts, _, value in data._fields if opts["name"] == "Body"))
+ return _Resp(400 if len(bodies) == 3 else 201)
+
+ adapter._http_session = _Session()
+ content = "\n\n".join(f"para {i:02d} " + "y" * 300 for i in range(20))
+ result = await adapter._send_with_retry("+15550002222", content)
+
+ assert not result.success
+ assert result.raw_response["partial_overflow"] and result.raw_response["delivered_chunks"] == 2
+ assert all("".join(bodies).count(f"para {i:02d} ") <= 1 for i in range(20)), "a delivered chunk was re-sent"