Skip to content

Official Codebase of 3DCodeVerse

Python

models: gemini goes streaming with stall detection, and the transport goes IPv4

gaoypeng24991208496e
diff --git a/harness/codeverse/models/gemini.py b/harness/codeverse/models/gemini.py
index 939a5204..aa014ef9 100644
--- a/harness/codeverse/models/gemini.py
+++ b/harness/codeverse/models/gemini.py
@@ -9,10 +9,11 @@ from __future__ import annotations
import io
import json
import logging
+import os
import re
import threading
import time
-from collections.abc import Callable, Sequence
+from collections.abc import Callable, Iterable, Sequence
from pathlib import Path
from typing import Any, Protocol, runtime_checkable
@@ -297,6 +298,17 @@ _RETRY_DELAY_RE = re.compile(r"retryDelay['\"]?\s*:\s*['\"]?(\d+(?:\.\d+)?)s")
#: when that ceiling was 300 s).
HTTP_TIMEOUT_FLOOR_S = 20.0
+#: ceiling of the per-READ (inter-chunk) HTTP timeout under streaming. Five runs
+#: died tonight (drill/vise/clamp x2, one plan hang) because a hung NON-streaming
+#: read holds the socket for the whole attempt budget — up to model_timeout_s
+#: (1200 s) — and the timeout is then terminal. Streaming separates the two
+#: cases: a hung socket delivers no chunk and dies within this ceiling with the
+#: rest of the retry budget intact, while a legitimate 930 s plan streams tokens
+#: continuously (145 tok/s p50, audit 2026-08-27) and is bounded only by its
+#: attempt budget. Generous vs the longest silent prefix we allow for thinking
+#: before the first chunk. ``CV3D_STREAM=0`` restores the buffered call.
+STREAM_STALL_S = 300.0
+
_pools: dict[tuple[str, ...], KeyPool] = {}
_clients: dict[tuple[str, int], genai.Client] = {}
_registry_lock = threading.Lock()
@@ -412,6 +424,78 @@ def _retry_after_s(exc: BaseException) -> float | None:
return min(float(m.group(1)), 120.0) if m else None
+def _ipv4_client_args() -> dict[str, Any]:
+ """Bind the sync transport to IPv4. Every one of tonight's five hung reads sat
+ on an IPv6 destination (2001:4860::/32) with the response headers never arriving
+ — the WSL2 IPv6 path drops these silently and a buffered read then holds the
+ socket for the whole attempt budget. ``CV3D_IPV4=0`` restores the default
+ (dual-stack) resolution."""
+ if os.environ.get("CV3D_IPV4", "1") == "0":
+ return {}
+ return {"transport": httpx.HTTPTransport(local_address="0.0.0.0")}
+
+
+def _streaming_enabled() -> bool:
+ return os.environ.get("CV3D_STREAM", "1") != "0"
+
+
+def _drain_stream(
+ it: Iterable[types.GenerateContentResponse],
+ deadline: float,
+ clock: Callable[[], float] = time.monotonic,
+) -> list[types.GenerateContentResponse]:
+ """Collect every chunk, enforcing the ATTEMPT budget between chunks. The wire
+ timeout under streaming only bounds the silence BETWEEN chunks (httpx applies
+ the read timeout per network read), so a healthy-but-endless stream is cut
+ here instead. Tokens generated before the cut were billed but cannot be
+ counted: usage_metadata only arrives on the final chunk."""
+ chunks: list[types.GenerateContentResponse] = []
+ for ch in it:
+ chunks.append(ch)
+ if clock() > deadline:
+ raise ModelError(
+ f"Gemini stream exceeded its attempt budget after {len(chunks)} chunks",
+ retryable=True,
+ )
+ return chunks
+
+
+def _merge_stream_chunks(
+ chunks: list[types.GenerateContentResponse],
+) -> types.GenerateContentResponse:
+ """One response out of a chunk sequence: parts concatenate in arrival order;
+ finish_reason, usage_metadata and prompt_feedback come from the last chunk
+ that carries each (usage is cumulative and final-chunk-only on this API)."""
+ if not chunks:
+ raise ModelError("Gemini stream yielded no chunks", retryable=True)
+ parts: list[types.Part] = []
+ finish = None
+ usage_md = None
+ feedback = None
+ base = None
+ for ch in chunks:
+ if ch.usage_metadata is not None:
+ usage_md = ch.usage_metadata
+ if ch.prompt_feedback is not None and ch.prompt_feedback.block_reason:
+ feedback = ch.prompt_feedback
+ if ch.candidates:
+ base = ch
+ cand = ch.candidates[0]
+ if cand.content and cand.content.parts:
+ parts.extend(cand.content.parts)
+ if cand.finish_reason is not None:
+ finish = cand.finish_reason
+ if base is None: # no chunk carried a candidate: let extract_candidate raise its way
+ base = chunks[-1]
+ else:
+ base.candidates[0].content = types.Content(role="model", parts=parts)
+ base.candidates[0].finish_reason = finish
+ base.usage_metadata = usage_md
+ if feedback is not None:
+ base.prompt_feedback = feedback
+ return base
+
+
class GeminiModel:
"""ChatModel for ``gemini:<model>``. See module docstring."""
@@ -477,7 +561,8 @@ class GeminiModel:
with _registry_lock:
client = _clients.get(ck)
if client is None:
- client = genai.Client(api_key=key, http_options=types.HttpOptions(timeout=ck[1]))
+ client = genai.Client(api_key=key, http_options=types.HttpOptions(
+ timeout=ck[1], client_args=_ipv4_client_args() or None))
_clients[ck] = client
return client
@@ -597,10 +682,28 @@ class GeminiModel:
warnings: list[str],
) -> ChatResponse:
client = self._client(key)
- with Stopwatch() as sw:
- resp = client.models.generate_content(
- model=self.model, contents=contents, config=config
- )
+ if not _streaming_enabled():
+ with Stopwatch() as sw:
+ resp = client.models.generate_content(
+ model=self.model, contents=contents, config=config
+ )
+ else:
+ # the attempt budget (what _attempt_config put on the wire for the
+ # buffered call) becomes an in-loop deadline; the wire timeout drops
+ # to the stall ceiling, which under streaming bounds only the gap
+ # between chunks. A hung socket now costs <=STREAM_STALL_S of the
+ # retry budget instead of all of it.
+ cfg_ms = config.http_options.timeout if config.http_options is not None else None
+ attempt_s = (float(cfg_ms) / 1000.0) if cfg_ms else self.timeout_s
+ wire = clip_timeout(config, int(min(attempt_s, STREAM_STALL_S) * 1000))
+ with Stopwatch() as sw:
+ chunks = _drain_stream(
+ client.models.generate_content_stream(
+ model=self.model, contents=contents, config=wire
+ ),
+ time.monotonic() + attempt_s,
+ )
+ resp = _merge_stream_chunks(chunks)
usage = parse_usage(resp, self.model) # BEFORE extract_candidate: its raises carry it
usage.latency_ms = sw.ms
usage.cost_usd = estimate_cost("gemini", self.model, usage)
diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.py
index 1ebf01de..40964ab5 100644
--- a/harness/codeverse/tracks/plan_features.py
+++ b/harness/codeverse/tracks/plan_features.py
@@ -76,6 +76,11 @@ LIVE_SWITCHES: dict[str, str] = {
# switch, read at call time by config.fewer_turns_enabled; acts after planning.
"CV3D_FEWER_TURNS": "codeverse/config.py",
"CV3D_SEED_RECIPES": "codeverse/config.py",
+ # model-transport switches (2026-08-28, the hung-read waves): streaming with
+ # inter-chunk stall detection, and the IPv4-only transport. Read at call time
+ # by every gemini request, so a control arm can set either to 0.
+ "CV3D_STREAM": "codeverse/models/gemini.py",
+ "CV3D_IPV4": "codeverse/models/gemini.py",
}
#: Switches that are DECLARED but read by no code path, with the reason. An A/B arm that
diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.py
index 4b03a1b8..c2a007a0 100644
--- a/harness/tests/cost/test_instrument.py
+++ b/harness/tests/cost/test_instrument.py
@@ -411,6 +411,9 @@ def test_a_hedge_losers_tokens_reach_the_ledger_when_it_lands(tmp_path: Path):
def __init__(self, key: str):
self.key, self.models = key, self
+ def generate_content_stream(self, **kw):
+ yield self.generate_content(**kw)
+
def generate_content(self, *, model, contents, config):
if self.key == "k1":
raise ModelError("503 high demand", retryable=True, status=503)
diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.py
index 96261c13..125cc5d4 100644
--- a/harness/tests/models/test_gemini.py
+++ b/harness/tests/models/test_gemini.py
@@ -85,6 +85,9 @@ class FakeModels:
raise item
return item
+ def generate_content_stream(self, *, model: str, contents, config):
+ yield self.generate_content(model=model, contents=contents, config=config)
+
class FakeClient:
def __init__(self, script, key, log):
@@ -219,6 +222,9 @@ class _KeyedClient:
raise self.fail[self.key]
return text_response(f"ok from {self.key}")
+ def generate_content_stream(self, *, model: str, contents, config):
+ yield self.generate_content(model=model, contents=contents, config=config)
+
def _keyed_model(
keys: list[str], fail: dict[str, BaseException], pool: KeyPool | None = None, **kw
@@ -628,3 +634,60 @@ def test_max_output_tokens_eaten_by_thinking_carries_the_thought_tokens():
assert "exhausted by thinking" in str(e.value)
assert e.value.usage.thoughts_tokens == 8000 and e.value.usage.cost_usd > 0
+
+
+# --------------------------------------------------------------------- streaming
+def test_merge_stream_chunks_reassembles_the_reply():
+ from codeverse.models.gemini import _merge_stream_chunks, extract_candidate
+
+ c1 = types.GenerateContentResponse(
+ candidates=[types.Candidate(content=types.Content(role="model", parts=[types.Part.from_text(text="hel")]))])
+ c2 = types.GenerateContentResponse(
+ candidates=[types.Candidate(content=types.Content(role="model", parts=[types.Part.from_text(text="lo")]),
+ finish_reason="STOP")],
+ usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=5, candidates_token_count=2))
+ merged = _merge_stream_chunks([c1, c2])
+ text, calls, finish = extract_candidate(merged)
+ assert (text, calls, finish) == ("hello", [], "STOP")
+ assert merged.usage_metadata.prompt_token_count == 5
+
+
+def test_merge_stream_chunks_empty_stream_is_retryable():
+ from codeverse.models.gemini import _merge_stream_chunks
+
+ with pytest.raises(ModelError) as e:
+ _merge_stream_chunks([])
+ assert e.value.retryable
+
+
+def test_drain_stream_cuts_a_stream_past_its_attempt_budget():
+ """The wire timeout under streaming bounds only inter-chunk silence, so a
+ healthy-but-endless stream must be cut by the attempt deadline instead."""
+ from codeverse.models.gemini import _drain_stream
+
+ ticks = iter([1.0, 10.0, 20.0])
+ chunk = types.GenerateContentResponse(candidates=[])
+ with pytest.raises(ModelError) as e:
+ _drain_stream(iter([chunk, chunk, chunk]), deadline=5.0, clock=lambda: next(ticks))
+ assert e.value.retryable and "attempt budget" in str(e.value)
+
+
+def test_streaming_toggle(monkeypatch):
+ from codeverse.models.gemini import _streaming_enabled
+
+ monkeypatch.delenv("CV3D_STREAM", raising=False)
+ assert _streaming_enabled()
+ monkeypatch.setenv("CV3D_STREAM", "0")
+ assert not _streaming_enabled()
+
+
+def test_ipv4_transport_toggle(monkeypatch):
+ import httpx
+
+ from codeverse.models.gemini import _ipv4_client_args
+
+ monkeypatch.delenv("CV3D_IPV4", raising=False)
+ args = _ipv4_client_args()
+ assert isinstance(args["transport"], httpx.HTTPTransport)
+ monkeypatch.setenv("CV3D_IPV4", "0")
+ assert _ipv4_client_args() == {}