Official Codebase of 3DCodeVerse
Python
Delete 503 hedging and the per-attempt ledger sink: a billed failed round-trip joins the call's one row; drop Gemini's C3D_STREAM/C3D_IPV4, retry_after, write-only raw fields, doctor's pool rows, transcript line rows, stale cost bits
gaoypenga4f1bb59904b
diff --git a/harness/codeverse3d/addons/costreport/audit.py b/harness/codeverse3d/addons/costreport/audit.pyindex d05e3f77..9a4d64a8 100644--- a/harness/codeverse3d/addons/costreport/audit.py+++ b/harness/codeverse3d/addons/costreport/audit.py@@ -55,7 +55,7 @@ def _rows(root: Path, led: RunLedger, *, recheck: bool) -> None:cached_tokens=row.cached_tokens, output_tokens=row.output_tokens,thoughts_tokens=row.thoughts_tokens, tool_calls=row.tool_calls, cost_usd=row.recorded_usd)cost, fields = price_call(usage, backend=row.backend, model=row.model_id or row.model,- cache_write_tokens=row.cache_write_tokens, reprice=True)+ reprice=True)row = row.model_copy(update={"cost_usd": cost, **fields})led.rows.append(row)diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.pyindex 5cf878d7..82abff3d 100644--- a/harness/codeverse3d/agents/cli_common.py+++ b/harness/codeverse3d/agents/cli_common.py@@ -30,10 +30,6 @@ from codeverse3d.proc import ()from codeverse3d.workspace import Workspace-#: per-session transcript caps; the unabridged (bounded) stream still lands in stdout.json-LINE_BUDGET_BYTES = 64 * 1024 * 1024-LINE_BUDGET_ROWS = 200_000-class Trajectory:@@ -41,9 +37,6 @@ class Trajectory:self.dir = Path(directory)self.dir.mkdir(parents=True, exist_ok=True)self._lock = threading.Lock()- self._budget = threading.Lock() # guards the counters below, never nested in _lock- self._rows = self._bytes = 0- self._spent = False# ------------------------------------------------------------------ paths@property@@ -70,19 +63,8 @@ class Trajectory:return pdef append(self, kind: str, **data: Any) -> None:- """Append one JSONL turn: ``{"t": epoch, "kind": kind, **data}``, until the- session's byte/row budget trips — then one marker row and nothing more."""- rec: dict[str, Any] = {"t": round(time.time(), 3), "kind": kind, **data}- with self._budget:- if self._spent:- return- self._rows += 1- self._bytes += len(json.dumps(rec, ensure_ascii=False, default=str))- self._spent = self._rows > LINE_BUDGET_ROWS or self._bytes > LINE_BUDGET_BYTES- if self._spent:- rec = {"t": rec["t"], "kind": "line_budget_exhausted",- "rows": self._rows - 1, "bytes": self._bytes}- append_jsonl_line(self.transcript_path, rec, self._lock)+ """Append one JSONL turn: ``{"t": epoch, "kind": kind, **data}``."""+ append_jsonl_line(self.transcript_path, {"t": round(time.time(), 3), "kind": kind, **data}, self._lock)def write_result(self, result: BaseModel, **extra: Any) -> None:write_json_atomic(self.result_path, result.model_dump(mode="json") | extra)@@ -311,9 +293,8 @@ class Session:# --------------------------------------------------------------------------- serialisation-#: agent kinds whose sessions are EXCLUSIVE per workspace (every kind): scope is checked post-session,-#: and a late session's ``pre:`` commit (``git add -A``) would absorb a sibling's in-flight writes.-EXCLUSIVE_KINDS = frozenset({"claude-code", "codex", "agy"})+# Sessions are EXCLUSIVE per workspace: scope is checked post-session, and a late session's+# ``pre:`` commit (``git add -A``) would absorb a sibling's in-flight writes._WS_SESSION_LOCKS: dict[str, threading.RLock] = {}_WS_SESSION_LOCKS_GUARD = threading.Lock()@@ -354,7 +335,7 @@ def _session_label(ws: Workspace, label: str, round_index: int) -> tuple[str, indef begin_session(job: AgentJob, kind: str) -> Session:"""Create the trajectory dir, write prompt.md and snapshot src/ (``pre:<label>``), taking the- per-workspace lock first for :data:`EXCLUSIVE_KINDS`."""+ per-workspace lock first."""ws = Workspace(job.workspace)if not ws.root.is_dir():raise FileNotFoundError(f"workspace does not exist: {ws.root}")@@ -365,14 +346,12 @@ def begin_session(job: AgentJob, kind: str) -> Session:traj = Trajectory(ws.trajectory_dir(label, round_index))traj.write_prompt(job.prompt, job.system_append)hints = _clean(job.files_hint)- lock = _session_lock(ws) if kind in EXCLUSIVE_KINDS else None- if lock is not None:- lock.acquire()+ lock = _session_lock(ws)+ lock.acquire()try:head_before = ws.commit(f"pre:{label}")except BaseException:- if lock is not None:- lock.release()+ lock.release()raisecontrol = {n: ((ws.root / n).read_bytes() if (ws.root / n).is_file() else None)for n in UNTRACKED_CONTROL_FILES}@@ -516,7 +495,7 @@ def invoke("""Run one CLI agent process under the watchdog and record it in the trajectory.The prompt goes to the CLI on STDIN for every backend (never argv or a file the agent must- read). Output lines go into the transcript; ``src/`` + ``public/`` (a ``shared_tree`` job's own+ read). The raw streams land in ``stdout_name`` and ``stderr.log``; ``src/`` + ``public/`` (a ``shared_tree`` job's ownfiles) plus ``activity`` are the activity dirs. ``stdout_name`` names the capture;``on_stdout`` / ``on_stderr`` also receive each line; ``invoke_extra`` lands in the ``invoke`` row."""@@ -530,7 +509,6 @@ def invoke(soft_timeout_s=soft, hard_timeout_s=hard, started=hard > 0, **invoke_extra)def on_line(stream: str, line: str) -> None:- s.traj.append("line", stream=stream, text=line[:4000])observer = on_stdout if stream == "stdout" else on_stderrif observer is not None:observer(line)diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.pyindex e4079527..15b0e061 100644--- a/harness/codeverse3d/config.py+++ b/harness/codeverse3d/config.py@@ -135,7 +135,7 @@ class Limits(BaseModel):class Rate(BaseModel):- """The model-call ceiling and the 503 hedge.+ """The model-call ceiling.``max_in_flight`` is machine-wide (flock'd slot files under ``<cache_dir>/slots/``), separatefrom the core-bound ``Limits`` fan-outs. 0 = unlimited. A vendor CLI session takes a key@@ -152,13 +152,6 @@ class Rate(BaseModel):"keys; raised 64 → 96 on 2026-10-15 for the 30-key pool after iteration 0 of the argon loop hit the ""64 cap 172 times at launch while the keys themselves showed no 429 pressure (12 concurrent calls on ""one key: 0 × 429; re-measure the knee when the loops run two tracks at once).")- hedge: int = Field(- default=2, ge=1,- description="keys a retry is raced on once a call has met its first 503 (1 = off). Measured "- "2026-08-26: a failed 503 costs the 21-50 s round-trip the provider holds before rejecting, "- "storm streaks average 4.7 attempts, and a 503 bills nothing — so the hedge is free while it "- "storms and wastes one call only when both keys answer (docs/COST.md §27). "- "C3D_RATE__HEDGE=1 for the A/B.")class Judge(BaseModel):@@ -296,10 +289,6 @@ class Settings(BaseSettings):camera_repair: Flag = Field(default=True, description="scene driver: move a camera out of geometry ""(zero triggers on a healthy battery; the case it exists for is fatal)")post: Flag = Field(default=True, description="scene pictures: the GTAO + bloom + grade post chain")- stream: Flag = Field(default=True, description="Gemini: stream replies with inter-chunk stall "- "detection (a hung buffered read held the socket for the whole attempt)")- ipv4: Flag = Field(default=True, description="Gemini: bind the transport to IPv4 (the WSL2 IPv6 "- "path dropped responses silently)")runtime_js: Path | None = Field(default=None, description="the node runtime directory; a ""non-editable install must point this at a checkout")diff --git a/harness/codeverse3d/cost/context.py b/harness/codeverse3d/cost/context.pyindex 1915a1be..6bb4da13 100644--- a/harness/codeverse3d/cost/context.py+++ b/harness/codeverse3d/cost/context.py@@ -8,12 +8,11 @@ process-wide fallback.from __future__ import annotations-from collections.abc import Callable, Iterator+from collections.abc import Iteratorfrom contextlib import contextmanagerfrom contextvars import ContextVarfrom dataclasses import dataclass, replace-from codeverse3d.contracts.common import Usagefrom codeverse3d.cost.types import Role, Stage, role_for_stage, stage_for_label@@ -167,44 +166,5 @@ def attribute(explicit: CallContext | None = None, *, label: str = "") -> CallCoreturn ctx.resolved()-# --------------------------------------------------------------------------- per-attempt sink-@dataclass(frozen=True)-class AttemptRecord:- """One round-trip of one logical model call, reported to the sink from :func:`attempt_recording`.-- Every round-trip is reported, winner included; a discarded one that cost money becomes a- ``source="extra"`` ledger row."""-- 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 #: the KeyPool report vocabulary (``models.retry``): ok | 429 | 5xx | error | dead, plus whatever the pool adds- 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; the backend captures it once at call entry so a-#: hedge loser landing later in another thread still reports.-_attempt_sink: ContextVar[AttemptSink | None] = ContextVar("c3d_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", "bound_run", "call_context", "context_from_label", "current",+__all__ = ["CallContext", "attribute", "bound_run", "call_context", "context_from_label", "current","run_binding"]diff --git a/harness/codeverse3d/cost/instrument.py b/harness/codeverse3d/cost/instrument.pyindex 0304b52c..c299b936 100644--- a/harness/codeverse3d/cost/instrument.py+++ b/harness/codeverse3d/cost/instrument.py@@ -13,29 +13,22 @@ from collections.abc import Iteratorfrom contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any-from uuid import uuid4from codeverse3d.contracts.agent import AgentJob, AgentResultfrom codeverse3d.contracts.chat import ChatRequest, ChatResponsefrom codeverse3d.contracts.common import Usagefrom codeverse3d.cost.context import (- AttemptRecord,- CallContext,- attempt_recording,- attribute,bound_run,call_context,- run_binding,)from codeverse3d.cost.ledger import (CostLedger,bound_ledger,- default_ledger,existing_ledger_path,open_run_ledger,record_call,)-from codeverse3d.cost.tally import Tally, book_time, open_tallies+from codeverse3d.cost.tally import book_timefrom codeverse3d.cost.types import Role, Stage, stage_for_labellog = logging.getLogger(__name__)@@ -69,97 +62,37 @@ class MeteredChatModel(_Proxy):# -- 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- ledger = default_ledger()- run = run_binding().run- ctx = attribute(label=request.label)- tallies = open_tallies()- booked: list[int] = [] # round-trips that already billed themselves as "extra"- trips = _RoundTrips()-- def attempt_row(rec: AttemptRecord) -> None:- trips.add(rec)- if self._record_attempt(request, call_id, rec, ledger, run, ctx, tallies):- booked.append(rec.attempt)-t0 = time.perf_counter()try:- with attempt_recording(attempt_row):- resp = self._inner.generate(request)+ resp = self._inner.generate(request)except BaseException as exc: # noqa: BLE001 - record the attempt, then re-raise- # a failed call may still have been billed (ModelError.usage), unless a round-trip already booked it+ # a failed call may still have been billed (ModelError.usage)ms = int((time.perf_counter() - t0) * 1000)usage = getattr(exc, "usage", None)usage = usage if isinstance(usage, Usage) else Usage(backend=self.provider, model=self.model)- book_time(ms / 1000, trips.lost_ms(ms, usage.latency_ms) / 1000)- if booked:- usage = Usage(backend=usage.backend, model=usage.model, latency_ms=usage.latency_ms)- self._record(usage, request, outcome=_outcome(exc), ms=ms,- attempts=getattr(exc, "attempts", 0), call_id=call_id)+ book_time(ms / 1000, _lost_s(ms, usage.latency_ms))+ self._record(usage, request, outcome=_outcome(exc), ms=ms, attempts=getattr(exc, "attempts", 0))raisems = int((time.perf_counter() - t0) * 1000)- book_time(ms / 1000, trips.lost_ms(ms, resp.usage.latency_ms) / 1000)+ book_time(ms / 1000, _lost_s(ms, resp.usage.latency_ms))self._record(resp.usage, request, outcome="ok", ms=ms,- key=resp.raw.get("key"), attempts=resp.raw.get("attempts", 0),- call_id=call_id)+ key=resp.raw.get("key"), attempts=resp.raw.get("attempts", 0))return respdef _record(self, usage: Usage, request: ChatRequest, *, outcome: str, ms: int,- key: object = None, attempts: object = 0, call_id: str = "") -> None:+ key: object = None, attempts: object = 0) -> 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), call_id=call_id)+ key=_key_suffix(key), attempts=int(attempts or 0))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, run: str = "",- ctx: CallContext | None = None, tallies: tuple[Tally, ...] | None = None) -> bool:- """Book a discarded round-trip that still cost money as ``source="extra"``; True when it did."""- if not (rec.discarded and rec.usage.cost_usd):- return False- try:- record_call(rec.usage, run=run, label=request.label,- stage=ctx.stage if ctx else None, role=ctx.role if ctx else None,- round=ctx.round if ctx else None,- 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="extra", key=_key_suffix(rec.key),- call_id=call_id, attempt=rec.attempt, discarded=rec.discarded,- ledger=ledger, tallies=tallies)- 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)- return False- return True---class _RoundTrips:- """The round-trips of one logical call, reduced to what the minutes need: time answered, any failure."""-- def __init__(self) -> None:- self.answered_ms = 0 # the winner, and a reply that came back unusable (bad JSON, empty)- self.failed = False # a round-trip with no answer at all: 503 / 429 / timeout / transport / dead key- self.seen = False-- def add(self, rec: AttemptRecord) -> None:- self.seen = True- if rec.discarded and rec.outcome == "ok":- return # a hedge loser that answered ran beside the winner, not before it- if rec.usage.latency_ms:- self.answered_ms += rec.usage.latency_ms- elif rec.outcome != "ok":- self.failed = True-- def lost_ms(self, wall_ms: int, answer_ms: int) -> int:- """Milliseconds lost to provider errors: everything outside the answered round-trips once one failed."""- if not self.seen:- return max(0, wall_ms - answer_ms)- return max(0, wall_ms - self.answered_ms) if self.failed else 0++def _lost_s(wall_ms: int, answered_ms: int) -> float:+ """Seconds lost to provider errors: the call's wall time outside the answered round-trips."""+ return max(0, wall_ms - answered_ms) / 1000def _key_suffix(key: object) -> str:diff --git a/harness/codeverse3d/cost/ledger.py b/harness/codeverse3d/cost/ledger.pyindex 981506b3..3efc32ef 100644--- a/harness/codeverse3d/cost/ledger.py+++ b/harness/codeverse3d/cost/ledger.py@@ -19,7 +19,7 @@ from typing import Anyfrom codeverse3d.contracts.common import Usagefrom codeverse3d.cost.context import CallContext, _stage, attribute-from codeverse3d.cost.tally import Tally, book_usage+from codeverse3d.cost.tally import book_usagefrom codeverse3d.cost.types import (CallCost,CostBucket,@@ -30,7 +30,6 @@ from codeverse3d.cost.types import (role_for_stage,)from codeverse3d.models.pricing import (- cache_write_surcharge,estimate_cost,price_provenance,unit_prices,@@ -139,7 +138,6 @@ def price_call(*,backend: str = "",model: str = "",- cache_write_tokens: int = 0,reprice: bool = False,) -> tuple[float, dict[str, Any]]:"""``(cost_usd, price fields)`` for one call.@@ -157,8 +155,6 @@ def price_call("price_checked": row.checked}if reprice or not cost:cost = estimate_cost(provider, name, usage)- if cache_write_tokens:- cost += cache_write_surcharge(provider, name, cache_write_tokens)source = row.match if row.price is not None else "unknown"if row.price is None and float(usage.cost_usd) > 0:source = "provider-reported" # the backend billed us; our table cannot explain it@@ -189,16 +185,14 @@ def record_call(model: str = "",outcome: str = "ok",latency_ms: int | None = None,- cache_write_tokens: int = 0,n_calls: int = 1,source: str = "live",ledger: CostLedger | str | Path | None = None,ts: float | None = None,reprice: bool = False,- tallies: tuple[Tally, ...] | None = None,**extra: Any,) -> CallCost:- """Append one priced call to the ledger, book it into the open tallies (or ``tallies``), return the row.+ """Append one priced call to the ledger, book it into the open tallies, return the row.Unstated ``run`` / ``round`` / ``stage`` / ``role`` resolve from the ambient context and label.Never raises."""@@ -209,8 +203,7 @@ def record_call(rl = ctx.role or role_for_stage(st)run, round, label = ctx.run, ctx.round, ctx.label # noqa: A001 - see the signaturetry:- cost, price_fields = price_call(u, backend=backend, model=model,- cache_write_tokens=cache_write_tokens, reprice=reprice)+ cost, price_fields = price_call(u, backend=backend, model=model, reprice=reprice)except Exception as e: # pragma: no cover - pricing must never break a runlog.warning("cost: pricing failed for %s/%s: %s", backend, model, e)cost, price_fields = float(u.cost_usd), {}@@ -225,7 +218,6 @@ def record_call(cached_tokens=int(u.cached_tokens),output_tokens=int(u.output_tokens),thoughts_tokens=int(u.thoughts_tokens),- cache_write_tokens=int(cache_write_tokens),tool_calls=int(u.tool_calls),cost_usd=cost,recorded_usd=float(u.cost_usd),@@ -241,7 +233,7 @@ def record_call(book_usage(Usage(backend=row.backend, model=row.model, input_tokens=row.input_tokens,output_tokens=row.output_tokens, cached_tokens=row.cached_tokens,thoughts_tokens=row.thoughts_tokens, tool_calls=row.tool_calls,- cost_usd=row.cost_usd, latency_ms=row.latency_ms), tallies)+ cost_usd=row.cost_usd, latency_ms=row.latency_ms))return rowdiff --git a/harness/codeverse3d/cost/tally.py b/harness/codeverse3d/cost/tally.pyindex 3800ab7f..e6f6bb6b 100644--- a/harness/codeverse3d/cost/tally.py+++ b/harness/codeverse3d/cost/tally.py@@ -56,18 +56,13 @@ def tally() -> Iterator[Tally]:_open.reset(token)-def open_tallies() -> tuple[Tally, ...]:- """The tallies this context books into, for callers whose work lands later in a thread without it."""- return _open.get()---def book_usage(usage: Usage, tallies: tuple[Tally, ...] | None = None) -> None:- for t in open_tallies() if tallies is None else tallies:+def book_usage(usage: Usage) -> None:+ for t in _open.get():t.add_usage(usage)def book_time(wall_s: float, lost_s: float) -> None:- for t in open_tallies():+ for t in _open.get():t.add_time(max(0.0, wall_s), max(0.0, lost_s))@@ -85,4 +80,4 @@ def timed(step: str, into: list[StepTime], *, round_index: int | None = None) ->lost_s=round(min(wall, t.lost_s()), 2)))-__all__ = ["Tally", "book_time", "book_usage", "open_tallies", "tally", "timed"]+__all__ = ["Tally", "book_time", "book_usage", "tally", "timed"]diff --git a/harness/codeverse3d/cost/types.py b/harness/codeverse3d/cost/types.pyindex 939f5690..62bdc795 100644--- a/harness/codeverse3d/cost/types.py+++ b/harness/codeverse3d/cost/types.py@@ -101,35 +101,27 @@ def role_for_stage(stage: Stage) -> Role:#: agent/backend kind → pricing provider, when the model id carries no ``provider:`` prefix_BACKEND_PROVIDER: dict[str, str] = {"gemini": "gemini",- "gemini-cli": "gemini","codex": "openai","openai": "openai","claude-code": "anthropic","anthropic": "anthropic","agy": "gemini",- "antigravity": "gemini",}def split_model_id(backend: str, model: str) -> tuple[str, str]:- """``("api-agent", "gemini:gemini-3.8-flash") -> ("gemini", "gemini-3.8-flash")``.+ """``("agy", "gemini:gemini-3.8-flash") -> ("gemini", "gemini-3.8-flash")``.Without a provider prefix the backend kind decides; an unknown backend yields provider ``""``."""m = (model or "").strip()if ":" in m:provider, _, rest = m.partition(":")- while ":" in rest: # api-agent:gemini:gemini-3.8-flash- provider, _, rest = rest.partition(":")return provider.strip().lower(), rest.strip()- kind = (backend or "").strip().lower()- if kind.startswith("api-agent"):- kind = "gemini"- return _BACKEND_PROVIDER.get(kind, ""), m+ return _BACKEND_PROVIDER.get((backend or "").strip().lower(), ""), m#: agent session kinds that are not themselves an API provider-AGENT_KINDS = frozenset({"api-agent", "gemini-cli", "claude-code", "codex", "agy", "antigravity",- "single-shot"})+AGENT_KINDS = frozenset({"claude-code", "codex", "agy"})def normalise_ids(backend: str, model: str) -> tuple[str, str, str]:@@ -163,7 +155,6 @@ class CallCost(BaseModel):cached_tokens: int = 0output_tokens: int = 0thoughts_tokens: int = 0- cache_write_tokens: int = 0tool_calls: int = 0price_input: float = 0.0 # USD / 1M@@ -177,19 +168,14 @@ class CallCost(BaseModel):recorded_usd: float = 0.0 # what the run was billed at the time (before any re-pricing)latency_ms: int = 0cache_hit: bool = False- outcome: str = "ok" # ok | error | timeout | budget | degraded | discarded+ outcome: str = "ok" # ok | error | timeout | budget | degradedn_calls: int = 1 # >1 when a row aggregates a whole agent session- #: extra = a discarded but billed round-trip (counts in every total); estimate = priced from the stream- source: str = "live" # live | record | events | transcript | stdout | residual | session | estimate | attempt | extra+ #: estimate = priced from the stream+ source: str = "live" # live | record | events | transcript | stdout | residual | session | estimate#: last 4 chars of the API key that served the call ("…ab12"); "" when nonekey: str = ""#: round-trips issued for this call (1 = clean, 0 = not recorded)attempts: int = 0- #: joins a call's per-attempt rows to its logical row- call_id: str = ""- attempt: int = 0- #: this round-trip's response was thrown away (paid: ``source="extra"``, counted; free: ``attempt``, filtered)- discarded: bool = Falseclass CostBucket(BaseModel):diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.pyindex 66cd9fd1..273f3e7a 100644--- a/harness/codeverse3d/doctor.py+++ b/harness/codeverse3d/doctor.py@@ -233,21 +233,6 @@ def check_gpu_probe(timeout_s: int = 120) -> list[Row]:f"{'GPU' if res.get('gpu') else 'CPU/software'}: {renderer[:120]}")]-def check_pool(live: bool) -> list[Row]:- from codeverse3d.models.gemini import shared_pool-- s = get_settings()- if not live or not s.gemini_api_keys:- return []- st = shared_pool(list(s.gemini_api_keys)).stats()- return [(- "gemini pool", "WARN" if st["n_dead"] else "OK",- f"{st['n_keys']} keys · in-flight {st['in_flight']} (peak {st['peak_in_flight']}) · "- f"{st['acquired']} acquired, {st['ok']} ok, {st['429']} x429, {st['5xx']} x5xx, "- f"{st['n_dead']} dead, {st['n_cooling']} cooling (this process)",- )]--def check_keys(live: bool) -> list[Row]:s = get_settings()n = len(s.gemini_api_keys)@@ -281,10 +266,6 @@ def check_clis() -> list[Row]:rows.append((name, "OK" if okk else "WARN", v if okk else f"{v} (backend {name} unavailable)"))okk, v = _ver(["git", "--version"])rows.append(("git", "OK" if okk else "FAIL", v))- n = len(s.gemini_api_keys)- rows.append(("agy gemini keys", "OK" if n else "FAIL",- f"{n}-key pool (Gemini-API mode, 3dcode MCP, priced)" if n- else "no Gemini keys: agy runs on API keys only, so the default generator cannot run"))return rows@@ -309,7 +290,6 @@ def run_doctor(*, live: bool = False, gpu: bool = True) -> list[Row]:if gpu:rows += check_gpu_probe()rows += check_keys(live)- rows += check_pool(live)rows += check_clis()rows += check_mcp()return rowsdiff --git a/harness/codeverse3d/models/gemini.py b/harness/codeverse3d/models/gemini.pyindex 6b678086..49897c6f 100644--- a/harness/codeverse3d/models/gemini.py+++ b/harness/codeverse3d/models/gemini.py@@ -1,11 +1,10 @@"""Gemini backend: ``ChatRequest`` ⇄ google-genai conversion, and ``GeminiModel`` (shared-``KeyPool``, ``rotate_with_retries`` with hedge, streaming with stall detection, per-attempt ledger rows)."""+``KeyPool``, ``rotate_with_retries``, streaming with stall detection)."""from __future__ import annotationsimport loggingimport random-import reimport threadingimport timefrom collections.abc import Callable, Iterable@@ -24,9 +23,9 @@ from codeverse3d.contracts.chat import (ImagePart,)from codeverse3d.contracts.common import Usage-from codeverse3d.cost.context import AttemptRecord, attempt_sinkfrom codeverse3d.models.base import ModelErrorfrom codeverse3d.models.parts import (+ FailedBills,Stopwatch,attempt_timeout_s,default_timeout_s,@@ -36,7 +35,7 @@ from codeverse3d.models.parts import (retryable_status,)from codeverse3d.models.pricing import estimate_cost-from codeverse3d.models.retry import KeyPool, KeyPoolExhausted, OnAttempt, _Try, rotate_with_retries+from codeverse3d.models.retry import KeyPool, KeyPoolExhausted, rotate_with_retriesfrom codeverse3d.models.schema_utils import JsonParseError, parse_json_lenient, to_gemini_schema#: thinking level → token budget@@ -168,10 +167,8 @@ def extract_candidate(# ===================================================================== geminilog = logging.getLogger(__name__)-_RETRY_DELAY_RE = re.compile(r"retryDelay['\"]?\s*:\s*['\"]?(\d+(?:\.\d+)?)s")-#: ceiling of the inter-chunk read timeout under streaming: a hung socket dies within it,-#: while a long healthy stream is bounded only by its attempt budget (``C3D_STREAM=off`` buffers)+#: while a long healthy stream is bounded only by its attempt budgetSTREAM_STALL_S = 300.0_pools: dict[tuple[str, ...], KeyPool] = {}@@ -218,7 +215,9 @@ def _client_for(key: str, timeout_s: float, factory: Callable[[str], Any] | Noneclient = _clients.get(ck)if client is None:client = genai.Client(api_key=key, http_options=types.HttpOptions(- timeout=ck[1], client_args=_ipv4_client_args() or None))+ timeout=ck[1],+ # the WSL2 IPv6 path silently hangs reads: bind the transport to IPv4+ client_args={"transport": httpx.HTTPTransport(local_address="0.0.0.0")}))_clients[ck] = clientreturn client@@ -240,18 +239,6 @@ def classify_exception(exc: BaseException) -> ModelError:return ModelError(f"Gemini unexpected error: {type(exc).__name__}: {exc}", retryable=False)-def _retry_after_s(exc: BaseException) -> float | None:- """Gemini 429 bodies carry ``details[].retryDelay: "7s"``; honour it (capped)."""- m = _RETRY_DELAY_RE.search(str(exc))- 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: the WSL2 IPv6 path silently hangs reads- (``C3D_IPV4=off`` restores dual-stack)."""- return {"transport": httpx.HTTPTransport(local_address="0.0.0.0")} if get_settings().ipv4 else {}--def _drain_stream(it: Iterable[types.GenerateContentResponse],deadline: float,@@ -319,15 +306,12 @@ class GeminiModel:timeout_s: float | None = None,max_attempts: int = 6,storm_attempts: int | None = None,- hedge: int | None = None,sleep: Callable[[float], None] = time.sleep,client_factory: Callable[[str], Any] | None = None,) -> None:self.model = model#: None = rotate_with_retries' default; 0 = a 503 is final (the storm branch ignores max_attempts)self.storm_attempts = storm_attempts- #: keys a retry is raced on after the first 503 (1 = off)- self.hedge = max(1, int(_rate().hedge if hedge is None else hedge))keys = _keys_or_raise(keys, pool)self.pool = pool or shared_pool(keys)self.timeout_s = default_timeout_s() if timeout_s is None else timeout_s@@ -345,7 +329,6 @@ class GeminiModel:# --------------------------------------------------------------- generatedef generate(self, request: ChatRequest) -> ChatResponse:contents = to_contents(request.messages)- warnings: list[str] = []state = {"config": self._config(request)}def downgrade_thinking(err: ModelError) -> bool:@@ -354,31 +337,34 @@ class GeminiModel:return Falsewith self._lock:self._thinking_ok = False- warnings.append(f"{self.model} rejected thinking config; retrying without it: {err}")+ log.warning("%s rejected thinking config; retrying without it: %s", self.model, err)state["config"] = self._config(request)return Truebudget = retry_budget_s(request.max_wait_s)deadline = time.monotonic() + budgetstats: dict[str, Any] = {}- resp = rotate_with_retries(- self.pool,- lambda key: self._once(- key, contents, self._attempt_config(state["config"], deadline),- request, warnings,- ),- classify=classify_exception,- max_attempts=self.max_attempts,- max_total_s=budget,- hedge=self.hedge,- sleep=self._sleep,- on_free_retry=downgrade_thinking,- retry_after=_retry_after_s,- label=f"gemini {self.model}",- stats=stats,- on_attempt=self._attempt_hook(),- **({} if self.storm_attempts is None else {"storm_attempts": self.storm_attempts}),- )+ bills = FailedBills()+ try:+ resp = rotate_with_retries(+ self.pool,+ bills.track(lambda key: self._once(+ key, contents, self._attempt_config(state["config"], deadline),+ request,+ )),+ classify=classify_exception,+ max_attempts=self.max_attempts,+ max_total_s=budget,+ sleep=self._sleep,+ on_free_retry=downgrade_thinking,+ label=f"gemini {self.model}",+ stats=stats,+ **({} if self.storm_attempts is None else {"storm_attempts": self.storm_attempts}),+ )+ except ModelError as e:+ bills.charge(e)+ raise+ resp = bills.join(resp)resp.raw["attempts"] = int(stats.get("attempts", 0))return resp@@ -395,52 +381,27 @@ class GeminiModel:"""Config whose HTTP timeout is the remaining retry budget (see ``attempt_timeout_s``)."""return clip_timeout(config, int(attempt_timeout_s(deadline, self.timeout_s) * 1000))- def _attempt_hook(self) -> OnAttempt:- """Per-round-trip observer feeding the ledger's attempt sink (books discarded round-trips).- The sink is captured once per call so a late hedge loser still reports."""- sink = attempt_sink()-- 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)- if sink is not None:- sink(AttemptRecord(attempt=no, key=t.key, outcome=outcome,- discarded=discarded, usage=usage, error=error))-- return on_attempt-def _once(self,key: str,contents: list[types.Content],config: types.GenerateContentConfig,request: ChatRequest,- warnings: list[str],) -> ChatResponse:client = _client_for(key, self.timeout_s, self._client_factory)- if not get_settings().stream: # C3D_STREAM=off: the buffered call- with Stopwatch() as sw:- resp = client.models.generate_content(- model=self.model, contents=contents, config=config- )- else:- # the attempt budget becomes an in-loop deadline; the wire timeout drops to the stall ceiling- 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)+ # the attempt budget becomes an in-loop deadline; the wire timeout drops to the stall ceiling+ 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, whose raises carry itusage.latency_ms = sw.msusage.cost_usd = estimate_cost("gemini", self.model, usage)@@ -464,12 +425,5 @@ class GeminiModel:) from excelif finish in RETRYABLE_FINISH and not text.strip():raise ModelError(f"Gemini finish_reason={finish}", retryable=True, usage=usage)- raw: dict[str, Any] = {- "finish_reason": finish,- "model_version": resp.model_version,- "response_id": resp.response_id,- "key": f"…{key[-4:]}",- }- if warnings:- raw["warnings"] = list(warnings)- return ChatResponse(text=text, parsed=parsed, finish_reason=finish, usage=usage, raw=raw)+ return ChatResponse(text=text, parsed=parsed, finish_reason=finish, usage=usage,+ raw={"key": f"…{key[-4:]}"})diff --git a/harness/codeverse3d/models/health.py b/harness/codeverse3d/models/health.pyindex 70304233..ba7434d3 100644--- a/harness/codeverse3d/models/health.py+++ b/harness/codeverse3d/models/health.py@@ -103,7 +103,7 @@ def _bare_model(model_id: str, timeout_s: float, key: str | None = None):model_id = f"gemini:{model_id}"extra: dict[str, Any] = {}if model_id.startswith("gemini:"):- extra = {"storm_attempts": 0, "hedge": 1}+ extra = {"storm_attempts": 0}if key is not None:extra["keys"] = [key]return build_chat_model(model_id, timeout_s=timeout_s, max_attempts=1, **extra)diff --git a/harness/codeverse3d/models/parts.py b/harness/codeverse3d/models/parts.pyindex 0f99efa7..23141659 100644--- a/harness/codeverse3d/models/parts.py+++ b/harness/codeverse3d/models/parts.py@@ -146,26 +146,51 @@ def attempt_timeout_s(deadline: float, ceiling: float) -> float:return min(ceiling, max(SDK_TIMEOUT_FLOOR_S, deadline - time.monotonic()))+class FailedBills:+ """What the failed attempts of ONE logical call were billed for (``ModelError.usage``): it joins+ the call's single ledger row, on success and on a final failure alike."""++ def __init__(self) -> None:+ self.usage = Usage()++ def track[T](self, attempt: Callable[..., T]) -> Callable[..., T]:+ """``attempt`` that remembers the usage of every ``ModelError`` it raises."""+ def run(*args: Any) -> T:+ try:+ return attempt(*args)+ except ModelError as e:+ if e.usage is not None:+ self.usage = self.usage + e.usage+ raise+ return run++ @property+ def billed(self) -> bool:+ return bool(self.usage.input_tokens or self.usage.output_tokens)++ def join(self, resp: Any) -> Any:+ """``resp`` with the failed attempts' usage added."""+ return resp.model_copy(update={"usage": resp.usage + self.usage}) if self.billed else resp++ def charge(self, err: ModelError) -> None:+ """A finally-raised error carries ALL the usage billed (its own attempt included)."""+ if self.billed:+ err.usage = self.usage++def retry_one_key(attempt: Any, *, label: str, classify: Any, attempts: int, sleep: Any,max_wait_s: float | None = None) -> Any:- """The SDK adapters' retry loop: ``rotate_with_retries`` over a one-key pool, no cooldown,- storm patience or hedge, inside the request's ``max_wait_s`` deadline."""+ """The SDK adapters' retry loop: ``rotate_with_retries`` over a one-key pool, no cooldown or+ storm patience, inside the request's ``max_wait_s`` deadline."""from codeverse3d.models.retry import KeyPool, rotate_with_retries- billed = Usage() # what failed attempts were billed for (ModelError.usage): joins the winner's row-- def once() -> Any:- nonlocal billed- try:- return attempt()- except ModelError as e:- if e.usage is not None:- billed = billed + e.usage- raise-- resp = rotate_with_retries(KeyPool([label], cooldown_s=0.0), lambda _key: once(), classify=classify,- max_attempts=attempts, max_total_s=retry_budget_s(max_wait_s),- storm_attempts=0, hedge=1, sleep=sleep, label=label)- if billed.input_tokens or billed.output_tokens:- resp = resp.model_copy(update={"usage": resp.usage + billed})- return resp+ bills = FailedBills()+ try:+ resp = rotate_with_retries(KeyPool([label], cooldown_s=0.0), lambda _key: bills.track(attempt)(),+ classify=classify, max_attempts=attempts,+ max_total_s=retry_budget_s(max_wait_s), storm_attempts=0,+ sleep=sleep, label=label)+ except ModelError as e:+ bills.charge(e)+ raise+ return bills.join(resp)diff --git a/harness/codeverse3d/models/retry.py b/harness/codeverse3d/models/retry.pyindex 100222e6..85c3bf48 100644--- a/harness/codeverse3d/models/retry.py+++ b/harness/codeverse3d/models/retry.py@@ -2,7 +2,7 @@``KeyPool``: multi-key pool with 429 cooldown, dead-key benching, health scores and amachine-wide ``max_in_flight`` ceiling (``Slots``, flock'd lock files). ``rotate_with_retries``:-the one retry loop (pool, hedging, ``RETRY_DEADLINE_S``); SDK adapters run it over a one-key pool.+the one retry loop (pool, ``RETRY_DEADLINE_S``); SDK adapters run it over a one-key pool.Every wait clips to ``MAX_WAIT_S``. ``report`` outcomes: ok | 429 | 5xx | error | dead | skip(``skip`` = a content failure the key did not cause). Thread-safe; ``clock`` / ``sleep`` injectable."""@@ -16,10 +16,8 @@ import osimport randomimport threadingimport time-from collections.abc import Callable, Sequence-from concurrent.futures import Future, ThreadPoolExecutor, as_completed+from collections.abc import Callablefrom dataclasses import dataclass-from functools import partialfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal@@ -82,8 +80,6 @@ class _KeyState:n_429: int = 0n_5xx: int = 0n_error: int = 0- n_dead: int = 0- n_acquired: int = 0health_ts: float = 0.0def recover(self, now: float, rate: float = 0.01) -> None:@@ -191,7 +187,6 @@ class KeyPool:self._lock = threading.Lock()self._rr = start % len(uniq)self._in_flight = 0- self._peak_in_flight = 0# machine-wide ceiling on concurrent model calls; 0 = unlimitedself._max_in_flight = int(max_in_flight or 0)if self._max_in_flight and slots_dir is None:@@ -232,23 +227,6 @@ class KeyPool:self._hold(slot)return key- def try_acquire(self, *, exclude: set[str] | frozenset[str] | None = None) -> str | None:- """:meth:`acquire` that never waits: a key usable now, else ``None``. Used for hedge- partners; a returned key holds a slot and must be :meth:`release`-d."""- slot = None- if self.slots is not None and (slot := self.slots.try_take()) is None:- return None- try:- key = self._acquire_key(exclude, 0.0)- except BaseException as exc:- if slot is not None:- Slots.give(slot)- if isinstance(exc, KeyPoolExhausted):- return None- raise- self._hold(slot)- return key-def lease_session_key(self, leases: Path | str, *, timeout_s: float | None = ACQUIRE_TIMEOUT_S) -> tuple[str, int | None]:"""A key for a vendor-CLI session: rotation, cooldowns and benching like :meth:`acquire`but no in-flight slot, and one live session per key machine-wide while keys suffice@@ -270,8 +248,6 @@ class KeyPool:except BlockingIOError:os.close(fd)busy.add(key)- with self._lock:- self._by_key[key].n_acquired -= 1 # passed over, not handed outcontinuereturn key, fd@@ -283,7 +259,6 @@ class KeyPool:def _hold(self, slot: int | None) -> None:with self._lock:self._in_flight += 1- self._peak_in_flight = max(self._peak_in_flight, self._in_flight)if slot is not None:self._held.append(slot)@@ -294,7 +269,6 @@ class KeyPool:now = self._clock()chosen = self._pick(now, exclude or ())if chosen is not None:- chosen.n_acquired += 1return chosen.keysoonest = min((max(now, s.cooldown_until) for s in self._states if s.key not in (exclude or ())),@@ -322,8 +296,8 @@ class KeyPool:if slot is not None:Slots.give(slot)- def report(self, key: str, outcome: Outcome, *, retry_after_s: float | None = None) -> None:- """Feed back a call's result (``retry_after_s``: a 429's delay, clipped to ``MAX_WAIT_S``)."""+ def report(self, key: str, outcome: Outcome) -> None:+ """Feed back a call's result."""with self._lock:st = self._by_key.get(key)if st is None:@@ -336,16 +310,14 @@ class KeyPool:elif outcome == "429":st.n_429 += 1st.health *= 0.5- cool = retry_after_s if retry_after_s and retry_after_s > 0 else self._cooldown_s- # rotate to another key rather than sit out the provider's delay- cool = min(cool, MAX_WAIT_S)+ # rotate to another key rather than sit out a long delay+ cool = min(self._cooldown_s, MAX_WAIT_S)st.cooldown_until = max(st.cooldown_until, now + cool)elif outcome == "5xx":st.n_5xx += 1st.health *= 0.8elif outcome == "dead":# key-scoped failure: bench until the long cooldown passes- st.n_dead += 1st.health = 0.0st.dead_until = max(st.dead_until, now + self._dead_cooldown_s)st.cooldown_until = max(st.cooldown_until, st.dead_until)@@ -353,37 +325,14 @@ class KeyPool:st.n_error += 1st.health *= 0.9- def stats(self) -> dict[str, Any]:- """Counters per key (keys redacted to their last 4 chars)."""+ def stats(self) -> dict[str, int]:+ """The reported outcomes summed over the keys (what the concurrency probe reads)."""with self._lock:- now = self._clock()- per_key = [- {- "key": f"…{s.key[-4:]}",- "health": round(s.health, 3),- "cooldown_s": round(max(0.0, s.cooldown_until - now), 1),- "acquired": s.n_acquired,- "ok": s.n_ok,- "429": s.n_429,- "5xx": s.n_5xx,- "error": s.n_error,- "dead": s.n_dead,- }- for s in self._states- ]return {- "n_keys": len(self._states),- "n_cooling": sum(1 for s in self._states if s.cooldown_until > now),- "n_dead": sum(1 for s in self._states if s.dead_until > now),- "in_flight": self._in_flight,- "peak_in_flight": self._peak_in_flight,- "acquired": sum(s.n_acquired for s in self._states),"ok": sum(s.n_ok for s in self._states),"429": sum(s.n_429 for s in self._states),"5xx": sum(s.n_5xx for s in self._states),"error": sum(s.n_error for s in self._states),- "dead": sum(s.n_dead for s in self._states),- "keys": per_key,}# ----------------------------------------------------------------- private@@ -415,9 +364,6 @@ class KeyPool:MIN_HEALTH = 0.3RETRY_DEADLINE_S = 1800.0 # ceiling of one logical call, retries included-#: keys a retry is raced on once a call has met its first 503/529-DEFAULT_HEDGE = 2-if TYPE_CHECKING: # pragma: no coverfrom codeverse3d.models.base import ModelError@@ -429,10 +375,6 @@ def cause_for(err: BaseException, exc: BaseException | None) -> BaseException |self-cause chain recurses forever in naive walkers)."""return None if exc is err else exc-#: per-round-trip hook of :func:`rotate_with_retries`: ``(try, attempt_no, discarded)``; fired once per round-trip-OnAttempt = Callable[["_Try", int, bool], None]--def backoff_delay(attempt: int, *, base_delay: float, max_delay: float, jitter: bool = True) -> float:@@ -456,14 +398,11 @@ def rotate_with_retries[T](storm_attempts: int = 60,storm_max_delay: float = MAX_WAIT_S,max_total_s: float = RETRY_DEADLINE_S,- hedge: int = DEFAULT_HEDGE,sleep: Callable[[float], None] = time.sleep,monotonic: Callable[[], float] = time.monotonic,on_free_retry: Callable[[ModelError], bool] | None = None,- retry_after: Callable[[BaseException], float | None] | 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.@@ -477,19 +416,11 @@ def rotate_with_retries[T](non-retryable raise at once.* everything is bounded by ``max_total_s``.- Hedging (``hedge``; 1 disables): from the first 503/529 on, each attempt runs on up to- ``hedge`` distinct keys at once and the first success wins. Extra keys come from- ``try_acquire`` (never waited for); losers finish on their own and report to the pool and- ``on_attempt``. When all fail, the worst error decides the branch (``_severity``).-- ``stats`` receives ``attempts``, ``hedged`` and ``storm`` counts. ``on_attempt`` hears- every round-trip once (exceptions from it are swallowed).+ ``stats`` receives the ``attempts`` and ``storm`` counts."""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 = None+ counts = {"attempts": 0, "storm": 0}def bench() -> None:# bench dead-looking keys once another key got past the auth layer@@ -498,8 +429,8 @@ def rotate_with_retries[T](dead_keys.clear()def run_one(key: str) -> _Try:- """One round-trip on ``key``: report to the pool and release the slot. Touches none of- this call's state (it may run in a hedge thread)."""+ """One round-trip on ``key``: report to the pool and release the slot."""+ counts["attempts"] += 1try:try:result = call(key)@@ -507,50 +438,17 @@ def rotate_with_retries[T](err = classify(exc)outcome = outcome_of(err)# a dead-looking key is benched later, by bench()- pool.report(key, "error" if outcome == "dead" else outcome,- retry_after_s=retry_after(exc) if (outcome == "429" and retry_after) else None)+ pool.report(key, "error" if outcome == "dead" else outcome)return _Try(key, None, err, exc, outcome)pool.report(key, "ok")return _Try(key, result, None, None, "ok")finally:pool.release()- def run_attempt(keys: Sequence[str]) -> list[_Try]:- """Issue ``call`` on every key; return tries completed up to the first success."""- first_no = counts["attempts"] + 1- counts["attempts"] += len(keys)- if len(keys) == 1:- t = run_one(keys[0])- finished.append((first_no, t))- return [t]- counts["hedged"] += 1- executor = 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-trips- done: 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 id(other) not in consumed_futs:- # fires once, at once if the sibling already landed- other.add_done_callback(- partial(_discard_loser, on_attempt=on_attempt,- attempt_no=nos[id(other)])- )- break- return done-last_err: ModelError | None = Nonelast_exc: BaseException | None = Noneattempt = 0storm = 0- hedging = False # flips on the first 503/529; every later attempt is hedgeddeadline = monotonic() + max_total_s if max_total_s > 0 else float("inf")def out_of_time() -> bool:@@ -564,9 +462,6 @@ def rotate_with_retries[T](log.warning("%s giving up after %.0f s of retrying (%s)", label, max_total_s, err)return err- def is_storm(err: ModelError) -> bool:- return bool(err.retryable and err.status in (503, 529))-try:while attempt < max_attempts:if out_of_time() and last_err is not None:@@ -577,44 +472,30 @@ def rotate_with_retries[T](exclude = dead_keys | (failed_keys if len(failed_keys) < len(pool) else set())budget_left = None if deadline == float("inf") else max(0.0, deadline - monotonic())try:- keys = [pool.acquire(+ key = pool.acquire(exclude=exclude,timeout_s=ACQUIRE_TIMEOUT_S if budget_left is Noneelse min(ACQUIRE_TIMEOUT_S, budget_left),- )]+ )except KeyPoolExhausted as exc:raise classify(exc) from exc- while hedging and len(keys) < max(1, hedge):- extra = pool.try_acquire(exclude=exclude | set(keys))- if extra is None:- break # no fresh key / slot right now: never wait for a hedge partner- keys.append(extra)- tries = run_attempt(keys)- free = False- for t in tries:- if t.err is None:- continue- if on_free_retry is not None and on_free_retry(t.err):- free = True- elif t.outcome == "dead":- dead_keys.add(t.key)- failed_keys.add(t.key)- if is_storm(t.err) and hedge > 1:- hedging = True- won = next((t for t in tries if t.err is None), None)- if won is not None:- winner = won+ t = run_one(key)+ if t.err is None:bench()- return won.result- worst = min(tries, key=_severity)- err, exc, key = worst.err, worst.exc, worst.key- assert err is not None+ return t.result+ err, exc = t.err, t.exclast_err = errlast_exc = exc+ free = False+ if on_free_retry is not None and on_free_retry(err):+ free = True+ elif t.outcome == "dead":+ dead_keys.add(key)+ failed_keys.add(key)if free:attempt -= 1continue- if worst.outcome == "dead":+ if t.outcome == "dead":if len(dead_keys) < len(pool):if out_of_time():raise gave_up(err) from cause_for(err, exc)@@ -622,14 +503,13 @@ def rotate_with_retries[T](attempt -= 1continueraise err from cause_for(err, exc) # every key failed the same way: not the keys' fault- if is_storm(err) and storm < storm_attempts and not out_of_time():- failed_keys.update(t.key for t in tries)+ if err.retryable and err.status in (503, 529) and storm < storm_attempts and not out_of_time():+ failed_keys.add(key)if len(failed_keys) < len(pool):# a 503 is per key: while an untried key remains rotation is freeattempt -= 1- log.warning("%s key …%s 503 (%s); rotating to a fresh key (%d/%d tried%s)",- label, key[-4:], err, len(failed_keys), len(pool),- f", hedging x{hedge}" if hedging else "")+ log.warning("%s key …%s 503 (%s); rotating to a fresh key (%d/%d tried)",+ label, key[-4:], err, len(failed_keys), len(pool))continue# capacity storm: every key said 503, so wait (own budget, not max_attempts)storm += 1@@ -642,8 +522,8 @@ def rotate_with_retries[T](sleep(delay)attempt -= 1continue- if worst.outcome == "429":- failed_keys.update(t.key for t in tries if t.outcome == "429")+ if t.outcome == "429":+ failed_keys.add(key)if len(failed_keys) < len(pool):if out_of_time():raise gave_up(err) from cause_for(err, exc)@@ -674,13 +554,6 @@ def rotate_with_retries[T](finally:if stats is not None:stats.update(counts)- if on_attempt is not None:- # flush completed round-trips; a loser still in flight reports via _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)@@ -692,33 +565,3 @@ class _Try:err: ModelError | Noneexc: BaseException | Noneoutcome: str---def _severity(t: _Try) -> int:- """Rank a failed try: non-retryable 0 < retryable 1 < 429 2 < dead key 3 < 503/529 4."""- err = t.err- assert err is not None- if t.outcome == "dead":- return 3- if err.retryable and err.status in (503, 529):- return 4- if not err.retryable:- return 0- return 2 if t.outcome == "429" else 1---def _discard_loser(- fut: Future[_Try], on_attempt: OnAttempt | None = None, attempt_no: int = 0-) -> None:- """A hedge sibling that finished after the winner: handed to ``on_attempt`` as discarded."""- try:- t = fut.result()- except BaseException as exc: # noqa: BLE001 - a crashed loser must not crash the caller- log.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/docs/INSTALL.md b/harness/docs/INSTALL.mdindex f242fb4a..a9d51f09 100644--- a/harness/docs/INSTALL.md+++ b/harness/docs/INSTALL.md@@ -323,7 +323,7 @@ The generator is always a vendor CLI: `--generator agy:… | claude-code:… | cdefault is `agy:gemini-4-argon`, so **`agy` is the one CLI a default run needs**. The harnessruns agy **only in Gemini-API mode**, so it needs Gemini keys (§8.1): one key from the harness'sown pool per session, the 3dcode MCP tools, priced at Gemini list price — no sign-in, no-non-Gemini model. Without keys an agy session fails at once (doctor row `agy gemini keys`).+non-Gemini model. Without keys an agy session fails at once (doctor row `gemini keys`).The other two are needed only when you name them.`setup.sh` brings all three to their latest release on every run (`--no-clis` skips it): agy@@ -384,7 +384,7 @@ export C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}' # per-model prompt/skillEvery knob the harness reads is a `Settings` field (`codeverse3d/config.py`, one descriptioneach): `C3D_<FIELD>` at the top level, `C3D_<SECTION>__<FIELD>` nested, plus three flatspellings of nested knobs — `C3D_MAX_IN_FLIGHT`, `C3D_RENDER_GPU`, `C3D_AGENT_MAX_TURNS`. An-on/off switch (`C3D_SKILLS`, `C3D_STREAM`, `C3D_PLAN_BRIEF`, … — every `Flag` field) takes+on/off switch (`C3D_SKILLS`, `C3D_POST`, `C3D_PLAN_BRIEF`, … — every `Flag` field) takeson/off, 1/0, true/false or yes/no in any case; a typo warns and keeps the default, and an emptyvalue is unset. The node side also reads `C3D_RENDER_GPU` and `C3D_CACHE_DIR` itself, and onevariable only it reads: `C3D_BROWSER_REUSE=off` disables the shared headless-Chrome daemon.@@ -399,8 +399,8 @@ cd harness && 3dcodeverse doctor # add --live for one tiny Gemini call, -One row per check (`python`, `python deps`, `blender`, `blender cycles`, `blender eevee`,`blender gpu slots`, `node`, `three`, `puppeteer`, `chrome webgl`, `gemini keys`, `in-flight-slots`, `anthropic key`, `openai key`, `agy`, `claude`, `codex`, `git`, `agy gemini keys`,-`mcp`; `--live` adds `gemini live call` and `gemini pool`); any FAIL row makes it exit 1, WARN+slots`, `anthropic key`, `openai key`, `agy`, `claude`, `codex`, `git`,+`mcp`; `--live` adds `gemini live call`); any FAIL row makes it exit 1, WARNrows name what is optional or busy.### Troubleshooting table@@ -427,7 +427,6 @@ rows name what is optional or busy.| `anthropic key` / `openai key` | WARN | not set | expected unless you use `anthropic:*` / `openai:*`; export the key to clear it || `agy` / `claude` / `codex` | WARN | CLI not on `PATH` | only that `--generator` is unavailable — but `agy` serves the default generator (§8.2) || `git` | FAIL | git missing | install git — run workspaces are git repos |-| `agy gemini keys` | FAIL | no Gemini keys: agy runs on API keys only, so the default generator cannot run | export `GEMINI_API_KEYS` (§8.1), or name a `claude-code:` / `codex:` generator || `mcp` | WARN | `mcp` package or the server module missing | `pip install -e 'harness[mcp]'`; only affects the agentic CLI backends || `gemini live call` (`--live`) | FAIL | key rejected / no network | check the key value and outbound access; a `503 … high demand` is transient, not an install problem || `in-flight slots` | WARN | every machine-wide slot is held right now (`busy n/n`), or `max_in_flight=0` switched the cap off | busy: other harness processes are mid-call and new calls wait for a slot — nothing to fix unless it stays full; a slot is held only while a call is out and a killed process frees its slots at once. Off: unset `C3D_MAX_IN_FLIGHT` |diff --git a/harness/tests/agents/test_antigravity.py b/harness/tests/agents/test_antigravity.pyindex 826be50e..b050070a 100644--- a/harness/tests/agents/test_antigravity.py+++ b/harness/tests/agents/test_antigravity.py@@ -120,7 +120,7 @@ def test_a_session_runs_on_a_pool_key_in_a_home_of_its_own(tmp_ws: Workspace, famonkeypatch.setenv("FAKE_MODE", "429")res2 = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="api429", timeout_s=30, spatial_tools=False))assert not res2.ok and res2.exit_reason == "budget" and res2.transient- assert backends._key_pool().stats()["keys"][0]["429"] >= 1+ assert backends._key_pool().stats()["429"] >= 1assert json.loads((tmp_ws.src / "seen.json").read_text())["mcp"] == {"mcpServers": {}}diff --git a/harness/tests/cost/conftest.py b/harness/tests/cost/conftest.pyindex deaa4375..75f76d50 100644--- a/harness/tests/cost/conftest.py+++ b/harness/tests/cost/conftest.py@@ -15,13 +15,13 @@ from codeverse3d.cost.ledger import record_call@pytest.fixturedef fake_run(tmp_path: Path) -> Path:- """plan + one gemini-cli baseline session + one judge verdict, each a ledger row."""+ """plan + one agy baseline session + one judge verdict, each a ledger row."""ws = tmp_path / "fake_run"ledger = ws / "telemetry" / "cost.jsonl"flash = {"backend": "gemini", "model": "gemini-3.8-flash"}record_call(Usage(**flash, input_tokens=4_000, output_tokens=900, latency_ms=12_000), run=ws.name,stage="plan", label="planner", ledger=ledger)- record_call(Usage(backend="gemini-cli", model="gemini-3.8-flash", input_tokens=30_000, cached_tokens=10_000,+ record_call(Usage(backend="agy", model="gemini-3.8-flash", input_tokens=30_000, cached_tokens=10_000,output_tokens=300, latency_ms=30_000), run=ws.name, round=0, stage="baseline",label="baseline", source="session", n_calls=2, ledger=ledger)record_call(Usage(backend="gemini", model="gemini-3.1-pro-preview", input_tokens=12_000, output_tokens=1_000,diff --git a/harness/tests/cost/test_audit_read.py b/harness/tests/cost/test_audit_read.pyindex d5a5c4d1..b23153b0 100644--- a/harness/tests/cost/test_audit_read.py+++ b/harness/tests/cost/test_audit_read.py@@ -28,7 +28,7 @@ def test_a_losing_candidate_is_waste(fake_run: Path, tmp_path: Path):shutil.copytree(fake_run, ws)(ws / "rounds").mkdir(exist_ok=True)(ws / "rounds" / "candidates.json").write_text(json.dumps({"n": 2, "selected": 1}))- usage = Usage(backend="gemini-cli", model="gemini-3.8-flash", input_tokens=10_000, output_tokens=500)+ usage = Usage(backend="agy", model="gemini-3.8-flash", input_tokens=10_000, output_tokens=500)for k in (0, 1):record_call(usage, stage=Stage.CANDIDATE, round=0, label=f"baseline_c{k}", source="session",ledger=ws / "telemetry" / "cost.jsonl")diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex f562ebea..dc2ea1e9 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -76,9 +76,8 @@ def test_a_full_key_never_reaches_the_ledger(tmp_path: Path):assert "secret" not in (tmp_path / "telemetry" / "cost.jsonl").read_text()-def test_a_billed_but_invalid_attempt_is_in_the_total_exactly_once(tmp_path: Path):- """A charged invalid attempt is counted exactly once beside its winner."""- from codeverse3d.cost.ledger import summarise+def test_a_billed_but_invalid_attempt_joins_its_winners_row(tmp_path: Path):+ """A charged invalid attempt is counted exactly once, inside its winner's one row."""from tests.models.test_gemini import make_model, text_responsem, _log, _ = make_model([text_response("not json"), text_response('{"ok": true}')])@@ -87,15 +86,9 @@ def test_a_billed_but_invalid_attempt_is_in_the_total_exactly_once(tmp_path: PatChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"},label="planner"))assert resp.parsed == {"ok": True}- rows = load_ledger(tmp_path) # "extra" is the discarded round-trip's money- bad, = [r for r in rows if r.source == "extra"]- logical, = [r for r in rows if r.source == "live"]- assert logical.outcome == "ok" and logical.attempts == 2 and logical.call_id- assert bad.discarded and bad.outcome == "discarded" and bad.input_tokens == 100- assert bad.call_id == logical.call_id and bad.cost_usd > 0- total = summarise(rows).total- assert total.input_tokens == logical.input_tokens + bad.input_tokens- assert {r.source for r in rows} == {"live", "extra"}+ (row,) = load_ledger(tmp_path)+ assert row.outcome == "ok" and row.attempts == 2 and row.source == "live"+ assert row.input_tokens == 200 and row.cost_usd > 0 # the bad reply's 100 + the winner's 100def test_a_failed_call_is_recorded_re_raised_and_carries_what_was_billed(tmp_path: Path):diff --git a/harness/tests/install/test_docs.py b/harness/tests/install/test_docs.pyindex ae7f9381..23574cb8 100644--- a/harness/tests/install/test_docs.py+++ b/harness/tests/install/test_docs.py@@ -233,7 +233,7 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:settings = SimpleNamespace(gemini_api_keys=("fake",), anthropic_api_key="", openai_api_key="",rate=SimpleNamespace(max_in_flight=1),- binaries=SimpleNamespace(node="node", gemini_cli="gemini", claude_cli="claude",+ binaries=SimpleNamespace(node="node", claude_cli="claude",codex_cli="codex", agy_cli="agy"),resolve_blender=lambda: "blender",runtime_js_dir=lambda: HARNESS / "runtime_js",@@ -246,9 +246,7 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:)busy = SimpleNamespace(n=1, root="/fake/slots", busy=lambda: 1) # saturated: the WARN wordingmonkeypatch.setattr("codeverse3d.models.gemini.shared_pool",- lambda keys, **kw: SimpleNamespace(slots=busy, stats=lambda: {- "n_keys": 1, "in_flight": 0, "peak_in_flight": 0, "acquired": 0, "ok": 0,- "429": 0, "5xx": 0, "n_dead": 0, "n_cooling": 0}))+ lambda keys, **kw: SimpleNamespace(slots=busy))from codeverse3d.models.health import Healthmonkeypatch.setattr("codeverse3d.models.health.probe", lambda **kw: Health(model="gemini:m", n_ok=1, n_tried=1))diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.pyindex 60363433..7d6cd62c 100644--- a/harness/tests/models/test_gemini.py+++ b/harness/tests/models/test_gemini.py@@ -87,19 +87,18 @@ THROTTLED = genai_errors.APIError("error": {"message": "quota","status": "RESOURCE_EXHAUSTED",- "details": [{"retryDelay": "7s"}],}},)-def test_429_rotates_keys_and_honours_retry_delay():+def test_429_rotates_keys_and_cools_the_throttled_ones():m, log, pool = make_model([THROTTLED, THROTTLED, text_response("third time lucky")])assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "third time lucky"assert [e["key"] for e in log] == ["k1", "k2", "k3"]st = pool.stats()- assert st["429"] == 2 and st["ok"] == 1 and st["n_cooling"] == 2- assert 0 < {k["key"]: k["cooldown_s"] for k in st["keys"]}["…k1"] <= 7.0+ assert st["429"] == 2 and st["ok"] == 1+ assert [pool.acquire() for _ in range(3)] == ["k3"] * 3, "k1 and k2 are cooling"def test_text_usage_cost_and_raw():@@ -124,7 +123,7 @@ def test_api_key_invalid_400_is_treated_as_dead_key():m, log, pool = make_model([bad, text_response("ok")], keys=("k1", "k2"))assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"assert [event["key"] for event in log] == ["k1", "k2"]- assert pool.stats()["dead"] == 1+ assert [pool.acquire() for _ in range(3)] == ["k2"] * 3, "the dead key is benched"assert failure_outcome(classify_exception(bad)) == "dead"assert failure_outcome(classify_exception(SUSPENDED)) == "dead"assert failure_outcome(classify_exception(THROTTLED)) == "429"@@ -145,7 +144,6 @@ def test_thinking_rejected_falls_back_without_thinking_config():r = m.generate(ChatRequest(messages=[ChatMessage.user("x")], thinking="high"))assert r.text == "ok"assert log[0]["config"].thinking_config is not None and log[1]["config"].thinking_config is None- assert any("thinking" in w for w in r.raw["warnings"])def test_a_charged_but_invalid_reply_carries_its_usage_on_the_error():@@ -155,7 +153,8 @@ def test_a_charged_but_invalid_reply_carries_its_usage_on_the_error():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+ # every billed attempt, not just the last: 6 replies of 100 in / 20 out+ assert ei.value.usage.input_tokens == 600 and ei.value.usage.output_tokens == 120assert ei.value.usage.cost_usd > 0diff --git a/harness/tests/models/test_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.pyindex f3481dcc..bd10c928 100644--- a/harness/tests/models/test_gemini_scheduling.py+++ b/harness/tests/models/test_gemini_scheduling.py@@ -1,4 +1,4 @@-"""GeminiModel's side of the key pool: slots, the shared pool, the retry budget, the hedge.+"""GeminiModel's side of the key pool: slots, the shared pool, the retry budget.Offline: the provider is a fake client, the pool is real, and nothing sleeps."""@@ -19,15 +19,15 @@ def api_error(code: int, msg: str = "boom") -> genai_errors.APIError:def test_a_recovered_call_reports_its_attempts_and_a_failed_call_carries_its_count():- hedged, log, _ = make_model(+ rotated, log, _ = make_model([api_error(503), api_error(503), text_response("recovered")],pool=KeyPool(["k1", "k2", "k3"], cooldown_s=0.0),max_attempts=3,)- recovered = hedged.generate(ChatRequest(messages=[ChatMessage.user("x")]))+ recovered = rotated.generate(ChatRequest(messages=[ChatMessage.user("x")]))assert recovered.text == "recovered" and len(log) == 3assert recovered.raw["attempts"] == 3- assert recovered.raw["key"] in ("…k2", "…k3")+ assert recovered.raw["key"] == "…k3"m2, _log2, _ = make_model([api_error(503, "high demand")] * 2, keys=("k1",), max_attempts=1, storm_attempts=0diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.pyindex 07b59924..e7169cca 100644--- a/harness/tests/models/test_keypool.py+++ b/harness/tests/models/test_keypool.py@@ -29,13 +29,8 @@ def test_dead_key_is_benched_for_an_hour_and_all_dead_raises_at_once():# passive health recovery must not bring it back: it stays benched for an hourclock.t += 1800assert [pool.acquire() for _ in range(6)] == ["ok"] * 6- st = pool.stats()- assert st["n_dead"] == 1 and st["dead"] == 1- by = {k["key"]: k for k in st["keys"]}- assert by["…dead"]["dead"] == 1 and by["…dead"]["cooldown_s"] > 0clock.t += 1801assert "dead" in [pool.acquire() for _ in range(3)] # re-probed once the bench ends- assert pool.stats()["n_dead"] == 0# every key dead: raise at once instead of waiting out the timeoutpool, clock = make(keys=("a", "b"), dead_cooldown_s=3600)pool.report("a", "dead")@@ -46,24 +41,6 @@ def test_dead_key_is_benched_for_an_hour_and_all_dead_raises_at_once():assert clock.t == t0 # no pointless 120 s wait: availability only moves later-def test_try_acquire_never_waits_for_a_key_or_a_slot(tmp_path):- """The extra keys of a hedged retry (``rotate_with_retries(hedge=...)``) come from- ``try_acquire``: a key that is usable right now, else None — never a wait."""- never = lambda s: (_ for _ in ()).throw(AssertionError(f"try_acquire slept {s}s")) # noqa: E731- pool = KeyPool(["k1", "k2"], max_in_flight=2, slots_dir=tmp_path, cooldown_s=30, sleep=never)- a = pool.try_acquire()- assert a == "k1" and pool.stats()["in_flight"] == 1- assert pool.try_acquire(exclude={a}) == "k2"- assert pool.try_acquire() is None, "both max_in_flight slots are held"- pool.release()- pool.release()- assert pool.stats()["in_flight"] == 0- pool.report("k1", "429")- 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_a_session_lease_keeps_one_session_per_key_across_pools_until_keys_run_out(tmp_path):"""Two pools = two processes: each leases a key no other live session holds; all leased -> shared (None)."""a, _ = make(keys=("k1", "k2"))diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.pyindex 8b75d25e..01874963 100644--- a/harness/tests/models/test_retry.py+++ b/harness/tests/models/test_retry.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport randomimport threading-import timeimport pytest@@ -41,7 +40,7 @@ def _outcome(err: ModelError) -> Outcome:def _503(e: BaseException) -> ModelError:- """Read every exception as a retryable 503 — the storm/hedge tests' classifier."""+ """Read every exception as a retryable 503 — the storm tests' classifier."""return ModelError(str(e), retryable=True, status=503)@@ -98,7 +97,7 @@ def test_rotate_every_key_dead_raises_without_benching():with pytest.raises(ModelError) as ei:_rotate(pool, call)assert ei.value.status == 403 and calls == ["k1", "k2", "k3"]- assert pool.stats()["dead"] == 0 # the request, not the keys, is suspect+ assert pool.acquire() == "k1" # nothing was benched: the request, not the keys, is suspectdef test_one_call_cannot_retry_for_hours():@@ -111,7 +110,6 @@ def test_one_call_cannot_retry_for_hours():raise RuntimeError("503 high demand")with pytest.raises(ModelError):- # hedge=1: the fake clock is serial, so two hedged 300 s calls would add 600 s_rotate503(_pool(2),call,@@ -119,71 +117,35 @@ def test_one_call_cannot_retry_for_hours():storm_attempts=60,sleep=clock.sleep,monotonic=clock,- hedge=1,)# bounded by the clock: the ONLY legal overshoot is the one floored attempt that was# already in flight when the deadline passedassert clock.t <= RETRY_DEADLINE_S + SDK_TIMEOUT_FLOOR_S, "the 5.1-hour regression"-# --------------------------------------------------------------------------- hedging (audit 2026-08-26 §5.2)-def _wait_idle(pool, timeout: float = 5.0) -> None:- """Block until every hedged loser has finished and released its slot."""- t_end = time.monotonic() + timeout- while pool.stats()["in_flight"] and time.monotonic() < t_end:- time.sleep(0.005)- assert pool.stats()["in_flight"] == 0---def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wins(tmp_path):- """After a 503, fresh keys race and the first success wins."""- pool = KeyPool(["k1", "k2", "k3", "k4"], max_in_flight=8, slots_dir=tmp_path)- release_k2 = threading.Event()- lock = threading.Lock()- calls: list[str] = []+# --------------------------------------------------------------------------- 503 storms+def test_a_503_rotates_to_a_fresh_key_without_sleeping_and_counts_every_attempt():+ """A 503 is per key: while an untried key remains, rotation is free (sequential, one key at a time)."""+ pool = _pool(3)naps: list[float] = []+ calls: list[str] = []stats: dict = {}def call(key):- with lock:- calls.append(key)- if key == "k1":- raise RuntimeError("503 high demand")- if key == "k2": # the slow loser: still held by the provider when k3 answers- assert release_k2.wait(5.0)+ calls.append(key)+ if key != "k3":raise RuntimeError("503 high demand")return f"ok:{key}"- out = rotate_with_retries(- pool,- call,- classify=_503,- outcome_of=lambda e: "5xx",- max_attempts=3,- storm_attempts=10,- sleep=naps.append,- stats=stats,- )- assert out == "ok:k3"- assert naps == [], "a hedged retry sleeps for nothing"- assert calls[0] == "k1" and sorted(calls[1:]) == ["k2", "k3"], (- "two distinct fresh keys, k1 excluded"- )- assert stats == {"attempts": 3, "hedged": 1, "storm": 0}- st = pool.stats()- assert st["in_flight"] == 1 and st["peak_in_flight"] == 2, (- "the loser still holds its max_in_flight slot"- )- assert st["ok"] == 1 and st["5xx"] == 1- release_k2.set()- _wait_idle(pool)+ out = _rotate503(pool, call, max_attempts=3, storm_attempts=10, sleep=naps.append, stats=stats)+ assert out == "ok:k3" and calls == ["k1", "k2", "k3"] and naps == []+ assert stats == {"attempts": 3, "storm": 0}st = pool.stats()- assert st["5xx"] == 2 and st["in_flight"] == 0, "the loser's 503 is reported when it lands"+ assert st["ok"] == 1 and st["5xx"] == 2[email protected](("hedge", "want_calls", "want_naps"), [(1, {9}, 7), (2, {9, 10}, 4)])-def test_503_storm_has_its_own_patience_budget(hedge, want_calls, want_naps):- """A 503 storm gets a separate budget; hedging reduces its waits."""+def test_503_storm_has_its_own_patience_budget():+ """A 503 storm gets a separate budget."""lock = threading.Lock()calls = {"n": 0}naps: list[float] = []@@ -204,12 +166,11 @@ def test_503_storm_has_its_own_patience_budget(hedge, want_calls, want_naps):storm_attempts=10,storm_max_delay=0.05,sleep=naps.append,- hedge=hedge,)- assert out == "ok" and calls["n"] in want_calls+ assert out == "ok" and calls["n"] == 9# the first 503 rotates to k2 for free (no nap); k2's 503 leaves no untried key in the# 2-key pool, so that one is the storm- assert len(naps) == want_naps and all(d <= 0.05 for d in naps) # the cap is the cap+ assert len(naps) == 7 and all(d <= 0.05 for d in naps) # the cap is the capdef test_storm_waits_never_exceed_the_house_limit_at_production_defaults(monkeypatch):@@ -220,54 +181,6 @@ def test_storm_waits_never_exceed_the_house_limit_at_production_defaults(monkeypassert naps and max(naps) == MAX_WAIT_S-def test_on_attempt_hears_every_round_trip_and_a_late_hedge_loser():- """The attempt hook reports winners, failures, and late hedge losers."""- pool = _pool(4)- 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 = _pool(1)-- def hook(t, no, discarded):- raise RuntimeError("accounting on fire")-- assert _rotate(pool, lambda key: "ok", on_attempt=hook) == "ok"--def test_backoff_grows_and_caps():d = [backoff_delay(i, base_delay=1.0, max_delay=8.0, jitter=False) for i in range(1, 7)]assert d == [1.0, 2.0, 4.0, 8.0, 8.0, 8.0]@@ -287,7 +200,6 @@ def test_the_deadline_does_not_cut_a_call_that_is_making_progress():raise RuntimeError("503 high demand")return "ok"- # hedge=1: serial fake clock and call counter (see the hedge tests for the raced form)out = _rotate503(_pool(2),call,@@ -295,26 +207,10 @@ def test_the_deadline_does_not_cut_a_call_that_is_making_progress():storm_attempts=60,sleep=clock.sleep,monotonic=clock,- hedge=1,)assert out == "ok" and calls["n"] == 3-def test_the_worst_error_decides_a_hedged_attempt():- """A nonretryable hedge error outranks a sibling 503."""- pool = _pool(3)- stats: dict = {}-- def call(key):- if key == "k3":- raise ModelError("bad request", retryable=False, status=400)- raise ModelError("503 high demand", retryable=True, status=503)-- with pytest.raises(ModelError) as ei:- _rotate(pool, call, max_attempts=6, storm_attempts=10, stats=stats)- assert ei.value.status == 400 and stats == {"attempts": 3, "hedged": 1, "storm": 0}--def test_free_429_rotation_cannot_outlive_the_deadline():"""Free key rotation still consumes wall-clock budget."""clock = Clock()@@ -330,3 +226,27 @@ def test_free_429_rotation_cannot_outlive_the_deadline():assert ei.value.status == 429assert 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_one_key_adapters_join_every_billed_attempt_on_success_and_on_failure():+ """``retry_one_key``: failed-but-billed attempts join the call's usage, whether it ends well or not."""+ from codeverse3d.contracts.chat import ChatResponse+ from codeverse3d.contracts.common import Usage+ from codeverse3d.models.parts import retry_one_key++ def run(replies):+ it = iter(replies)++ def attempt():+ r = next(it)+ if isinstance(r, ChatResponse):+ return r+ raise ModelError("bad reply", retryable=True, usage=Usage(input_tokens=100))++ return retry_one_key(attempt, label="t", classify=lambda e: e, attempts=3, sleep=lambda s: None)++ won = run([ModelError("x"), ChatResponse(text="ok", usage=Usage(input_tokens=100))])+ assert won.usage.input_tokens == 200+ with pytest.raises(ModelError) as ei:+ run([ModelError("x")] * 3)+ assert ei.value.usage.input_tokens == 300