Skip to content

The agent that grows with you

fix(gemini): bound long decode by hops; scale the non-stream stale budget; first-hop context buckets

kshitijk4poore6370f400463
diff --git a/agent/gemini_long_decode.py b/agent/gemini_long_decode.py
index d78c725515c..440457cb9b7 100644
--- a/agent/gemini_long_decode.py
+++ b/agent/gemini_long_decode.py
@@ -18,6 +18,8 @@ from typing import Any, Optional
# Effort above ``high`` (Gemini 4's top thinkingLevel) buys a larger total thinking+output budget.
# 262,144 is Google's starting point for hard reasoning; the API caps 1,048,576 at the window minus input.
_LONG_DECODE_BUDGETS = {"xhigh": 262_144, "max": 1_048_576, "ultra": 1_048_576}
+# Smallest per-request cap (unary; streamed hops get 65,536): hop counts derived from it are upper bounds.
+_HOP_TOKENS = 32_768
_USAGE_COUNT_KEYS = (
"promptTokenCount", "cachedContentTokenCount", "candidatesTokenCount", "thoughtsTokenCount",
"toolUsePromptTokenCount", "totalTokenCount",
@@ -32,6 +34,22 @@ def long_decode_max_output_tokens(model: str, reasoning_config: Any) -> Optional
return _LONG_DECODE_BUDGETS.get(str(reasoning_config.get("effort") or "").strip().lower())
+def long_decode_hops(max_output_tokens: Any) -> int:
+ """Most hops a request with this total budget can take; 1 when it fits one request. The stale
+ watchdog scales by it (one timer spans every unary hop) and the hop loops stop one past it, so a
+ server that keeps answering CONTINUATION can't bill forever."""
+ budget = max_output_tokens if isinstance(max_output_tokens, int) and not isinstance(max_output_tokens, bool) else 0
+ return max(1, -(-budget // _HOP_TOKENS))
+
+
+def long_decode_stale_multiplier(api_payload: Any) -> int:
+ """Non-streaming stale budgets are one timer around every unary hop of a long decode: scale it by
+ the hop count so a healthy multi-hop answer isn't killed and re-billed from hop 1. The run-budget
+ cap still applies afterwards; streaming re-arms on every chunk and needs no scaling."""
+ extra = api_payload.get("extra_body") if isinstance(api_payload, dict) else None
+ return long_decode_hops(extra.get("max_output_tokens")) if isinstance(extra, dict) else 1
+
+
def _candidate(payload: dict[str, Any]) -> dict[str, Any]:
candidates = payload.get("candidates") if isinstance(payload, dict) else None
first = candidates[0] if isinstance(candidates, list) and candidates else None
@@ -48,7 +66,9 @@ def continuation_token(payload: dict[str, Any]) -> Optional[str]:
def merge_hop_usage(hops: list[dict[str, Any]]) -> dict[str, Any]:
"""Sum every count across hops; ``initialPromptTokenCount`` (the google-genai name) is hop 1's prompt."""
merged = {key: sum(int(h.get(key) or 0) for h in hops) for key in _USAGE_COUNT_KEYS if any(key in h for h in hops)}
- merged["initialPromptTokenCount"] = int(hops[0].get("promptTokenCount") or 0) if hops else 0
+ first = hops[0] if hops else {}
+ merged["initialPromptTokenCount"] = int(first.get("promptTokenCount") or 0)
+ merged["initialCachedContentTokenCount"] = int(first.get("cachedContentTokenCount") or 0)
return merged
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index 1a5f75c4145..1fc678700b1 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -20,7 +20,7 @@ from typing import Any, Dict, Iterator, List, Optional
import httpx
from agent.bounded_response import read_streaming_error_body
-from agent.gemini_long_decode import continuation_token, merge_hop_responses, split_stream_continuation
+from agent.gemini_long_decode import continuation_token, long_decode_hops, merge_hop_responses, merge_hop_usage, split_stream_continuation
from agent.retry_utils import parse_retry_after_seconds
from agent.gemini_schema import prepare_gemini_tool_parameters, sanitize_gemini_tool_parameters
@@ -622,7 +622,8 @@ def _usage_from_metadata(usage_meta: dict[str, Any]) -> SimpleNamespace:
count = lambda key: int(usage_meta.get(key) or 0)
reasoning_tokens = count("thoughtsTokenCount")
# Multi-hop long decode: the counts are summed over hops (billing); the context size is hop 1's prompt.
- initial = {"initial_prompt_tokens": count("initialPromptTokenCount")} if "initialPromptTokenCount" in usage_meta else {}
+ initial = {"initial_prompt_tokens": count("initialPromptTokenCount"),
+ "initial_cached_tokens": count("initialCachedContentTokenCount")} if "initialPromptTokenCount" in usage_meta else {}
return SimpleNamespace(
prompt_tokens=count("promptTokenCount"), completion_tokens=count("candidatesTokenCount") + reasoning_tokens,
total_tokens=count("totalTokenCount"), prompt_tokens_details=SimpleNamespace(cached_tokens=count("cachedContentTokenCount")),
@@ -934,7 +935,10 @@ class GeminiNativeClient:
if stream:
return self._stream_completion(model, f"{url}{self.STREAM_METHOD}?alt=sse", request, timeout)
hops = [self._generate(url + self.GENERATE_METHOD, request, timeout)]
- while token := continuation_token(hops[-1]): # long decode: same request + token, never the partial output
+ max_hops = long_decode_hops(request["generationConfig"].get("maxOutputTokens")) + 1
+ # Long decode: same request + token, never the partial output. Past the ceiling the last hop's
+ # CONTINUATION finish translates to ``length``.
+ while (token := continuation_token(hops[-1])) and len(hops) < max_hops:
hops.append(self._generate(url + self.GENERATE_METHOD, {**request, "continuationToken": token}, timeout))
return translate_gemini_response(merge_hop_responses(hops) if len(hops) > 1 else hops[0], model=model)
@@ -952,6 +956,7 @@ 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]] = []
+ max_hops = long_decode_hops(request["generationConfig"].get("maxOutputTokens")) + 1
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.
@@ -963,7 +968,12 @@ class GeminiNativeClient:
if response.status_code != 200:
raise self._http_error(response, read_streaming_error_body(response))
for event in _iter_sse_events(response):
+ hops_done = len(hop_usage)
event, token = split_stream_continuation(event, hop_usage)
+ if token and len(hop_usage) > hops_done and len(hop_usage) >= max_hops:
+ # Hop ceiling: end the turn as truncated, usage summed over every hop.
+ cand = {**event["candidates"][0], "finishReason": "MAX_TOKENS"}
+ event, token = {**event, "candidates": [cand], "usageMetadata": merge_hop_usage(hop_usage)}, None
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
diff --git a/agent/turn_usage.py b/agent/turn_usage.py
index e275e7ed4fc..6fd993664be 100644
--- a/agent/turn_usage.py
+++ b/agent/turn_usage.py
@@ -111,14 +111,17 @@ def record_response_usage(
# the context actually in the window is the first hop's prompt: compaction and the meter read that.
_initial_prompt = getattr(response.usage, "initial_prompt_tokens", None)
context_prompt_tokens = _initial_prompt if isinstance(_initial_prompt, int) and _initial_prompt > 0 else None
+ # The canonical buckets follow the same split, so engines reading them never see cache_read > prompt.
+ _initial_cached = getattr(response.usage, "initial_cached_tokens", 0) if context_prompt_tokens else None
+ context_cache_read = _initial_cached if isinstance(_initial_cached, int) else None
# Canonical token + cache buckets for context engines; legacy keys stay for back-compat.
usage_dict = {
"prompt_tokens": context_prompt_tokens or prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": (context_prompt_tokens + completion_tokens) if context_prompt_tokens else total_tokens,
- "input_tokens": canonical_usage.input_tokens,
+ "input_tokens": (context_prompt_tokens - context_cache_read) if context_cache_read is not None else canonical_usage.input_tokens,
"output_tokens": canonical_usage.output_tokens,
- "cache_read_tokens": canonical_usage.cache_read_tokens,
+ "cache_read_tokens": canonical_usage.cache_read_tokens if context_cache_read is None else context_cache_read,
"cache_write_tokens": canonical_usage.cache_write_tokens,
"reasoning_tokens": canonical_usage.reasoning_tokens,
}
diff --git a/run_agent.py b/run_agent.py
index 7d38b2e1fb2..bfa28ee443b 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -567,6 +567,7 @@ class AIAgent(
return float("inf")
from agent.chat_completion_helpers import _high_effort_silence_floor, cap_to_run_budget, estimate_request_context_tokens
+ from agent.gemini_long_decode import long_decode_stale_multiplier
est_tokens = estimate_request_context_tokens(api_payload)
timeout = max(stale_base, 240.0) if est_tokens > 100_000 else max(stale_base, 150.0) if est_tokens > 50_000 else stale_base
explicit = self._stale_timeout_is_explicit()
@@ -574,6 +575,8 @@ class AIAgent(
# cap below, so the floor can never outlive the run budget.
if self.api_mode == "codex_responses" and not explicit:
timeout = max(timeout, _high_effort_silence_floor(self))
+ if not explicit:
+ timeout *= long_decode_stale_multiplier(api_payload)
# Run-budget cap: an implicit stale timeout is capped at half the remaining budget (>= 60s) so one
# hung call cannot eat the run. Never raises the timeout; explicit user config still wins.
if not explicit:
diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.py
index c9a8b1a41f8..2002a43c958 100644
--- a/tests/agent/test_gemini_native_adapter.py
+++ b/tests/agent/test_gemini_native_adapter.py
@@ -977,3 +977,70 @@ 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 test_long_decode_hop_ceiling_ends_as_length(monkeypatch):
+ """A server that keeps answering CONTINUATION must not bill forever: past ceil(budget / 32,768) + 1
+ hops the turn ends as ``length`` (unary and streaming), with usage summed over the hops taken."""
+ from agent.gemini_native_adapter import GeminiNativeClient
+
+ def hop(n):
+ cand = {"content": {"role": "model", "parts": [{"text": f"p{n} "}]}, "finishReason": "CONTINUATION",
+ "continuationToken": f"tok-{n}"}
+ return {"candidates": [cand], "usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "totalTokenCount": 15}}
+
+ sent = []
+
+ class _Stream:
+ def __init__(self, payload):
+ self.status_code, self._payload = 200, payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def iter_text(self):
+ yield f"data: {json.dumps(self._payload)}\n\n"
+
+ class DummyHTTP:
+ def post(self, url, json=None, headers=None, timeout=None):
+ sent.append(json)
+ return DummyResponse(payload=hop(len(sent)))
+
+ def stream(self, method, url, json=None, headers=None, timeout=None):
+ sent.append(json)
+ return _Stream(hop(len(sent)))
+
+ 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": "go"}], "max_tokens": 65_536}
+
+ response = client.chat.completions.create(**kwargs)
+ assert len(sent) == 3 # 65,536 / 32,768 = 2 hops, +1 slack
+ assert response.choices[0].finish_reason == "length"
+ assert response.choices[0].message.content == "p1 p2 p3 "
+
+ sent.clear()
+ chunks = list(client.chat.completions.create(**kwargs, stream=True))
+ assert len(sent) == 3
+ finishes = [c for c in chunks if c.choices[0].finish_reason]
+ assert [c.choices[0].finish_reason for c in finishes] == ["length"]
+ assert (finishes[0].usage.prompt_tokens, finishes[0].usage.initial_prompt_tokens) == (30, 10)
+
+
+def test_long_decode_usage_keeps_canonical_buckets_on_first_hop():
+ """Context engines read the canonical buckets: input/cache_read follow the same first-hop split as
+ prompt_tokens, so cache_read never exceeds the context-facing prompt."""
+ from agent.gemini_long_decode import merge_hop_usage
+ from agent.gemini_native_adapter import _usage_from_metadata
+
+ hops = [{"promptTokenCount": 100, "cachedContentTokenCount": 40, "candidatesTokenCount": 32768},
+ {"promptTokenCount": 32868, "cachedContentTokenCount": 32800, "candidatesTokenCount": 10}]
+ usage = _usage_from_metadata(merge_hop_usage(hops))
+ assert (usage.prompt_tokens, usage.prompt_tokens_details.cached_tokens) == (32968, 32840) # billing: summed
+ assert (usage.initial_prompt_tokens, usage.initial_cached_tokens) == (100, 40)
diff --git a/tests/agent/test_run_budget.py b/tests/agent/test_run_budget.py
index f8741eb4c51..54e6346b951 100644
--- a/tests/agent/test_run_budget.py
+++ b/tests/agent/test_run_budget.py
@@ -359,3 +359,18 @@ def test_wrapup_lands_in_the_persisted_row_via_pre_flush_hook(monkeypatch, tmp_p
session_db.close()
# ── turn clock stamping ────────────────────────────────────────────────────
+
+def test_gemini_long_decode_scales_implicit_stale_timeout_by_hops(monkeypatch, tmp_path):
+ """One non-streaming stale timer spans every unary long-decode hop: an xhigh budget (262,144 tokens,
+ 8 hops of 32,768) gets 8x the 600s gemini-4 floor, not 600s for the whole answer. Explicit config
+ still wins untouched, and a request without a long-decode budget is unchanged."""
+ import run_agent
+ monkeypatch.setattr(run_agent, "get_provider_stale_timeout", lambda *a, **k: None)
+ agent = _make_agent(tmp_path, monkeypatch, model="gemini-4-argon", provider="gemini", api_key="AQ.dummy",
+ base_url="https://generativelanguage.googleapis.com/v1beta")
+ payload = {"messages": [{"role": "user", "content": "hi"}], "model": "gemini-4-argon"}
+ assert agent._compute_non_stream_stale_timeout(payload) == 600.0
+ long_decode = {**payload, "extra_body": {"max_output_tokens": 262_144}}
+ assert agent._compute_non_stream_stale_timeout(long_decode) == 600.0 * 8
+ monkeypatch.setenv("HERMES_API_CALL_STALE_TIMEOUT", "120")
+ assert agent._compute_non_stream_stale_timeout(long_decode) == 120.0
diff --git a/tests/agent/test_turn_usage_log_line.py b/tests/agent/test_turn_usage_log_line.py
index 878463056fd..4c8da42b035 100644
--- a/tests/agent/test_turn_usage_log_line.py
+++ b/tests/agent/test_turn_usage_log_line.py
@@ -64,3 +64,19 @@ def test_forensics_parser_reads_the_new_fields(tmp_path):
assert [c["n"] for c in calls] == [3, 4]
assert calls[0]["write"] == 28604 and calls[0]["id"] == "gen-1788636728-qMa1" and calls[0]["upstream"] == "Claude Platform on AWS"
assert "write" not in calls[1] and "id" not in calls[1]
+
+
+def test_long_decode_context_buckets_use_the_first_hop(tmp_path, monkeypatch, caplog):
+ """A multi-hop Gemini long decode sums every hop's re-sent prefix for billing; the context engine's
+ prompt AND canonical input/cache buckets carry hop 1, so cache_read never exceeds prompt there."""
+ a = _agent(tmp_path, monkeypatch)
+ usage = _usage(32_840, 0, 32_968)
+ usage.initial_prompt_tokens, usage.initial_cached_tokens = 100, 40
+ seen = {}
+ monkeypatch.setattr(a.context_compressor, "update_from_response", lambda u: seen.update(u))
+ try:
+ line = _line(a, caplog, SimpleNamespace(usage=usage, id=None, model="anthropic/claude-fable-5.1"))
+ finally:
+ a.close()
+ assert " in=32968 " in line # the log line keeps the billed sum
+ assert (seen["prompt_tokens"], seen["input_tokens"], seen["cache_read_tokens"]) == (100, 60, 40)