The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): a newer chunk no longer cancels a committed batch flush
Tekniumfbd482d5c5f6
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex e1cec9fbf23..d3493da1427 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -627,6 +627,8 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):self._pending_photo_batch_tasks: dict[str, asyncio.Task] = {}self._media_group_events: dict[str, MessageEvent] = {}self._media_group_tasks: dict[str, asyncio.Task] = {}+ # Flushes past their pop, by (family, key): a newer chunk must not cancel them (teardown still does).+ self._committed_flush_tasks: dict[tuple[str, str], asyncio.Task] = {}# Aggregate client-side splits of long messages into one MessageEvent; bounds are conservative# for Telegram's ~1 edit/s flood envelope.self._text_batch_delay_seconds = self._env_float_clamped(@@ -3295,6 +3297,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):pending_tasks = self._collect_live_tasks([*self._media_group_tasks.values(), *self._pending_photo_batch_tasks.values(), *self._pending_text_batch_tasks.values(),+ *getattr(self, "_committed_flush_tasks", {}).values(),getattr(self, "_polling_error_task", None), getattr(self, "_polling_progress_verifier_task", None),# Hold-queue redispatch must be cancellable+awaitable on teardown too.getattr(self, "_held_inbound_redispatch_task", None),@@ -6554,6 +6557,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):"""Shared delayed-flush body: sleep, pop, hold if teardown started, else dispatch. A cancel afterthe pop but before durable dispatch re-holds the event (never lose it)."""current_task = asyncio.current_task()+ committed = self.__dict__.setdefault("_committed_flush_tasks", {})event = Nonetry:await asyncio.sleep(delay)@@ -6565,6 +6569,13 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):event = pending.pop(key, None)if not event:return+ # Committed: leave the per-key slot so a newer chunk re-arms without cancelling this+ # dispatch mid-flight (e.g. during a root-DM createForumTopic, whose ID would be lost).+ tasks.pop(key, None)+ prior = committed.get((where, key))+ committed[(where, key)] = current_task+ if prior is not None and not prior.done():+ await asyncio.wait({prior}) # dispatch in order, after the earlier batch settlesif self._should_drop_delayed_delivery():self._hold_inbound_event(event, where=f"{where}-flush")event = None@@ -6578,6 +6589,8 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):self._hold_inbound_event(event, where=f"{where}-flush-cancelled")raisefinally:+ if committed.get((where, key)) is current_task:+ committed.pop((where, key), None)if tasks.get(key) is current_task:tasks.pop(key, None)diff --git a/tests/gateway/test_telegram_dm_topic_auto_transfer.py b/tests/gateway/test_telegram_dm_topic_auto_transfer.pyindex 075631eeb97..d5cfe408e00 100644--- a/tests/gateway/test_telegram_dm_topic_auto_transfer.py+++ b/tests/gateway/test_telegram_dm_topic_auto_transfer.py@@ -234,3 +234,37 @@ async def test_new_topic_reply_anchor_survives_native_codec(tmp_path, monkeypatc# The default (None) override stays out of the envelope, so older retries keep their fingerprint.plain = MessageEvent(text="x", source=_make_source(), message_id="4243")assert "reply_anchor_override" not in snapshot_native(runner, plain)["native_text_v1"]["event"]+++async def test_second_root_dm_does_not_cancel_an_in_flight_topic_transfer(tmp_path, monkeypatch):+ """A second root-DM chunk arriving while ``createForumTopic`` for the first is still in flight must+ not cancel the committed flush: the first message keeps its topic (no hold + replay into a second+ topic) and every created topic receives its message."""+ _runner, adapter, db, runs = _rig(tmp_path, monkeypatch, extra={"dm_topic_auto_transfer": True})+ adapter._text_batch_delay_seconds = adapter._text_batch_split_delay_seconds = 0.0+ release = asyncio.Event()+ ids = iter(range(NEW_TOPIC_ID, NEW_TOPIC_ID + 10))++ async def paused_create(**_kwargs):+ await release.wait()+ return SimpleNamespace(message_thread_id=next(ids))++ adapter._bot.create_forum_topic = AsyncMock(side_effect=paused_create)+ first = MessageEvent(text="plan the migration", source=_make_source(thread_id=None), message_id="4242")+ second = MessageEvent(text="and the rollback", source=_make_source(thread_id=None), message_id="4243")+ adapter._enqueue_text_event(first)+ await async_wait_until(lambda: adapter._bot.create_forum_topic.await_count == 1, what="first create in flight")+ adapter._enqueue_text_event(second)+ await async_wait_until(lambda: not adapter._pending_text_batches, what="second chunk's flush popped it")+ release.set()+ await async_wait_until(lambda: len(runs) >= 2 and not adapter._pending_text_batches+ and all(t.done() for t in adapter._session_tasks.values()), what="both turns ran")+ await asyncio.gather(*adapter._session_tasks.values(), return_exceptions=True)+ db.close()+ assert not getattr(adapter, "_held_inbound_events", None), "the first message was held for replay"+ created = adapter._bot.create_forum_topic.await_count+ assert first.source.thread_id == str(NEW_TOPIC_ID)+ landed = {first.source.thread_id, second.source.thread_id}+ assert landed == {str(NEW_TOPIC_ID + i) for i in range(created)}, "a created topic was left empty"+ assert len(runs) == 2