Skip to content

The agent that grows with you

perf(stream): replace per-chunk repr() with delta-length byte estimate

teknium10034da2975c5
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index fac42cc3cf7..33d8452e75c 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -227,6 +227,53 @@ def _env_float(name: str, default: float) -> float:
return default
+def _estimate_chunk_bytes(chunk: Any) -> int:
+ """Cheap per-chunk size estimate for the stream diagnostic counters.
+
+ The previous implementation used ``len(repr(chunk))`` — a full recursive
+ repr of a pydantic model on EVERY streaming chunk (5.5-8.8 µs each,
+ ~20-30 ms of pure CPU on a 3,000-chunk response, in the hottest loop in
+ the agent). The counter only feeds a retry-diagnostic log line, so an
+ estimate based on the delta payload lengths is plenty (2.1-2.4 µs, ~3x
+ cheaper, and independent of model/pydantic field count). Chat Completions
+ chunks are sized from their delta content/reasoning/tool-argument strings
+ plus a small framing constant; anything shape-unknown (Anthropic events,
+ stub providers) falls back to a flat constant so `bytes` stays monotonic
+ and roughly proportional to traffic.
+ """
+ size = 40 # SSE/JSON framing floor per chunk
+ try:
+ choices = getattr(chunk, "choices", None)
+ if choices:
+ delta = getattr(choices[0], "delta", None)
+ if delta is not None:
+ for attr in ("content", "reasoning_content", "reasoning"):
+ v = getattr(delta, attr, None)
+ if isinstance(v, str):
+ size += len(v)
+ tool_calls = getattr(delta, "tool_calls", None)
+ if tool_calls:
+ for tc in tool_calls:
+ fn = getattr(tc, "function", None)
+ if fn is not None:
+ args = getattr(fn, "arguments", None)
+ if isinstance(args, str):
+ size += len(args)
+ name = getattr(fn, "name", None)
+ if isinstance(name, str):
+ size += len(name)
+ else:
+ # Non-chat-completions shapes (Anthropic events etc.): try the
+ # common text fields, else keep the framing floor.
+ for attr in ("text", "partial_json"):
+ v = getattr(getattr(chunk, "delta", None), attr, None)
+ if isinstance(v, str):
+ size += len(v)
+ except Exception:
+ pass
+ return size
+
+
def _codex_wait_notice_recovery(
*,
stale_timeout: float,
@@ -3108,12 +3155,13 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
_diag["chunks"] = int(_diag.get("chunks", 0)) + 1
if _diag.get("first_chunk_at") is None:
_diag["first_chunk_at"] = last_chunk_time["t"]
- # Approximate byte size from the chunk's repr — exact wire
- # bytes aren't exposed by the SDK, but len(repr(chunk)) is
- # a stable proxy for "how much content arrived" that
- # survives stub provider differences.
+ # Approximate byte size from the chunk's delta payload —
+ # exact wire bytes aren't exposed by the SDK. A full
+ # repr() per chunk was 5.5-8.8 µs of pure CPU on the
+ # hottest loop in the agent; the delta-length estimate
+ # is ~3x cheaper and stays proportional to traffic.
try:
- _diag["bytes"] = int(_diag.get("bytes", 0)) + len(repr(chunk))
+ _diag["bytes"] = int(_diag.get("bytes", 0)) + _estimate_chunk_bytes(chunk)
except Exception:
pass
except Exception:
@@ -3554,7 +3602,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
_diag["chunks"] = int(_diag.get("chunks", 0)) + 1
if _diag.get("first_chunk_at") is None:
_diag["first_chunk_at"] = last_chunk_time["t"]
- _diag["bytes"] = int(_diag.get("bytes", 0)) + len(repr(event))
+ _diag["bytes"] = int(_diag.get("bytes", 0)) + _estimate_chunk_bytes(event)
except Exception:
pass
if agent._interrupt_requested:
diff --git a/tests/agent/test_stream_chunk_byte_estimate.py b/tests/agent/test_stream_chunk_byte_estimate.py
new file mode 100644
index 00000000000..fd53adc0035
--- /dev/null
+++ b/tests/agent/test_stream_chunk_byte_estimate.py
@@ -0,0 +1,88 @@
+"""Tests for _estimate_chunk_bytes — the cheap per-chunk stream size proxy.
+
+Replaced ``len(repr(chunk))`` in the streaming hot loop. Contract:
+- proportional to delta payload length (content, reasoning, tool args);
+- never raises on unknown shapes (returns the framing floor);
+- monotonic accumulation stays positive.
+"""
+
+from openai.types.chat import ChatCompletionChunk
+from openai.types.chat.chat_completion_chunk import (
+ Choice,
+ ChoiceDelta,
+ ChoiceDeltaToolCall,
+ ChoiceDeltaToolCallFunction,
+)
+
+from agent.chat_completion_helpers import _estimate_chunk_bytes
+
+
+def _chunk(delta):
+ return ChatCompletionChunk(
+ id="chatcmpl-1",
+ created=1730000000,
+ model="m",
+ object="chat.completion.chunk",
+ choices=[Choice(index=0, delta=delta, finish_reason=None)],
+ )
+
+
+def test_content_chunk_scales_with_payload():
+ small = _estimate_chunk_bytes(_chunk(ChoiceDelta(content="hi")))
+ large = _estimate_chunk_bytes(_chunk(ChoiceDelta(content="x" * 500)))
+ assert large - small == 498
+ assert small > 0
+
+
+def test_reasoning_content_counted():
+ base = _estimate_chunk_bytes(_chunk(ChoiceDelta()))
+
+ class Delta:
+ content = None
+ reasoning_content = "thinking..."
+ reasoning = None
+ tool_calls = None
+
+ class Choice0:
+ delta = Delta()
+
+ class Chunk:
+ choices = [Choice0()]
+
+ assert _estimate_chunk_bytes(Chunk()) == base + len("thinking...")
+
+
+def test_tool_call_arguments_counted():
+ delta = ChoiceDelta(
+ tool_calls=[
+ ChoiceDeltaToolCall(
+ index=0,
+ function=ChoiceDeltaToolCallFunction(
+ arguments='{"path": "/tmp/file"}', name="read_file"
+ ),
+ )
+ ]
+ )
+ est = _estimate_chunk_bytes(_chunk(delta))
+ assert est >= 40 + len('{"path": "/tmp/file"}') + len("read_file")
+
+
+def test_unknown_shape_returns_floor_never_raises():
+ class Weird:
+ pass
+
+ assert _estimate_chunk_bytes(Weird()) == 40
+ assert _estimate_chunk_bytes(None) == 40
+ assert _estimate_chunk_bytes(object()) == 40
+
+
+def test_anthropic_style_event_text_counted():
+ class Delta:
+ text = "anthropic text delta"
+ partial_json = None
+
+ class Event:
+ choices = None
+ delta = Delta()
+
+ assert _estimate_chunk_bytes(Event()) == 40 + len("anthropic text delta")