fix(telegram): an observer's return does not receipt an unserved update

The group-99 gateway_platform_event observer returned early whenever no
hook was registered, and that bare return marked the admission claim
completed: an update no group-0 core handler serves (e.g. a dice
message) was receipted, suppressing redelivery of an update nobody
served, with no log line to correlate the loss. Only core (group 0)
callbacks complete a claim now; an unserved, unfailed update stays
unreceipted and logs one INFO line naming its update id and field names
only, never values. Native plugin callbacks accept as before via the
explicit handoff marker, so plugin-served shapes still receipt.

Fixes #141570
This commit is contained in:
liuhao1024
2026-10-20 01:23:36 +08:00
committed by Teknium
parent 311e1063bf
commit 4a2b984fd2
3 changed files with 65 additions and 6 deletions

View File

@@ -65,6 +65,19 @@ def _load_receipts(adapter, bot_id) -> None:
bounded_put(seen, key, ts, _SEEN_CAP)
def _field_names(update: Update) -> str:
"""Field names of an update and of its objects (e.g. its message), never values.
PTB serializes unset service flags as False; those are left out as absent.
"""
def names(data):
return [name for name, value in sorted(data.items()) if value is not False]
data = update.to_dict()
return ", ".join(f"{name}({','.join(names(data[name]))})" if isinstance(data[name], dict) else name
for name in names(data))
def _record_receipt(adapter, key: str) -> None:
bounded_put(adapter._seen_update_ids, key, time.time(), _SEEN_CAP)
adapter._update_receipts_dirty.add(key.split(":", 1)[0])
@@ -96,6 +109,7 @@ async def _flush_receipts(adapter) -> None:
class _Claim:
key: str
dispatch_task: asyncio.Task | None
update: Update
accepted: bool = False
completed: bool = False
failed: bool = False
@@ -190,15 +204,16 @@ class TelegramApplication(Application):
def add_handler(self, handler, group=0):
super().add_handler(handler, group)
self._admit_callbacks(handler)
# Core handlers live in group 0; the adapter's group-99 observer only watches.
self._admit_callbacks(handler, observer=group != 0)
def _admit_callbacks(self, handler):
def _admit_callbacks(self, handler, observer=False):
# 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)
self._admit_callbacks(child, observer)
return
callback = getattr(handler, "callback", None)
if callback is None or getattr(callback, "_telegram_admitted", False):
@@ -222,7 +237,8 @@ class TelegramApplication(Application):
# groups already scheduled via block=False; their outcomes settle below.
if asyncio.current_task() is claim.dispatch_task:
raise ApplicationHandlerStop
else:
elif not observer:
# An observer returning is not service: unserved updates stay unreceipted.
claim.completed = True
return result
@@ -266,6 +282,10 @@ class TelegramApplication(Application):
del self.adapter._inflight_update_ids[claim.key]
if claim.accepted or (claim.completed and not claim.failed):
_record_receipt(self.adapter, claim.key)
elif not claim.failed:
# No receipt, so a redelivery is not suppressed. Names only: no content or ids.
logger.info("[Telegram] Update %s matched no core handler; not receipted (fields: %s)",
claim.update.update_id, _field_names(claim.update))
async def process_error(self, update, error, job=None, coroutine=None):
claim = self._current_claim.get()
@@ -287,7 +307,7 @@ class TelegramApplication(Application):
pending = self.adapter._inflight_update_ids
if key in seen or key in pending:
return
claim = _Claim(key, asyncio.current_task())
claim = _Claim(key, asyncio.current_task(), update)
# 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

View File

@@ -202,7 +202,8 @@ class TestHoldInboundAcrossReconnect:
from plugins.platforms.telegram.update_admission import _Claim
old, new = _make_adapter(), _make_adapter()
old._update_admission = ContextVar("claim", default=_Claim("1:1", None))
from telegram import Update
old._update_admission = ContextVar("claim", default=_Claim("1:1", None, Update(update_id=1)))
old._mark_disconnected()
new.adopt_held_inbound(old)
old._pending_text_batches["k"] = _make_event("late-salvage")

View File

@@ -182,6 +182,9 @@ async def test_replay_is_admitted_once_before_dispatch(monkeypatch, tmp_path, ki
assert [event.text for event in delivered] == ["hello", "changed", "hello"]
assert observer.await_count == 2
if mode == "retention":
async def native_serve(unused, context):
return None # plugin-owned: bare update ids are accepted, so they receipt
app.add_handler(TypeHandler(Update, native_serve))
now = time.time()
with monkeypatch.context() as clock:
clock.setattr(time, "time", lambda: now + 6.5 * 60 * 60)
@@ -886,3 +889,38 @@ async def test_slow_update_does_not_block_other_chats(monkeypatch):
assert next(e.source.chat_id for e in delivered) == "43"
same_chat = "\n".join(e.text for e in delivered if e.source.chat_id == "42")
assert same_chat == "hello\nsecond"
@pytest.mark.asyncio
async def test_unserved_update_not_receipted_and_logs_field_names(monkeypatch, caplog):
"""#141570: an update that no group-0 handler serves (e.g. a dice message) must not be
receipted by the group-99 observer's return — the receipt would suppress redelivery of
an update nobody served, silently. Instead one INFO line names the update id and the
field names only (never values), and a redelivery dispatches again."""
import logging as stdlib_logging
dice_payload = {
"update_id": 77,
"message": {
"message_id": 473, "date": 1800000000,
"chat": {"id": 42, "type": "private"},
"from": {"id": 88, "is_bot": False, "first_name": "Human"},
"dice": {"emoji": "🎲", "value": 4},
},
}
async with connected(monkeypatch) as (adapter, app, delivered):
caplog.set_level(stdlib_logging.INFO, logger="plugins.platforms.telegram.update_admission")
dice = Update.de_json(dice_payload, app.bot)
await app.process_update(dice)
assert not delivered # no core handler serves a dice message
assert f"{app.bot.id}:77" not in adapter._seen_update_ids # not receipted
records = [r for r in caplog.records if "matched no core handler" in r.message]
assert len(records) == 1
text = records[0].getMessage()
assert "Update 77" in text
assert "message(chat,date,dice,from,message_id)" in text # field names only
assert "🎲" not in text and "473" not in text and "88" not in text # never values
# No receipt: a redelivery of the same id dispatches again instead of being dropped.
await app.process_update(dice)
records = [r for r in caplog.records if "matched no core handler" in r.message]
assert len(records) == 2