fix(telegram): typing keep-alives send one call per chat and share its outbound budget

_keep_typing runs per session, but Telegram meters per chat: every DM topic
shares one chat id, so N active topics sent N sendChatAction calls per tick
into one chat, and send_typing walked past the chat's send flood window and
the shared send+edit slot. telegram_typing_gate.typing_may_fire now allows one
typing call per chat per 2 s, stays quiet inside the chat's flood window or
while a send/edit holds its slot, and takes that slot when it fires, so a
send right after a typing call is paced behind it. _typing_in_cooldown moves
into the same sibling.

Live (real adapter + PTB against the Bot API stand-in, three topic sessions
in one chat for 6.5 s): 12 sendChatAction calls on main, 4 here.

Fixes #99643
This commit is contained in:
Teknium
2026-11-09 02:08:20 -08:00
parent a0d954f62d
commit 5948ab52e2
3 changed files with 79 additions and 14 deletions

View File

@@ -198,6 +198,7 @@ from plugins.platforms.telegram.telegram_network import (
from plugins.platforms.telegram.telegram_outbound import is_visually_empty, resolve_notifications_mode
from plugins.platforms.telegram.telegram_send_path_recovery import TelegramSendPathRecoveryMixin, mark_send_path_recovered
from plugins.platforms.telegram.telegram_send_errors import is_entity_parse_error
from plugins.platforms.telegram.telegram_typing_gate import typing_may_fire
from plugins.platforms.telegram.telegram_group_observe import apply_group_observe_attribution, shared_sender_suffix
from plugins.platforms.telegram.telegram_picker_labels import model_button_labels
from plugins.platforms.telegram.telegram_topic_routing import TelegramTopicRoutingMixin
@@ -5231,18 +5232,6 @@ class TelegramAdapter(TelegramContactMixin, TelegramHeldInboundMixin, TelegramTo
delay = self._telegram_typing_cooldown_seconds
self._telegram_typing_cooldown_until[str(chat_id)] = asyncio.get_running_loop().time() + max(1.0, min(delay, 300.0))
def _typing_in_cooldown(self, chat_id: str) -> bool:
if not hasattr(self, "_telegram_typing_cooldown_until"):
self._telegram_typing_cooldown_until = {}
self._telegram_typing_cooldown_seconds = 30.0
until = self._telegram_typing_cooldown_until.get(str(chat_id))
if until is None:
return False
if asyncio.get_running_loop().time() < until:
return True
self._telegram_typing_cooldown_until.pop(str(chat_id), None)
return False
# --- per-chat send ordering + flood cooldown (#114396) ---------------------------------------------
# Both keyed by the Bot-API-normalized chat id: the text path passes the raw chat_id while the media
# funnel's send_kwargs carry the normalized value. ``__dict__.setdefault``: tests build adapters via
@@ -5318,7 +5307,7 @@ class TelegramAdapter(TelegramContactMixin, TelegramHeldInboundMixin, TelegramTo
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):
if not self._bot or not typing_may_fire(self, chat_id):
return
_is_dm_topic: bool = False
message_thread_id: Optional[int] = None

View File

@@ -0,0 +1,48 @@
"""Per-chat gate for Telegram typing keep-alives.
``_keep_typing`` runs once per session, but Telegram meters per chat: every DM topic shares one
chat id, so N active topics sent N ``sendChatAction`` calls per tick into one chat. A typing call
also spends the same per-chat budget as sends and edits: it stays quiet while that chat is in a
flood window or its shared outbound slot is taken, and takes that slot when it fires.
"""
from __future__ import annotations
import asyncio
from typing import Any
# One typing call per chat per this many seconds, however many sessions refresh it (Telegram shows
# the indicator for ~5 s; ``_keep_typing`` ticks every 2 s per session).
TYPING_CHAT_MIN_INTERVAL_SECS = 2.0
def _typing_in_cooldown(adapter: Any, chat_id: Any) -> bool:
"""A transient typing failure (``_record_typing_cooldown``) pauses this chat's typing calls."""
until_by_chat: dict[str, float] = adapter.__dict__.setdefault("_telegram_typing_cooldown_until", {})
until = until_by_chat.get(str(chat_id))
if until is None:
return False
if asyncio.get_running_loop().time() < until:
return True
until_by_chat.pop(str(chat_id), None)
return False
def typing_may_fire(adapter: Any, chat_id: Any) -> bool:
"""True when a typing call for ``chat_id`` may go out now; reserves the chat's typing tick."""
if _typing_in_cooldown(adapter, chat_id) or adapter._send_flood_cooldown_remaining(chat_id) is not None:
return False
if adapter._chat_outbound_slot_remaining(chat_id) > 0:
return False # a send/edit holds the chat's slot: typing never delays the reply itself
from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id
last: dict[str, float] = adapter.__dict__.setdefault("_telegram_typing_last_sent", {})
key = str(normalize_telegram_chat_id(chat_id))
now = asyncio.get_running_loop().time()
if now - last.get(key, float("-inf")) < TYPING_CHAT_MIN_INTERVAL_SECS:
return False
for stale in [k for k, t in last.items() if now - t >= TYPING_CHAT_MIN_INTERVAL_SECS]:
del last[stale] # bounded dict
last[key] = now
adapter._hold_chat_outbound_slot(chat_id) # typing spends the same per-chat budget as sends/edits
return True

View File

@@ -71,7 +71,8 @@ async def test_typing_dm_topic_fallback_success_does_not_cool_down(monkeypatch):
@pytest.mark.asyncio
async def test_typing_bad_thread_failure_does_not_cool_down(monkeypatch):
adapter = _make_adapter()
monkeypatch.setattr("plugins.platforms.telegram.adapter.asyncio.get_running_loop", lambda: type("Loop", (), {"time": lambda self: 10.0})())
now = {"value": 10.0}
monkeypatch.setattr("plugins.platforms.telegram.adapter.asyncio.get_running_loop", lambda: type("Loop", (), {"time": lambda self: now["value"]})())
async def bad_request(**kwargs):
raise ValueError("message thread not found")
@@ -79,7 +80,34 @@ async def test_typing_bad_thread_failure_does_not_cool_down(monkeypatch):
adapter._bot.send_chat_action = AsyncMock(side_effect=bad_request)
await adapter.send_typing("123", metadata={"thread_id": "99"})
now["value"] += 3.0 # next keep-alive tick (one typing call per chat per tick)
await adapter.send_typing("123", metadata={"thread_id": "99"})
assert adapter._bot.send_chat_action.await_count == 2
assert "123" not in adapter._telegram_typing_cooldown_until
@pytest.mark.asyncio
async def test_typing_is_one_call_per_chat_across_topics_and_spends_the_shared_slot():
"""N DM topics share one chat id: their keep-alives must not multiply sendChatAction (#99643)."""
adapter = _make_adapter()
adapter._bot.send_chat_action = AsyncMock(return_value=None)
for topic in ("11", "12", "13"):
await adapter.send_typing("4242", metadata={"thread_id": topic})
assert adapter._bot.send_chat_action.await_count == 1
assert adapter._chat_outbound_slot_remaining("4242") > 0 # a send right after waits its turn
await adapter.send_typing("777") # another chat has its own budget
assert adapter._bot.send_chat_action.await_count == 2
@pytest.mark.asyncio
async def test_typing_stays_quiet_inside_the_chat_send_flood_window():
adapter = _make_adapter()
adapter._bot.send_chat_action = AsyncMock(return_value=None)
adapter._record_send_flood_cooldown("4242", 120.0)
await adapter.send_typing("4242")
adapter._bot.send_chat_action.assert_not_awaited()