Skip to content

The agent that grows with you

fix(telegram): pace sends and edits against a shared per-chat slot

Haisam Abbasfb2f3e213a55
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 4e6aceee668..ca0d6d65a20 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -163,6 +163,15 @@ _TELEGRAM_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif"}
# — a 97-minute penalty on the boot path froze inbound on every platform (#91969).
_FLOOD_INLINE_WAIT_CAP_SECS = 5.0
+# Shared per-chat outbound budget (#116312): Telegram counts an editMessageText against the
+# SAME per-chat allowance as a sendMessage, but streaming previews used to pace only edits at
+# DEFAULT_STREAMING_EDIT_INTERVAL = 0.8s (1.25 msg/s into one chat before any reply was sent)
+# — that was 83% of measured flood penalties. One shared slot per chat: a SEND waits for its
+# slot (skipping a send would drop a message), an INTERIM edit is skipped (the next tick shows
+# the same text anyway), and the FINAL edit is never gated (the answer itself is never
+# withheld). Tunable: validated in production by the issue reporter at 0 flood events.
+_TELEGRAM_CHAT_OUTBOUND_BUDGET_SECS = 1.0
+
def _flood_cap_result(wait: float) -> "SendResult":
"""The shared fail-closed SendResult for an over-cap flood wait."""
@@ -3607,6 +3616,15 @@ class TelegramAdapter(BasePlatformAdapter):
"[%s] Telegram flood control still active for chat %s (%.0fs left); refusing locally without an API call",
self.name, chat_id, cooldown)
return _flood_cap_result(cooldown)
+ # Shared per-chat budget (#116312): a send WAITS for its slot (a send that waits
+ # is delivered; one that is skipped would drop a message).
+ slot_remaining = self._chat_outbound_slot_remaining(chat_id)
+ if slot_remaining > 0:
+ logger.debug(
+ "[%s] pacing send for chat %s (shared send+edit budget: slot in %.1fs)",
+ self.name, chat_id, slot_remaining)
+ await asyncio.sleep(slot_remaining)
+ self._hold_chat_outbound_slot(chat_id)
error_types = self._telegram_error_types()
chunks: List[str] = []
delivered: List[str] = []
@@ -3769,6 +3787,22 @@ class TelegramAdapter(BasePlatformAdapter):
continuations, and return the final chunk's id as the next edit target."""
if not self._bot:
return SendResult(success=False, error="Not connected")
+ # Shared per-chat budget (#116312): an interim (preview) edit is SKIPPED when the slot is busy —
+ # the text it would show is shown by the next edit anyway, so a burst of edits can't trip flood
+ # control. A final edit is never gated (the completed answer is always delivered). Sends wait for
+ # their slot; edits defer instead. Over-cap interim edits are exempt: the saturated-preview dedup
+ # below already throttles them to one real edit per ~4096-char growth. Consumed only when the
+ # edit actually fires.
+ if (
+ not finalize
+ and utf16_len(content) <= self.MAX_MESSAGE_LENGTH
+ and self._chat_outbound_slot_remaining(chat_id) > 0
+ ):
+ logger.debug(
+ "[%s] skipping interim edit for chat %s (shared send+edit budget: slot busy)",
+ self.name, chat_id)
+ return SendResult(success=True, message_id=message_id)
+ self._hold_chat_outbound_slot(chat_id)
# Rich finalize (Bot API 10.1): edit the preview IN PLACE via rich_message — no fresh send + delete.
# Before the 4,096 pre-flight because the rich cap is 32,768; falls back to legacy on rejection.
# Rich finalize (Bot API 10.1): when the completed content has constructs the legacy MarkdownV2 edit
@@ -5420,6 +5454,31 @@ class TelegramAdapter(BasePlatformAdapter):
until.pop(key, None)
return None
+ # --- shared per-chat send+edit pacing budget (#116312) -----------------------------------------
+ # One slot per chat that sendMessage AND editMessageText both draw from (Telegram counts them
+ # against the same per-chat allowance). ``_telegram_chat_outbound_slot_until`` maps the
+ # normalized chat id to the loop-time when the next outbound call may fire.
+
+ def _chat_outbound_slot_remaining(self, chat_id: Any) -> float:
+ """Seconds until this chat's shared send+edit slot is open again (0 = may fire now)."""
+ slot_until: Dict[str, float] = self.__dict__.setdefault("_telegram_chat_outbound_slot_until", {})
+ key = str(normalize_telegram_chat_id(chat_id))
+ deadline = slot_until.get(key)
+ if deadline is None:
+ return 0.0
+ remaining = deadline - asyncio.get_running_loop().time()
+ if remaining <= 0:
+ slot_until.pop(key, None) # expired — bounded dict, like the send locks
+ return 0.0
+ return remaining
+
+ def _hold_chat_outbound_slot(self, chat_id: Any) -> None:
+ """Arm/re-arm this chat's slot after an actual send/edit API call fires."""
+ slot_until: Dict[str, float] = self.__dict__.setdefault("_telegram_chat_outbound_slot_until", {})
+ budget = getattr(self, "_telegram_chat_outbound_slot_secs", _TELEGRAM_CHAT_OUTBOUND_BUDGET_SECS)
+ slot_until[str(normalize_telegram_chat_id(chat_id))] = (
+ asyncio.get_running_loop().time() + max(0.0, budget))
+
async def send_typing(self, chat_id: str, metadata: Optional[Dict[str, Any]] = None) -> None:
"""Send typing indicator."""
if not self._bot or self._typing_in_cooldown(chat_id):
diff --git a/tests/gateway/test_telegram_shared_outbound_budget.py b/tests/gateway/test_telegram_shared_outbound_budget.py
new file mode 100644
index 00000000000..d0971c98791
--- /dev/null
+++ b/tests/gateway/test_telegram_shared_outbound_budget.py
@@ -0,0 +1,117 @@
+"""Shared per-chat send+edit pacing budget (#116312).
+
+sendMessage and editMessageText count against the same per-chat Telegram allowance; a stream that edits
+too often while the assistant's own backend sends were also in flight tripped FloodWait (23 events).
+A per-chat 1/s slot shared by both: a SEND waits for its slot (never dropped), an INTERIM edit is
+skipped (the next edit shows the same text anyway), and the FINAL edit is never gated (the completed
+answer is always delivered).
+"""
+import asyncio
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from gateway.config import PlatformConfig
+from plugins.platforms.telegram.adapter import TelegramAdapter
+
+
+def _adapter(send_message: AsyncMock) -> TelegramAdapter:
+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
+ adapter._rich_send_disabled = True
+ adapter._bot = MagicMock()
+ adapter._bot.send_message = send_message
+ adapter._bot.edit_message_text = AsyncMock(return_value=MagicMock())
+ return adapter
+
+
+def _now() -> float:
+ return asyncio.get_running_loop().time()
+
+
+async def test_interim_edit_skipped_when_slot_busy_but_final_edit_never_gated():
+ """An interim edit while the shared slot is held returns success with the SAME message id and makes
+ no API call; a finalize edit to the same chat still fires even though the slot is still held."""
+ adapter = _adapter(AsyncMock())
+
+ result = await adapter.edit_message("c1", "900", "part one", finalize=False)
+ assert result.success is True # consumed a slot on the first real edit
+
+ busy = _chat_slot_remaining(adapter, "c1")
+ assert busy > 0
+
+ skipped = await adapter.edit_message("c1", "900", "part two", finalize=False)
+ assert skipped.success is True and skipped.message_id == "900"
+ assert adapter._bot.edit_message_text.await_count == 1
+
+ final = await adapter.edit_message("c1", "900", "part two final", finalize=True)
+ assert final.success is True
+ assert adapter._bot.edit_message_text.await_count == 2 # the final edit is never gated
+
+
+async def test_skipped_interim_edit_consumes_no_slot():
+ """A skipped interim edit returns success but does NOT consume the slot — the next interim edit is
+ still allowed to fire."""
+ adapter = _adapter(AsyncMock())
+ await adapter.edit_message("c1", "900", "one", finalize=False)
+ await adapter.edit_message("c1", "900", "two", finalize=False) # skipped, no slot consumed
+ await adapter.edit_message("c1", "900", "three", finalize=False) # slot still held, skipped
+
+ assert adapter._bot.edit_message_text.await_count == 1
+
+
+async def test_send_waits_for_held_slot():
+ """A send to a chat whose slot is held defers until the slot opens and then fires exactly once."""
+ adapter = _adapter(AsyncMock())
+ await adapter.edit_message("c1", "900", "one", finalize=False) # hold the shared slot for c1
+
+ sleeps: list[float] = []
+
+ async def fake_sleep(seconds: float):
+ sleeps.append(seconds)
+
+ original_sleep = asyncio.sleep
+ asyncio.sleep = fake_sleep # type: ignore[assignment]
+ try:
+ result = await adapter.send("c1", "hello")
+ finally:
+ asyncio.sleep = original_sleep # type: ignore[assignment]
+
+ assert result.success is True
+ assert adapter._bot.send_message.await_count == 1
+ assert sleeps, "send should have awaited asyncio.sleep for the pending slot"
+
+
+def _chat_slot_remaining(adapter: TelegramAdapter, chat_id: str) -> float:
+ return adapter._chat_outbound_slot_remaining(chat_id)
+
+
+async def test_slot_is_per_chat():
+ """The shared slot is keyed per chat: one chat's burst must not gate another chat."""
+ adapter = _adapter(AsyncMock())
+ await adapter.edit_message("c1", "900", "one", finalize=False) # holds c1's slot
+ assert _chat_slot_remaining(adapter, "c1") > 0
+
+ result = await adapter.send("c2", "hello other")
+ assert result.success is True
+ assert adapter._bot.send_message.await_count == 1 # c2 untouched by c1's slot
+ assert _chat_slot_remaining(adapter, "c2") > 0 # c2 consumed its own slot
+
+
+async def test_slot_expiry_lets_interim_edit_fire():
+ """Once the budget window passes, the slot opens and an interim edit is allowed again."""
+ adapter = _adapter(AsyncMock())
+ await adapter.edit_message("c1", "900", "one", finalize=False)
+ assert adapter._bot.edit_message_text.await_count == 1
+
+ deadline = adapter._telegram_chat_outbound_slot_until["c1"]
+ adapter._telegram_chat_outbound_slot_until["c1"] = _now() - 1.0 # expire the window
+ assert deadline is not None
+
+ result = await adapter.edit_message("c1", "900", "two", finalize=False)
+ assert result.success is True
+ assert adapter._bot.edit_message_text.await_count == 2 # fired again now that the slot is free
\ No newline at end of file
diff --git a/tests/gateway/test_telegram_typing_retrigger.py b/tests/gateway/test_telegram_typing_retrigger.py
index d9d7013ce80..7c427cc9390 100644
--- a/tests/gateway/test_telegram_typing_retrigger.py
+++ b/tests/gateway/test_telegram_typing_retrigger.py
@@ -21,6 +21,11 @@ def _make_adapter():
adapter._bot = AsyncMock()
adapter._bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=1))
adapter._bot.send_chat_action = AsyncMock(return_value=None)
+ # This test models a burst of streamed chunks landing back-to-back; the shared send+edit
+ # pacing slot (#116312) would space those sends out to ~1/s, so real time elapses between them
+ # and typing re-arms — exactly its collapse cadence. Shut the slot off to keep the burst
+ # instantaneous so only the per-chat collapse is measured.
+ adapter._telegram_chat_outbound_slot_secs = 0.0
return adapter