Skip to content

The agent that grows with you

fix(telegram): keep per-chat chain intact when a waiting update is cancelled

kshitijk4poorff9045726756
diff --git a/plugins/platforms/telegram/update_admission.py b/plugins/platforms/telegram/update_admission.py
index 55f1a5d4419..5e6bbb02246 100644
--- a/plugins/platforms/telegram/update_admission.py
+++ b/plugins/platforms/telegram/update_admission.py
@@ -150,12 +150,20 @@ class PerChatUpdateProcessor(BaseUpdateProcessor):
self._tails[chat.id] = done
try:
if prev is not None:
- await prev
+ # shield: cancelling this waiter must not cancel the predecessor's tail future.
+ await asyncio.shield(prev)
await coroutine
finally:
- done.set_result(None)
- if self._tails.get(chat.id) is done:
- del self._tails[chat.id]
+ def release(_prev=None):
+ done.set_result(None)
+ if self._tails.get(chat.id) is done:
+ del self._tails[chat.id]
+
+ # A cancelled waiter hands its turn on only once its predecessor finishes (per-chat FIFO).
+ if prev is None or prev.done():
+ release()
+ else:
+ prev.add_done_callback(release)
async def initialize(self) -> None:
pass
diff --git a/tests/plugins/test_telegram_update_admission.py b/tests/plugins/test_telegram_update_admission.py
index b78ab28e778..85d3b9edeb3 100644
--- a/tests/plugins/test_telegram_update_admission.py
+++ b/tests/plugins/test_telegram_update_admission.py
@@ -809,6 +809,27 @@ async def test_connect_builds_concurrent_update_processor(monkeypatch):
async with connected(monkeypatch, extra={"max_concurrent_updates": "lots"}) as (adapter, app, delivered):
assert app.concurrent_updates == 32
+ # Cancelling a waiting same-chat update must neither fail its running predecessor nor
+ # let the next update of that chat overtake it.
+ processor, order, gate = app.update_processor, [], asyncio.Event()
+
+ async def handler(name):
+ order.append(f"start {name}")
+ if name == "A":
+ await gate.wait()
+
+ chat = SimpleNamespace(effective_chat=SimpleNamespace(id=1))
+ tasks = []
+ for name in "ABC":
+ tasks.append(asyncio.create_task(processor.process_update(chat, handler(name))))
+ await asyncio.sleep(0.01)
+ tasks[1].cancel()
+ await asyncio.sleep(0.01)
+ gate.set()
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+ assert results[0] is None and results[2] is None
+ assert order == ["start A", "start C"]
+
@pytest.mark.asyncio
async def test_slow_update_does_not_block_other_chats(monkeypatch):