The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): time the new-topic follow on send time, not handler time (#136567)
Teknium406580697a9d
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex a3a02b85c63..51c90a138d7 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -685,9 +685,9 @@ class TelegramAdapter(TelegramHeldInboundMixin, TelegramTopicRoutingMixin, BasePself._send_path_degraded: bool = Falseself._general_request_drain_lock = asyncio.Lock()self._dm_topics: dict[str, int] = {} # topic_name -> message_thread_id- # (chat_id, sender_id) -> (new topic id, monotonic stamp) for client-created DM topics whose- # thread-less opener may still arrive (#136567); see TelegramTopicRoutingMixin.- self._pending_created_topics: dict[tuple[str, str], tuple[str, float]] = {}+ # (chat_id, sender_id) -> (new topic id, last Message.date, monotonic record time) for client-created+ # DM topics whose thread-less opener may still arrive (#136567); see TelegramTopicRoutingMixin.+ self._pending_created_topics: dict[tuple[str, str], tuple[str, float, float]] = {}self._forum_command_registered: set[int] = set() # forum chats with commands registeredself._command_menu_fingerprint: str = "" # language + menu payload last pushed via set_my_commandsself._forum_lock = asyncio.Lock()diff --git a/plugins/platforms/telegram/telegram_topic_routing.py b/plugins/platforms/telegram/telegram_topic_routing.pyindex d444e9779d8..11caa16c7fb 100644--- a/plugins/platforms/telegram/telegram_topic_routing.py+++ b/plugins/platforms/telegram/telegram_topic_routing.py@@ -23,16 +23,25 @@ logger = logging.getLogger("plugins.platforms.telegram.adapter")class TelegramTopicRoutingMixin:"""Topic-creation bookkeeping for ``TelegramAdapter`` (relies on its ``_chat_type_str``/``_chat_id_str``)."""- # A thread-less message from the creator adopts the new topic while it arrives within this many+ # A thread-less message from the creator adopts the new topic while it was SENT within this many# seconds of the creation or of the previous adopted message (the client sends the opener# ~0.2-1 s after the creation; a split long text or an album follows within the same second).+ # Measured on Telegram's ``Message.date`` stamps, never on handler time: per-chat FIFO holds a+ # follow-up behind the previous handler (a photo download, STT), and it must not age out there._NEW_TOPIC_FOLLOW_SECONDS = 5.0_NEW_TOPIC_OPENER_MAX_PENDING = 256+ # Memory bound only (local clock), far above any handler backlog; adoption never reads it.+ _NEW_TOPIC_RECORD_TTL_SECONDS = 600.0@staticmethoddef _creator_key(message) -> str:return str(getattr(getattr(message, "from_user", None), "id", ""))+ @staticmethod+ def _sent_at(message) -> Optional[float]:+ date = getattr(message, "date", None)+ return date.timestamp() if hasattr(date, "timestamp") else None+async def _handle_forum_topic_created(self, update: Any, context: Any) -> None:"""Record an authorized, non-bot private-chat topic creation (#136567).@@ -47,24 +56,25 @@ class TelegramTopicRoutingMixin:returnthread_id = getattr(message, "message_thread_id", None)sender = getattr(message, "from_user", None)- if thread_id is None or sender is None or getattr(sender, "is_bot", False) is True:+ sent_at = self._sent_at(message)+ if thread_id is None or sent_at is None or sender is None or getattr(sender, "is_bot", False) is True:returnif not self._is_user_authorized_from_message(message):returnpending = self.__dict__.setdefault("_pending_created_topics", {})now = time.monotonic()- for key in [k for k, (_t, stamp) in pending.items() if now - stamp > self._NEW_TOPIC_FOLLOW_SECONDS]:+ for key in [k for k, rec in pending.items() if now - rec[2] > self._NEW_TOPIC_RECORD_TTL_SECONDS]:del pending[key]while len(pending) >= self._NEW_TOPIC_OPENER_MAX_PENDING:- del pending[min(pending, key=lambda k: pending[k][1])]+ del pending[min(pending, key=lambda k: pending[k][2])]chat_id = self._chat_id_str(message)- pending[(chat_id, self._creator_key(message))] = (str(thread_id), now)+ pending[(chat_id, self._creator_key(message))] = (str(thread_id), sent_at, now)logger.debug("[%s] Recorded new Telegram topic %s (chat=%s)", self.name, thread_id, chat_id)def _adopt_created_topic_thread(self, message: Any, chat_type: str, thread_id: Optional[str]) -> Optional[str]:"""Thread id of the topic this sender just created, for its thread-less follow-up messages.- A threaded message (the topic now routes normally) or a gap longer than+ A threaded message (the topic now routes normally) or a send gap longer than``_NEW_TOPIC_FOLLOW_SECONDS`` ends the follow; each adoption extends it, so every chunk of asplit opener lands in the same topic."""@@ -76,11 +86,11 @@ class TelegramTopicRoutingMixin:record = pending.pop(key, None)if record is None or thread_id is not None or getattr(message, "message_thread_id", None) is not None:return thread_id- created_thread_id, stamp = record- now = time.monotonic()- if now - stamp > self._NEW_TOPIC_FOLLOW_SECONDS:+ created_thread_id, last_sent_at, _recorded = record+ sent_at = self._sent_at(message)+ if sent_at is None or sent_at - last_sent_at > self._NEW_TOPIC_FOLLOW_SECONDS:return thread_id- pending[key] = (created_thread_id, now)+ pending[key] = (created_thread_id, max(sent_at, last_sent_at), time.monotonic())logger.info("[%s] Thread-less message %s adopted by new Telegram topic %s (chat=%s)",self.name, getattr(message, "message_id", "?"), created_thread_id, key[0])return created_thread_iddiff --git a/tests/gateway/test_telegram_new_topic_opener.py b/tests/gateway/test_telegram_new_topic_opener.pyindex f97760822e2..0ec4553933a 100644--- a/tests/gateway/test_telegram_new_topic_opener.py+++ b/tests/gateway/test_telegram_new_topic_opener.py@@ -5,6 +5,7 @@ Telegram for Android 13.0.x sends the opener of a topic created from "All messag"""import sys+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespaceimport pytest@@ -19,29 +20,31 @@ import plugins.platforms.telegram.telegram_topic_routing as routingfrom plugins.platforms.telegram.adapter import TelegramAdapterCHAT, USER, NEW_TOPIC = 111, 42, 600+T0 = datetime(2026, 10, 14, 13, 21, 2, tzinfo=UTC)+WINDOW = routing.TelegramTopicRoutingMixin._NEW_TOPIC_FOLLOW_SECONDS-def _msg(message_id, *, thread_id=None, created=False, user_id=USER, chat_id=CHAT, text="hi"):+def _msg(message_id, sent, *, thread_id=None, created=False, user_id=USER, chat_id=CHAT, text="hi"):chat = SimpleNamespace(id=chat_id, type="private", title=None, full_name="T")return SimpleNamespace(chat=chat, from_user=SimpleNamespace(id=user_id, full_name="T", is_bot=False),text=None if created else text, message_thread_id=thread_id, is_topic_message=thread_id is not None,- message_id=message_id, reply_to_message=None, date=None,+ message_id=message_id, reply_to_message=None, date=T0 + timedelta(seconds=sent),forum_topic_created=SimpleNamespace(name="New topic") if created else None)@pytest.fixturedef adapter(monkeypatch):- clock = [1000.0]+ clock = [1000.0] # local handler time; adoption must not depend on itmonkeypatch.setattr(routing.time, "monotonic", lambda: clock[0])a = TelegramAdapter(PlatformConfig(enabled=True, token="***", extra={"allow_from": [str(USER)]}))a.clock = clockreturn a-async def _create(adapter, message_id, **kw):+async def _create(adapter, message_id, sent=0.0, **kw):await adapter._handle_forum_topic_created(- SimpleNamespace(effective_message=_msg(message_id, thread_id=NEW_TOPIC, created=True, **kw)), None)+ SimpleNamespace(effective_message=_msg(message_id, sent, thread_id=NEW_TOPIC, created=True, **kw)), None)def _thread(adapter, msg):@@ -52,21 +55,22 @@ def _thread(adapter, msg):async def test_thread_less_messages_after_creation_land_in_the_new_topic(adapter):await _create(adapter, 9379)# Not creation+1: private-chat ids are one sequence shared by every chat of the bot.- assert _thread(adapter, _msg(9382)) == str(NEW_TOPIC)- adapter.clock[0] += 0.4- assert _thread(adapter, _msg(9383, text="second chunk of a split text")) == str(NEW_TOPIC)+ assert _thread(adapter, _msg(9382, 0.2)) == str(NEW_TOPIC)+ # The next chunk was sent 0.5 s later but its handler ran 30 s later (per-chat FIFO behind a+ # slow photo download / STT): the window follows send time, so it still lands in the topic.+ adapter.clock[0] += 30+ assert _thread(adapter, _msg(9383, 0.7, text="second chunk")) == str(NEW_TOPIC)# A message the client stamped ends the follow; a later lobby message stays lobby.- assert _thread(adapter, _msg(9384, thread_id=NEW_TOPIC)) == str(NEW_TOPIC)- assert _thread(adapter, _msg(9385)) is None+ assert _thread(adapter, _msg(9384, 1.0, thread_id=NEW_TOPIC)) == str(NEW_TOPIC)+ assert _thread(adapter, _msg(9385, 1.2)) is Noneassert f"{CHAT}:New topic" not in adapter._dm_topics # must not block session-title auto-rename@pytest.mark.asyncioasync def test_creation_is_not_adopted_late_or_by_others(adapter):await _create(adapter, 10)- assert _thread(adapter, _msg(11, user_id=7)) is None # another sender- assert _thread(adapter, _msg(12, chat_id=222)) is None # another chat- adapter.clock[0] += routing.TelegramTopicRoutingMixin._NEW_TOPIC_FOLLOW_SECONDS + 1- assert _thread(adapter, _msg(13)) is None # a lobby message well after the creation+ assert _thread(adapter, _msg(11, 0.1, user_id=7)) is None # another sender+ assert _thread(adapter, _msg(12, 0.1, chat_id=222)) is None # another chat+ assert _thread(adapter, _msg(13, WINDOW + 1)) is None # a lobby message sent well after the creationawait _create(adapter, 20, user_id=7) # creation by a user the adapter would rejectassert not adapter._pending_created_topics