Official Codebase of 3DCodeVerse
Python
billing: rows keep their money and their attribution
gaoypeng8fc16bafbfa0
diff --git a/harness/bench/rejudge_offline.py b/harness/bench/rejudge_offline.pyindex bedf3015..7cb88eb4 100644--- a/harness/bench/rejudge_offline.py+++ b/harness/bench/rejudge_offline.py@@ -46,6 +46,7 @@ from pydantic import BaseModel, Fieldfrom codeverse.contracts.artifacts import GateReport, Severityfrom codeverse.contracts.plan import AcceptanceItemfrom codeverse.contracts.run import RoundRecord+from codeverse.judges.calibration import _run_labelfrom codeverse.judges.rubrics import (SCORING_VERSION,JudgeOutput,@@ -151,12 +152,6 @@ def round_files(roots: list[Path]) -> list[Path]:return out-def _run_label(run_dir: Path) -> str:- parts = run_dir.resolve().parts- tail = [q for q in parts[-4:] if q not in ("runs", "cells")]- return "/".join(tail[-3:]) if tail and tail[-1] in ("run",) else "/".join(tail[-2:])--def _acceptance_items(run_dir: Path) -> list[AcceptanceItem]:"""The plan's acceptance list; a candidate sub-workspace inherits its parent's plan."""d = run_dirdiff --git a/harness/codeverse/cost/instrument.py b/harness/codeverse/cost/instrument.pyindex c5459c36..a16156ba 100644--- a/harness/codeverse/cost/instrument.py+++ b/harness/codeverse/cost/instrument.py@@ -36,7 +36,9 @@ from codeverse.contracts.chat import ChatRequest, ChatResponsefrom codeverse.contracts.common import Usagefrom codeverse.cost.context import (AttemptRecord,+ CallContext,attempt_recording,+ attribute,bound_run,call_context,run_binding,@@ -100,14 +102,17 @@ class MeteredChatModel:# -- the meter --------------------------------------------------------def generate(self, request: ChatRequest) -> ChatResponse:call_id = uuid4().hex # joins the per-attempt rows to the call's logical row- # captured NOW: a hedge loser lands after this call returned, in a thread- # with no context, so neither the run's ledger nor its name is reachable there+ # captured NOW: a hedge loser lands after this call returned, in a thread with+ # no context, so neither the run's ledger, its name nor the stage/role/round+ # attribution is reachable there — the loser's row used to fall back to what+ # the label alone says (baseline/None instead of candidate/r0)ledger = default_ledger()run = run_binding().run+ ctx = attribute(label=request.label)booked: list[int] = [] # round-trips that already billed themselves as "extra"def attempt_row(rec: AttemptRecord) -> None:- if self._record_attempt(request, call_id, rec, ledger, run):+ if self._record_attempt(request, call_id, rec, ledger, run, ctx):booked.append(rec.attempt)t0 = time.perf_counter()@@ -146,7 +151,8 @@ class MeteredChatModel:log.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 = "") -> bool:+ ledger: CostLedger | None, run: str = "",+ ctx: CallContext | None = None) -> bool:"""One row per round-trip. A round-trip that was DISCARDED and still cost money(a billed-but-invalid reply, a hedge loser that landed) is money nothing elserecords, so it goes in as ``source="extra"`` and counts in every total; the rest@@ -155,6 +161,8 @@ class MeteredChatModel:extra = bool(rec.discarded and rec.usage.cost_usd)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",diff --git a/harness/codeverse/judges/calibration.py b/harness/codeverse/judges/calibration.pyindex 3c171262..ef93a629 100644--- a/harness/codeverse/judges/calibration.py+++ b/harness/codeverse/judges/calibration.py@@ -43,10 +43,12 @@ log = logging.getLogger(__name__)def _run_label(run_dir: Path) -> str:"""A label that stays unique across a battery: bench cells all end in ``.../run``, so- ``run_dir.name`` collided for every cell and their judgment files overwrote each other."""+ ``run_dir.name`` collided for every cell and their judgment files overwrote each other.+ The whole filtered tail is kept — a 2-part tail (``<arm>_run``) still collided across+ a battery's prompts, and dropped the control/treatment arm in an ab_plan layout."""parts = run_dir.resolve().parts- tail = [q for q in parts[-3:] if q not in ("runs", "cells")]- return "_".join(tail[-2:]) if tail[-1] == "run" else tail[-1]+ tail = [q for q in parts[-5:] if q not in ("runs", "cells")]+ return "_".join(tail) if tail[-1] == "run" else tail[-1]# --------------------------------------------------------------------------- datadiff --git a/harness/codeverse/models/schema_utils.py b/harness/codeverse/models/schema_utils.pyindex bb2abdaa..a1166cbe 100644--- a/harness/codeverse/models/schema_utils.py+++ b/harness/codeverse/models/schema_utils.py@@ -375,16 +375,16 @@ def ask_structured(model: Any, schema: type[BaseModel], *, system: str, text: st(thinking="low", the 65 536 ceiling, the 900 s wait), caught the same two failurefamilies and parsed the same two ways. They differ only in what they RETURN onfailure, which is why this hands the error back rather than raising or deciding.- Not for callers that need the failed call's own ``Usage`` or separate parse- errors from call errors (``judges.pairwise``, ``tracks.planner``).+ Not for callers that need to separate parse errors from call errors+ (``judges.pairwise``, ``tracks.planner``)."""req = ChatRequest(messages=[ChatMessage.user(text, images=list(images) or None)], system=system,response_schema=schema.model_json_schema(), temperature=temperature,thinking="low", max_output_tokens=65_536, max_wait_s=900.0, label=label)try:resp = model.generate(req)- except ModelError as e:- return None, Usage(), f"call failed: {e}"+ except ModelError as e: # e.usage is what the provider ALREADY billed for the failure+ return None, e.usage, f"call failed: {e}"try: # the parse is inside: every provider raises ModelError first today, but this# function must not depend on all three keeping that half of the ChatModel contractpayload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex 2802bc67..7f98289b 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -442,6 +442,46 @@ def test_a_hedge_losers_tokens_reach_the_ledger_when_it_lands(tmp_path: Path):logical.cost_usd + loser.cost_usd), "the loser is in the total exactly once"+def test_a_late_hedge_loser_keeps_its_stage_role_and_round(tmp_path: Path):+ """The loser lands AFTER generate() returned, from its own thread with empty+ contextvars: its 'extra' row used to fall back to what the label alone says+ (baseline/None) instead of the originating call's candidate/r0 attribution."""+ import threading++ from codeverse.cost.context import AttemptRecord, attempt_sink, call_context++ loser_usage = _usage(cost_usd=0.30)++ class Hedging:+ provider, model = "gemini", "gemini-3.7-flash"+ id = "gemini:gemini-3.7-flash"+ late: threading.Thread | None = None++ def supports_vision(self):+ return True++ def generate(self, req):+ sink = attempt_sink() # captured once, like gemini._attempt_hook++ def loser_lands():+ sink(AttemptRecord(attempt=2, key="k" * 20, outcome="ok", discarded=True,+ usage=loser_usage, error=""))++ self.late = threading.Thread(target=loser_lands) # fresh thread = empty context+ return ChatResponse(text="winner", usage=_usage(cost_usd=0.01))++ inner = Hedging()+ with run_ledger(tmp_path, run="r1"):+ with call_context(stage="candidate", role="generator", round=0):+ MeteredChatModel(inner).generate(ChatRequest(messages=[ChatMessage.user("x")], label="baseline"))+ assert inner.late is not None+ inner.late.start()+ inner.late.join()+ loser, = [r for r in load_ledger(tmp_path) if r.source == "extra"]+ assert loser.discarded and loser.stage is Stage.CANDIDATE+ assert loser.role is Role.GENERATOR and loser.round == 0++def test_a_failed_calls_error_row_carries_what_was_billed(tmp_path: Path):"""A final ModelError carries its billed usage into the error row."""from codeverse.models.base import ModelErrordiff --git a/harness/tests/judges/test_calibration.py b/harness/tests/judges/test_calibration.pyindex 06827bde..fdf4c046 100644--- a/harness/tests/judges/test_calibration.py+++ b/harness/tests/judges/test_calibration.py@@ -84,3 +84,21 @@ def test_calibrate_offline(tmp_path):(empty / "spec.json").write_text(make_spec(id="empty").model_dump_json())with pytest.raises(ValueError, match="no judgeable rounds"):calibrate([empty], model_id="fake:fake-1", out_dir=tmp_path / "out", chat_model=model)+++def test_run_labels_stay_distinct_across_battery_layouts():+ """Bench cells all end in .../run: compare_backends cells for DIFFERENT prompts+ (and ab_plan's control vs treatment arms) used to collapse to one label, so+ their judgment sidecars overwrote each other (V9c)."""+ from codeverse.judges.calibration import _run_label++ # compare_backends: <battery>/cells/<prompt>/<arm>/run+ a = _run_label(Path("/bench/out/compare_v1/cells/chair/harness-gemini/run"))+ b = _run_label(Path("/bench/out/compare_v1/cells/table/harness-gemini/run"))+ # ab_plan: <out>/<arm>/cells/<item>/<slug>/run+ c = _run_label(Path("/bench/out/ab/control/cells/chair/g37/run"))+ d = _run_label(Path("/bench/out/ab/treatment/cells/chair/g37/run"))+ e = _run_label(Path("/bench/out/ab/control/cells/table/g37/run"))+ assert len({a, b, c, d, e}) == 5, (a, b, c, d, e)+ # a plain harness run keeps its slug as the whole label+ assert _run_label(Path("/home/u/proj/runs/chair_bl")) == "chair_bl"diff --git a/harness/tests/models/test_schema_utils.py b/harness/tests/models/test_schema_utils.pyindex 48b43d36..ba7e9fef 100644--- a/harness/tests/models/test_schema_utils.py+++ b/harness/tests/models/test_schema_utils.py@@ -226,3 +226,26 @@ def test_ask_structured_returns_the_triple_for_prose_it_cannot_parse():out, usage, err = ask_structured(Prose(), Answer, system="s", text="t", temperature=0.2, label="l")assert out is None and usage.cost_usd == 0.01 and err.startswith("answer unparsable:")+++def test_ask_structured_returns_the_usage_a_failed_call_was_billed():+ """A bad-JSON reply is charged like a good one — ModelError carries that usage, and+ ask_structured used to drop it (return Usage()), so every caller-side tally+ (BudgetGuard.charge, refset.usage, record.json spend) undercounted while the+ metered ledger recorded the real bill."""+ from codeverse.contracts.common import Usage+ from codeverse.models.base import ModelError+ from codeverse.models.schema_utils import ask_structured++ class Answer(BaseModel):+ ok: bool++ billed = Usage(input_tokens=42_000, output_tokens=100, cost_usd=0.123, backend="gemini")++ class Failing:+ def generate(self, request):+ raise ModelError("bad JSON reply, still billed", usage=billed)++ out, usage, err = ask_structured(Failing(), Answer, system="s", text="t", temperature=0.0, label="l")+ assert out is None and err.startswith("call failed:")+ assert usage.cost_usd == 0.123 and usage.input_tokens == 42_000