Skip to content

The agent that grows with you

refactor(agent/stream_diag,repetition_guard,thread_scoped_output,stream_single_writer): compact loops and docstrings

Teknium6fe8f9e76ce6
diff --git a/agent/repetition_guard.py b/agent/repetition_guard.py
index c84f5dec371..ea6f1e27326 100644
--- a/agent/repetition_guard.py
+++ b/agent/repetition_guard.py
@@ -1,15 +1,12 @@
"""Cheap content-sanity checks for the truncated-response continuation path.
-A model in a degenerate repetition loop can spend its ENTIRE output budget
-echoing one fragment; the ``finish_reason=length`` continuation path would
-then stitch that fragment into the final response with a "continue" nudge
-(one incident: a 60k-char turn delivered as 31 Discord messages). These
-helpers detect repetition-dominated fragments BEFORE the nudge so the turn
-aborts with a clear error (like the ``_thinking_exhausted`` guard).
-
-Deliberately conservative: only LONG verbatim repeats (60+ chars) covering a
-majority of the fragment trip the guard, so ordinary truncations (a sentence
-cut mid-word, a repeated heading, similar code lines) are never blocked.
+A model in a degenerate repetition loop can spend its ENTIRE output budget echoing one
+fragment; the ``finish_reason=length`` continuation path would then stitch that fragment
+into the final response with a "continue" nudge (one incident: a 60k-char turn delivered
+as 31 Discord messages). These helpers detect repetition-dominated fragments BEFORE the
+nudge so the turn aborts with a clear error. Deliberately conservative: only LONG verbatim
+repeats (60+ chars) covering a majority of the fragment trip the guard, so ordinary
+truncations (a sentence cut mid-word, a repeated heading, similar code lines) never do.
"""
from __future__ import annotations
@@ -19,39 +16,30 @@ import math
# Below this length the check doesn't run: short truncations trivially
# contain repeated tokens and are legitimately continued.
MIN_FRAGMENT_LENGTH = 400
-
-# Exact-repeat window; a verbatim repeat this long is far beyond ordinary
-# phrasing reuse (citations, headings, similar code).
+# Exact-repeat window; far beyond ordinary phrasing reuse (citations, headings, similar code).
_REPEAT_WINDOW = 60
-
# A window repeating at least this often is a signal even for short fragments.
_MIN_REPEAT_COUNT = 5
-
# "Repetition-dominated" = repeated windows cover at least this fraction.
_DOMINANCE_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, where
- continuing would only stitch in more repeats.
-
- Fail-open: False for non-string / empty / short inputs.
- """
+ """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."""
if not isinstance(text, str):
return False
n = len(text)
if n < MIN_FRAGMENT_LENGTH:
return False
- # Fast path: one normalized line duplicated enough to cover half the
- # fragment (the most common echo shape). Cheap, no big allocations.
+ # Fast path: one normalized line duplicated enough to cover half the fragment (the common echo shape).
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).
+ # 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).
window = _REPEAT_WINDOW
needed = max(_MIN_REPEAT_COUNT, math.ceil(n * _DOMINANCE_RATIO / window))
counts: dict[str, int] = {}
diff --git a/agent/stream_diag.py b/agent/stream_diag.py
index 61733afc227..f75e6a0ceaf 100644
--- a/agent/stream_diag.py
+++ b/agent/stream_diag.py
@@ -17,16 +17,8 @@ logger = logging.getLogger(__name__)
# Lowercased upstream headers captured per attempt for post-hoc analysis.
STREAM_DIAG_HEADERS = (
- "cf-ray",
- "cf-cache-status",
- "x-openrouter-provider",
- "x-openrouter-model",
- "x-openrouter-id",
- "x-request-id",
- "x-vercel-id",
- "via",
- "server",
- "x-forwarded-for",
+ "cf-ray", "cf-cache-status", "x-openrouter-provider", "x-openrouter-model", "x-openrouter-id",
+ "x-request-id", "x-vercel-id", "via", "server", "x-forwarded-for",
)
@@ -75,9 +67,7 @@ def flatten_exception_chain(error: BaseException) -> str:
"""
seen: List[BaseException] = []
link: Optional[BaseException] = error
- while link is not None and len(seen) < 4:
- if link in seen:
- break
+ while link is not None and len(seen) < 4 and link not in seen:
seen.append(link)
nxt = getattr(link, "__cause__", None) or getattr(link, "__context__", None)
if nxt is None or nxt is link:
@@ -104,10 +94,9 @@ def log_stream_retry(
) -> None:
"""Structured WARNING to ``agent.log`` for a transient stream drop + retry.
- Always logged regardless of UI verbosity (subagent retries no longer spam the
- parent's terminal but keep full detail here). With *diag*, also records upstream
- headers, HTTP status, bytes/chunks streamed, elapsed and TTFB on the dying attempt —
- enough to tell "one CF edge / downstream provider" from "random across runs".
+ Always logged regardless of UI verbosity. With *diag*, also records upstream headers,
+ HTTP status, bytes/chunks streamed, elapsed and TTFB on the dying attempt — enough to
+ tell "one CF edge / downstream provider" from "random across runs".
"""
try:
try:
@@ -122,12 +111,10 @@ def log_stream_retry(
_chain = type(error).__name__
_now = time.time()
- _bytes = 0
- _chunks = 0
+ _bytes = _chunks = 0
_elapsed = 0.0
_ttfb = None
- _headers_repr = "-"
- _http_status = "-"
+ _headers_repr = _http_status = "-"
if isinstance(diag, dict):
try:
_bytes = int(diag.get("bytes") or 0)
@@ -152,20 +139,13 @@ def log_stream_retry(
"chain=%s "
"http_status=%s bytes=%d chunks=%d elapsed=%.2fs ttfb=%s "
"upstream=[%s]",
- kind,
- attempt,
- max_attempts,
+ kind, attempt, max_attempts,
getattr(agent, "_subagent_id", None) or "-",
getattr(agent, "_delegate_depth", 0),
agent.provider or "-",
agent.base_url or "-",
- type(error).__name__,
- _summary,
- _chain,
- _http_status,
- _bytes,
- _chunks,
- _elapsed,
+ type(error).__name__, _summary, _chain,
+ _http_status, _bytes, _chunks, _elapsed,
f"{_ttfb:.2f}s" if _ttfb is not None else "-",
_headers_repr,
extra={"mid_tool_call": mid_tool_call},
diff --git a/agent/stream_single_writer.py b/agent/stream_single_writer.py
index 52907f28a5e..e59ca78e26f 100644
--- a/agent/stream_single_writer.py
+++ b/agent/stream_single_writer.py
@@ -1,11 +1,11 @@
"""Best-effort accessors for the single-writer stream fence.
The fence lives on ``AIAgent`` (``_claim_stream_writer`` / ``_stream_writer_is_current``)
-but is used from other streaming modules. Calling it directly would turn an
-*additive* safety net into a fatal AttributeError on a partially-updated checkout,
-hot-reloaded gateway, duck-typed agent, or test double (a cron job died this way).
-The fence may only drop a *provably* superseded stream, never the sole writer, so
-when it is unavailable or raises the correct degradation is "no fence": keep streaming.
+but is used from other streaming modules. Calling it directly would turn an *additive*
+safety net into a fatal AttributeError on a partially-updated checkout, hot-reloaded
+gateway, duck-typed agent, or test double (a cron job died this way). The fence may only
+drop a *provably* superseded stream, never the sole writer, so when it is unavailable or
+raises the correct degradation is "no fence": keep streaming.
"""
from __future__ import annotations
@@ -29,9 +29,7 @@ def claim_stream_writer(agent: Any) -> int:
def stream_writer_is_current(agent: Any, token: int) -> bool:
"""True when ``token`` is still the active writer; a falsy token or a fence-less agent cannot prove supersession, so True."""
- if not token:
- return True
- is_current = getattr(agent, "_stream_writer_is_current", None)
+ is_current = getattr(agent, "_stream_writer_is_current", None) if token else None
if callable(is_current):
try:
return bool(is_current(token))
diff --git a/agent/thread_scoped_output.py b/agent/thread_scoped_output.py
index bbbb24f3ae2..56322a9f1d1 100644
--- a/agent/thread_scoped_output.py
+++ b/agent/thread_scoped_output.py
@@ -1,11 +1,10 @@
"""Thread-scoped stdout/stderr silencing for background worker threads.
-``contextlib.redirect_stdout`` reassigns the *process-global* stream, so a
-daemon worker silencing itself also silences every other thread (gateway
-event loop included) for the duration. This module installs a per-thread
-routing proxy as ``sys.stdout``/``sys.stderr``: silenced threads write to a
-sink, everyone else passes through to the original stream. Installed once,
-idempotently, and never uninstalled (that would race other threads mid-write).
+``contextlib.redirect_stdout`` reassigns the *process-global* stream, so a daemon worker
+silencing itself also silences every other thread (gateway event loop included). This
+module installs a per-thread routing proxy as ``sys.stdout``/``sys.stderr``: silenced
+threads write to a sink, everyone else passes through to the original stream. Installed
+once, idempotently, and never uninstalled (that would race other threads mid-write).
"""
from __future__ import annotations
@@ -74,9 +73,8 @@ class _ThreadRoutingStream:
return None
def writelines(self, lines): # type: ignore[no-untyped-def]
- target = self._target()
try:
- return target.writelines(lines)
+ return self._target().writelines(lines)
except Exception:
return None
@@ -127,12 +125,14 @@ def _ensure_installed(attr: str, passthrough: TextIO) -> "_ThreadRoutingStream":
def thread_scoped_silence() -> Iterator[None]:
"""Silence ``stdout``/``stderr`` for the *current thread only*."""
ident = threading.get_ident()
- out_proxy = _ensure_installed("stdout", sys.__stdout__ or sys.stdout)
- err_proxy = _ensure_installed("stderr", sys.__stderr__ or sys.stderr)
- out_proxy.silence(ident)
- err_proxy.silence(ident)
+ proxies = (
+ _ensure_installed("stdout", sys.__stdout__ or sys.stdout),
+ _ensure_installed("stderr", sys.__stderr__ or sys.stderr),
+ )
+ for proxy in proxies:
+ proxy.silence(ident)
try:
yield
finally:
- out_proxy.unsilence(ident)
- err_proxy.unsilence(ident)
+ for proxy in proxies:
+ proxy.unsilence(ident)