Skip to content

Official Codebase of 3DCodeVerse

Python

cost: record the serving key (last 4 chars) and the attempt count on every ledger row

gaoypeng18736b6de1c4
diff --git a/harness/codeverse/cost/audit.py b/harness/codeverse/cost/audit.py
index 441bae4c..b2cc47b8 100644
--- a/harness/codeverse/cost/audit.py
+++ b/harness/codeverse/cost/audit.py
@@ -29,7 +29,7 @@ from codeverse.cost.types import CallCost, CostBucket, Role, Stage, Summary
#: dimensions the audit always aggregates on
AUDIT_DIMENSIONS = ("run", "track", "language", "stage", "role", "backend", "model", "provider",
- "status", "outcome", "source")
+ "status", "outcome", "source", "key")
@dataclass
diff --git a/harness/codeverse/cost/instrument.py b/harness/codeverse/cost/instrument.py
index 35cf35e4..f0cf8db9 100644
--- a/harness/codeverse/cost/instrument.py
+++ b/harness/codeverse/cost/instrument.py
@@ -135,21 +135,34 @@ class MeteredChatModel:
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))
+ outcome=_outcome(exc), ms=int((time.perf_counter() - t0) * 1000),
+ attempts=getattr(exc, "attempts", 0))
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 read
self._record(resp.usage, request, outcome="ok",
- ms=int((time.perf_counter() - t0) * 1000))
+ ms=int((time.perf_counter() - t0) * 1000),
+ key=resp.raw.get("key"), attempts=resp.raw.get("attempts", 0))
return resp
- def _record(self, usage: Usage, request: ChatRequest, *, outcome: str, ms: int) -> None:
+ def _record(self, usage: Usage, request: ChatRequest, *, outcome: str, ms: int,
+ 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)
+ latency_ms=usage.latency_ms or ms,
+ key=_key_suffix(key), attempts=int(attempts or 0))
except Exception as e: # pragma: no cover - accounting must never break a call
log.debug("cost: could not record %s: %s", request.label, e)
+def _key_suffix(key: object) -> str:
+ """The last 4 chars of an API key as ``…ab12`` — the ledger never holds more."""
+ s = str(key or "").strip()
+ return f"…{s[-4:]}" if s else ""
+
+
def _outcome(exc: BaseException) -> str:
name = type(exc).__name__.lower()
if "timeout" in name:
diff --git a/harness/codeverse/cost/report.py b/harness/codeverse/cost/report.py
index df7dedda..3a9a6fa9 100644
--- a/harness/codeverse/cost/report.py
+++ b/harness/codeverse/cost/report.py
@@ -48,11 +48,20 @@ def bucket_rows(buckets: Sequence[CostBucket], total: float) -> list[list[object
b.key, _usd(b.cost_usd), f"{100 * b.cost_usd / total:.1f}%" if total else "-",
f"{b.n_calls:,}", _tok(b.input_tokens), f"{100 * b.cached_fraction:.0f}%",
_tok(b.output_tokens), f"${b.usd_per_1k_tokens:.5f}", f"{b.latency_ms / 3.6e6:.1f} h",
+ f"{b.attempts_per_call:.2f}" if b.n_attempted else "-",
])
return rows
-BUCKET_HEADERS = ("key", "USD", "share", "calls", "input", "cached", "output", "$/1k tok", "model time")
+BUCKET_HEADERS = ("key", "USD", "share", "calls", "input", "cached", "output", "$/1k tok", "model time",
+ "tries/call")
+
+
+def keyed_buckets(audit: Audit) -> list[CostBucket]:
+ """Per-API-key buckets (``CallCost.key``), most calls first; empty for ledgers
+ written before the key suffix was recorded (2026-08-26)."""
+ return sorted((b for b in audit.summary.dimension("key").values() if b.key != "(none)"),
+ key=lambda b: -b.n_calls)
def dimension_table(audit: Audit, dim: str, *, limit: int | None = None, order: Sequence[str] = ()) -> str:
@@ -105,6 +114,8 @@ def markdown(audit: Audit, *, title: str = "Cost audit") -> str:
("track", "Per track", ()), ("backend", "Per backend", ()),
("model", "Per model", ())):
parts += ["", f"## {heading}", "", dimension_table(audit, dim, order=order)]
+ if keyed_buckets(audit):
+ parts += ["", "## Per API key (last 4 chars)", "", dimension_table(audit, "key")]
parts += ["", "## Most expensive runs", "", runs_table(audit)]
parts += ["", "## Where a dollar bought nothing", "", waste_table(audit)]
parts += ["", "## Model time per stage", "",
@@ -133,6 +144,11 @@ def console(audit: Audit) -> str:
lines += ["", "role:"]
for b in audit.summary.ranked("role"):
lines.append(f" {b.key:<12} {_usd(b.cost_usd):>10} {100 * b.cost_usd / audit.total_usd:5.1f}%")
+ if keyed := keyed_buckets(audit):
+ lines += ["", "key (last 4 chars):"]
+ for b in keyed:
+ lines.append(f" {b.key:<8} {b.n_calls:>6,} calls {_usd(b.cost_usd):>10} "
+ f"tries/call {b.attempts_per_call:.2f} model time {b.latency_ms / 6e4:.0f} min")
lines += ["", "waste:"]
for k, (n, usd) in audit.waste_by_kind().items():
lines.append(f" {k:<20} {n:>3} {_usd(usd):>10}")
diff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.py
index 3835b14a..e97c38b6 100644
--- a/harness/codeverse/cost/types.py
+++ b/harness/codeverse/cost/types.py
@@ -185,6 +185,12 @@ class CallCost(BaseModel):
outcome: str = "ok" # ok | error | timeout | budget | degraded | discarded
n_calls: int = 1 # >1 when a row aggregates a whole agent session
source: str = "live" # live | record | events | transcript | stdout | residual
+ #: 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-26
+ key: str = ""
+ #: round-trips the retry machine issued for this call (hedged siblings included);
+ #: 1 = clean, 0 = not recorded
+ attempts: int = 0
@property
def uncached_tokens(self) -> int:
@@ -213,10 +219,15 @@ class CostBucket(BaseModel):
cost_usd: float = 0.0
latency_ms: int = 0
approximate_usd: float = 0.0 # spend priced from an approximate/unknown row
+ attempts: int = 0 # round-trips over the rows that recorded them
+ n_attempted: int = 0 # calls in those rows
def add(self, row: CallCost) -> None:
self.n_calls += max(1, row.n_calls)
self.n_rows += 1
+ if row.attempts:
+ self.attempts += row.attempts
+ self.n_attempted += max(1, row.n_calls)
self.input_tokens += row.input_tokens
self.cached_tokens += min(row.cached_tokens, row.input_tokens) if row.input_tokens else row.cached_tokens
self.output_tokens += row.output_tokens
@@ -247,6 +258,11 @@ class CostBucket(BaseModel):
def usd_per_call(self) -> float:
return self.cost_usd / self.n_calls if self.n_calls else 0.0
+ @property
+ def attempts_per_call(self) -> float:
+ """Mean round-trips per call (1.0 = every call landed first time); 0 when unrecorded."""
+ return self.attempts / self.n_attempted if self.n_attempted else 0.0
+
class Summary(BaseModel):
"""``summarise()`` output: a total plus one bucket map per dimension."""
diff --git a/harness/codeverse/models/base.py b/harness/codeverse/models/base.py
index ce7b187c..749f927c 100644
--- a/harness/codeverse/models/base.py
+++ b/harness/codeverse/models/base.py
@@ -32,7 +32,14 @@ class ChatModel(Protocol):
class ModelError(RuntimeError):
- def __init__(self, message: str, *, retryable: bool = False, status: int | None = None):
+ """A model call failed. ``attempts`` is how many round-trips the retry machine
+ issued before giving up (0 = unknown / not a retried call); the cost ledger
+ records it on the error row (``docs/COST.md`` §24)."""
+
+ def __init__(
+ self, message: str, *, retryable: bool = False, status: int | None = None, attempts: int = 0
+ ):
super().__init__(message)
self.retryable = retryable
self.status = status
+ self.attempts = attempts
diff --git a/harness/codeverse/models/gemini.py b/harness/codeverse/models/gemini.py
index 7fb37595..645d5a82 100644
--- a/harness/codeverse/models/gemini.py
+++ b/harness/codeverse/models/gemini.py
@@ -251,25 +251,35 @@ class GeminiModel:
# the caller's budget clips the retry deadline, never extends it
budget = RETRY_DEADLINE_S if request.max_wait_s is None else min(RETRY_DEADLINE_S, float(request.max_wait_s))
- return rotate_with_retries(
- self.pool,
- lambda key: self._once(key, contents, state["config"], request, warnings),
- classify=classify_exception,
- outcome_of=failure_outcome,
- 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,
- on_free_retry=downgrade_thinking,
- retry_after=_retry_after_s,
- tokens_of=lambda r: r.usage.input_tokens,
- tokens_hint=request_tokens(request, model_id=self.id),
- storm_gate=self.storm_gate,
- label=f"gemini {self.model}",
- **({} if self.storm_attempts is None else {"storm_attempts": self.storm_attempts}),
- )
+ stats: dict[str, Any] = {}
+ try:
+ resp = rotate_with_retries(
+ self.pool,
+ lambda key: self._once(key, contents, state["config"], request, warnings),
+ classify=classify_exception,
+ outcome_of=failure_outcome,
+ 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,
+ on_free_retry=downgrade_thinking,
+ retry_after=_retry_after_s,
+ tokens_of=lambda r: r.usage.input_tokens,
+ tokens_hint=request_tokens(request, model_id=self.id),
+ storm_gate=self.storm_gate,
+ label=f"gemini {self.model}",
+ stats=stats,
+ **({} if self.storm_attempts is None else {"storm_attempts": self.storm_attempts}),
+ )
+ except ModelError as err:
+ err.attempts = int(stats.get("attempts", 0)) # the ledger's error row wants it too
+ raise
+ # how hard the call was, next to which key served it (``_once``): ledger fields
+ resp.raw["attempts"] = int(stats.get("attempts", 0))
+ resp.raw["hedged"] = int(stats.get("hedged", 0))
+ return resp
def _config(self, request: ChatRequest, warnings: list[str]) -> types.GenerateContentConfig:
return build_config(
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index 8457a132..fd3659e4 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -1256,6 +1256,16 @@ wait: **≈ 930 s/run blender, 1 400 s threejs, 600 s cadquery, 450 s graphics**
nothing, so the hedge is free while it storms; only a success-then-success wastes one call
(cents for a chat turn — `GeminiImageModel` keeps `hedge=1` because an image is billed per image).
+
+*The ledger records the key and the attempt count.* `keys.py` scanned 1 542 files of the corpus
+for the `"key": "…xxxx"` that `gemini.py:_once` puts in `ChatResponse.raw` and found none, so
+"is one key hammered" was unanswerable. `rotate_with_retries(stats=)` hands back `attempts`
+(round-trips issued, hedged siblings included; 1 = clean) and `hedged`; `GeminiModel` puts both
+in `raw` and `attempts` on the raised `ModelError`; `cost/instrument.py` copies the key suffix
+(last 4 chars, never more) and `attempts` onto every `CallCost` row (`key`, `attempts`, both
+defaulted so old rows load); `3dcv cost` / `bench/cost_report.py` add a per-key table and a
+`tries/call` column (`CostBucket.attempts_per_call`) whenever the ledger carries them.
+
## 25. Where the time goes — the 2026-08-26 audit (`docs/TIME_AUDIT_2026-08-26.md`)
51 storm-day runs against 52 baseline runs, every stage and every model call, scripts in
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 2b74d5bd..60e1ece8 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -52,6 +52,7 @@ from codeverse.models import get_chat_model # (model_id) -> ChatModel
resp = m.generate(ChatRequest(messages=[...], system=..., response_schema=..., temperature=..., thinking=..., label=..., max_wait_s=None))
# max_wait_s: the longest this ONE call may spend, retries included (None = models.retry.RETRY_DEADLINE_S = 900 s);
# GeminiModel clips its retry deadline to it; api_agent 20-120 s per turn, VlmJudge 240 s per sample, planner 300 s
+# resp.raw["key"] = "…ab12" (the key that answered), resp.raw["attempts"] = round-trips issued (hedged siblings included)
resp.parsed / resp.text / resp.tool_calls / resp.usage # Usage always has cost_usd (models.pricing)
from codeverse.models.keypool import KeyPool, KeyPoolExhausted
KeyPool(keys, *, rpm_per_key=900, tpm_per_key=None, cooldown_s=30, dead_cooldown_s=3600)
diff --git a/harness/tests/cost/test_cli.py b/harness/tests/cost/test_cli.py
index 6ccf0a38..038926de 100644
--- a/harness/tests/cost/test_cli.py
+++ b/harness/tests/cost/test_cli.py
@@ -90,6 +90,22 @@ def test_a_live_ledger_is_read_instead_of_being_reconstructed(fake_run: Path):
assert "unattributed" in r.output or "difference" in r.output
+def test_cost_reports_the_calls_per_key_when_the_ledger_recorded_them(fake_run: Path, tmp_path: Path):
+ """audit 2026-08-26 §4: no row said which key served a call, so 'is one key hammered' could
+ only be probed. Live rows now carry the key suffix and the round-trip count; the report
+ shows both, and a ledger without them (older, or reconstructed) simply has no key section."""
+ base = {"run": fake_run.name, "round": 0, "stage": "baseline", "role": "generator", "backend": "gemini",
+ "provider": "gemini", "model": "gemini-3.7-flash", "input_tokens": 1_000, "output_tokens": 10,
+ "cost_usd": 0.001, "price_source": "exact"}
+ _live_ledger(fake_run, [dict(base, key="…k1", attempts=1), dict(base, key="…k1", attempts=3),
+ dict(base, key="…k2", attempts=1)])
+ r = runner.invoke(app, ["cost", str(fake_run), "--md", str(tmp_path / "c.md")])
+ assert r.exit_code == 0, r.output
+ assert "key (last 4 chars):" in r.output and "…k1" in r.output and "tries/call 2.00" in r.output
+ md = (tmp_path / "c.md").read_text()
+ assert "## Per API key" in md and "tries/call" in md
+
+
def test_cost_cache_reports_the_cold_head_of_every_session(fake_run: Path):
_live_ledger(fake_run, [
{"run": "x", "round": 0, "stage": "baseline", "label": "api-agent:baseline:t0",
diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.py
index 9de389e5..c519704b 100644
--- a/harness/tests/cost/test_instrument.py
+++ b/harness/tests/cost/test_instrument.py
@@ -291,3 +291,69 @@ def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Pat
for name in names:
rows = load_ledger(tmp_path / name)
assert len(rows) == 3 and {r.run for r in rows} == {name}
+
+
+# ------------------------------------------------------- key + attempts on the row (audit 2026-08-26 §4)
+class KeyedChat(FakeChat):
+ """A gemini-shaped response: ``raw`` names the key that answered and the round-trips."""
+
+ def __init__(self, raw: dict):
+ super().__init__()
+ self.raw = raw
+
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ self.requests.append(request)
+ return ChatResponse(text="ok", usage=_usage(), raw=dict(self.raw))
+
+
+def test_the_row_says_which_key_served_the_call_and_how_many_round_trips(tmp_path: Path):
+ """No telemetry row used to say which key served a call — `keys.py` scanned 1 542 files of
+ the storm-day corpus for the `"key": "…xxxx"` that gemini.py puts in ``raw`` and found none,
+ so the per-key distribution could only be probed, never read."""
+ with run_ledger(tmp_path, run="r1"):
+ MeteredChatModel(KeyedChat({"key": "…ab12", "attempts": 3, "hedged": 1})).generate(
+ ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
+ (row,) = load_ledger(tmp_path)
+ assert row.key == "…ab12" and row.attempts == 3
+
+
+def test_a_full_key_never_reaches_the_ledger(tmp_path: Path):
+ with run_ledger(tmp_path, run="r1"):
+ MeteredChatModel(KeyedChat({"key": "AIzaSy-a-whole-secret-key-9999"})).generate(
+ ChatRequest(messages=[ChatMessage.user("x")], label="planner"))
+ (row,) = load_ledger(tmp_path)
+ assert row.key == "…9999" and row.attempts == 0
+ assert "secret" not in (tmp_path / "telemetry" / "cost.jsonl").read_text()
+
+
+def test_a_failed_call_records_its_attempts_but_no_key(tmp_path: Path):
+ from codeverse.models.base import ModelError
+
+ err = ModelError("503 high demand", retryable=True, status=503, attempts=7)
+ 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 == 7 and row.key == ""
+
+
+def test_per_key_buckets_and_tries_per_call(tmp_path: Path):
+ from types import SimpleNamespace
+
+ from codeverse.cost.ledger import record_call, summarise
+ from codeverse.cost.report import BUCKET_HEADERS, bucket_rows, keyed_buckets
+
+ led = tmp_path / "cost.jsonl"
+ rows = [
+ record_call(_usage(), label="planner", ledger=led, key="…k1", attempts=1),
+ record_call(_usage(), label="planner", ledger=led, key="…k1", attempts=3),
+ record_call(_usage(), label="planner", ledger=led, key="…k2", attempts=1),
+ record_call(_usage(), label="baseline", ledger=led, n_calls=4, source="session"), # a CLI session: no key
+ ]
+ by = summarise(rows, dimensions=("key",)).dimension("key")
+ assert by["…k1"].n_calls == 2 and by["…k1"].attempts_per_call == 2.0
+ assert by["…k2"].attempts_per_call == 1.0
+ assert by["(none)"].n_calls == 4 and by["(none)"].attempts_per_call == 0.0
+ audit = SimpleNamespace(summary=summarise(rows, dimensions=("key",)))
+ 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"
diff --git a/harness/tests/models/test_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.py
index b98ec65d..0b12320b 100644
--- a/harness/tests/models/test_gemini_scheduling.py
+++ b/harness/tests/models/test_gemini_scheduling.py
@@ -11,6 +11,7 @@ import pytest
from google.genai import errors as genai_errors
from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
+from codeverse.models.base import ModelError
from codeverse.models.gemini import GeminiModel, shared_pool
from codeverse.models.keypool import KeyPool
from codeverse.models.storm import StormGate
@@ -183,6 +184,18 @@ def test_max_wait_s_must_be_positive():
ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=0)
+def test_a_second_503_is_hedged_across_keys_and_the_response_says_how_hard_it_was():
+ """§5.2: after the first 503 (a free rotation) the next attempt goes out on two fresh
+ keys at once; the response carries the winner's key suffix and the round-trip count."""
+ pool = KeyPool(["k1", "k2", "k3"], cooldown_s=0.0)
+ m, log, _ = make_model([api_error(503, "high demand"), api_error(503, "high demand"), text_response("ok")],
+ pool=pool, max_attempts=3)
+ r = m.generate(ChatRequest(messages=[ChatMessage.user("hi")]))
+ assert r.text == "ok" and len(log) == 3
+ assert r.raw["attempts"] == 3 and r.raw["hedged"] == 1
+ assert r.raw["key"] in ("…k2", "…k3"), "the key that answered, never the first one that 503'd"
+
+
def test_the_hedge_is_a_settings_knob_and_a_constructor_argument(monkeypatch):
from codeverse.config import Rate, get_settings
@@ -191,3 +204,12 @@ def test_the_hedge_is_a_settings_knob_and_a_constructor_argument(monkeypatch):
monkeypatch.setattr(get_settings(), "rate", Rate(hedge=1))
assert make_model([])[0].hedge == 1, "CV3D_RATE__HEDGE=1 is the A/B switch"
+
+def test_a_clean_call_reports_one_attempt_and_a_failed_call_carries_its_count():
+ m, _log, _ = make_model([text_response("hi")])
+ r = m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert r.raw["attempts"] == 1 and r.raw["hedged"] == 0 and r.raw["key"] == "…k1"
+ m2, _log2, _ = make_model([api_error(503, "high demand")] * 2, keys=("k1",), max_attempts=1, storm_attempts=0)
+ 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"