Skip to content

The agent that grows with you

fix(agent): detect repetition across completion paths

fangliquanflq54d81e783c30
diff --git a/agent/repetition_guard.py b/agent/repetition_guard.py
index 9afdeb56280..e7c0f08a782 100644
--- a/agent/repetition_guard.py
+++ b/agent/repetition_guard.py
@@ -1,4 +1,4 @@
-"""Cheap content-sanity checks for the truncated-response continuation path.
+"""Cheap content-sanity checks for completed model output.
A model in a degenerate repetition loop can spend its ENTIRE output budget echoing one fragment;
the ``finish_reason=length`` continuation would then stitch it into the final response with a
@@ -9,7 +9,6 @@ conservative: only LONG verbatim repeats (60+ chars) covering a majority of the
from __future__ import annotations
-import math
from collections import Counter
# Below this length the check doesn't run: short truncations trivially
@@ -28,6 +27,13 @@ _DOMINANCE_RATIO = 0.5
# to know the reply degenerated and was cut off.
REPETITION_LOOP_INTERRUPTED = "[the reply degenerated into a repetition loop and was interrupted]"
+# Sampling bounds keep the general path linear in output size with a small,
+# fixed multiplier. A dominant contiguous run necessarily crosses many of
+# these evenly spaced anchors.
+_MAX_ANCHOR_SAMPLES = 32
+_MAX_ANCHOR_MATCHES = 8
+
+
# ``is_runaway_repetition``: a multi-line partial must be mostly copies of a few lines. Batch-style
# output (distinct INSERT rows, similar table rows) shares long prefixes and trips the window
# scan, but every line is distinct; a loop re-emits the same line(s).
@@ -35,11 +41,9 @@ _RUNAWAY_DISTINCT_LINE_RATIO = 0.5
def is_repetition_dominated(text: str) -> bool:
- """True when a single 60+ char substring recurs often enough to cover at least half
- of ``text`` — the signature of a repetition loop. Fail-open for non-string/short input.
-
- That shape is the signature of a model repetition loop (issue #86581), and continuing such a fragment is
- pointless — the continuation nudge would just stitch more repeated text into the final response.
+ """True when a contiguous run of at least five exact repetitions covers at least half
+ of ``text`` — the signature of a model repetition loop (issue #86581). Coverage is measured
+ with the true period, so long multi-line loop units count fully. Fail-open for short input.
"""
if not isinstance(text, str):
return False
@@ -51,21 +55,67 @@ def is_repetition_dominated(text: str) -> bool:
if _line_repetition_dominated(text, n):
return True
- # General path: fixed-size windows sliding one char at a time, catching loops that
- # don't align to line boundaries. A window must appear ``needed`` times to cover
- # >= _DOMINANCE_RATIO (and >= _MIN_REPEAT_COUNT).
+ return _periodic_run_dominated(text, n)
+
+
+def _periodic_run_dominated(text: str, n: int) -> bool:
+ """Detect a dominant exact periodic run from evenly spaced anchors.
+
+ Matching a 60-character anchor at a later position supplies a candidate
+ period. Expanding the equality ``text[i] == text[i + period]`` in both
+ directions recovers the full run, so coverage is measured using the true
+ repeating unit rather than crediting every occurrence with only 60 chars.
+ """
window = _REPEAT_WINDOW
- needed = max(_MIN_REPEAT_COUNT, math.ceil(n * _DOMINANCE_RATIO / window))
- counts: dict[str, int] = {}
- for i in range(n - window + 1):
- key = text[i : i + window]
- c = counts.get(key, 0) + 1
- if c >= needed:
- return True
- counts[key] = c
+ max_start = n - window
+ if max_start < 1:
+ return False
+
+ sample_step = max(
+ 1,
+ (max_start + _MAX_ANCHOR_SAMPLES - 2) // (_MAX_ANCHOR_SAMPLES - 1),
+ )
+ sample_starts = list(range(0, max_start + 1, sample_step))
+ if sample_starts[-1] != max_start:
+ sample_starts.append(max_start)
+
+ for start in sample_starts:
+ anchor = text[start : start + window]
+ search_from = start + 1
+ for _ in range(_MAX_ANCHOR_MATCHES):
+ match = text.find(anchor, search_from)
+ if match < 0:
+ break
+ period = match - start
+ if _candidate_run_dominated(text, n, start, period, window):
+ return True
+ search_from = match + 1
return False
+def _candidate_run_dominated(
+ text: str,
+ n: int,
+ start: int,
+ period: int,
+ matched: int,
+) -> bool:
+ """Expand one known equal window and judge its exact run coverage."""
+ left = start
+ while left > 0 and text[left - 1] == text[left - 1 + period]:
+ left -= 1
+
+ right = start + matched
+ while right + period < n and text[right] == text[right + period]:
+ right += 1
+
+ run_length = right + period - left
+ return (
+ run_length >= _MIN_REPEAT_COUNT * period
+ and run_length >= n * _DOMINANCE_RATIO
+ )
+
+
def is_runaway_repetition(text: str) -> bool:
"""Stricter than :func:`is_repetition_dominated`: also require the runaway shape.
diff --git a/agent/turn_final_response.py b/agent/turn_final_response.py
index 84fba083dec..11ebe06a44c 100644
--- a/agent/turn_final_response.py
+++ b/agent/turn_final_response.py
@@ -12,8 +12,19 @@ import logging
from typing import Any, Dict, Optional
from agent.message_metadata import append_message
+from agent.repetition_guard import is_repetition_dominated
from agent.turn_empty_response import recover_empty_response
from agent.turn_stop_gates import apply_stop_gates
+from agent.turn_truncation import partial_result
+
+_REPETITION_STOPPED = (
+ "🔁 Response dominated by repeated text — stopping before delivery.",
+ "⚠️ **Response Stopped — Repetition Detected**\n\nThe model fell into a repetition loop while "
+ "writing this response, so the repeated output was discarded.\n\n"
+ "→ Switch to a different model with `/model`\n"
+ "→ Or resend your message (your conversation history is preserved)",
+ "Model output entered a repetition loop; refusing to return a degenerate response.",
+)
logger = logging.getLogger("agent.conversation_loop")
@@ -51,6 +62,7 @@ def finish_text_response(
_preflight_compression_blocked: Any, codex_ack_continuations: Any,
truncated_response_parts: Any, length_continue_retries: Any,
_pending_verification_response: Any, _pending_verification_response_previewed: Any,
+ effective_task_id: Any = None,
) -> FinalResponseVerdict:
"""Finish (or defer) a text-only assistant response in the original guard order. Every
continuation path sets ``final_response = None`` so an acknowledgment never suppresses
@@ -243,6 +255,16 @@ def finish_text_response(
final_response = agent._strip_think_blocks(final_response).strip()
+ # A provider may end a degenerate loop normally with finish_reason="stop" instead of
+ # exhausting its output cap (#100716). Check every completed visible text response before
+ # any verify/kanban interim emission or durable transcript write.
+ if final_response and is_repetition_dominated(final_response):
+ line, user_response, error = _REPETITION_STOPPED
+ agent._vprint(f"{agent.log_prefix}{line}", force=True)
+ agent._cleanup_task_resources(effective_task_id)
+ agent._persist_session(messages, conversation_history)
+ return _verdict("return", partial_result(messages, api_call_count, user_response, error))
+
final_msg = agent._build_assistant_message(assistant_message, finish_reason)
if _promoted:
# Replay sidecar only: ``content`` stays empty so the row is never mistaken for a
diff --git a/tests/agent/test_continuation_repetition_guard.py b/tests/agent/test_continuation_repetition_guard.py
index 0fd2c5a0ce7..6a2983f11d1 100644
--- a/tests/agent/test_continuation_repetition_guard.py
+++ b/tests/agent/test_continuation_repetition_guard.py
@@ -1,10 +1,8 @@
-"""Regression tests for the truncated-response repetition guard (#86581).
+"""Regression tests for repetition-dominated response handling.
-A truncated response (``finish_reason=length``) dominated by verbatim
-repeated text must NOT be continued: the continuation nudge would stitch the
-pathological fragment into the final response (the #86581 incident delivered
-60,698 chars as 31 Discord messages). The turn aborts with a clear
-user-facing error instead, mirroring the existing thinking-budget guard.
+A response dominated by verbatim repeated text must be discarded whether it
+ends normally or at the output cap. The turn aborts with a clear user-facing
+error instead of persisting and delivering the pathological fragment.
"""
from __future__ import annotations
@@ -44,21 +42,30 @@ def loop_agent():
return a
-def _stub(content):
+def _response(
+ content,
+ *,
+ finish_reason=FINISH_REASON_LENGTH,
+ response_id=PARTIAL_STREAM_STUB_ID,
+):
from tests.agent.test_run_agent import _mock_assistant_msg
return SimpleNamespace(
- id=PARTIAL_STREAM_STUB_ID,
+ id=response_id,
model="test/model",
choices=[SimpleNamespace(
index=0,
message=_mock_assistant_msg(content=content),
- finish_reason=FINISH_REASON_LENGTH,
+ finish_reason=finish_reason,
)],
usage=None,
)
+def _stub(content):
+ return _response(content)
+
+
def _run(agent, message):
with (
patch.object(agent, "_persist_session"),
@@ -86,6 +93,28 @@ class TestContinuationRepetitionGuard:
# Exactly one API call — no continuation was attempted.
assert loop_agent.client.chat.completions.create.call_count == 1
+ def test_repetition_dominated_stop_response_aborts(self, loop_agent):
+ paragraph = (
+ "A long paragraph that should never be delivered hundreds of times "
+ "when a model enters a repetition loop.\n"
+ "The second line makes this a multiline repeating unit.\n"
+ )
+ echo = paragraph * 500
+ loop_agent.client.chat.completions.create.side_effect = [
+ _response(echo, finish_reason="stop", response_id="completed-response")
+ ]
+
+ result = _run(loop_agent, "write me a long report")
+
+ assert result["completed"] is False
+ assert result["partial"] is True
+ assert "Repetition" in (result["final_response"] or "")
+ assert not any(
+ isinstance(m, dict) and m.get("content") == echo
+ for m in result["messages"]
+ )
+ assert loop_agent.client.chat.completions.create.call_count == 1
+
def test_legit_truncation_still_continues(self, loop_agent):
# Ordinary short truncated fragments still get continuation retries.
loop_agent.client.chat.completions.create.side_effect = [
diff --git a/tests/agent/test_repetition_guard.py b/tests/agent/test_repetition_guard.py
index 369ab213657..8495319c982 100644
--- a/tests/agent/test_repetition_guard.py
+++ b/tests/agent/test_repetition_guard.py
@@ -1,7 +1,9 @@
-"""Unit tests for the truncated-response repetition guard (issue #86581)."""
+"""Unit tests for repetition-dominated model output detection."""
from __future__ import annotations
+import random
+
from agent.repetition_guard import MIN_FRAGMENT_LENGTH, is_repetition_dominated
# The exact sentence from the #86581 incident (echoed hundreds of times by
@@ -21,6 +23,30 @@ class TestRepetitionGuard:
assert len(text) >= MIN_FRAGMENT_LENGTH
assert is_repetition_dominated(text) is True
+ def test_multiline_paragraph_run_uses_true_period_coverage(self):
+ rng = random.Random(11)
+ paragraph = "\n".join(
+ "".join(rng.choice("abcdefghijklmnopqrstuvwxyz ") for _ in range(151))
+ for _ in range(5)
+ ) + "\n"
+
+ # The incident unit was approximately 764 characters. Detection must
+ # remain scale-free as the number of exact repeats grows.
+ for repeat_count in (100, 1_000, 10_000):
+ assert is_repetition_dominated(paragraph * repeat_count) is True
+
+ def test_dominant_run_with_unique_prefix_and_suffix_flags(self):
+ paragraph = (
+ "A deliberately long repeated paragraph has enough distinct text "
+ "to make its period exceed the guard's minimum anchor length.\n"
+ "It also spans multiple lines, matching the real incident shape.\n"
+ )
+ repeated = paragraph * 20
+ text = ("unique introduction " * 20) + repeated + (" unique ending" * 20)
+
+ assert len(repeated) > len(text) * 0.5
+ assert is_repetition_dominated(text) is True
+
def test_long_legitimate_text_not_flagged(self):
# Long, unique prose — no 60-char window ever repeats.
text = " ".join(