From 3b5572ded3f43556d69d037396db0ee4a2b8c215 Mon Sep 17 00:00:00 2001 From: Teknium Date: Thu, 16 Apr 2026 05:44:34 -0700 Subject: [PATCH] fix(stream-consumer): only confirm final delivery on successful best-effort send MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cancellation handler previously promoted any partial send (already_sent=True) to final_response_sent=True unconditionally. This meant if intermediate text (e.g. 'Let me search…') was streamed and the consumer was cancelled before delivering the actual answer, the gateway's suppression check would still prevent the fallback send. Now final_response_sent is only set in the cancellation path when: - The best-effort send of accumulated content actually succeeded, OR - It was already confirmed before cancellation Companion fix for PR #11000's run.py changes — closes the cancellation-path loophole that would otherwise let partial streams suppress final delivery during queued follow-ups. --- gateway/stream_consumer.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.py index 50321a3036e..a644547e6ab 100644 --- a/gateway/stream_consumer.py +++ b/gateway/stream_consumer.py @@ -403,18 +403,20 @@ class GatewayStreamConsumer: except asyncio.CancelledError: # Best-effort final edit on cancellation + _best_effort_ok = False if self._accumulated and self._message_id: try: - await self._send_or_edit(self._accumulated) + _best_effort_ok = bool(await self._send_or_edit(self._accumulated)) except Exception: pass - # If we delivered any content before being cancelled, mark the - # final response as sent so the gateway's already_sent check - # doesn't trigger a duplicate message. The 5-second - # stream_task timeout (gateway/run.py) can cancel us while - # waiting on a slow Telegram API call — without this flag the - # gateway falls through to the normal send path. - if self._already_sent: + # Only confirm final delivery if the best-effort send above + # actually succeeded OR if the final response was already + # confirmed before we were cancelled. Previously this + # promoted any partial send (already_sent=True) to + # final_response_sent — which suppressed the gateway's + # fallback send even when only intermediate text (e.g. + # "Let me search…") had been delivered, not the real answer. + if _best_effort_ok and not self._final_response_sent: self._final_response_sent = True except Exception as e: logger.error("Stream consumer error: %s", e)