Official Codebase of 3DCodeVerse
Python
models/cost: max_wait_s is now a real deadline; every physical attempt is a ledger row
gaoypeng2d1d0e1a700c
diff --git a/harness/codeverse/cost/context.py b/harness/codeverse/cost/context.pyindex b56f3cdd..9e0620fe 100644--- a/harness/codeverse/cost/context.py+++ b/harness/codeverse/cost/context.py@@ -32,11 +32,12 @@ one run.from __future__ import annotationsimport threading-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom contextlib import contextmanagerfrom contextvars import ContextVarfrom dataclasses import dataclass, replace+from codeverse.contracts.common import Usagefrom codeverse.cost.types import Role, Stage, role_for_stage, stage_for_label@@ -226,5 +227,49 @@ def attribute(explicit: CallContext | None = None, *, label: str = "") -> CallCoreturn ctx.resolved()-__all__ = ["CallContext", "attribute", "bind_run", "call_context", "context_from_label", "current",+# --------------------------------------------------------------------------- per-attempt sink+@dataclass(frozen=True)+class AttemptRecord:+ """One round-trip of one logical model call (``models.retry.rotate_with_retries``).++ The metering layer (``instrument.MeteredChatModel``) installs a sink for these+ with :func:`attempt_recording`; the backend reports every round-trip — the+ winner included — so a hedge loser's and a charged-but-invalid reply's tokens+ reach the ledger instead of vanishing (audit 2026-08-27). Rows written from+ these carry ``source="attempt"`` and are excluded from every total."""++ attempt: int #: 1-based issue order within the logical call+ key: str #: the full API key that served it; the ledger keeps only its last 4 chars+ outcome: str #: KeyPool vocabulary: ok | 429 | 5xx | error | dead+ discarded: bool #: True for every round-trip that is not the winning one+ usage: Usage #: what the provider billed for THIS round-trip+ error: str = "" #: str(ModelError) when the round-trip failed+++AttemptSink = Callable[[AttemptRecord], None]++#: Request-scoped sink for per-attempt rows. A ContextVar rather than a new+#: parameter because ``ChatModel.generate(request)`` is a protocol many backends+#: implement; the backend captures the sink ONCE at call entry, so a hedge loser+#: that lands later in its own thread still reports through the captured callable.+_attempt_sink: ContextVar[AttemptSink | None] = ContextVar("cv3d_cost_attempt_sink", default=None)+++def attempt_sink() -> AttemptSink | None:+ """The sink installed for the current logical call (``None`` = nobody meters)."""+ return _attempt_sink.get()+++@contextmanager+def attempt_recording(sink: AttemptSink) -> Iterator[None]:+ """Install ``sink`` for the duration of ONE logical ``generate`` call."""+ token = _attempt_sink.set(sink)+ try:+ yield+ finally:+ _attempt_sink.reset(token)+++__all__ = ["AttemptRecord", "AttemptSink", "CallContext", "attempt_recording", "attempt_sink",+ "attribute", "bind_run", "call_context", "context_from_label", "current","run_binding"]diff --git a/harness/codeverse/cost/instrument.py b/harness/codeverse/cost/instrument.pyindex f0cf8db9..14608405 100644--- a/harness/codeverse/cost/instrument.py+++ b/harness/codeverse/cost/instrument.py@@ -31,13 +31,21 @@ from contextlib import contextmanagerfrom contextvars import ContextVarfrom pathlib import Pathfrom typing import Any+from uuid import uuid4from codeverse.contracts.agent import AgentJob, AgentResultfrom codeverse.contracts.chat import ChatRequest, ChatResponsefrom codeverse.contracts.common import Usage-from codeverse.cost.context import bind_run, call_context, run_binding+from codeverse.cost.context import (+ AttemptRecord,+ attempt_recording,+ bind_run,+ call_context,+ run_binding,+)from codeverse.cost.ledger import (CostLedger,+ default_ledger,default_ledger_path,existing_ledger_path,open_run_ledger,@@ -130,32 +138,64 @@ class MeteredChatModel:# -- the meter --------------------------------------------------------def generate(self, request: ChatRequest) -> ChatResponse:+ call_id = uuid4().hex # joins the per-attempt rows to the call's logical row+ # captured NOW: a hedge loser lands after this call returned, in a thread+ # with no context, and its row must still reach THIS run's ledger+ ledger = default_ledger()++ def attempt_row(rec: AttemptRecord) -> None:+ self._record_attempt(request, call_id, rec, ledger)+t0 = time.perf_counter()try:- resp = self._inner.generate(request)+ with attempt_recording(attempt_row):+ resp = self._inner.generate(request)except BaseException as exc: # noqa: BLE001 - record the attempt, then re-raise- self._record(Usage(backend=self.provider, model=self.model), request,- outcome=_outcome(exc), ms=int((time.perf_counter() - t0) * 1000),- attempts=getattr(exc, "attempts", 0))+ # a failed call may still have been billed: ModelError.usage carries what+ # the provider charged (a bad-JSON reply costs like a good one)+ usage = getattr(exc, "usage", None)+ self._record(usage if isinstance(usage, Usage)+ else Usage(backend=self.provider, model=self.model),+ request, outcome=_outcome(exc),+ ms=int((time.perf_counter() - t0) * 1000),+ attempts=getattr(exc, "attempts", 0), call_id=call_id)raise# which key served it and how many round-trips it took (gemini.py puts both in# ``raw``); until 2026-08-26 no telemetry row carried either, so the per-key# distribution of calls could only be probed, never readself._record(resp.usage, request, outcome="ok",ms=int((time.perf_counter() - t0) * 1000),- key=resp.raw.get("key"), attempts=resp.raw.get("attempts", 0))+ key=resp.raw.get("key"), attempts=resp.raw.get("attempts", 0),+ call_id=call_id)return respdef _record(self, usage: Usage, request: ChatRequest, *, outcome: str, ms: int,- key: object = None, attempts: object = 0) -> None:+ key: object = None, attempts: object = 0, call_id: str = "") -> None:try:record_call(usage, label=request.label, backend=usage.backend or self.provider,model=usage.model or self.model, outcome=outcome,latency_ms=usage.latency_ms or ms,- key=_key_suffix(key), attempts=int(attempts or 0))+ key=_key_suffix(key), attempts=int(attempts or 0), call_id=call_id)except Exception as e: # pragma: no cover - accounting must never break a calllog.debug("cost: could not record %s: %s", request.label, e)+ def _record_attempt(self, request: ChatRequest, call_id: str, rec: AttemptRecord,+ ledger: CostLedger | None) -> None:+ """One ``source="attempt"`` row per round-trip. Excluded from every total+ (``ledger.load_ledger`` / ``summarise``); they exist so a hedge loser's or+ a charged-but-invalid reply's tokens are visible at all (audit 2026-08-27)."""+ try:+ record_call(rec.usage, label=request.label,+ backend=rec.usage.backend or self.provider,+ model=rec.usage.model or self.model,+ outcome="discarded" if rec.discarded else "ok",+ latency_ms=rec.usage.latency_ms,+ source="attempt", key=_key_suffix(rec.key),+ call_id=call_id, attempt=rec.attempt, discarded=rec.discarded,+ ledger=ledger)+ except Exception as e: # pragma: no cover - accounting must never break a call+ log.debug("cost: could not record attempt %s#%d: %s", request.label, rec.attempt, e)+def _key_suffix(key: object) -> str:"""The last 4 chars of an API key as ``…ab12`` — the ledger never holds more."""diff --git a/harness/codeverse/cost/ledger.py b/harness/codeverse/cost/ledger.pyindex ca1a081d..22fec073 100644--- a/harness/codeverse/cost/ledger.py+++ b/harness/codeverse/cost/ledger.py@@ -88,8 +88,8 @@ class CostLedger:log.warning("cost ledger append failed (%s): %s", self.path, e)return row- def read(self) -> list[CallCost]:- return load_ledger(self.path)+ def read(self, *, include_attempts: bool = False) -> list[CallCost]:+ return load_ledger(self.path, include_attempts=include_attempts)def summarise(self, **kw: Any) -> Summary:return summarise(self.read(), **kw)@@ -343,10 +343,15 @@ def record_call(return row-def load_ledger(path: str | Path) -> list[CallCost]:+def load_ledger(path: str | Path, *, include_attempts: bool = False) -> list[CallCost]:"""Read a ledger file (or a run directory containing one: ``telemetry/cost.jsonl``first, then the legacy root ``cost_ledger.jsonl``). Bad lines are skipped with a- debug log — a truncated last line never loses the rest of the file."""+ debug log — a truncated last line never loses the rest of the file.++ ``source="attempt"`` rows (one per round-trip, ``instrument.MeteredChatModel``)+ are left out unless ``include_attempts=True``: the winning round-trip's tokens+ are already on the call's logical row, so every aggregate built on this reader+ (``summarise``, ``reconstruct``, the CLI) keeps counting each call exactly once."""p = Path(path)if p.is_dir():found = existing_ledger_path(p)@@ -356,9 +361,13 @@ def load_ledger(path: str | Path) -> list[CallCost]:rows: list[CallCost] = []for i, line in iter_jsonl_lines(p):try:- rows.append(CallCost.model_validate_json(line))+ row = CallCost.model_validate_json(line)except Exception as e: # pragma: no cover - defensivelog.debug("cost ledger %s:%d unreadable: %s", p, i, e)+ continue+ if not include_attempts and row.source == "attempt":+ continue+ rows.append(row)return rows@@ -374,6 +383,8 @@ def summarise(rows: Iterable[CallCost], *, dimensions: Sequence[str] = DIMENSIONof :class:`CallCost` (defaults to :data:`DIMENSIONS`)."""out = Summary()for row in rows:+ if row.source == "attempt":+ continue # per-round-trip forensic rows; their call is already a rowout.total.add(row)for dim in dimensions:bucket = out.by.setdefault(dim, {}).setdefault(_key(row, dim), CostBucket(key=_key(row, dim)))diff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.pyindex e97c38b6..d79414e6 100644--- a/harness/codeverse/cost/types.py+++ b/harness/codeverse/cost/types.py@@ -184,13 +184,23 @@ class CallCost(BaseModel):cache_hit: bool = Falseoutcome: str = "ok" # ok | error | timeout | budget | degraded | discardedn_calls: int = 1 # >1 when a row aggregates a whole agent session- source: str = "live" # live | record | events | transcript | stdout | residual+ source: str = "live" # live | record | events | transcript | stdout | residual | session | attempt#: which API key served the call, as its last 4 chars ("…ab12") — never the key#: itself; "" for a failed call, a session row, or a row older than 2026-08-26key: str = ""#: round-trips the retry machine issued for this call (hedged siblings included);#: 1 = clean, 0 = not recordedattempts: int = 0+ #: joins a call's per-attempt rows (``source="attempt"``) to its logical row;+ #: minted per logical call by ``instrument.MeteredChatModel`` (uuid4 hex), ""+ #: for rows older than 2026-08-27 and for writers that do not mint one+ call_id: str = ""+ #: 1-based round-trip number within its logical call (``source="attempt"`` rows)+ attempt: int = 0+ #: True when this round-trip's response was thrown away: a hedge loser, or a+ #: failed try of a call that went on to retry. Real money, but never part of a+ #: total — ``ledger.load_ledger`` / ``summarise`` exclude ``source="attempt"``+ discarded: bool = False@propertydef uncached_tokens(self) -> int:diff --git a/harness/codeverse/models/base.py b/harness/codeverse/models/base.pyindex 749f927c..043261a7 100644--- a/harness/codeverse/models/base.py+++ b/harness/codeverse/models/base.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom typing import Protocol, runtime_checkablefrom codeverse.contracts.chat import ChatRequest, ChatResponse+from codeverse.contracts.common import Usage@runtime_checkable@@ -34,12 +35,23 @@ class ChatModel(Protocol):class ModelError(RuntimeError):"""A model call failed. ``attempts`` is how many round-trips the retry machineissued before giving up (0 = unknown / not a retried call); the cost ledger- records it on the error row (``docs/COST.md`` §24)."""+ records it on the error row (``docs/COST.md`` §24). ``usage`` is what the+ provider ALREADY billed for the failed call — a bad-JSON reply is charged like+ a good one — so the ledger and the key pool's TPM accounting can see real+ consumption instead of assuming a failure was free (mirrors+ ``tracks.planner.PlanningError.usage``); empty when nothing was billed."""def __init__(- self, message: str, *, retryable: bool = False, status: int | None = None, attempts: int = 0+ self,+ message: str,+ *,+ retryable: bool = False,+ status: int | None = None,+ attempts: int = 0,+ usage: Usage | None = None,):super().__init__(message)self.retryable = retryableself.status = statusself.attempts = attempts+ self.usage = usage if usage is not None else Usage()diff --git a/harness/codeverse/models/gemini.py b/harness/codeverse/models/gemini.pyindex 82d38de6..63a3604f 100644--- a/harness/codeverse/models/gemini.py+++ b/harness/codeverse/models/gemini.py@@ -27,11 +27,13 @@ from google.genai import errors as genai_errorsfrom google.genai import typesfrom codeverse.contracts.chat import ChatRequest, ChatResponse+from codeverse.contracts.common import Usagefrom codeverse.models.base import ModelErrorfrom codeverse.models.gemini_convert import (FATAL_FINISH,RETRYABLE_FINISH,build_config,+ clip_timeout,extract_candidate,parse_usage,to_contents,@@ -39,7 +41,7 @@ from codeverse.models.gemini_convert import (from codeverse.models.keypool import MAX_WAIT_S, KeyPool, KeyPoolExhausted, Outcomefrom codeverse.models.parts import Stopwatchfrom codeverse.models.pricing import estimate_cost-from codeverse.models.retry import RETRY_DEADLINE_S, rotate_with_retries+from codeverse.models.retry import RETRY_DEADLINE_S, OnAttempt, _Try, rotate_with_retriesfrom codeverse.models.schema_utils import JsonParseError, parse_json_lenientfrom codeverse.models.storm import StormGatefrom codeverse.models.storm import storm_gate as storm_gate_for@@ -49,6 +51,15 @@ log = logging.getLogger(__name__)_RETRY_DELAY_RE = re.compile(r"retryDelay['\"]?\s*:\s*['\"]?(\d+(?:\.\d+)?)s")+#: floor of the per-attempt HTTP read timeout derived from the remaining retry+#: budget (``ChatRequest.max_wait_s``): a call that starts near its deadline still+#: gets ONE real attempt instead of an instant socket timeout. 20 s matches the+#: callers' own floors (``agents.api_agent.TURN_WAIT_MIN_S`` = 20 s,+#: ``judges.vlm_judge.SAMPLE_MIN_WAIT_S`` = 20 s), so an in-flight attempt may+#: overshoot the deadline by at most this floor — never by the full ``timeout_s``+#: (300 s) read timeout, which was the dominant overshoot (audit 2026-08-27).+HTTP_TIMEOUT_FLOOR_S = 20.0+_pools: dict[tuple[str, ...], KeyPool] = {}_clients: dict[tuple[str, int], genai.Client] = {}_registry_lock = threading.Lock()@@ -251,11 +262,15 @@ class GeminiModel:# the caller's budget clips the retry deadline, never extends itbudget = RETRY_DEADLINE_S if request.max_wait_s is None else min(RETRY_DEADLINE_S, float(request.max_wait_s))+ deadline = time.monotonic() + budget # mirrors rotate_with_retries' own deadlinestats: dict[str, Any] = {}try:resp = rotate_with_retries(self.pool,- lambda key: self._once(key, contents, state["config"], request, warnings),+ lambda key: self._once(+ key, contents, self._attempt_config(state["config"], deadline),+ request, warnings,+ ),classify=classify_exception,outcome_of=failure_outcome,max_attempts=self.max_attempts,@@ -271,6 +286,7 @@ class GeminiModel:storm_gate=self.storm_gate,label=f"gemini {self.model}",stats=stats,+ on_attempt=self._attempt_hook(),**({} if self.storm_attempts is None else {"storm_attempts": self.storm_attempts}),)except ModelError as err:@@ -289,6 +305,43 @@ class GeminiModel:warnings=warnings,)+ def _attempt_config(+ self, config: types.GenerateContentConfig, deadline: float+ ) -> types.GenerateContentConfig:+ """The config for ONE attempt: its HTTP read timeout is the remaining retry+ budget, capped at ``self.timeout_s`` and floored at+ :data:`HTTP_TIMEOUT_FLOOR_S`. A 20 s-budget turn used to hand the provider+ a 300 s socket — the dominant deadline overshoot (audit 2026-08-27)."""+ remaining = deadline - time.monotonic()+ want_s = min(self.timeout_s, max(HTTP_TIMEOUT_FLOOR_S, remaining))+ return clip_timeout(config, int(want_s * 1000))++ def _attempt_hook(self) -> OnAttempt | None:+ """The per-attempt ledger recorder, when the metering layer installed one+ (``cost.instrument.MeteredChatModel``). Captured once per logical call so+ a hedge loser landing later, in its own thread, still reports through it.+ Imported lazily: the models package must not import the cost package at+ module level (``cost.ledger`` imports ``models.pricing``)."""+ try:+ from codeverse.cost.context import AttemptRecord, attempt_sink+ except Exception: # pragma: no cover - accounting must never break a call+ return None+ sink = attempt_sink()+ if sink is None:+ return None++ def on_attempt(t: _Try, no: int, discarded: bool) -> None:+ if t.err is None:+ usage: Usage = t.result.usage+ outcome, error = "ok", ""+ else:+ usage = getattr(t.err, "usage", None) or Usage()+ outcome, error = t.outcome, str(t.err)+ sink(AttemptRecord(attempt=no, key=t.key, outcome=outcome,+ discarded=discarded, usage=usage, error=error))++ return on_attempt+def _once(self,key: str,@@ -318,13 +371,15 @@ class GeminiModel:f"structured output unavailable (finish_reason={finish}; "f"raise max_output_tokens if truncated): {exc}",retryable=False,+ usage=usage, # the provider billed this reply; the ledger wants it) from excraise ModelError(f"structured output is not valid JSON (finish_reason={finish}): {exc}",retryable=True,+ usage=usage,) from excelif finish in RETRYABLE_FINISH and not calls and not text.strip():- raise ModelError(f"Gemini finish_reason={finish}", retryable=True)+ raise ModelError(f"Gemini finish_reason={finish}", retryable=True, usage=usage)raw: dict[str, Any] = {"finish_reason": finish,"model_version": resp.model_version,diff --git a/harness/codeverse/models/gemini_convert.py b/harness/codeverse/models/gemini_convert.pyindex b4c1f191..707ba804 100644--- a/harness/codeverse/models/gemini_convert.py+++ b/harness/codeverse/models/gemini_convert.py@@ -155,6 +155,21 @@ def build_config(return types.GenerateContentConfig(**cfg)+def clip_timeout(+ config: types.GenerateContentConfig, timeout_ms: int+) -> types.GenerateContentConfig:+ """A copy of ``config`` whose per-request HTTP timeout is ``timeout_ms`` (the+ SAME object when it already matches — the common full-budget case allocates+ nothing). :func:`build_config` owns the initial ``timeout_ms``; this is the+ one sanctioned way to shorten it for a single attempt whose remaining retry+ budget is smaller than the configured read timeout+ (``GeminiModel._attempt_config``)."""+ current = config.http_options.timeout if config.http_options is not None else None+ if current == timeout_ms:+ return config+ return config.model_copy(update={"http_options": types.HttpOptions(timeout=timeout_ms)})++# ------------------------------------------------------------------ responsedef parse_usage(resp: types.GenerateContentResponse, model: str) -> Usage:um = resp.usage_metadatadiff --git a/harness/codeverse/models/gemini_image.py b/harness/codeverse/models/gemini_image.pyindex 5593df7d..81e7f76d 100644--- a/harness/codeverse/models/gemini_image.py+++ b/harness/codeverse/models/gemini_image.py@@ -49,7 +49,7 @@ from codeverse.models.gemini_convert import FATAL_FINISH, parse_usagefrom codeverse.models.keypool import MAX_WAIT_S, KeyPoolfrom codeverse.models.parts import Stopwatchfrom codeverse.models.pricing import estimate_cost-from codeverse.models.retry import rotate_with_retries+from codeverse.models.retry import RETRY_DEADLINE_S, rotate_with_retrieslog = logging.getLogger(__name__)@@ -186,8 +186,10 @@ class GeminiImageModel:n: int = 1,seed: int | None = None,reference_images: Sequence[Image.Image | Path | str] = (),+ max_wait_s: float | None = None,) -> list[Image.Image]:- images, _ = self.generate_with_usage(prompt, size=size, n=n, seed=seed, reference_images=reference_images)+ images, _ = self.generate_with_usage(prompt, size=size, n=n, seed=seed,+ reference_images=reference_images, max_wait_s=max_wait_s)return imagesdef generate_with_usage(@@ -198,7 +200,13 @@ class GeminiImageModel:n: int = 1,seed: int | None = None,reference_images: Sequence[Image.Image | Path | str] = (),+ max_wait_s: float | None = None,) -> tuple[list[Image.Image], Usage]:+ """``max_wait_s`` is the caller's retry budget for ONE image (each of the+ ``n`` images gets its own window, and a fallback model too), exactly like+ ``ChatRequest.max_wait_s`` clips ``GeminiModel.generate``; ``None`` = the+ full ``retry.RETRY_DEADLINE_S`` (900 s). Kept off the ``ImageModel``+ protocol so fakes stay conformant; callers that hold a deadline pass it."""if not prompt.strip():raise ModelError("empty image prompt")if n < 1:@@ -206,7 +214,8 @@ class GeminiImageModel:images: list[Image.Image] = []usage = Usage(backend="gemini-image", model=self.model)for i in range(n):- got, u = self._one(prompt, size=size, seed=None if seed is None else seed + i, refs=reference_images)+ got, u = self._one(prompt, size=size, seed=None if seed is None else seed + i,+ refs=reference_images, max_wait_s=max_wait_s)images.extend(got)usage = usage + uif len(images) > n:@@ -226,12 +235,14 @@ class GeminiImageModel:return orderdef _one(- self, prompt: str, *, size: int, seed: int | None, refs: Sequence[Image.Image | Path | str]+ self, prompt: str, *, size: int, seed: int | None,+ refs: Sequence[Image.Image | Path | str], max_wait_s: float | None = None,) -> tuple[list[Image.Image], Usage]:last: ModelError | None = Nonefor model in self._models():try:- return self._attempts(model, prompt, size=size, seed=seed, refs=refs)+ return self._attempts(model, prompt, size=size, seed=seed, refs=refs,+ max_wait_s=max_wait_s)except ModelError as err:last = errif model == self.model and self.fallback and (err.retryable or _is_model_missing(err)):@@ -245,7 +256,8 @@ class GeminiImageModel:raise lastdef _attempts(- self, model: str, prompt: str, *, size: int, seed: int | None, refs: Sequence[Image.Image | Path | str]+ self, model: str, prompt: str, *, size: int, seed: int | None,+ refs: Sequence[Image.Image | Path | str], max_wait_s: float | None = None,) -> tuple[list[Image.Image], Usage]:parts: list[types.Part] = [_to_part(r) for r in refs]parts.append(types.Part.from_text(text=prompt))@@ -256,6 +268,9 @@ class GeminiImageModel:seed=seed,http_options=types.HttpOptions(timeout=int(self.timeout_s * 1000)),)+ # the caller's budget clips the retry deadline, never extends it (the same+ # contract as GeminiModel.generate with ChatRequest.max_wait_s)+ budget = RETRY_DEADLINE_S if max_wait_s is None else min(RETRY_DEADLINE_S, float(max_wait_s))return rotate_with_retries(self.pool,lambda key: self._call(key, model, contents, config, size),@@ -264,6 +279,7 @@ class GeminiImageModel:max_attempts=self.max_attempts,base_delay=self.base_delay,max_delay=self.max_delay,+ max_total_s=budget,hedge=self.hedge,sleep=self._sleep,retry_after=_retry_after_s,diff --git a/harness/codeverse/models/keypool.py b/harness/codeverse/models/keypool.pyindex 00f62058..96d5e23d 100644--- a/harness/codeverse/models/keypool.py+++ b/harness/codeverse/models/keypool.py@@ -47,6 +47,14 @@ so the harness rotates rather than sitting out a long backoff. Patience comesfrom the NUMBER of attempts, never from the length of one sleep."""+ACQUIRE_TIMEOUT_S = 120.0+"""Default total wait budget of one :meth:`KeyPool.acquire` (seconds).++Covers BOTH the ``max_in_flight`` slot wait and the key/cooldown wait; a caller+with a deadline passes something smaller (``retry.rotate_with_retries`` passes+``min(ACQUIRE_TIMEOUT_S, remaining budget)``). ``None`` waits forever.+"""+@dataclassclass TokenBucket:@@ -184,7 +192,7 @@ class KeyPool:*,tokens_hint: int = 0,exclude: set[str] | frozenset[str] | None = None,- timeout_s: float | None = 120.0,+ timeout_s: float | None = ACQUIRE_TIMEOUT_S,) -> str:"""Return the next usable key, blocking (bounded by ``timeout_s``) while allkeys are throttled. ``exclude`` skips keys that already failed this call.@@ -194,9 +202,19 @@ class KeyPool:``tokens_hint`` is the estimated prompt tokens of the pending call: theyare reserved in the chosen key's TPM bucket now and reconciled by:meth:`report`. When ``max_in_flight`` is set the call also waits for a- free concurrency slot; :meth:`release` hands it back."""+ free concurrency slot; :meth:`release` hands it back. ``timeout_s`` bounds+ the slot wait AND the key wait together (``None`` = wait forever): the slot+ wait used to be unbounded, so a caller 20 s from its deadline could sit on+ the semaphore for minutes."""if self._slots is not None:- self._slots.acquire()+ t0 = self._clock()+ if not self._slots.acquire(timeout=timeout_s):+ raise KeyPoolExhausted(+ f"all {self._max_in_flight} in-flight slots busy; waited {timeout_s}s"+ )+ if timeout_s is not None:+ # the slot wait spent part of the budget; the key wait gets the rest+ timeout_s = max(0.0, timeout_s - (self._clock() - t0))try:return self._acquire_key(tokens_hint, exclude, timeout_s)except BaseException:diff --git a/harness/codeverse/models/retry.py b/harness/codeverse/models/retry.pyindex ea3c46d6..6a74bd49 100644--- a/harness/codeverse/models/retry.py+++ b/harness/codeverse/models/retry.py@@ -18,9 +18,10 @@ import timefrom collections.abc import Callable, Sequencefrom concurrent.futures import Future, ThreadPoolExecutor, as_completedfrom dataclasses import dataclass+from functools import partialfrom typing import TYPE_CHECKING, Any, TypeVar-from codeverse.models.keypool import MAX_WAIT_S, KeyPoolExhausted+from codeverse.models.keypool import ACQUIRE_TIMEOUT_S, MAX_WAIT_S, KeyPoolExhausted#: the longest ONE logical call may spend being retried, waits and timeouts included.#: The storm branch used to be bounded only in ATTEMPTS: 60 storm attempts x (a 300 s@@ -51,6 +52,13 @@ T = TypeVar("T")OnRetry = Callable[[int, BaseException, float], None]+#: per-round-trip hook of :func:`rotate_with_retries`: ``(try, attempt_no, discarded)``.+#: ``attempt_no`` is the 1-based issue order within the logical call; ``discarded``+#: is True for every round-trip that is not the winning one (hedge losers included).+#: Fired exactly once per round-trip: buffered tries flush when the call settles,+#: and a hedge loser still in flight reports the moment it lands (its own thread).+OnAttempt = Callable[["_Try", int, bool], None]+def backoff_delay(attempt: int, *, base_delay: float, max_delay: float, jitter: bool = True@@ -123,6 +131,7 @@ def rotate_with_retries[T](storm_gate: StormGate | None = None,label: str = "model",stats: dict[str, Any] | None = None,+ on_attempt: OnAttempt | None = None,) -> T:"""Run ``call(key)`` against a rotating :class:`KeyPool` until it succeeds.@@ -195,10 +204,17 @@ def rotate_with_retries[T](included; 1 = clean), ``hedged`` = hedged attempts, ``storm`` = storm waits.``GeminiModel`` copies ``attempts`` into ``ChatResponse.raw`` and onto the raised``ModelError`` so the cost ledger can say how hard each call was.++ ``on_attempt`` (optional) hears every round-trip exactly once — see+ :data:`OnAttempt`; the cost layer uses it to write per-attempt ledger rows so a+ hedge loser's and a charged-but-invalid reply's tokens stop vanishing.+ Exceptions from the hook are swallowed: accounting must never break a call."""failed_keys: set[str] = set() # keys that 429'd / 503'd or looked dead during this calldead_keys: set[str] = set()counts = {"attempts": 0, "hedged": 0, "storm": 0}+ finished: list[tuple[int, _Try]] = [] # (attempt_no, try): the on_attempt flush buffer+ winner: _Try | None = Nonedef bench() -> None:# mark keys that failed with key-scoped errors dead — called once the call@@ -219,9 +235,16 @@ def rotate_with_retries[T](outcome = outcome_of(err)# a key that looks dead is reported "error" now and benched only once a# sibling proves the request itself is fine (bench())+ # a charged-but-invalid reply (bad JSON with real usage) DID consume+ # its prompt tokens: report them so the pool does not refund a spent+ # reservation (a 42k-token invalid reply used to hand the key 42k TPM+ # back). Failures billed nothing (429 / 503 / transport) carry an+ # empty ``ModelError.usage`` and are refunded exactly as before.+ consumed = getattr(err, "usage", None)pool.report(key,"error" if outcome == "dead" else outcome,+ tokens=int(consumed.input_tokens) if consumed is not None else 0,reserved=tokens_hint,retry_after_s=retry_after(exc) if (outcome == "429" and retry_after) else None,)@@ -235,26 +258,40 @@ def rotate_with_retries[T](def run_attempt(keys: Sequence[str]) -> list[_Try]:"""Issue ``call`` on every key; return the tries that completed up to andincluding the first success, in completion order. Losers still in flight- finish on their own (``run_one`` reports and releases for them)."""+ finish on their own (``run_one`` reports and releases for them, and the+ ``on_attempt`` hook hears their tokens when they land)."""+ first_no = counts["attempts"] + 1counts["attempts"] += len(keys)if len(keys) == 1:- return [run_one(keys[0])]+ t = run_one(keys[0])+ finished.append((first_no, t))+ return [t]counts["hedged"] += 1executor = ThreadPoolExecutor(max_workers=len(keys), thread_name_prefix=f"hedge {label}")futures = [executor.submit(run_one, k) for k in keys]+ nos = {id(f): first_no + i for i, f in enumerate(futures)}executor.shutdown(wait=False) # no new work; the threads end with their round-tripsdone: list[_Try] = []+ consumed_futs: set[int] = set()for fut in as_completed(futures):+ consumed_futs.add(id(fut))t = fut.result()+ finished.append((nos[id(fut)], t))done.append(t)if t.err is None:for other in futures:- if not other.done():- other.add_done_callback(_discard_loser)+ if id(other) not in consumed_futs:+ # fires at once when the sibling already landed — either way+ # exactly once, so the hook still hears a loser's tokens+ other.add_done_callback(+ partial(_discard_loser, on_attempt=on_attempt,+ attempt_no=nos[id(other)])+ )breakreturn donelast_err: ModelError | None = None+ last_exc: BaseException | None = Noneattempt = 0storm = 0hedging = False # flips on the first 503/529; every later attempt is hedged@@ -268,14 +305,26 @@ def rotate_with_retries[T](try:while attempt < max_attempts:+ if out_of_time() and last_err is not None:+ # checked wherever the loop can spend time, not only around the+ # sleeps: a free rotation must not out-live the caller's budget+ log.warning("%s giving up after %.0f s of retrying (%s)",+ label, max_total_s, last_err)+ raise last_err from last_excattempt += 1# never go back to a key that looked dead this call; throttled keys are# excluded while an untried one remains, else acquire() waits for a cooldownexclude = dead_keys | (failed_keys if len(failed_keys) < len(pool) else set())if storm_gate is not None:- storm_gate.enter()+ storm_gate.enter(None if deadline == float("inf") else deadline)+ budget_left = None if deadline == float("inf") else max(0.0, deadline - monotonic())try:- keys = [pool.acquire(exclude=exclude, tokens_hint=tokens_hint)]+ # the key/slot wait must fit the remaining budget, never outlive it+ keys = [pool.acquire(+ exclude=exclude, tokens_hint=tokens_hint,+ timeout_s=ACQUIRE_TIMEOUT_S if budget_left is None+ else min(ACQUIRE_TIMEOUT_S, budget_left),+ )]except KeyPoolExhausted as exc:raise classify(exc) from excwhile hedging and len(keys) < max(1, hedge):@@ -299,6 +348,7 @@ def rotate_with_retries[T](hedging = Truewon = next((t for t in tries if t.err is None), None)if won is not None:+ winner = wonif storm_gate is not None:storm_gate.ok()bench()@@ -308,6 +358,7 @@ def rotate_with_retries[T](err, exc, key = worst.err, worst.exc, worst.keyassert err is not Nonelast_err = err+ last_exc = excif free:attempt -= 1continue@@ -315,6 +366,10 @@ def rotate_with_retries[T](# key-scoped: move on at once (no budget, no sleep); the key is only# benched once another key proves the request itself is fineif len(dead_keys) < len(pool):+ if out_of_time():+ log.warning("%s giving up after %.0f s of retrying (%s)",+ label, max_total_s, err)+ raise err from exclog.warning("%s key …%s looks dead (%s); rotating", label, key[-4:], err)attempt -= 1continue@@ -340,13 +395,17 @@ def rotate_with_retries[T](# "<=5 s" wait land at 6.25 s in the wild (observed 2026-08-24).raw = base_delay * (2 ** min(storm, 8)) * (0.75 + 0.5 * random.random())delay = min(storm_max_delay, raw)+ if deadline != float("inf"):+ # clip the storm sleep to the remainder: sleeping past the+ # deadline only to give up on waking helps nobody+ delay = min(delay, max(0.0, deadline - monotonic()))if storm_gate is not None:# tell every other worker as well: the next one to arrive parks at# the gate instead of spending its own round-trip to find the stormdelay = max(delay, storm_gate.hit(retry_after(exc) if (retry_after and exc) else None))log.warning("%s capacity storm %d/%d (%s); gate closed %.0fs",label, storm, storm_attempts, err, delay)- storm_gate.enter()+ storm_gate.enter(None if deadline == float("inf") else deadline)else:log.warning("%s capacity storm %d/%d (%s); waiting %.0fs",label, storm, storm_attempts, err, delay)@@ -356,6 +415,10 @@ def rotate_with_retries[T](if worst.outcome == "429":failed_keys.update(t.key for t in tries if t.outcome == "429")if len(failed_keys) < len(pool):+ if out_of_time():+ log.warning("%s giving up after %.0f s of retrying (%s)",+ label, max_total_s, err)+ raise err from exc# an untried key remains: rotation is free, only a courtesy pauseattempt -= 1log.warning(@@ -381,6 +444,14 @@ def rotate_with_retries[T](finally:if stats is not None:stats.update(counts)+ if on_attempt is not None:+ # flush every completed round-trip now that the winner is known; a hedge+ # loser still in flight reports itself when it lands (_discard_loser)+ for no, t in finished:+ try:+ on_attempt(t, no, t is not winner)+ except Exception as hook_exc: # noqa: BLE001 - accounting is best-effort+ log.debug("on_attempt hook failed for round-trip %d: %s", no, hook_exc)@dataclass(frozen=True)@@ -408,12 +479,21 @@ def _severity(t: _Try) -> int:return 2 if t.outcome == "429" else 1-def _discard_loser(fut: Future[_Try]) -> None:+def _discard_loser(+ fut: Future[_Try], on_attempt: OnAttempt | None = None, attempt_no: int = 0+) -> None:"""A hedged sibling that finished after the winner: its pool report and slot- release already happened in ``run_one``; here it is only logged."""+ release already happened in ``run_one``; here it is logged and handed to the+ ``on_attempt`` hook — always as discarded, a late success included — so its+ paid tokens reach the cost ledger at all."""try:t = fut.result()except BaseException as exc: # noqa: BLE001 - a crashed loser must not crash the callerlog.debug("hedge loser crashed: %s", exc)return+ if on_attempt is not None:+ try:+ on_attempt(t, attempt_no, True)+ except Exception as hook_exc: # noqa: BLE001 - accounting is best-effort+ log.debug("on_attempt hook failed for hedge loser: %s", hook_exc)log.debug("hedge loser …%s finished (%s); discarded", t.key[-4:], t.outcome)diff --git a/harness/codeverse/models/storm.py b/harness/codeverse/models/storm.pyindex cc498b60..4733476f 100644--- a/harness/codeverse/models/storm.py+++ b/harness/codeverse/models/storm.py@@ -70,14 +70,21 @@ class StormGate:def storming(self) -> bool:return self._storm- def enter(self) -> float:- """Block until this thread may issue a call; returns the seconds waited."""+ def enter(self, deadline: float | None = None) -> float:+ """Block until this thread may issue a call; returns the seconds waited.++ ``deadline`` (a point on this gate's ``clock``) bounds the parking: each+ wait is clipped to it and once it passes ``enter`` returns even though the+ storm may still be on — the caller's own deadline machinery+ (``retry.rotate_with_retries``), not the gate, decides to give up."""t0 = self._clock()while True:with self._lock:now = self._clock()if not self._storm:return now - t0+ if deadline is not None and now >= deadline:+ return now - t0 # budget exhausted: hand control backif now < self._closed_until:wait = min(self._max_wait, self._closed_until - now)elif now >= self._probe_until:@@ -88,6 +95,8 @@ class StormGate:else:wait = min(self._max_wait, self._probe_until - now)wait = max(0.01, wait)+ if deadline is not None:+ wait = min(wait, max(0.01, deadline - now))self.parked_s += waitself._sleep(wait)diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex c519704b..7690f7ff 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -357,3 +357,90 @@ def test_per_key_buckets_and_tries_per_call(tmp_path: Path):assert [b.key for b in keyed_buckets(audit)] == ["…k1", "…k2"], "most calls first, unkeyed rows left out"table = bucket_rows(keyed_buckets(audit), total=1.0)assert BUCKET_HEADERS[-1] == "tries/call" and table[0][-1] == "2.00" and table[1][-1] == "1.00"+# ------------------------------------------------------- per-attempt rows (audit 2026-08-27)+def test_a_bad_json_reply_reaches_the_ledger_as_a_discarded_attempt_row(tmp_path: Path):+ """A charged-but-invalid reply used to vanish: the logical row carries only the+ winner's usage. Its tokens now land as a source="attempt" row that joins the+ logical row by call_id — and never double-counts in any total."""+ from codeverse.cost.ledger import summarise+ from tests.models.test_gemini import make_model, text_response++ m, _log, _ = make_model([text_response("not json"), text_response('{"ok": true}')])+ with run_ledger(tmp_path, run="r1"):+ resp = MeteredChatModel(m).generate(+ ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"},+ label="planner"))+ assert resp.parsed == {"ok": True}+ (logical,) = load_ledger(tmp_path) # attempt rows are filtered by default+ assert logical.outcome == "ok" and logical.attempts == 2 and logical.call_id+ rows = load_ledger(tmp_path, include_attempts=True)+ attempts = sorted((r for r in rows if r.source == "attempt"), key=lambda r: r.attempt)+ assert [r.attempt for r in attempts] == [1, 2]+ bad, win = attempts+ assert bad.discarded and bad.outcome == "discarded" and bad.input_tokens == 100+ assert not win.discarded and win.outcome == "ok"+ assert bad.call_id == win.call_id == logical.call_id+ assert summarise(rows).total.input_tokens == logical.input_tokens, \+ "attempt rows never double-count"+++def test_a_hedge_losers_tokens_reach_the_ledger_when_it_lands(tmp_path: Path):+ """The loser of a raced 503 retry keeps running after the winner returned; when+ it lands, its billed tokens must appear as a discarded attempt row — before,+ that money left no trace anywhere."""+ import threading+ import time as _time++ from codeverse.models.base import ModelError+ from codeverse.models.gemini import GeminiModel+ from codeverse.models.keypool import KeyPool+ from tests.models.test_gemini import text_response++ release_k2 = threading.Event()++ class Client:+ def __init__(self, key: str):+ self.key, self.models = key, self++ def generate_content(self, *, model, contents, config):+ if self.key == "k1":+ raise ModelError("503 high demand", retryable=True, status=503)+ if self.key == "k2":+ assert release_k2.wait(5.0)+ return text_response("late loser")+ return text_response("winner")++ pool = KeyPool(["k1", "k2", "k3"], rpm_per_key=10_000)+ m = GeminiModel("gemini-3.7-flash", pool=pool, sleep=lambda s: None, client_factory=Client)+ with run_ledger(tmp_path, run="r1"):+ resp = MeteredChatModel(m).generate(+ ChatRequest(messages=[ChatMessage.user("x")], label="planner"))+ assert resp.text == "winner"+ release_k2.set()+ deadline = _time.monotonic() + 5.0+ loser = None+ while _time.monotonic() < deadline:+ rows = load_ledger(tmp_path, include_attempts=True)+ loser = next((r for r in rows if r.source == "attempt" and r.key == "…k2"), None)+ if loser is not None:+ break+ _time.sleep(0.01)+ assert loser is not None, "the loser's row never arrived"+ assert loser.discarded and loser.input_tokens == 100, "the loser's paid tokens are on the ledger"+ (logical,) = load_ledger(tmp_path)+ # endswith, not ==: the 2-char fake key is shorter than the …last-4 redaction+ assert logical.key.endswith("k3") and logical.call_id == loser.call_id+++def test_a_failed_calls_error_row_carries_what_was_billed(tmp_path: Path):+ """instrument's error path used to write an EMPTY Usage; it now records+ ``ModelError.usage`` — the money a failed-after-retries call still cost."""+ from codeverse.models.base import ModelError++ err = ModelError("bad json after retries", retryable=True, attempts=6, usage=_usage())+ with run_ledger(tmp_path, run="r1"), pytest.raises(ModelError):+ MeteredChatModel(FakeChat(err)).generate(+ ChatRequest(messages=[ChatMessage.user("x")], label="planner"))+ (row,) = load_ledger(tmp_path)+ assert row.outcome == "error" and row.attempts == 6+ assert row.input_tokens == 12_000 and row.cost_usd > 0, "a billed failure is no longer a $0 row"diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.pyindex b9548b32..1b828cd0 100644--- a/harness/tests/models/test_gemini.py+++ b/harness/tests/models/test_gemini.py@@ -520,3 +520,12 @@ def test_empty_max_tokens_is_not_retried():with pytest.raises(ModelError) as ei:m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_output_tokens=50))assert not ei.value.retryable and len(log) == 1 and "thinking" in str(ei.value)+def test_a_charged_but_invalid_reply_carries_its_usage_on_the_error():+ """``ModelError.usage``: what the provider billed for the failed call — a+ bad-JSON reply is charged like a success (mirrors tracks.planner.PlanningError),+ so the ledger's error row and the pool's TPM accounting can see real money."""+ m, _log, _ = make_model([text_response("nope")] * 6)+ with pytest.raises(ModelError) as ei:+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"}))+ assert ei.value.usage.input_tokens == 100 and ei.value.usage.output_tokens == 20+ assert ei.value.usage.cost_usd > 0diff --git a/harness/tests/models/test_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.pyindex 22887b42..1535417f 100644--- a/harness/tests/models/test_gemini_scheduling.py+++ b/harness/tests/models/test_gemini_scheduling.py@@ -214,3 +214,25 @@ def test_a_clean_call_reports_one_attempt_and_a_failed_call_carries_its_count():with pytest.raises(ModelError) as ei:m2.generate(ChatRequest(messages=[ChatMessage.user("x")]))assert ei.value.attempts == 1, "the ledger's error row gets the count too"+# ------------------------------------------ per-attempt HTTP timeout (audit 2026-08-27)+def test_a_small_budget_shortens_the_per_attempt_http_timeout():+ """A 20 s-budget turn used to hand the provider a 300 s socket: the per-attempt+ HTTP timeout is now min(timeout_s, remaining budget), floored at+ HTTP_TIMEOUT_FLOOR_S so a nearly-expired call still gets one real attempt."""+ from codeverse.models.gemini import HTTP_TIMEOUT_FLOOR_S++ m, log, _ = make_model([text_response("a"), text_response("b"), text_response("c")],+ timeout_s=300.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))+ assert log[0]["config"].http_options.timeout == 300_000 # plenty of budget: the full read timeout+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=60))+ assert 55_000 <= log[1]["config"].http_options.timeout <= 60_000+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=5))+ assert log[2]["config"].http_options.timeout == int(HTTP_TIMEOUT_FLOOR_S * 1000)+++def test_the_floor_never_raises_an_explicitly_small_read_timeout():+ """A model built with timeout_s below the floor keeps its own ceiling."""+ m, log, _ = make_model([text_response("a")], timeout_s=8.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=5))+ assert log[0]["config"].http_options.timeout == 8_000diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.pyindex 8e697127..7f16068c 100644--- a/harness/tests/models/test_keypool.py+++ b/harness/tests/models/test_keypool.py@@ -3,6 +3,7 @@from __future__ import annotationsimport threading+import timeimport pytest@@ -174,3 +175,14 @@ def test_try_acquire_never_waits_for_a_key_or_a_slot():pool.report("k2", "429")assert pool.try_acquire() is None, "every key is cooling down: no wait, no key"assert pool.stats()["in_flight"] == 0, "a refused try_acquire holds nothing"+def test_the_in_flight_slot_wait_is_bounded_by_timeout():+ """acquire()'s max_in_flight semaphore used to be an unbounded wait; the same+ timeout budget now bounds it and raises the pool's own error shape."""+ pool = KeyPool(["a"], max_in_flight=1, rpm_per_key=10_000)+ pool.acquire()+ t0 = time.monotonic()+ with pytest.raises(KeyPoolExhausted):+ pool.acquire(timeout_s=0.05)+ assert time.monotonic() - t0 < 2.0, "the slot wait must honour the timeout"+ pool.release()+ assert pool.acquire(timeout_s=0.5) == "a", "the slot came back; nothing leaked"diff --git a/harness/tests/models/test_keypool_tpm.py b/harness/tests/models/test_keypool_tpm.pyindex a58716be..ddc736e0 100644--- a/harness/tests/models/test_keypool_tpm.py+++ b/harness/tests/models/test_keypool_tpm.py@@ -69,13 +69,25 @@ def test_the_bucket_may_go_negative_and_is_paid_off_by_refill():def test_a_call_that_never_reached_the_model_is_refunded():- """429 / capacity storm: nothing was spent, so the reservation comes back."""+ """429 / capacity storm: nothing was spent, so the reservation comes back.+ (A charged-but-invalid reply is NOT this case — retry.py reports its real+ ``ModelError.usage`` prompt tokens; see the next test.)"""pool, _ = make(keys=("a",), tpm_per_key=100_000, cooldown_s=0.0)pool.acquire(tokens_hint=90_000)pool.report("a", "5xx", reserved=90_000)assert tpm_left(pool, "a") == pytest.approx(100_000)+def test_a_charged_but_invalid_reply_keeps_its_consumption():+ """A bad-JSON reply is billed like a good one: reporting its real tokens must+ reconcile the reservation instead of refunding it (the 42k-TPM-giveback bug,+ fixed 2026-08-27 — retry.run_one now passes ``tokens=err.usage.input_tokens``)."""+ pool, _ = make(keys=("a",), tpm_per_key=100_000)+ pool.acquire(tokens_hint=50_000)+ pool.report("a", "error", tokens=42_000, reserved=50_000)+ assert tpm_left(pool, "a") == pytest.approx(58_000)++def test_tokens_used_counter_is_reported():pool, _ = make(keys=("a",), tpm_per_key=100_000)pool.acquire(tokens_hint=1_000)diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.pyindex 9b2636c6..0ca35158 100644--- a/harness/tests/models/test_retry.py+++ b/harness/tests/models/test_retry.py@@ -321,8 +321,15 @@ def test_one_call_cannot_retry_for_hours():logical call, while the docstring claimed "~5 min". Measured 2026-08-24: combinedwith a wall-clock ceiling that is only checked when a call is BILLED (a stalledcall bills nothing), a run with --max-minutes 90 reached 200 minutes.++ Since 2026-08-27 the deadline is threaded through every branch of the loop and+ ``GeminiModel`` clips each attempt's HTTP read timeout to the remaining budget,+ floored at ``HTTP_TIMEOUT_FLOOR_S`` (simulated by ``call`` below) — so ONE call+ may overshoot by at most one floored in-flight attempt, never by a full 300 s+ socket."""from codeverse.models.base import ModelError+ from codeverse.models.gemini import HTTP_TIMEOUT_FLOOR_Sfrom codeverse.models.keypool import KeyPoolfrom codeverse.models.retry import RETRY_DEADLINE_S, rotate_with_retries@@ -334,7 +341,10 @@ def test_one_call_cannot_retry_for_hours():clock["t"] += ddef call(_key):- clock["t"] += 300.0 # the read timeout each doomed attempt burns+ # the budget-clipped read timeout each doomed attempt burns+ # (gemini.py _attempt_config: min(300 s, remaining), floored at 20 s)+ remaining = RETRY_DEADLINE_S - clock["t"]+ clock["t"] += min(300.0, max(HTTP_TIMEOUT_FLOOR_S, remaining))raise RuntimeError("503 high demand")with pytest.raises(ModelError):@@ -345,9 +355,10 @@ def test_one_call_cannot_retry_for_hours():sleep=sleep, monotonic=lambda: clock["t"],hedge=1, # the fake clock is serial; two hedged 300 s calls would add 600 s, not 300)- # the whole point: bounded by the clock, not by 60 x (timeout + wait)- assert clock["t"] <= RETRY_DEADLINE_S + 305.0, (- f"one call burned {clock['t'] / 3600:.1f} h; the deadline is {RETRY_DEADLINE_S / 60:.0f} min")+ # the whole point: bounded by the clock — the ONLY legal overshoot is the one+ # floored attempt that was already in flight when the deadline passed+ assert clock["t"] <= RETRY_DEADLINE_S + HTTP_TIMEOUT_FLOOR_S, (+ f"one call burned {clock['t'] / 3600:.2f} h; the deadline is {RETRY_DEADLINE_S / 60:.0f} min")assert clock["t"] < 5 * 3600, "this is the 5.1-hour regression"@@ -607,3 +618,145 @@ def test_a_dead_key_among_the_hedge_is_benched_once_the_sibling_wins():assert _rotate(pool, call, max_attempts=3, storm_attempts=10) == "ok:k3"_wait_idle(pool)assert pool.stats()["n_dead"] == 1, "k3 proved the request fine, so k2's 403 was the key's fault"+# --------------------------------------------------------------------------- deadline threading (2026-08-27)+def test_the_key_wait_is_clipped_to_the_remaining_budget():+ """pool.acquire used to be called with its own 120 s default no matter how little+ budget the call had left; now it gets min(ACQUIRE_TIMEOUT_S, remaining)."""+ from codeverse.models.keypool import ACQUIRE_TIMEOUT_S++ seen: list[float | None] = []++ class SpyPool(KeyPool):+ def acquire(self, *, tokens_hint=0, exclude=None, timeout_s=None):+ seen.append(timeout_s)+ return super().acquire(tokens_hint=tokens_hint, exclude=exclude, timeout_s=timeout_s)++ pool = SpyPool(["k1"], rpm_per_key=10_000)+ assert _rotate(pool, lambda key: "ok", max_total_s=50.0) == "ok"+ assert _rotate(pool, lambda key: "ok") == "ok" # the default budget: the pool default caps+ assert seen[0] == pytest.approx(50.0, abs=1.0)+ assert seen[1] == pytest.approx(ACQUIRE_TIMEOUT_S, abs=1.0)+++def test_a_storm_wait_is_clipped_to_the_remaining_budget():+ """Sleeping past the deadline only to give up on waking helps nobody."""+ clock = {"t": 0.0}+ naps: list[float] = []++ def sleep(d):+ naps.append(d)+ clock["t"] += d++ with pytest.raises(ModelError):+ rotate_with_retries(+ KeyPool(["k1"], rpm_per_key=10_000),+ lambda key: (_ for _ in ()).throw(RuntimeError("503 high demand")),+ classify=lambda e: ModelError(str(e), retryable=True, status=503),+ outcome_of=lambda e: "5xx", max_attempts=6, storm_attempts=60,+ base_delay=4.0, storm_max_delay=5.0, max_total_s=3.0,+ sleep=sleep, monotonic=lambda: clock["t"], hedge=1,+ )+ assert naps, "expected the storm path to sleep"+ assert clock["t"] <= 3.0 + 1e-6, f"slept past the deadline: {clock['t']}"+++def test_free_429_rotation_cannot_outlive_the_deadline():+ """Free rotation costs no attempts but DOES cost wall clock (0.5 s per hop):+ with many keys it used to spin long past the budget."""+ clock = {"t": 0.0}+ keys = [f"k{i}" for i in range(1, 11)]+ pool = KeyPool(keys, rpm_per_key=10_000, cooldown_s=0.0,+ clock=lambda: clock["t"], sleep=lambda s: clock.__setitem__("t", clock["t"] + s))+ calls: list[str] = []++ def call(key):+ calls.append(key)+ raise ModelError("quota", retryable=True, status=429)++ def sleep(d):+ clock["t"] += d++ with pytest.raises(ModelError) as ei:+ rotate_with_retries(+ pool, call, classify=_classify, outcome_of=_outcome, max_attempts=6,+ max_total_s=2.0, sleep=sleep, monotonic=lambda: clock["t"],+ )+ assert ei.value.status == 429+ assert clock["t"] <= 2.5, f"free rotation outlived the deadline: {clock['t']}"+ assert len(calls) <= 5, "ten keys would all have been tried before"+++def test_the_pool_is_not_refunded_for_a_charged_but_invalid_reply():+ """retry.py used to report tokens=0 for a bad-JSON failure, refunding a TPM+ reservation the provider had actually consumed — a 42k-token invalid reply+ handed the key 42k TPM back. ``ModelError.usage`` now carries the real bill."""+ from codeverse.contracts.common import Usage++ clock = {"t": 1000.0}+ pool = KeyPool(["k1"], rpm_per_key=10_000, tpm_per_key=100_000,+ clock=lambda: clock["t"], sleep=lambda s: clock.__setitem__("t", clock["t"] + s))+ calls = {"n": 0}++ def call(key):+ calls["n"] += 1+ if calls["n"] == 1:+ raise ModelError("structured output is not valid JSON", retryable=True,+ usage=Usage(input_tokens=42_000))+ return "ok"++ out = _rotate(pool, call, max_attempts=3, tokens_hint=1_000, tokens_of=lambda r: 100)+ assert out == "ok" and calls["n"] == 2+ left = pool._by_key["k1"].tpm.tokens # noqa: SLF001 - white-box on purpose+ assert left == pytest.approx(100_000 - 42_000 - 100)+++# --------------------------------------------------------------------------- on_attempt hook (2026-08-27)+def test_on_attempt_hears_every_round_trip_and_a_late_hedge_loser():+ """The per-attempt hook: the winner flushes as not-discarded, every failed try+ as discarded, and a hedge loser still in flight reports (discarded — a late+ success included) when it lands. That is how a loser's paid tokens reach the+ cost ledger at all."""+ pool = KeyPool(["k1", "k2", "k3", "k4"], rpm_per_key=10_000)+ release_k2 = threading.Event()+ lock = threading.Lock()+ recs: list[tuple[int, str, str, bool]] = [] # (attempt_no, key, outcome, discarded)++ def on_attempt(t, no, discarded):+ with lock:+ recs.append((no, t.key, t.outcome, discarded))++ def call(key):+ if key == "k1":+ raise ModelError("503 high demand", retryable=True, status=503)+ if key == "k2":+ assert release_k2.wait(5.0)+ return "late:k2"+ return "ok:k3"++ out = _rotate(pool, call, max_attempts=3, storm_attempts=10, on_attempt=on_attempt)+ assert out == "ok:k3"+ with lock:+ flushed = list(recs)+ assert (1, "k1", "5xx", True) in flushed+ winner = next(r for r in flushed if not r[3])+ assert winner[1] == "k3" and winner[2] == "ok"+ release_k2.set()+ t_end = time.monotonic() + 5.0+ while time.monotonic() < t_end:+ with lock:+ if len(recs) == 3:+ break+ time.sleep(0.005)+ with lock:+ loser = next(r for r in recs if r[1] == "k2")+ assert loser[3] is True and loser[2] == "ok", "a loser that succeeds late is still discarded"+ _wait_idle(pool)+++def test_a_broken_on_attempt_hook_never_breaks_the_call():+ pool = KeyPool(["k1"], rpm_per_key=10_000)++ def hook(t, no, discarded):+ raise RuntimeError("accounting on fire")++ assert _rotate(pool, lambda key: "ok", on_attempt=hook) == "ok"diff --git a/harness/tests/models/test_storm.py b/harness/tests/models/test_storm.pyindex e73e4bf9..55e41671 100644--- a/harness/tests/models/test_storm.py+++ b/harness/tests/models/test_storm.py@@ -154,3 +154,11 @@ def test_many_workers_share_one_storm_discovery():for t in threads:t.join(3)assert len(calls) == 12 # everybody gets through once the gate reopens+def test_enter_returns_at_the_deadline_even_mid_storm():+ """A parked worker with a retry deadline gets control back at that deadline+ (rotate_with_retries then raises); the gate never holds it hostage."""+ gate, clock = make(base_delay=4.0)+ gate.hit()+ waited = gate.enter(deadline=clock.t + 1.5)+ assert waited == pytest.approx(1.5)+ assert gate.storming, "the storm is still on; only this caller's budget ended"