Skip to content

The agent that grows with you

fix(telegram): admit replayed updates before PTB dispatch

Austin Pickett992f569fc1a3
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 6f627f130e4..9c2ba012db6 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -541,6 +541,9 @@ class TelegramAdapter(BasePlatformAdapter):
super().__init__(config, Platform.TELEGRAM)
extra = self.config.extra
self._app: Optional[Application] = None
+ self._seen_update_ids: dict = {}
+ self._inflight_update_ids: dict = {}
+ self._update_admission = None
self._bot: Optional[Bot] = None
self._webhook_mode: bool = False
self._mention_patterns = self._compile_mention_patterns()
@@ -602,7 +605,7 @@ class TelegramAdapter(BasePlatformAdapter):
# began, and when the last successful getUpdates round-trip completed.
self._polling_generation_started_monotonic: Optional[float] = None
self._polling_last_progress_monotonic: Optional[float] = None
- # Ingress accounting (#102260): received (getUpdates wire) vs dispatched (PTB group-99 catch-all).
+ # Ingress accounting (#102260): received (getUpdates wire) vs dispatched (PTB admission).
self._updates_received_total: int = 0
self._updates_dispatched_total: int = 0
self._ingress_dispatched_seen: int = 0
@@ -778,6 +781,7 @@ class TelegramAdapter(BasePlatformAdapter):
logger.warning(
"[Telegram] Held-inbound queue full (%d); dropping oldest (%d chars)", max_n, len(getattr(dropped, "text", None) or ""))
held.append(event)
+ self._accept_update()
logger.warning(
"[Telegram] Holding inbound (%s, %d chars, queue=%d)%s", where, len(getattr(event, "text", None) or ""), len(held),
" - will redispatch on reconnect" if self._should_drop_delayed_delivery() else (" - scheduling redispatch" if schedule else ""))
@@ -2771,9 +2775,11 @@ class TelegramAdapter(BasePlatformAdapter):
async def _on_platform_update(self, update, context) -> None:
"""Catch-all PTB handler (group 99) firing ``gateway_platform_event`` per inbound update with a
stable envelope (no raw SDK objects) and an internal auth source. Never raises into PTB."""
- # Last handler group PTB runs: stamp before any early return so the dispatch counter covers
- # gateways without the plugin hook (#102260).
- self._updates_dispatched_total = getattr(self, "_updates_dispatched_total", 0) + 1
+ # Admission counts dispatch before any preparation can stop this group. Retain
+ # accounting for callers outside that Application boundary (#102260).
+ admission = getattr(self, "_update_admission", None)
+ if admission is None or admission.get() is None:
+ self._updates_dispatched_total = getattr(self, "_updates_dispatched_total", 0) + 1
handler: Optional[Callable[[Dict[str, Any], Any], Awaitable[None]]] = getattr(self, "_platform_event_handler", None)
if handler is None:
return
@@ -2783,6 +2789,7 @@ class TelegramAdapter(BasePlatformAdapter):
return
event = self._normalize_platform_event(update)
except Exception:
+ self._fail_update_preparation()
logger.debug("[%s] gateway_platform_event normalize error", self.name, exc_info=True)
return
if event is None:
@@ -2790,8 +2797,10 @@ class TelegramAdapter(BasePlatformAdapter):
# The gateway-owned boundary runs the full profile-scoped auth chain before plugin dispatch.
try:
source = self._source_for_platform_event_auth(update)
+ self._accept_update()
await handler(event, source)
except Exception:
+ self._fail_update_preparation()
logger.debug("[%s] gateway_platform_event dispatch error", self.name, exc_info=True)
def _source_for_platform_event_auth(self, update):
@@ -2885,6 +2894,24 @@ class TelegramAdapter(BasePlatformAdapter):
"text": text[:8192] if text is not None else None, "edited_at": edited_at},
}
+ def _accept_update(self) -> None:
+ """Handoff is irreversible for replay purposes, even if later work raises/cancels."""
+ admission = getattr(self, "_update_admission", None)
+ claim = admission.get() if admission is not None else None
+ if claim is not None:
+ claim.accepted = True
+
+ def _fail_update_preparation(self) -> None:
+ """A caught preparation error is not a successful no-op or an auth refusal."""
+ admission = getattr(self, "_update_admission", None)
+ claim = admission.get() if admission is not None else None
+ if claim is not None:
+ claim.failed = True
+
+ async def handle_message(self, event: MessageEvent) -> None:
+ self._accept_update()
+ await super().handle_message(event)
+
def _register_handlers(self, app) -> None:
"""Register every PTB handler on ``app`` (initial connect and the transient-init rebuild)."""
app.add_handler(TelegramMessageHandler(filters.TEXT & ~filters.COMMAND, self._handle_text_message))
@@ -3149,7 +3176,9 @@ 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
builder = Application.builder().token(self.config.token)
+ builder.application_class(TelegramApplication, {"adapter": self})
custom_base_url = self.config.extra.get("base_url")
if custom_base_url:
builder = builder.base_url(custom_base_url)
@@ -4573,8 +4602,10 @@ class TelegramAdapter(BasePlatformAdapter):
if not authorized:
try:
from plugins.platforms.telegram.inline_picker import CACHE_TIME_SECONDS as _deny_cache
+ self._accept_update()
await inline_query.answer([], cache_time=_deny_cache, is_personal=True)
except Exception:
+ self._fail_update_preparation()
logger.debug("[%s] inline picker empty answer failed", self.name, exc_info=True)
return
try:
@@ -4591,8 +4622,10 @@ class TelegramAdapter(BasePlatformAdapter):
for r in results
]
# is_personal: catalogs differ per user (auth, disabled skills) — never share cached pages.
+ self._accept_update()
await inline_query.answer(articles, cache_time=_CACHE, is_personal=True, next_offset=next_offset)
except Exception:
+ self._fail_update_preparation()
logger.debug("[%s] inline picker answer failed", self.name, exc_info=True)
@staticmethod
@@ -4619,6 +4652,7 @@ class TelegramAdapter(BasePlatformAdapter):
query = update.callback_query
if not query or not query.data:
return
+ self._accept_update()
data = query.data
cb = self._callback_ctx(query)
# Model picker / generic choice picker (/reasoning, /fast) need a chat id.
@@ -6210,6 +6244,7 @@ class TelegramAdapter(BasePlatformAdapter):
f"\u26a0\ufe0f Couldn't download your {kind}{named} ({exc.__class__.__name__}). Please try sending it again.")
if notice:
try:
+ self._accept_update()
await msg.reply_text(notice)
except Exception as reply_err:
logger.warning("[Telegram] Failed to notify user about %s cache failure: %s", kind, reply_err, exc_info=True)
@@ -6235,11 +6270,13 @@ class TelegramAdapter(BasePlatformAdapter):
"timestamp": datetime.now(tz=timezone.utc).isoformat(), "observed": True}
if event.message_id:
entry["message_id"] = str(event.message_id)
+ self._accept_update()
store.append_to_transcript(session_entry.session_id, entry)
logger.info(
"[%s] Telegram group message observed (no bot trigger): chat=%s from=%s", adapter_name,
getattr(getattr(message, "chat", None), "id", "unknown"), event.source.user_id or "unknown")
except Exception as exc:
+ self._fail_update_preparation()
logger.warning("[%s] Failed to observe Telegram group message: %s", adapter_name, exc)
def _is_own_message(self, message: Message) -> bool:
@@ -6429,6 +6466,7 @@ class TelegramAdapter(BasePlatformAdapter):
self._hold_inbound_event(event, where="text-enqueue")
return
super()._enqueue_text_event(event)
+ self._accept_update()
async def _flush_buffered(self, pending: dict, tasks: dict, key: str, delay: float, where: str, log_fn=None) -> None:
"""Shared delayed-flush body: sleep, pop, hold if teardown started, else dispatch. A cancel after
@@ -6514,6 +6552,7 @@ class TelegramAdapter(BasePlatformAdapter):
self._hold_inbound_event(event, where="photo-enqueue")
return
self._merge_into_pending(self._pending_photo_batches, batch_key, event)
+ self._accept_update()
prior_task = self._pending_photo_batch_tasks.get(batch_key)
if prior_task and not prior_task.done():
prior_task.cancel()
@@ -6726,6 +6765,7 @@ class TelegramAdapter(BasePlatformAdapter):
self._hold_inbound_event(event, where="media-group-enqueue")
return
self._merge_into_pending(self._media_group_events, media_group_id, event)
+ self._accept_update()
prior_task = self._media_group_tasks.get(media_group_id)
if prior_task:
prior_task.cancel()
@@ -6758,6 +6798,7 @@ class TelegramAdapter(BasePlatformAdapter):
cached_path = await cache_image_from_bytes_async(bytes(image_bytes), ext=".webp")
logger.info("[Telegram] Analyzing sticker at %s", cached_path)
from tools.vision_tools import vision_analyze_tool
+ self._accept_update() # Cancellation cannot undo an already submitted auxiliary LLM request.
result = json.loads(await vision_analyze_tool(image_url=cached_path, user_prompt=STICKER_VISION_PROMPT))
if result.get("success"):
description = result.get("analysis", "a sticker")
diff --git a/plugins/platforms/telegram/update_admission.py b/plugins/platforms/telegram/update_admission.py
new file mode 100644
index 00000000000..0ae321a444a
--- /dev/null
+++ b/plugins/platforms/telegram/update_admission.py
@@ -0,0 +1,175 @@
+"""Telegram admission before every PTB handler group, including native plugins.
+
+Claims belong to the receiving adapter across Application rebuilds. Completed
+history is bounded and has no TTL; dispatch and its PTB tasks pin active claims.
+No disk receipt, cross-process coordination or exactly-once effects are promised.
+"""
+
+import asyncio
+from contextvars import ContextVar
+from dataclasses import dataclass
+from functools import wraps
+
+from telegram import Update
+from telegram.ext import Application, ApplicationHandlerStop, ConversationHandler
+
+from gateway.platforms.helpers import bounded_put
+
+
+_DEFAULT_BLOCK = object()
+
+
+@dataclass
+class _Claim:
+ key: str
+ dispatch_task: asyncio.Task | None
+ accepted: bool = False
+ completed: bool = False
+ failed: bool = False
+ owners: int = 1
+
+
+class _ErrorCallback:
+ """Admit callback entry while keeping PTB's original registration/removal key."""
+
+ def __init__(self, callback):
+ self.__wrapped__ = callback
+
+ def __hash__(self):
+ return hash(self.__wrapped__)
+
+ def __eq__(self, other):
+ if isinstance(other, _ErrorCallback):
+ other = other.__wrapped__
+ return self.__wrapped__ == other
+
+ async def __call__(self, update, context):
+ # Registration is a native extension boundary, unlike PTB's internal logger.
+ # Resolve the receiving app so a shared callback never accepts another bot's claim.
+ admission = getattr(context.application, "_current_claim", None)
+ claim = admission.get() if admission is not None else None
+ if claim is not None and claim.owners:
+ claim.accepted = True
+ return await self.__wrapped__(update, context)
+
+
+class TelegramApplication(Application):
+ __slots__ = ("adapter", "_current_claim")
+
+ def __init__(self, *, adapter, **kwargs):
+ super().__init__(**kwargs)
+ self.adapter = adapter
+ if adapter._update_admission is None:
+ adapter._update_admission = ContextVar[_Claim | None]("telegram_update_claim", default=None)
+ self._current_claim: ContextVar[_Claim | None] = adapter._update_admission
+
+ def add_handler(self, handler, group=0):
+ super().add_handler(handler, group)
+ self._admit_callbacks(handler)
+
+ def _admit_callbacks(self, handler):
+ # ConversationHandler has no callback. Keep its identity (including persistence,
+ # state transitions and block resolution) and instrument its selected children.
+ if isinstance(handler, ConversationHandler):
+ for child in [*handler.entry_points, *handler.fallbacks,
+ *(child for handlers in handler.states.values() for child in handlers)]:
+ self._admit_callbacks(child)
+ return
+ callback = getattr(handler, "callback", None)
+ if callback is None or getattr(callback, "_telegram_admitted", False):
+ return
+
+ @wraps(callback)
+ async def admitted_callback(update, context):
+ # Native plugins own arbitrary effects. Entry is the handoff; retrying a partly
+ # completed plugin would be unsafe. Core preparation has explicit handoff markers.
+ # A plugin may reuse the same handler across applications/reconnects. Resolve
+ # the receiving claim at invocation, rather than closing over its first owner.
+ application = context.application
+ admission = getattr(application, "_current_claim", None)
+ claim = admission.get() if admission is not None else None
+ if claim is not None and getattr(callback, "__self__", None) is not application.adapter:
+ claim.accepted = True
+ result = await callback(update, context)
+ if claim is not None:
+ if claim.failed and not claim.accepted:
+ # Stop subsequent groups only in blocking dispatch. PTB cannot stop
+ # groups already scheduled via block=False; their outcomes settle below.
+ if asyncio.current_task() is claim.dispatch_task:
+ raise ApplicationHandlerStop
+ else:
+ claim.completed = True
+ return result
+
+ admitted_callback._telegram_admitted = True
+ handler.callback = admitted_callback
+
+ def add_error_handler(self, callback, block=_DEFAULT_BLOCK):
+ if not isinstance(callback, _ErrorCallback):
+ callback = _ErrorCallback(callback)
+ # Omitted block must remain PTB's default, not explicit True (bot defaults differ).
+ if block is _DEFAULT_BLOCK:
+ super().add_error_handler(callback)
+ else:
+ super().add_error_handler(callback, block=block)
+
+ def _Application__create_task(self, coroutine, update=None, is_error_handler=False, name=None):
+ # PTB's process_error bypasses public create_task. Delegate at the shared task seam
+ # without copying dispatch or losing its is_error_handler recursion protection.
+ task = super()._Application__create_task(
+ coroutine, update=update, is_error_handler=is_error_handler, name=name)
+ claim = self._current_claim.get()
+ if claim is not None and claim.owners:
+ # Pin scheduled work before callback entry, including cancellation before entry.
+ claim.owners += 1
+
+ def finished(done):
+ # PTB's task wrapper may never start, leaving its callback unawaited.
+ if done.cancelled() and asyncio.iscoroutine(coroutine):
+ coroutine.close()
+ self._release_claim(claim, done)
+
+ task.add_done_callback(finished)
+ return task
+
+ def _release_claim(self, claim, task=None):
+ if task is not None and task.cancelled():
+ claim.failed = True
+ claim.owners -= 1
+ if claim.owners:
+ return
+ del self.adapter._inflight_update_ids[claim.key]
+ if claim.accepted or (claim.completed and not claim.failed):
+ bounded_put(self.adapter._seen_update_ids, claim.key, None, 4096)
+
+ async def process_error(self, update, error, job=None, coroutine=None):
+ claim = self._current_claim.get()
+ if claim is not None:
+ claim.failed = True
+ stopped = await super().process_error(update, error, job, coroutine)
+ # PTB catches callback errors. Do not let a later observer accept a failed preparation.
+ return stopped or (claim is not None and not claim.accepted)
+
+ async def process_update(self, update):
+ if not isinstance(update, Update):
+ return await super().process_update(update)
+ key = f"{self.bot.id}:{update.update_id}"
+ # Dispatch happened even when preparation fails before the group-99 observer.
+ self.adapter._updates_dispatched_total += 1
+ seen = self.adapter._seen_update_ids
+ pending = self.adapter._inflight_update_ids
+ if key in seen or key in pending:
+ return
+ claim = _Claim(key, asyncio.current_task())
+ # Atomic on PTB's event loop: no await between lookup and claim. Dispatch and its
+ # PTB tasks share ownership; completed-history pressure cannot evict active work.
+ pending[key] = claim
+ token = self._current_claim.set(claim)
+ try:
+ await super().process_update(update)
+ except BaseException:
+ claim.failed = True
+ raise
+ finally:
+ self._current_claim.reset(token)
+ self._release_claim(claim)