Skip to content

The agent that grows with you

fix(gemini): resume a dropped long-decode stream from its last checkpoint

Teknium121aee41b6a6
diff --git a/agent/gemini_long_decode.py b/agent/gemini_long_decode.py
index ef540a2a0ac..d78c725515c 100644
--- a/agent/gemini_long_decode.py
+++ b/agent/gemini_long_decode.py
@@ -6,7 +6,8 @@ Gemini 4 caps each request (32,768 tokens unary, 65,536 streamed) but lets ``max
that token (never the partial output) until any other finish reason. Each hop re-reads the prompt plus
everything generated so far, so per-hop ``promptTokenCount`` grows: usage is summed for billing (what
the google-genai SDK reports and Google bills) while the first hop's prompt is kept as the context size,
-because compaction fed the summed prompt would fire far too early.
+because compaction fed the summed prompt would fire far too early. A dropped stream resumes from its
+last checkpoint token rather than restarting (Google bills a dropped stream up to that checkpoint).
Docs: https://ai.google.dev/gemini-api/docs/generate-content/long-decode
"""
@@ -61,18 +62,21 @@ def merge_hop_responses(hops: list[dict[str, Any]]) -> dict[str, Any]:
def split_stream_continuation(event: dict[str, Any], hop_usage: list[dict[str, Any]]) -> tuple[dict[str, Any], Optional[str]]:
- """``(event to translate, token)`` for one SSE event of a possibly multi-hop stream.
+ """``(event to translate, token to resend with if the stream ends here)`` for one SSE event.
A CONTINUATION finish is not the end: its finish reason and (per-stream cumulative) usage are
held back in ``hop_usage`` and the token returned for the next hop. The real final event gets
- the usage summed over every hop. Mid-stream checkpoint tokens are ignored: a dropped stream is
- retried from the start by the caller, which is always valid (resuming is a cost optimisation).
+ the usage summed over every hop. A token on an event with no finish is a mid-stream checkpoint
+ (every ~5K tokens past 32K): it commits that event and everything before it, so the caller resumes
+ a dropped stream by resending the request with it; a drop with no clean checkpoint restarts.
"""
token = continuation_token(event)
if token:
hop_usage.append(event.get("usageMetadata") or {})
cand = {k: v for k, v in _candidate(event).items() if k not in ("finishReason", "continuationToken")}
return {k: v for k, v in event.items() if k != "usageMetadata"} | {"candidates": [cand]}, token
- if hop_usage and _candidate(event).get("finishReason"):
+ cand = _candidate(event)
+ if hop_usage and cand.get("finishReason"):
return {**event, "usageMetadata": merge_hop_usage([*hop_usage, event.get("usageMetadata") or {}])}, None
- return event, None
+ checkpoint = None if cand.get("finishReason") else cand.get("continuationToken")
+ return event, checkpoint if isinstance(checkpoint, str) and checkpoint else None
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index 24287e022ee..9376bf7e3d5 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -80,6 +80,7 @@ _INTERRUPTED_RESPONSE_PLACEHOLDER = "[The previous response was interrupted befo
# without this sentinel Gemini 3 thinking models reject replayed history with 400 INVALID_ARGUMENT.
_SKIP_SIGNATURE = "skip_thought_signature_validator"
_END = object() # stream-exhausted marker for _advance_stream_iterator
+_MAX_TOKEN_SENDS = 3 # requests one long-decode token may ride, so a network that keeps dropping ends in an error
_TOOL_CHOICE_MODES = {"auto": "AUTO", "required": "ANY", "none": "NONE"}
_FINISH_REASON_MAP = {
"STOP": "stop", "MAX_TOKENS": "length", "SAFETY": "content_filter", "RECITATION": "content_filter", "OTHER": "stop",
@@ -925,21 +926,29 @@ class GeminiNativeClient:
def _stream_completion(self, model: str, url: str, request: dict[str, Any], timeout: Any) -> Iterator[_GeminiStreamChunk]:
tool_call_indices: dict[str, dict[str, Any]] = {} # shared across hops: they form one model turn
hop_usage: list[dict[str, Any]] = []
- body: Optional[dict[str, Any]] = request
- try:
- while body is not None:
+ body: dict[str, Any] = request
+ # ``resume``: the latest token (hop end or mid-stream checkpoint) with nothing yielded after it.
+ # The next hop, or a dropped stream, resends the request with it; ``sends`` bounds a stuck token.
+ resume, sends = None, 0
+ while True:
+ try:
headers = {**self._headers(), "Accept": "text/event-stream"}
with self._http.stream("POST", url, json=body, headers=headers, timeout=timeout) as response:
if response.status_code != 200:
raise self._http_error(response, read_streaming_error_body(response))
- body = None
for event in _iter_sse_events(response):
event, token = split_stream_continuation(event, hop_usage)
- if token:
- body = {**request, "continuationToken": token}
- yield from translate_stream_event(event, model, tool_call_indices)
- except httpx.HTTPError as exc:
- raise GeminiAPIError(f"Gemini streaming request failed: {exc}", code="gemini_stream_error") from exc
+ chunks = translate_stream_event(event, model, tool_call_indices)
+ if token or chunks: # a token commits its own event's chunks; a later chunk voids it
+ resume, sends = token, 0 if token else sends
+ yield from chunks
+ except httpx.HTTPError as exc:
+ if not resume or sends >= _MAX_TOKEN_SENDS: # nothing committed to resume from: retry from the start
+ raise GeminiAPIError(f"Gemini streaming request failed: {exc}", code="gemini_stream_error") from exc
+ logger.warning("Gemini stream dropped (%s); resuming from its last checkpoint", exc)
+ if not resume or sends >= _MAX_TOKEN_SENDS:
+ return
+ body, sends = {**request, "continuationToken": resume}, sends + 1
class AsyncGeminiNativeClient:
diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.py
index c9a8b1a41f8..8069601ea29 100644
--- a/tests/agent/test_gemini_native_adapter.py
+++ b/tests/agent/test_gemini_native_adapter.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from types import SimpleNamespace
+import httpx
import pytest
@@ -977,3 +978,73 @@ def test_long_decode_continues_across_hops_and_reports_first_hop_prompt(monkeypa
assert [c.choices[0].finish_reason for c in finishes] == ["stop"] # CONTINUATION is not the end
assert "".join(c.choices[0].delta.content or "" for c in chunks) == "part one part two"
assert (finishes[0].usage.prompt_tokens, finishes[0].usage.initial_prompt_tokens) == (32968, 100)
+
+
+def _scripted_stream_client(monkeypatch, streams):
+ """A GeminiNativeClient whose Nth stream yields ``streams[N]``: event dicts, then httpx drops on ``"DROP"``."""
+ from agent.gemini_native_adapter import GeminiNativeClient
+
+ sent = []
+
+ class _Stream:
+ status_code = 200
+
+ def __init__(self, script):
+ self._script = script
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def iter_text(self):
+ for item in self._script:
+ if item == "DROP":
+ raise httpx.RemoteProtocolError("peer closed connection without sending complete message body")
+ yield f"data: {json.dumps(item)}\n\n"
+
+ class DummyHTTP:
+ def stream(self, method, url, json=None, headers=None, timeout=None):
+ sent.append(json)
+ return _Stream(streams[min(len(sent), len(streams)) - 1])
+
+ def close(self):
+ return None
+
+ monkeypatch.setattr("agent.gemini_native_adapter.httpx.Client", lambda *a, **k: DummyHTTP())
+ client = GeminiNativeClient(api_key="AQ.test", base_url="https://generativelanguage.googleapis.com/v1beta")
+ kwargs = {"model": "gemini-4-argon", "messages": [{"role": "user", "content": "count"}], "stream": True}
+ return client, kwargs, sent
+
+
+def _ld_event(text, token=None, finish=None):
+ cand = {"content": {"role": "model", "parts": [{"text": text}]}}
+ return {"candidates": [{**cand, **({"continuationToken": token} if token else {}), **({"finishReason": finish} if finish else {})}]}
+
+
+def test_dropped_long_decode_stream_resumes_from_its_last_checkpoint(monkeypatch):
+ """Past 32K a stream checkpoints every ~5K tokens (the token rides the event whose text it commits).
+ A drop after a checkpoint resends the SAME request plus that token: no restart, no duplicated text."""
+ streams = [[_ld_event("1\n"), _ld_event("2\n", token="ckpt-2"), "DROP"], [_ld_event("3\n", finish="STOP")]]
+ client, kwargs, sent = _scripted_stream_client(monkeypatch, streams)
+
+ chunks = list(client.chat.completions.create(**kwargs))
+ assert sent[1] == {**sent[0], "continuationToken": "ckpt-2"}
+ assert "".join(c.choices[0].delta.content or "" for c in chunks) == "1\n2\n3\n"
+ assert [c.choices[0].finish_reason for c in chunks if c.choices[0].finish_reason] == ["stop"]
+
+
[email protected]("streams, requests", [
+ ([[_ld_event("1\n"), "DROP"]], 1), # before the first checkpoint: nothing to resume from
+ ([[_ld_event("1\n", token="ckpt-1"), _ld_event("2\n"), "DROP"]], 1), # "2" was shown but not committed
+ ([[_ld_event("1\n", token="ckpt-1"), "DROP"], ["DROP"]], 4), # bounded: one token rides at most 3 resends
+])
+def test_dropped_stream_without_a_clean_checkpoint_raises(monkeypatch, streams, requests):
+ from agent.gemini_native_adapter import GeminiAPIError
+
+ client, kwargs, sent = _scripted_stream_client(monkeypatch, streams)
+ with pytest.raises(GeminiAPIError) as excinfo:
+ list(client.chat.completions.create(**kwargs))
+ assert excinfo.value.code == "gemini_stream_error"
+ assert len(sent) == requests