Skip to content

The agent that grows with you

fix(cron): a partly delivered split send is not re-sent by the standalone fallback

teknium1be5e9f72c668
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index 74b906c46ea..5fdbb17c297 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -1481,7 +1481,7 @@ def _live_send_text(
"""Schedule the text send on the gateway loop; returns ``(adapter_ok, timed_out, message_id)``.
Re-raises a real send error so the caller falls through to standalone."""
from agent.async_utils import safe_schedule_threadsafe
- from gateway.delivery import DeliveryRouter, DeliveryTarget
+ from gateway.delivery import DeliveryRouter, DeliveryTarget, PartialDeliveryError
job = t.job
router = DeliveryRouter(t.config, t.target_adapters)
route_target = DeliveryTarget(
@@ -1529,6 +1529,13 @@ def _live_send_text(
"to avoid duplicate)",
job["id"], t.platform_name, t.chat_id)
return True, True, None
+ except PartialDeliveryError as ex:
+ # The head of a split send is already on screen: a standalone resend would duplicate it.
+ raw = getattr(ex.result, "raw_response", None) or {}
+ _note_target_error(
+ job, f"live adapter send to {t.where} delivered {raw.get('delivered_chunks', '?')} of "
+ f"{raw.get('total_chunks', '?')} chunks, then failed: {ex}", delivery_errors)
+ return True, False, None
except Exception as ex:
# Real send error (not a slow confirmation): fall through to standalone. The router raises
# a failed SendResult's error string, so this is where send_path_degraded arrives.
diff --git a/gateway/delivery.py b/gateway/delivery.py
index 23451454d8a..582ffe8ef2d 100644
--- a/gateway/delivery.py
+++ b/gateway/delivery.py
@@ -36,6 +36,15 @@ def _is_silence_narration(content: Optional[str]) -> bool:
return bool(stripped) and len(stripped) <= 64 and bool(_SILENCE_NARRATION.match(stripped))
+class PartialDeliveryError(RuntimeError):
+ """A split send failed after earlier chunks were delivered (``raw_response["partial_overflow"]``).
+ Callers must not fall back to re-sending the whole payload: the recipient already has the head."""
+
+ def __init__(self, message: str, result: Any):
+ super().__init__(message)
+ self.result = result
+
+
@dataclass(frozen=True)
class DeliveryTransport:
"""Resolved live transport for one logical delivery platform."""
@@ -318,5 +327,8 @@ class DeliveryRouter:
send_metadata["thread_id"] = await _ensure_named_dm_topic(adapter, target.chat_id, named_topic, refresh=True)
send_metadata["telegram_dm_topic_created_for_send"] = True
if error is not None:
+ from gateway.platforms.base import BasePlatformAdapter
+ if BasePlatformAdapter._is_partial_delivery(result):
+ raise PartialDeliveryError(error, result)
raise RuntimeError(error or f"{target.platform.value} delivery failed")
return result
diff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.py
index f5592a4e36a..9d29b5bba75 100644
--- a/tests/cron/test_scheduler.py
+++ b/tests/cron/test_scheduler.py
@@ -1842,6 +1842,40 @@ class TestDeliverResultTimeoutCancelsFuture:
standalone_send.assert_awaited_once()
adapter.send.assert_not_awaited()
+class TestDeliverResultPartialSplitDelivery:
+ def test_partial_split_delivery_is_not_resent_by_standalone(self):
+ """A split send that failed after delivering its head must not fall through to standalone,
+ which would deliver the whole payload again; the run reports the partial failure instead."""
+ import asyncio
+ import threading
+ from gateway.config import Platform
+ from gateway.platforms.base import SendResult
+
+ loop = asyncio.new_event_loop()
+ threading.Thread(target=loop.run_forever, daemon=True).start()
+ adapter = MagicMock()
+ adapter.splits_long_messages = True
+ adapter.send = AsyncMock(return_value=SendResult(
+ success=False, error="Twilio 400: rejected",
+ raw_response={"partial_overflow": True, "delivered_chunks": 2, "total_chunks": 5}))
+ pconfig = MagicMock()
+ pconfig.enabled = True
+ mock_cfg = MagicMock()
+ mock_cfg.platforms = {Platform.TELEGRAM: pconfig}
+ job = {"id": "partial-job", "deliver": "origin", "origin": {"platform": "telegram", "chat_id": "123"}}
+ standalone_send = AsyncMock(return_value={"success": True})
+ try:
+ with patch("gateway.config.load_gateway_config", return_value=mock_cfg), \
+ patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \
+ patch("tools.send_message_tool._send_to_platform", new=standalone_send):
+ result = _deliver_result(job, "Hello world", adapters={Platform.TELEGRAM: adapter}, loop=loop)
+ finally:
+ loop.call_soon_threadsafe(loop.stop)
+ adapter.send.assert_awaited_once()
+ standalone_send.assert_not_awaited()
+ assert result and "delivered 2 of 5 chunks" in result, result
+
+
class TestDeliverResultLiveAdapterUnconfirmed:
"""Regression for #47056.