Skip to content

The agent that grows with you

fix(telegram): keep same-chat updates in order under concurrent dispatch

kshitijk4poora6d7e08fd171
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index e4c6f40f9ad..9bfa5b5af5d 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -473,8 +473,9 @@ _POLLING_STALL_TIMEOUT = 150.0
# Ingress dispatch stall (#102260, #130407): the transport probes prove getUpdates round-trips complete, not
# that PTB's dispatcher ever handed the fetched updates to a handler. A backlog with no dispatch progress for
# four heartbeats (360s) hands the adapter to the supervisor for a rebuild (an in-place restart keeps the
-# wedged dispatcher). Sized past _POLLING_ERROR_TASK_STUCK_TIMEOUT (300s), the bound on a slow handler: PTB
-# dispatches sequentially, so e.g. a sticker vision_analyze (120s default) must not trip it. Re-arms on progress.
+# wedged dispatcher). Sized past _POLLING_ERROR_TASK_STUCK_TIMEOUT (300s), the bound on a slow handler: updates
+# of one chat still dispatch in order (PerChatUpdateProcessor), so e.g. a sticker vision_analyze (120s default)
+# must not trip it. Re-arms on progress.
_INGRESS_DISPATCH_STALL_HEARTBEATS = 4
# sendVideo transcodes before answering, outlasting the 20s read timeout; also how long a user waits
# to hear the attachment failed, so kept modest.
@@ -3275,7 +3276,7 @@ class TelegramAdapter(BasePlatformAdapter):
try:
if not self._acquire_platform_lock('telegram-bot-token', self.config.token, 'Telegram bot token'):
return False
- from plugins.platforms.telegram.update_admission import TelegramApplication
+ from plugins.platforms.telegram.update_admission import TelegramApplication, build_update_processor
builder = Application.builder().token(self.config.token)
builder.application_class(TelegramApplication, {"adapter": self})
custom_base_url = self.config.extra.get("base_url")
@@ -3290,18 +3291,10 @@ class TelegramAdapter(BasePlatformAdapter):
logger.info("[%s] Using Telegram local_mode (read files from disk)", self.name)
request, get_updates_request = await self._build_ptb_requests()
builder = builder.request(request).get_updates_request(get_updates_request)
- # PTB defaults to SimpleUpdateProcessor(max_concurrent_updates=1): the update fetcher
- # awaits each update's full handler chain inline, so one slow turn (long provider retry,
- # compaction loop) deafens every other chat and even local commands until it finishes.
- # Default to a bounded parallel pool (True→PTB's 256); opt down/up via config extra.
- concurrent = 32
- raw = (self.config.extra or {}).get("max_concurrent_updates")
- if raw is not None:
- try:
- concurrent = max(1, int(raw))
- except (TypeError, ValueError):
- concurrent = 32
- builder = builder.concurrent_updates(concurrent)
+ # PTB's default processor awaits each update inline, so one slow turn deafens every chat.
+ # Concurrent across chats, FIFO within a chat; the builder keeps this instance, so the
+ # connect-retry rebuild in _initialize_app_with_retries gets it too.
+ builder = builder.concurrent_updates(build_update_processor(self.config.extra, self.name))
self._app = builder.build()
self._bot = self._app.bot
# Plugin PTB handlers go BEFORE core: PTB dispatches the first matching handler per group.
diff --git a/plugins/platforms/telegram/update_admission.py b/plugins/platforms/telegram/update_admission.py
index 7ffb73ce0b4..55f1a5d4419 100644
--- a/plugins/platforms/telegram/update_admission.py
+++ b/plugins/platforms/telegram/update_admission.py
@@ -17,7 +17,7 @@ from dataclasses import dataclass
from functools import wraps
from telegram import Update
-from telegram.ext import Application, ApplicationHandlerStop, ConversationHandler
+from telegram.ext import Application, ApplicationHandlerStop, BaseUpdateProcessor, ConversationHandler
from gateway.platforms.helpers import bounded_put
from utils import atomic_json_write
@@ -25,6 +25,7 @@ from utils import atomic_json_write
logger = logging.getLogger(__name__)
_DEFAULT_BLOCK = object()
+DEFAULT_MAX_CONCURRENT_UPDATES = 32
_SEEN_CAP = 4096
# The Bot API keeps an unconfirmed update for at most 24 hours (getUpdates), so an older
# receipt can never match a redelivery. That is also well inside the week of silence after
@@ -124,6 +125,59 @@ class _ErrorCallback:
return await self.__wrapped__(update, context)
+class PerChatUpdateProcessor(BaseUpdateProcessor):
+ """Concurrent across chats, FIFO within one chat.
+
+ PTB's default processor (max_concurrent_updates=1) awaits every update inline, so one slow
+ handler deafens all chats; plain concurrency fixes that but lets a chat's second update finish
+ before its first. Each update here waits for the previous update of the same chat; updates
+ without a chat (inline queries) run unchained.
+ """
+
+ __slots__ = ("_tails",)
+
+ def __init__(self, max_concurrent_updates: int):
+ super().__init__(max_concurrent_updates)
+ self._tails: dict[int, asyncio.Future] = {}
+
+ async def do_process_update(self, update, coroutine) -> None:
+ chat = getattr(update, "effective_chat", None)
+ if chat is None:
+ await coroutine
+ return
+ prev = self._tails.get(chat.id)
+ done = asyncio.get_running_loop().create_future()
+ self._tails[chat.id] = done
+ try:
+ if prev is not None:
+ await prev
+ await coroutine
+ finally:
+ done.set_result(None)
+ if self._tails.get(chat.id) is done:
+ del self._tails[chat.id]
+
+ async def initialize(self) -> None:
+ pass
+
+ async def shutdown(self) -> None:
+ pass
+
+
+def build_update_processor(extra, name: str) -> PerChatUpdateProcessor:
+ """``platforms.telegram.extra.max_concurrent_updates`` (default 32); bad values warn and fall back."""
+ raw = (extra or {}).get("max_concurrent_updates", DEFAULT_MAX_CONCURRENT_UPDATES)
+ try:
+ limit = int(raw)
+ except (TypeError, ValueError):
+ limit = 0
+ if limit < 1:
+ logger.warning("[%s] Invalid max_concurrent_updates=%r; using %d",
+ name, raw, DEFAULT_MAX_CONCURRENT_UPDATES)
+ limit = DEFAULT_MAX_CONCURRENT_UPDATES
+ return PerChatUpdateProcessor(limit)
+
+
class TelegramApplication(Application):
__slots__ = ("adapter", "_current_claim")
diff --git a/tests/plugins/test_telegram_update_admission.py b/tests/plugins/test_telegram_update_admission.py
index c7a00b67f30..b78ab28e778 100644
--- a/tests/plugins/test_telegram_update_admission.py
+++ b/tests/plugins/test_telegram_update_admission.py
@@ -806,6 +806,9 @@ async def test_connect_builds_concurrent_update_processor(monkeypatch):
async with connected(monkeypatch, extra={"max_concurrent_updates": 7}) as (adapter, app, delivered):
assert app.concurrent_updates == 7
+ async with connected(monkeypatch, extra={"max_concurrent_updates": "lots"}) as (adapter, app, delivered):
+ assert app.concurrent_updates == 32
+
@pytest.mark.asyncio
async def test_slow_update_does_not_block_other_chats(monkeypatch):
@@ -813,12 +816,13 @@ async def test_slow_update_does_not_block_other_chats(monkeypatch):
while one chat's update is parked inside its handler chain, a different chat's
update must still be dequeued, dispatched and delivered (#125098). Under the PTB
default (max_concurrent_updates=1) the fetcher awaits each update inline, so the
- second update is never dequeued while the first is parked."""
+ second update is never dequeued while the first is parked. A later update of the
+ PARKED chat must wait for it: plain concurrency would deliver it first."""
gate = asyncio.Event()
async with connected(monkeypatch) as (adapter, app, delivered):
async def gate_keeper(update, context):
- if update.effective_chat and update.effective_chat.id == 42:
+ if update.update_id == 10:
await gate.wait()
# Group -1 runs before every core handler group inside PTB's real dispatch.
@@ -832,6 +836,7 @@ async def test_slow_update_does_not_block_other_chats(monkeypatch):
assert adapter._inflight_update_ids, "update 10 never started processing"
app.update_queue.put_nowait(update(app.bot, uid=11, chat=43))
+ app.update_queue.put_nowait(update(app.bot, uid=12, chat=42, text="second"))
dequeued = False
for _ in range(500):
if app.update_queue.qsize() == 0:
@@ -849,8 +854,11 @@ async def test_slow_update_does_not_block_other_chats(monkeypatch):
await asyncio.gather(*adapter._pending_text_batch_tasks.values())
assert [e.source.chat_id for e in delivered] == ["43"]
gate.set()
- for _ in range(500): # released u10 finishes its chain and delivers too
- if len(delivered) >= 2:
+ for _ in range(500): # released u10 finishes its chain, then u12 follows it
+ if any("second" in e.text for e in delivered):
break
await asyncio.sleep(0.02)
- assert [e.source.chat_id for e in delivered] == ["43", "42"]
+ await asyncio.gather(*adapter._pending_text_batch_tasks.values())
+ assert [e.source.chat_id for e in delivered][0] == "43"
+ same_chat = "\n".join(e.text for e in delivered if e.source.chat_id == "42")
+ assert same_chat == "hello\nsecond"