Skip to content

The agent that grows with you

fix(agent): the stream watch holds a bounded tail and reads both reasoning fields

John Paul Soliva8ceb1761c480
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 21efd7ae4d5..e97a61f12e7 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -3175,6 +3175,9 @@ class _StreamingCall(StreamingWaitMonitor):
# The raw channels, not the callback-delivered text: cron, subagents and callback-less
# gateway turns register no stream callback, so nothing else sees a loop mid-stream.
content_watch, reasoning_watch = RunawayStreamWatch(), RunawayStreamWatch()
+ # Own watch: the display takes one reasoning representation per chunk, but the plain
+ # field is persisted either way and need not mirror the details.
+ detail_watch = RunawayStreamWatch()
runaway = None
def _open_stream(next_api_kwargs: dict[str, Any]):
@@ -3275,7 +3278,8 @@ class _StreamingCall(StreamingWaitMonitor):
display_reasoning = detail_text or reasoning_text
if display_reasoning:
self._emit_reasoning(display_reasoning)
- if reasoning_watch.feed(display_reasoning):
+ looped = [reasoning_watch.feed(reasoning_text or ""), detail_watch.feed(detail_text)]
+ if any(looped):
runaway = "reasoning"
break
# Not routed to the live display: the transport promotes a sole-payload
diff --git a/agent/repetition_guard.py b/agent/repetition_guard.py
index f09b21e9be8..7bec6b7f1f4 100644
--- a/agent/repetition_guard.py
+++ b/agent/repetition_guard.py
@@ -169,10 +169,11 @@ class RunawayStreamWatch:
and the next one each time the text doubles, so the total work stays linear in the output.
"""
- __slots__ = ("_parts", "_chars", "_next_check")
+ __slots__ = ("_parts", "_held", "_chars", "_next_check")
def __init__(self) -> None:
self._parts: list[str] = []
+ self._held = 0
self._chars = 0
self._next_check = STOP_PATH_MIN_CHARS
@@ -181,10 +182,19 @@ class RunawayStreamWatch:
if not text:
return False
self._parts.append(text)
+ self._held += len(text)
self._chars += len(text)
+ # The gap between two checks doubles, so text held until the next check would grow
+ # with the reply. Trimming every tail's worth of new text keeps the cost linear.
+ if self._held >= 2 * _STREAM_TAIL_CHARS:
+ self._trim()
if self._chars < self._next_check:
return False
self._next_check = 2 * self._chars
+ return is_runaway_repetition(self._trim())
+
+ def _trim(self) -> str:
tail = "".join(self._parts)[-_STREAM_TAIL_CHARS:]
self._parts = [tail]
- return is_runaway_repetition(tail)
+ self._held = len(tail)
+ return tail
diff --git a/tests/agent/test_stream_runaway_repetition.py b/tests/agent/test_stream_runaway_repetition.py
index dd8dd4405bd..53c4a0f2b8b 100644
--- a/tests/agent/test_stream_runaway_repetition.py
+++ b/tests/agent/test_stream_runaway_repetition.py
@@ -19,9 +19,11 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
-from agent.repetition_guard import STOP_PATH_MIN_CHARS
+from agent.repetition_guard import _STREAM_TAIL_CHARS, STOP_PATH_MIN_CHARS, RunawayStreamWatch
_TURN_BOUND_S = 30.0
+# Reasoning whose plain field loops while the structured details beside it keep changing.
+_LOOP_BEHIND_DETAILS = "reasoning-behind-details"
_CYCLE_125650 = (
"De bot en de werkers blijven lopen. Ik zoek het punt waar de tekst binnenkomt. "
@@ -100,8 +102,12 @@ class _FakeEndpoint:
"choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],
}) + "\n\n"
- for piece in self._pieces():
- yield chunk({field: piece})
+ for n, piece in enumerate(self._pieces()):
+ if self.channel == _LOOP_BEHIND_DETAILS:
+ yield chunk({"reasoning_content": piece, "reasoning_details": [
+ {"type": "reasoning.text", "text": f"Step {n}: weighing option {n * 7919}. ", "index": 0}]})
+ else:
+ yield chunk({field: piece})
yield chunk({}, "stop")
yield "data: [DONE]\n\n"
@@ -178,10 +184,11 @@ def _run_turn(server: _FakeEndpoint, api_mode: str) -> dict:
[
("chat_completions", "content", _CYCLE_125650),
("chat_completions", "reasoning", _FULLWIDTH_ECHO_94224),
+ ("chat_completions", _LOOP_BEHIND_DETAILS, _CYCLE_125650),
("anthropic_messages", "content", _STATUS_LINE_78551),
("anthropic_messages", "reasoning", _CYCLE_125650),
],
- ids=["chat-content", "chat-reasoning", "anthropic-text", "anthropic-thinking"],
+ ids=["chat-content", "chat-reasoning", "chat-reasoning-behind-details", "anthropic-text", "anthropic-thinking"],
)
def test_looping_stream_is_cut_without_a_stream_callback(endpoint, api_mode, channel, loop):
server = endpoint(channel, loop, endless=True)
@@ -204,3 +211,15 @@ def test_repetitive_but_legitimate_stream_is_delivered(endpoint, text):
assert result["completed"] is True
assert result["final_response"] == text.strip()
+
+
+def test_watch_holds_a_bounded_tail_however_long_the_stream_runs():
+ watch, chunk_chars, held_max = RunawayStreamWatch(), 0, 0
+ for n in range(12_000): # far past several doublings of the check threshold
+ chunk = f"Row {n}: measured {n * 7919} units at site {n % 97}, carried into ledger {n * 31}.\n"
+ assert watch.feed(chunk) is False
+ chunk_chars = max(chunk_chars, len(chunk))
+ held_max = max(held_max, sum(map(len, watch._parts)))
+
+ assert watch._chars > 8 * _STREAM_TAIL_CHARS
+ assert held_max <= 2 * _STREAM_TAIL_CHARS + chunk_chars