fix(telegram): streaming drafts and deletes stay out of a chat's flood window
A 429 retry_after arms the chat's flood window, and sends, edits, typing and native media already respect it. Draft frames and deleteMessage did not, so every streaming tick and the end-of-turn preview cleanup kept hitting a penalty that Telegram extends while it is being hit. Now: - a draft frame inside the window is skipped (success, raw_response skipped), because the next frame or the final send replaces it. A 429 on a rich or plain draft arms the window and keeps the draft transport. - a delete waits a short window out inline. A longer window is waited out once by a tracked background task, so the caller is not parked. - a 429 on either call arms the window for every other path too. send_draft / delete_message bodies move into telegram_flood_window.py (adapter.py shrinks). Fixes #107612
This commit is contained in:
@@ -187,6 +187,7 @@ from plugins.platforms.telegram.telegram_polling_probe import TelegramPendingPro
|
||||
from plugins.platforms.telegram.telegram_intake import effective_update_message
|
||||
from plugins.platforms.telegram.telegram_media_group import add_item_note, flush_media_group_event, queue_media_group_event, tracking_album_items
|
||||
from plugins.platforms.telegram.telegram_media_flood import TelegramMediaFloodMixin
|
||||
from plugins.platforms.telegram import telegram_flood_window as _flood_window
|
||||
from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id, parse_send_target, parse_telegram_message_id
|
||||
from plugins.platforms.telegram.telegram_resolved_prompt import edit_keeping_prompt
|
||||
from plugins.platforms.telegram.telegram_clarify_binding import ClarifyPrompt, log_resolved, tap_matches_prompt
|
||||
@@ -1529,6 +1530,8 @@ class TelegramAdapter(TelegramContactMixin, TelegramHeldInboundMixin, TelegramTo
|
||||
self._bot.do_api_request("sendRichMessageDraft", api_kwargs=payload),
|
||||
timeout=_TEXT_SEND_DEADLINE, label="telegram-send", dump_on_blocked_loop=False))
|
||||
except Exception as exc:
|
||||
if _flood_window.note_flood(self, chat_id, exc):
|
||||
return False
|
||||
if self._is_rich_capability_error(exc):
|
||||
self._rich_draft_disabled = True
|
||||
logger.debug(
|
||||
@@ -3853,21 +3856,9 @@ class TelegramAdapter(TelegramContactMixin, TelegramHeldInboundMixin, TelegramTo
|
||||
return SendResult(success=True, message_id=last_id, continuation_message_ids=tuple(continuation_ids))
|
||||
|
||||
async def delete_message(self, chat_id: str, message_id: str) -> bool:
|
||||
"""Delete a bot-posted message (Bot API allows it within 48h); failures are non-fatal.
|
||||
|
||||
Used by the stream consumer's fresh-final cleanup path (ported from openclaw/openclaw#72038) to
|
||||
remove long-lived preview messages after sending the completed reply as a fresh message. Telegram's
|
||||
Bot API ``deleteMessage`` works for bot-posted messages in the last 48 hours. Failures are non-fatal
|
||||
— the caller leaves the preview in place and logs at debug level.
|
||||
"""
|
||||
if not self._bot:
|
||||
return False
|
||||
try:
|
||||
await self._bot.delete_message(chat_id=normalize_telegram_chat_id(chat_id), message_id=int(message_id))
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.debug("[%s] Failed to delete Telegram message %s: %s", self.name, message_id, _redact_telegram_error_text(e))
|
||||
return False
|
||||
"""Delete a bot-posted message (Bot API allows it within 48h); failures are non-fatal (False).
|
||||
Used by the stream consumer's fresh-final cleanup (openclaw/openclaw#72038); waits out the chat's flood window."""
|
||||
return await _flood_window.delete_message(self, chat_id, message_id)
|
||||
|
||||
def supports_draft_streaming(self, chat_type: Optional[str] = None, metadata: Optional[dict[str, Any]] = None) -> bool:
|
||||
"""sendMessageDraft works for private chats only (Bot API 9.5) and needs PTB >= 22.6; groups and
|
||||
@@ -3879,45 +3870,7 @@ class TelegramAdapter(TelegramContactMixin, TelegramHeldInboundMixin, TelegramTo
|
||||
async def send_draft(self, chat_id: str, draft_id: int, content: str, metadata: Optional[dict[str, Any]] = None) -> SendResult:
|
||||
"""Stream a partial message via ``sendRichMessageDraft`` (when rich is enabled and supported) else
|
||||
``sendMessageDraft``; reusing ``draft_id`` animates the preview. The caller sends the final text."""
|
||||
if not self._bot:
|
||||
return SendResult(success=False, error="not_connected")
|
||||
# Rich draft fast-path; any failure degrades to the plain draft below. Drafts have no message_id.
|
||||
if self._should_attempt_rich_draft(content) and await self._try_send_rich_draft(chat_id, draft_id, content, metadata):
|
||||
return SendResult(success=True, message_id=None)
|
||||
if not hasattr(self._bot, "send_message_draft"):
|
||||
return SendResult(success=False, error="api_unavailable")
|
||||
# Drafts share the regular-send UTF-16 length contract.
|
||||
text = content if len(
|
||||
content) <= self.MAX_MESSAGE_LENGTH else self.truncate_message(content, self.MAX_MESSAGE_LENGTH, len_fn=utf16_len)[0]
|
||||
# Same MarkdownV2 conversion as ``send`` (MarkdownV2 then plain) so the draft doesn't snap at the end. Exception: a Rich
|
||||
# final with rich drafts disabled previews raw — the legacy formatter would turn pipe tables into bullets.
|
||||
plain_rich_preview = bool(
|
||||
getattr(self, "_rich_messages_enabled", False) and not getattr(self, "_rich_drafts_enabled", False)
|
||||
and self._needs_rich_rendering(text))
|
||||
draft_thread_kwargs = self._thread_kwargs_for_draft(chat_id, metadata)
|
||||
for use_markdown in ((False,) if plain_rich_preview else (True, False)):
|
||||
kwargs: dict[str, Any] = {
|
||||
"chat_id": normalize_telegram_chat_id(chat_id), "draft_id": int(draft_id),
|
||||
"text": self.format_message(text) if use_markdown else text}
|
||||
if use_markdown:
|
||||
kwargs["parse_mode"] = ParseMode.MARKDOWN_V2
|
||||
kwargs.update(draft_thread_kwargs)
|
||||
try:
|
||||
if await _await_with_thread_deadline(
|
||||
self._bot.send_message_draft(**kwargs), timeout=_TEXT_SEND_DEADLINE, label="telegram-send", dump_on_blocked_loop=False):
|
||||
return SendResult(success=True, message_id=None)
|
||||
return SendResult(success=False, error="draft_rejected")
|
||||
except Exception as e:
|
||||
# MarkdownV2 parse failure → retry once as plain text; anything else returns to the caller,
|
||||
# which falls back to edit-based streaming for this response.
|
||||
if use_markdown and self._is_bad_request_error(e):
|
||||
logger.debug(
|
||||
"[%s] sendMessageDraft MarkdownV2 rejected, retrying as plain text (chat=%s draft_id=%s): %s",
|
||||
self.name, chat_id, draft_id, _redact_telegram_error_text(e))
|
||||
continue
|
||||
logger.debug("[%s] sendMessageDraft failed (chat=%s draft_id=%s): %s", self.name, chat_id, draft_id, e)
|
||||
return SendResult(success=False, error=_redact_telegram_error_text(e))
|
||||
return SendResult(success=False, error="draft_rejected")
|
||||
return await _flood_window.send_draft(self, chat_id, draft_id, content, metadata)
|
||||
|
||||
async def _send_message_with_thread_fallback(self, **kwargs):
|
||||
"""Send a control-style message (approval prompts, pickers, update prompts) that can carry a stale
|
||||
|
||||
134
plugins/platforms/telegram/telegram_flood_window.py
Normal file
134
plugins/platforms/telegram/telegram_flood_window.py
Normal file
@@ -0,0 +1,134 @@
|
||||
"""Streaming drafts and message deletes honour the chat's Telegram flood window (#107612).
|
||||
|
||||
A 429 ``retry_after`` arms the chat's send flood window (``_record_send_flood_cooldown``); sends,
|
||||
edits, typing and native media already stay out of it. Draft frames and ``deleteMessage`` fired
|
||||
straight into it, and Telegram lengthens a penalty that keeps getting hit. Now a draft frame inside
|
||||
the window is skipped (the next frame or the final send supersedes it, so nothing is lost), and a
|
||||
delete waits the window out: inline when it is short, else once from a tracked background task so
|
||||
the caller (the end-of-turn preview cleanup) is not parked for minutes. A 429 on either call arms
|
||||
the window for every other path too.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Any, Awaitable, Callable, Optional
|
||||
|
||||
from gateway.platforms.base import SendResult
|
||||
from plugins.platforms.telegram.telegram_media_flood import _MAX_WINDOW_WAITS, flood_wait_seconds
|
||||
|
||||
logger = logging.getLogger("plugins.platforms.telegram.adapter")
|
||||
|
||||
|
||||
def note_flood(adapter: Any, chat_id: Any, error: Exception) -> bool:
|
||||
"""Arm the chat's flood window when ``error`` is a ``retry_after`` refusal; True if it was."""
|
||||
wait = flood_wait_seconds(error)
|
||||
if wait is None:
|
||||
return False
|
||||
adapter._record_send_flood_cooldown(chat_id, wait)
|
||||
return True
|
||||
|
||||
|
||||
def skipped_draft(adapter: Any, chat_id: Any) -> Optional[SendResult]:
|
||||
"""A skipped-frame result while the chat is inside its flood window, else ``None`` (may fire)."""
|
||||
remaining = adapter._send_flood_cooldown_remaining(chat_id)
|
||||
if remaining is None:
|
||||
return None
|
||||
logger.debug("[%s] skipping draft frame for chat %s: flood window %.1fs left", adapter.name, chat_id, remaining)
|
||||
return SendResult(success=True, message_id=None, raw_response={"skipped": True})
|
||||
|
||||
|
||||
async def _after_window(adapter: Any, chat_id: Any, delete: Callable[[], Awaitable[bool]]) -> bool:
|
||||
for _ in range(_MAX_WINDOW_WAITS + 1):
|
||||
remaining = adapter._send_flood_cooldown_remaining(chat_id)
|
||||
if remaining is None:
|
||||
return await delete()
|
||||
await asyncio.sleep(remaining)
|
||||
logger.warning("[%s] message delete in chat %s dropped: flood window kept re-arming", adapter.name, chat_id)
|
||||
return False
|
||||
|
||||
|
||||
async def delete_outside_flood_window(adapter: Any, chat_id: Any, delete: Callable[[], Awaitable[bool]]) -> bool:
|
||||
"""Run ``delete`` once the chat's flood window is closed. A window longer than the inline cap is
|
||||
waited out by a tracked background task (shutdown cancels it) and the call returns True: the
|
||||
delete is owned by that task, so a caller's retry-on-False must not fire a second one into it."""
|
||||
from plugins.platforms.telegram.adapter import _FLOOD_INLINE_WAIT_CAP_SECS
|
||||
remaining = adapter._send_flood_cooldown_remaining(chat_id)
|
||||
if remaining is None or remaining <= _FLOOD_INLINE_WAIT_CAP_SECS:
|
||||
return await _after_window(adapter, chat_id, delete)
|
||||
logger.info("[%s] deferring message delete in chat %s past its flood window (%.0fs)", adapter.name, chat_id, remaining)
|
||||
task = asyncio.get_running_loop().create_task(_after_window(adapter, chat_id, delete))
|
||||
tracked = getattr(adapter, "_background_tasks", None)
|
||||
if isinstance(tracked, set):
|
||||
tracked.add(task)
|
||||
task.add_done_callback(tracked.discard)
|
||||
return True
|
||||
|
||||
|
||||
async def delete_message(adapter: Any, chat_id: str, message_id: str) -> bool:
|
||||
"""``TelegramAdapter.delete_message`` body: ``deleteMessage`` once the chat's flood window is closed."""
|
||||
from plugins.platforms.telegram.adapter import _redact_telegram_error_text, normalize_telegram_chat_id
|
||||
if not adapter._bot:
|
||||
return False
|
||||
|
||||
async def _delete() -> bool:
|
||||
try:
|
||||
await adapter._bot.delete_message(chat_id=normalize_telegram_chat_id(chat_id), message_id=int(message_id))
|
||||
return True
|
||||
except Exception as e: # health: allow BLE001 -- best-effort delete (moved from adapter.py): every failure is a logged False
|
||||
note_flood(adapter, chat_id, e)
|
||||
logger.debug("[%s] Failed to delete Telegram message %s: %s", adapter.name, message_id, _redact_telegram_error_text(e))
|
||||
return False
|
||||
return await delete_outside_flood_window(adapter, chat_id, _delete)
|
||||
|
||||
|
||||
async def send_draft(adapter: Any, chat_id: str, draft_id: int, content: str, metadata: Optional[dict[str, Any]]) -> SendResult:
|
||||
"""``TelegramAdapter.send_draft`` body: rich draft, else MarkdownV2 then plain ``sendMessageDraft``."""
|
||||
from plugins.platforms.telegram.adapter import (
|
||||
_TEXT_SEND_DEADLINE, ParseMode, _await_with_thread_deadline, _redact_telegram_error_text, normalize_telegram_chat_id,
|
||||
utf16_len)
|
||||
if not adapter._bot:
|
||||
return SendResult(success=False, error="not_connected")
|
||||
# A frame inside the chat's flood window is skipped (#107612): the next frame or the final send supersedes it.
|
||||
if (skipped := skipped_draft(adapter, chat_id)) is not None:
|
||||
return skipped
|
||||
# Rich draft fast-path; any failure degrades to the plain draft below. Drafts have no message_id.
|
||||
if adapter._should_attempt_rich_draft(content) and await adapter._try_send_rich_draft(chat_id, draft_id, content, metadata):
|
||||
return SendResult(success=True, message_id=None)
|
||||
if (skipped := skipped_draft(adapter, chat_id)) is not None: # the rich frame was refused with retry_after
|
||||
return skipped
|
||||
if not hasattr(adapter._bot, "send_message_draft"):
|
||||
return SendResult(success=False, error="api_unavailable")
|
||||
# Drafts share the regular-send UTF-16 length contract.
|
||||
text = content if len(
|
||||
content) <= adapter.MAX_MESSAGE_LENGTH else adapter.truncate_message(content, adapter.MAX_MESSAGE_LENGTH, len_fn=utf16_len)[0]
|
||||
# Same MarkdownV2 conversion as ``send`` (MarkdownV2 then plain) so the draft doesn't snap at the end. Exception: a Rich
|
||||
# final with rich drafts disabled previews raw — the legacy formatter would turn pipe tables into bullets.
|
||||
plain_rich_preview = bool(
|
||||
getattr(adapter, "_rich_messages_enabled", False) and not getattr(adapter, "_rich_drafts_enabled", False)
|
||||
and adapter._needs_rich_rendering(text))
|
||||
draft_thread_kwargs = adapter._thread_kwargs_for_draft(chat_id, metadata)
|
||||
for use_markdown in ((False,) if plain_rich_preview else (True, False)):
|
||||
kwargs: dict[str, Any] = {
|
||||
"chat_id": normalize_telegram_chat_id(chat_id), "draft_id": int(draft_id),
|
||||
"text": adapter.format_message(text) if use_markdown else text}
|
||||
if use_markdown:
|
||||
kwargs["parse_mode"] = ParseMode.MARKDOWN_V2
|
||||
kwargs.update(draft_thread_kwargs)
|
||||
try:
|
||||
if await _await_with_thread_deadline(
|
||||
adapter._bot.send_message_draft(**kwargs), timeout=_TEXT_SEND_DEADLINE, label="telegram-send", dump_on_blocked_loop=False):
|
||||
return SendResult(success=True, message_id=None)
|
||||
return SendResult(success=False, error="draft_rejected")
|
||||
except Exception as e: # health: allow BLE001 -- draft boundary (moved from adapter.py): any failure falls back to edit streaming
|
||||
# MarkdownV2 parse failure → retry once as plain text; anything else returns to the caller,
|
||||
# which falls back to edit-based streaming for this response.
|
||||
if use_markdown and adapter._is_bad_request_error(e):
|
||||
logger.debug(
|
||||
"[%s] sendMessageDraft MarkdownV2 rejected, retrying as plain text (chat=%s draft_id=%s): %s",
|
||||
adapter.name, chat_id, draft_id, _redact_telegram_error_text(e))
|
||||
continue
|
||||
logger.debug("[%s] sendMessageDraft failed (chat=%s draft_id=%s): %s", adapter.name, chat_id, draft_id, e)
|
||||
if note_flood(adapter, chat_id, e): # keep the draft transport; frames skip the window
|
||||
return skipped_draft(adapter, chat_id)
|
||||
return SendResult(success=False, error=_redact_telegram_error_text(e))
|
||||
return SendResult(success=False, error="draft_rejected")
|
||||
75
tests/gateway/test_telegram_draft_delete_flood_window.py
Normal file
75
tests/gateway/test_telegram_draft_delete_flood_window.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""Draft frames and message deletes stay out of a chat's Telegram flood window.
|
||||
|
||||
A 429 ``retry_after`` arms the chat's send flood window; ``send_draft`` and ``delete_message``
|
||||
must not fire Bot API calls into it (Telegram lengthens a penalty that keeps getting hit), and a
|
||||
429 on either arms the window for the other paths. SDK-free: the refusal is any exception that
|
||||
carries ``retry_after``, as PTB's ``RetryAfter`` does.
|
||||
"""
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from gateway.config import PlatformConfig
|
||||
from plugins.platforms.telegram.adapter import TelegramAdapter
|
||||
|
||||
|
||||
class _Flood(Exception):
|
||||
def __init__(self, seconds: float) -> None:
|
||||
super().__init__(f"Flood control exceeded. Retry in {seconds} seconds")
|
||||
self.retry_after = seconds
|
||||
|
||||
|
||||
def _adapter() -> TelegramAdapter:
|
||||
adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
|
||||
adapter._bot = MagicMock()
|
||||
adapter._bot.send_message_draft = AsyncMock(return_value=True)
|
||||
adapter._bot.delete_message = AsyncMock(return_value=True)
|
||||
return adapter
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_draft_frames_skip_the_flood_window_a_refused_draft_armed():
|
||||
adapter = _adapter()
|
||||
adapter._bot.send_message_draft = AsyncMock(side_effect=[_Flood(30), True])
|
||||
|
||||
refused = await adapter.send_draft("4242", 7, "frame 1")
|
||||
later = [await adapter.send_draft("4242", 7, f"frame {i}") for i in (2, 3)]
|
||||
|
||||
# The refusal keeps the draft transport (a skipped frame, not a failure) and fires nothing more.
|
||||
assert refused.success and refused.raw_response == {"skipped": True}
|
||||
assert all(r.success and r.raw_response == {"skipped": True} for r in later)
|
||||
assert adapter._bot.send_message_draft.await_count == 1
|
||||
# The window is the chat's: a send refuses locally too, and another chat still drafts.
|
||||
assert (await adapter.send("4242", "hello")).error.startswith("flood_control:")
|
||||
assert (await adapter.send_draft("777", 1, "other chat")).raw_response is None
|
||||
assert adapter._bot.send_message_draft.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_waits_out_the_flood_window_then_deletes():
|
||||
adapter = _adapter()
|
||||
adapter._record_send_flood_cooldown("4242", 1.0) # a refused send armed a short window
|
||||
|
||||
task = asyncio.create_task(adapter.delete_message("4242", "55"))
|
||||
for _ in range(5):
|
||||
await asyncio.sleep(0) # let the delete reach its wait
|
||||
assert adapter._bot.delete_message.await_count == 0 # nothing fired into the window
|
||||
assert await task is True
|
||||
adapter._bot.delete_message.assert_awaited_once_with(chat_id=4242, message_id=55)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_long_flood_window_defers_the_delete_and_a_refused_delete_arms_it():
|
||||
adapter = _adapter()
|
||||
adapter._bot.delete_message = AsyncMock(side_effect=_Flood(60))
|
||||
assert await adapter.delete_message("4242", "55") is False # the 429 itself
|
||||
assert adapter._send_flood_cooldown_remaining("4242") is not None
|
||||
|
||||
adapter._bot.delete_message = AsyncMock(return_value=True)
|
||||
# Past the inline cap the delete is owned by a tracked background task: the caller is not parked.
|
||||
assert await asyncio.wait_for(adapter.delete_message("4242", "56"), 0.5) is True
|
||||
assert adapter._bot.delete_message.await_count == 0
|
||||
pending = [t for t in adapter._background_tasks if not t.done()]
|
||||
assert len(pending) == 1
|
||||
await adapter.cancel_background_tasks()
|
||||
Reference in New Issue
Block a user