Skip to content

The agent that grows with you

fix(gateway/stream): a failed tail send at a tool boundary no longer loses the tail

teknium16d150c7e7813
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.py
index 7bf0b1c27a7..b82a27c2c1d 100644
--- a/gateway/stream_consumer.py
+++ b/gateway/stream_consumer.py
@@ -926,9 +926,10 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
continuation goes out once via _send_fallback_final."""
if self._cumulative_transport():
return
- # If the segment-break edit didn't land (flood control / fallback mode),
- # _accumulated holds unseen pre-boundary text — flush it before the reset.
- if (self._accumulated and not tick.update_visible and self._message_id
+ # If the segment-break edit or send didn't land (flood control / fallback mode, or a
+ # failed first send of a split tail with no message id yet), _accumulated holds unseen
+ # pre-boundary text — flush it before the reset clears it.
+ if (self._accumulated and not tick.update_visible
and self._message_id != "__no_edit__"):
await self._flush_segment_tail_on_edit_failure()
self._reset_segment_state(preserve_no_edit=True)
diff --git a/gateway/stream_consumer_fallback.py b/gateway/stream_consumer_fallback.py
index 335e5013e5a..9adf2e6eadf 100644
--- a/gateway/stream_consumer_fallback.py
+++ b/gateway/stream_consumer_fallback.py
@@ -305,6 +305,8 @@ class StreamFallbackMixin:
async def _flush_segment_tail_on_edit_failure(self) -> None:
"""Before a segment reset, send the unseen tail as a new message (and best-effort
strip the stuck cursor from the partial)."""
+ if getattr(self, "_egress_declined", False):
+ return # a new message is exactly the re-addressing the egress guard refused
if not self._fallback_final_send:
await self._try_strip_cursor()
visible = self._fallback_prefix or self._visible_prefix()
diff --git a/tests/gateway/test_stream_consumer_oversized_leftover.py b/tests/gateway/test_stream_consumer_oversized_leftover.py
index 3a81f050588..00c364c5dc7 100644
--- a/tests/gateway/test_stream_consumer_oversized_leftover.py
+++ b/tests/gateway/test_stream_consumer_oversized_leftover.py
@@ -16,7 +16,8 @@ send was correctly suppressed, which is what places the duplicate inside the
consumer rather than in the gateway's delivery ledger.
Contract pinned here: on a non-final lane the CONSUMER owns chunking, so no line
-of the answer reaches the channel twice as a new message.
+of the answer reaches the channel twice as a new message, and none is lost when a
+boundary or a failed tail send lands in the sealing tick.
"""
import asyncio
@@ -56,11 +57,18 @@ def _make_plain_adapter():
return adapter
-def _wire(adapter):
+def _wire(adapter, fail_first_send_of=None):
+ """Record delivered sends/edits. ``fail_first_send_of``: the first send whose content
+ contains that marker fails (success=False) and is not delivered."""
sends, edits = [], []
+ failed = []
async def fake_send(**kw):
- sends.append((kw.get("content", ""), (kw.get("metadata") or {}).get("notify")))
+ content = kw.get("content", "")
+ if fail_first_send_of and not failed and fail_first_send_of in content:
+ failed.append(content)
+ return SimpleNamespace(success=False, error="timeout")
+ sends.append((content, (kw.get("metadata") or {}).get("notify")))
return SimpleNamespace(success=True, message_id=f"m{len(sends)}")
async def fake_edit(**kw):
@@ -69,73 +77,53 @@ def _wire(adapter):
adapter.send = AsyncMock(side_effect=fake_send)
adapter.edit_message = AsyncMock(side_effect=fake_edit)
- return sends, edits
+ return sends, edits, failed
-async def _run(adapter):
- """Reproduce the live shape: a streamed head is already on screen when a long
- tail arrives and pushes the buffer far past the limit, so the seal leaves a
- leftover that STILL overflows."""
[email protected]("boundary", ["none", "commentary", "segment_break", "tail_send_fails"])
+async def test_every_tail_line_reaches_the_channel_exactly_once(boundary):
+ """Live shape: a streamed head is already on screen when a long tail pushes the buffer far
+ past the limit, so the seal leaves a leftover that STILL overflows. A commentary or tool
+ boundary may be drained in that same tick, and the tail send carrying the boundary may fail.
+ Every tail line must reach the channel, never twice as a new message, and post-boundary
+ text must start a new message instead of being glued onto the pre-boundary preview."""
+ adapter = _make_plain_adapter()
+ sends, edits, failed = _wire(
+ adapter, fail_first_send_of="tail line 239" if boundary == "tail_send_fails" else None)
config = StreamConsumerConfig(edit_interval=0.01, buffer_threshold=5, cursor="")
consumer = GatewayStreamConsumer(adapter, "chat_plain", config)
consumer.on_delta(HEAD)
task = asyncio.create_task(consumer.run())
await asyncio.sleep(0.06)
+ # Enqueued synchronously, so one drain folds TAIL and stops at the boundary.
consumer.on_delta(TAIL)
+ if boundary == "commentary":
+ consumer.on_commentary("COMMENTARY-MARKER")
+ if boundary != "none":
+ consumer.on_segment_break()
+ consumer.on_delta("POST-TOOL-MARKER")
await asyncio.sleep(0.12)
consumer.finish()
# asyncio.wait_for, never a bare await: a hold branch that fails to yield
# spins hot and would hang the suite instead of failing it.
await asyncio.wait_for(task, timeout=10)
- return consumer
-
-
-async def test_no_tail_line_is_published_twice_across_new_messages():
- adapter = _make_plain_adapter()
- sends, _edits = _wire(adapter)
-
- await _run(adapter)
+ if boundary == "tail_send_fails":
+ assert failed, "the harness never failed the tail send"
joined = "".join(c for c, _ in sends)
- repeated = [
- f"tail line {i:03d}" for i in range(240)
- if joined.count(f"tail line {i:03d}") > 1
- ]
+ repeated = [f"tail line {i:03d}" for i in range(240) if joined.count(f"tail line {i:03d}") > 1]
assert not repeated, (
f"{len(repeated)} tail line(s) reached the channel more than once as NEW "
f"messages (first: {repeated[:3]}) - that is the interleaved duplicate"
)
-
-
[email protected]("boundary", ["commentary", "segment_break"])
-async def test_boundary_in_the_sealing_tick_still_applies(boundary):
- """A commentary or tool boundary drained in the same tick that seals an oversized
- tail must still take effect: commentary is delivered, and post-boundary text starts
- a NEW message instead of being glued onto the pre-boundary preview."""
- adapter = _make_plain_adapter()
- sends, edits = _wire(adapter)
- config = StreamConsumerConfig(edit_interval=0.01, buffer_threshold=5, cursor="")
- consumer = GatewayStreamConsumer(adapter, "chat_plain", config)
- consumer.on_delta(HEAD)
- task = asyncio.create_task(consumer.run())
- await asyncio.sleep(0.06)
- # Enqueued synchronously, so one drain folds TAIL and stops at the boundary.
- consumer.on_delta(TAIL)
- if boundary == "commentary":
- consumer.on_commentary("COMMENTARY-MARKER")
- consumer.on_segment_break()
- consumer.on_delta("POST-TOOL-MARKER")
- await asyncio.sleep(0.12)
- consumer.finish()
- await asyncio.wait_for(task, timeout=10)
-
texts = [c for c, _ in sends] + edits
+ lost = [f"tail line {i:03d}" for i in range(240)
+ if not any(f"tail line {i:03d}" in t for t in texts)]
+ assert not lost, f"{len(lost)} tail line(s) never reached the channel (first: {lost[:3]})"
if boundary == "commentary":
assert any("COMMENTARY-MARKER" in t for t in texts), "commentary was dropped"
- glued = [t for t in texts if "POST-TOOL-MARKER" in t and "tail line" in t]
- assert not glued, "post-boundary text was glued onto the pre-boundary preview"
- assert any("POST-TOOL-MARKER" in t for t in texts)
- joined = "".join(c for c, _ in sends)
- assert all(joined.count(f"tail line {i:03d}") <= 1 for i in range(240))
+ if boundary != "none":
+ assert any("POST-TOOL-MARKER" in t for t in texts)
+ glued = [t for t in texts if "POST-TOOL-MARKER" in t and "tail line" in t]
+ assert not glued, "post-boundary text was glued onto the pre-boundary preview"