Skip to content

The agent that grows with you

fix(gateway): finish the split-delivery bug class so the fix cannot duplicate or still swallow

kshitij392e3a8c53bb
diff --git a/gateway/run.py b/gateway/run.py
index 1327ba454c6..e6aafc5d271 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -25668,9 +25668,20 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# user gets one corrected message; on edit failure fall through
# with already_sent unset so the normal final send delivers the
# complete text.
+ #
+ # Not valid for a multi-message split delivery: there
+ # ``message_id`` is only the LAST chunk, so editing it with the
+ # complete response would repeat every sealed head chunk's text
+ # inside the tail message. Fall through to the normal final send
+ # instead (#78541).
_sc_msg_id = _sc.message_id
_sc_adapter = getattr(_sc, "adapter", None)
- if _sc_msg_id and _sc_msg_id != "__no_edit__" and _sc_adapter is not None:
+ if getattr(_sc, "_turn_split_delivery", False):
+ logger.info(
+ "Stale streamed finalize detected for session %s on a multi-message split; skipping the in-place reconciliation edit and delivering the complete response via normal final send (#78541).",
+ session_key or "?",
+ )
+ elif _sc_msg_id and _sc_msg_id != "__no_edit__" and _sc_adapter is not None:
try:
_reconcile_res = await _sc_adapter.edit_message(
chat_id=source.chat_id,
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.py
index f9bb928b040..cb0f8c7e0df 100644
--- a/gateway/stream_consumer.py
+++ b/gateway/stream_consumer.py
@@ -419,16 +419,19 @@ class GatewayStreamConsumer:
self._stream_ledger += text
def _record_turn_final_payload(self, text: str) -> None:
- """Record the exact cleaned payload of a turn-final delivery.
+ """Record what the user has actually seen as this turn's final answer.
Normalized the same way ``_send_or_edit`` normalizes outgoing text
(media-directive strip + fence closing) so the gateway can compare it
against the completed ``final_response`` (#71643).
- For multi-message split delivery, prefer ``_stream_ledger`` (the
- unsplit segment text) so reconciliation still works (#78541). Older
- code cleared the record on split and forced legacy trust; that let a
- payload-less stale flag suppress later complete replies.
+ ``text`` is what the *calling* path just delivered. On a multi-message
+ split that is only the trailing chunk — the overflow paths truncate
+ ``_accumulated`` once head chunks are sealed — so ``_stream_ledger``
+ (the un-truncated segment text) is preferred there and ``text`` is
+ ignored. Without that substitution a split turn records a tail-only
+ payload, which the gateway reads as a mismatch and re-sends on top of
+ an answer the user already received (#78541).
"""
source = text or ""
if self._turn_split_delivery and self._stream_ledger:
@@ -945,6 +948,16 @@ class GatewayStreamConsumer:
self._message_created_ts = None
self._last_sent_text = ""
+ if chunks_delivered:
+ # A sealed head is on screen, so this turn is now a
+ # multi-message delivery. Flag it BEFORE the tail
+ # send below: the fresh-final route replaces every
+ # tracked preview with one message, which is only
+ # valid while the active message holds the whole
+ # answer. Once heads are sealed it does not, and
+ # deleting them would drop delivered text (#78541).
+ self._turn_split_delivery = True
+
self._last_edit_time = time.monotonic()
if got_done:
tail_delivered = True
@@ -963,9 +976,7 @@ class GatewayStreamConsumer:
# still reconcile against final_response
# (#71643, #78541).
self._turn_split_delivery = True
- self._record_turn_final_payload(
- self._stream_ledger or "".join(chunks)
- )
+ self._record_turn_final_payload(self._accumulated)
return
if got_segment_break:
self._message_id = None
@@ -1422,7 +1433,11 @@ class GatewayStreamConsumer:
self._final_response_sent = True
self._final_content_delivered = True
# The visible partial equals the complete final text (#71643).
- self._delivered_final_text = final_text.strip()
+ # Route through the recorder so a split turn records the full
+ # ledger rather than this tail-only payload — an unrecorded or
+ # tail-only split now reads as a mismatch and would re-send
+ # text the user already has (#78541).
+ self._record_turn_final_payload(final_text)
return
raw_limit = getattr(self.adapter, "MAX_MESSAGE_LENGTH", 4096)
@@ -1528,7 +1543,10 @@ class GatewayStreamConsumer:
# The fallback delivered the complete ``final_text`` (as one message
# or prefix + continuation chunks that union to it), so record it as
# the turn-final payload for the gateway's reconciliation (#71643).
- self._delivered_final_text = final_text.strip()
+ # On a split turn ``final_text`` is only the tail — the recorder
+ # substitutes the unsplit ledger so the sealed heads count as
+ # delivered too (#78541).
+ self._record_turn_final_payload(final_text)
self._last_sent_text = chunks[-1]
self._fallback_prefix = ""
self._fallback_preserve_partial_messages = False
@@ -1600,7 +1618,9 @@ class GatewayStreamConsumer:
self._final_response_sent = True
self._final_content_delivered = True
# Fresh commit of the complete answer after a failed finalize (#71643).
- self._delivered_final_text = final_text.strip()
+ # Recorder-routed so a split turn records the unsplit ledger instead of
+ # a tail-only payload the gateway would read as stale (#78541).
+ self._record_turn_final_payload(final_text)
self._last_sent_text = final_text
self._fallback_prefix = ""
self._fallback_preserve_partial_messages = False
@@ -1923,6 +1943,15 @@ class GatewayStreamConsumer:
# current one plus any continuation fragments tracked while streaming
# (an oversized reply split across the platform's edit limit). All of
# them are replaced by the single fresh message below.
+ #
+ # That replacement is only sound while ``text`` holds the whole answer.
+ # On a multi-message split the head chunks were sealed and dropped out
+ # of ``_accumulated``, so ``text`` is just the tail — deleting the
+ # sealed heads would erase text the user already received and leave the
+ # complete reply nowhere on screen (#78541). Keep the sealed messages
+ # and take the normal edit path instead.
+ if self._turn_split_delivery:
+ return False
stale_ids = set(self._preview_message_ids)
if self._message_id and self._message_id != "__no_edit__":
stale_ids.add(self._message_id)
@@ -2226,9 +2255,12 @@ class GatewayStreamConsumer:
self._final_content_delivered = True
# ``text`` is already cleaned/fence-closed here and
# equals the visible prefix — the on-screen content
- # IS this finalize payload (#71643).
- if not self._turn_split_delivery:
- self._delivered_final_text = text.strip()
+ # IS this finalize payload (#71643). Record it on
+ # split turns too: post-#78541 an unrecorded split
+ # reads as a mismatch and would re-send this
+ # already-visible answer, reintroducing the
+ # duplicate #45517 fixed (#36965 / #25349).
+ self._record_turn_final_payload(text)
raw_response = getattr(result, "raw_response", None)
if isinstance(raw_response, dict) and raw_response.get("partial_overflow"):
# Telegram edited/sent one or more overflow chunks,
diff --git a/tests/gateway/test_stale_finalize_suppression.py b/tests/gateway/test_stale_finalize_suppression.py
index 2021133bdc4..f4f70240a0d 100644
--- a/tests/gateway/test_stale_finalize_suppression.py
+++ b/tests/gateway/test_stale_finalize_suppression.py
@@ -20,6 +20,7 @@ with a live ``GatewayStreamConsumer``), per the review guidance on #71643:
Plus unit coverage for ``GatewayStreamConsumer.delivered_final_matches``.
"""
+import asyncio
import importlib
import sys
import types
@@ -336,15 +337,18 @@ async def test_payload_less_split_does_not_suppress_complete_response(
all_payloads = [c["content"] for c in adapter.sent] + [
e["content"] for e in adapter.edits
]
- assert any(FULL_RESPONSE in payload for payload in all_payloads), (
- f"complete response never reached the platform; payloads: {all_payloads!r}"
+ # The contract is "the complete reply is not swallowed", which has two
+ # legitimate shapes: _run_agent puts the full text on the wire itself
+ # (reconcile edit), or it declines to claim delivery so the caller's normal
+ # final send delivers it. A multi-message split takes the second shape --
+ # the reconcile edit is deliberately skipped there because it would repeat
+ # every sealed head chunk inside the tail message (#78541). Asserting only
+ # the first shape would pin the recovery route rather than the guarantee.
+ delivered_here = any(FULL_RESPONSE in payload for payload in all_payloads)
+ assert delivered_here or not result.get("already_sent"), (
+ "complete response was neither delivered nor left to the normal final "
+ f"send; already_sent={result.get('already_sent')!r} payloads={all_payloads!r}"
)
- # Must not silently claim delivery without putting the complete text on
- # the wire (the production ghost: already_sent with no full payload).
- if result.get("already_sent"):
- assert any(
- FULL_RESPONSE in payload for payload in all_payloads
- ), "already_sent=True but complete response never reached the platform"
# ---------------------------------------------------------------------------
@@ -415,3 +419,151 @@ class TestDeliveredFinalMatches:
assert consumer._delivered_final_text is None
assert consumer._turn_split_delivery is False
assert consumer._stream_ledger == ""
+
+
+# ---------------------------------------------------------------------------
+# End-to-end split delivery: drive the real overflow-split loop (no hand-set
+# private flags) and assert the no-duplicate / no-swallow contract on both
+# sides. These are the shapes that #78541's boundary fix has to not regress:
+# a genuine complete split must still suppress, and an incomplete one must not.
+# ---------------------------------------------------------------------------
+
+
+class _SplittingAdapter(FinalizeCaptureAdapter):
+ """Small message cap so real prose trips the consumer's overflow split.
+
+ Also records deletions and can be told to fail edits, so the fresh-final
+ and flood-control paths can be driven without patching internals.
+ """
+
+ MAX_MESSAGE_LENGTH = 220
+
+ def __init__(self, platform=Platform.TELEGRAM):
+ super().__init__(platform)
+ self.deleted = []
+ self.fail_edits = False
+
+ async def edit_message(
+ self, chat_id, message_id, content, *, finalize: bool = False, metadata=None
+ ) -> SendResult:
+ if self.fail_edits:
+ return SendResult(
+ success=False, error="Flood control exceeded. Retry in 12 seconds"
+ )
+ return await super().edit_message(
+ chat_id, message_id, content, finalize=finalize, metadata=metadata
+ )
+
+ async def delete_message(self, chat_id, message_id) -> bool:
+ self.deleted.append(message_id)
+ return True
+
+ def truncate_message(self, text, limit, len_fn=len):
+ chunks, rest = [], text
+ while len_fn(rest) > limit:
+ cut = rest.rfind("\n", 0, limit)
+ if cut < limit // 2:
+ cut = limit
+ chunks.append(rest[:cut])
+ rest = rest[cut:].lstrip("\n")
+ chunks.append(rest)
+ return chunks
+
+
+def _split_consumer():
+ adapter = _SplittingAdapter()
+ consumer = GatewayStreamConsumer(
+ adapter,
+ "chat-split",
+ StreamConsumerConfig(
+ edit_interval=0.0, buffer_threshold=1, cursor="",
+ fresh_final_after_seconds=0.0,
+ ),
+ )
+ return adapter, consumer
+
+
+async def _drain_split_turn(consumer, lines):
+ task = asyncio.create_task(consumer.run())
+ for line in lines:
+ consumer.on_delta(line + "\n")
+ await asyncio.sleep(0.005)
+ consumer.finish()
+ await asyncio.wait_for(task, timeout=10)
+
+
+async def test_complete_overflow_split_still_suppresses_duplicate():
+ """A fully delivered multi-message reply must NOT be re-sent (#45517)."""
+ adapter, consumer = _split_consumer()
+ lines = [f"line {i} " + "x" * 60 for i in range(12)]
+ await _drain_split_turn(consumer, lines)
+
+ complete = "\n".join(lines)
+ assert consumer._turn_split_delivery is True, "overflow split never triggered"
+ # The user received the whole answer across several messages, so the
+ # gateway must keep suppressing its own final send.
+ assert consumer.delivered_final_matches(complete) is True
+
+
+async def test_split_delivery_missing_tail_does_not_suppress():
+ """#78541 — when the completed response exceeds what the split delivered,
+ the matcher must report a mismatch so the gateway still sends it."""
+ adapter, consumer = _split_consumer()
+ lines = [f"line {i} " + "x" * 60 for i in range(12)]
+ await _drain_split_turn(consumer, lines)
+
+ never_streamed = "\n".join(lines) + "\n\n" + "tail the user never saw " * 8
+ assert consumer._turn_split_delivery is True
+ assert consumer.delivered_final_matches(never_streamed) is False
+
+
+async def test_split_delivery_keeps_sealed_heads_on_fresh_final():
+ """The fresh-final route must not delete sealed head messages.
+
+ ``_try_fresh_final`` replaces every tracked preview with one fresh message,
+ which only holds the whole answer on a single-message turn. After a split
+ the sealed heads carry text that the fresh message does not, so deleting
+ them would drop delivered content (#78541).
+ """
+ adapter, consumer = _split_consumer()
+ head_id = await consumer._send_new_chunk("HEAD text. " * 12, None, final=False)
+ consumer._turn_split_delivery = True
+
+ assert head_id in consumer._preview_message_ids
+ assert await consumer._try_fresh_final("TAIL text. " * 12) is False
+ assert head_id not in adapter.deleted, "sealed head chunk was deleted"
+
+
+async def test_failed_final_edit_after_split_records_visible_payload():
+ """A flood-controlled cosmetic final edit must not cause a duplicate.
+
+ The complete answer is already on screen; only the cursor-strip edit
+ failed. Recording the visible payload keeps the gateway suppressing its
+ own send instead of posting the whole answer twice (#36965 / #25349).
+ """
+ adapter = _SplittingAdapter()
+ cursor = " \u2589"
+ consumer = GatewayStreamConsumer(
+ adapter,
+ "chat-split",
+ StreamConsumerConfig(
+ edit_interval=0.0, buffer_threshold=1, cursor=cursor,
+ fresh_final_after_seconds=0.0,
+ ),
+ )
+ full = "The complete answer. " * 8
+ # Streaming already put the whole answer on screen, cursor and all.
+ await consumer._send_or_edit(full + cursor)
+ assert consumer._last_sent_text.endswith(cursor)
+ consumer._turn_split_delivery = True
+ consumer._stream_ledger = full
+ adapter.fail_edits = True
+
+ # The cosmetic cursor-strip edit is rate-limited and fails.
+ assert await consumer._send_or_edit(full, finalize=True) is False
+ assert consumer._final_content_delivered is True
+ assert consumer.delivered_final_matches(full) is True