Official Codebase of 3DCodeVerse
Python
cost: routing.py goes — COST §8 is the one home of the routing table
gaoypeng4f36b0b70c0f
diff --git a/harness/codeverse3d/addons/costreport/report.py b/harness/codeverse3d/addons/costreport/report.pyindex 3e9c9460..30d9e15a 100644--- a/harness/codeverse3d/addons/costreport/report.py+++ b/harness/codeverse3d/addons/costreport/report.py@@ -18,7 +18,6 @@ from codeverse3d.addons.costreport.audit import (uncached_if_no_cache,)from codeverse3d.cost.reconstruct import RunLedger-from codeverse3d.cost.routing import pro_break_even, routing_tablefrom codeverse3d.cost.types import CostBucketSTAGE_ORDER = ("plan", "skeleton", "assets", "env", "zones", "assemble", "baseline", "candidate",@@ -145,14 +144,6 @@ def markdown(audit: Audit, *, title: str = "Cost audit") -> str:[[k, f"{v / 3600:.2f}", f"{share * 100:.1f}%"] for k, (v, share) in stage_latency(audit).items()])]parts += ["", "## Price confidence", "",table(("price source", "USD"), [[k, _usd(v)] for k, v in price_confidence(audit).items()])]- be = pro_break_even()- parts += ["", "## Routing", "",- table(("role", "model", "$/call", "measured quality", "when"), routing_table()),- "",- f"Matching the pro judge's precision (σ 0.030) with flash needs "- f"**{be['samples_needed']:.0f} samples** = ${be['cheap_matched_usd']:.3f} per verdict "- f"vs ${be['pro_usd']:.3f} for one pro verdict — pro is **{be['ratio']:.1f}x cheaper** "- f"at equal precision (and flash's rank is anti-correlated with the gates, which sampling cannot fix)."]return "\n".join(parts) + "\n"diff --git a/harness/codeverse3d/cost/__init__.py b/harness/codeverse3d/cost/__init__.pyindex 16035053..dc37e291 100644--- a/harness/codeverse3d/cost/__init__.py+++ b/harness/codeverse3d/cost/__init__.py@@ -3,11 +3,11 @@ top of ``models/pricing.py``, and a pre-send cost guard. (The audit of FINISHEDits report are ``codeverse3d.addons.costreport``.)This package re-exports only the names other packages actually import through it.-Everything else lives in — and is imported from — its own module: ``cost.profiles`` (get_profile/PROFILES), ``cost.routing``-(ROUTES/Route), ``cost.instrument`` (metered_chat_model/MeteredAgent),+Everything else lives in — and is imported from — its own module: ``cost.profiles``+(get_profile/PROFILES), ``cost.instrument`` (metered_chat_model/MeteredAgent),``cost.types`` (CallCost/CostBucket/Summary), ``cost.reconstruct`` (RunLedger).-Keeping the shim narrow also keeps profiles/routing out of the eager import-graph of ``import codeverse3d.cost``.+Keeping the shim narrow also keeps profiles out of the eager import graph of+``import codeverse3d.cost``.Nothing here imports tracks/ or orchestrator/, so any layer may use it."""diff --git a/harness/codeverse3d/cost/routing.py b/harness/codeverse3d/cost/routing.pydeleted file mode 100644index be7c7b73..00000000--- a/harness/codeverse3d/cost/routing.py+++ /dev/null@@ -1,120 +0,0 @@-"""Which model should do which job — with the measured trade-off behind it.--Every number in :data:`ROUTES` was measured on this box (see ``docs/COST.md``):-prices from ``models/pricing.py`` (checked 2026-08-23), $/call from the 61-recorded runs, judge noise from ``judges/calibration.py`` (n=3 on the e2e-rounds), generator quality from ``eval/bench/out/compare_v1_live2``.--The one non-obvious result: **a noisy cheap judge is not cheap.** Averaging-flash to pro's precision needs ``(σ_flash/σ_pro)²`` samples — and even then it-does not buy pro's *correlation* with the deterministic gates, so a biased rank-stays biased. :func:`samples_for_precision` and :func:`pro_break_even` do that-arithmetic for a caller that wants to decide at runtime.-"""--from __future__ import annotations--from dataclasses import dataclass-from math import ceil--from codeverse3d.cost.types import Role--#: judge score noise (std of the overall score over n=3 samples) and the-#: correlation of the score with deterministic gate errors, per judge model.-#: Source: ``judges/calibration.py`` on the e2e rounds, 2026-08-23.-JUDGE_NOISE: dict[str, tuple[float, float]] = {- "gemini-3.7-flash": (0.083, -0.33),- "gemini-3.1-pro-preview": (0.030, +0.63),-}---@dataclass(frozen=True)-class Route:- """One recommended (role, model) pairing with its measured price and caveat."""-- role: Role- model_id: str- usd_per_call: float # measured median from the recorded runs- quality: str- when: str- default: bool = False---ROUTES: tuple[Route, ...] = (- # ---------------------------------------------------------------- planner- Route(Role.PLANNER, "gemini:gemini-3.7-flash", 0.013,- "plans are structured output; no measured failure attributable to the planner",- "always — the plan is 0.8% of a run; a pro planner would double that for no measured gain",- default=True),- # -------------------------------------------------------------- generator- Route(Role.GENERATOR, "gemini-cli:gemini-3.6-flash", 0.52,- "compare_v1: mean judge 0.835 on easy static objects (best arm measured)",- "the arm compare_v1 was measured on; kept for comparison against those numbers"),- Route(Role.GENERATOR, "single-shot:gemini:gemini-3.7-flash", 0.05,- "graphics track: 5/6 passed, median 0.810, $0.099 per run",- "glsl_shader / opengl_python — one file, compiler feedback, no tool loop needed"),- # the runtime default since 2026-08-28 (contracts.common.Backends.generator):- # the default=True route must name what actually runs, not the arm we measured first- Route(Role.GENERATOR, "gemini-cli:gemini-3.7-flash", 0.73,- "compare_v1: 0.827 — statistically the same as the since-deleted api-agent arm at 2x the price",- "the default; ~2x the 3.6 arm's price for quality measured as the same, so the number to beat",- default=True),- Route(Role.GENERATOR, "codex:gpt-5.6-sol", 1.93,- "one-shot 0.786 for $0.20; inside the harness loop $1.93/run (long cached context at $0.40/M)",- "strong one-shot baseline; expensive as a loop generator"),- Route(Role.GENERATOR, "oneshot:claude-code", 1.04,- "compare_v1: 0.673 mean, 0/2 passed — the weakest score per dollar measured here",- "not recommended for bulk generation on this battery"),- # ------------------------------------------------------------------ judge- Route(Role.JUDGE, "gemini:gemini-3.1-pro-preview", 0.060,- "σ 0.030, pearson(gate errors, score) +0.63",- "every verdict that persists: the round a pick hands over, dataset tiering",- default=True),- Route(Role.JUDGE, "gemini:gemini-3.7-flash", 0.027,- "σ 0.083 and pearson −0.33 (anti-correlated with the gates)",- "in-loop refine hints only — its scores are what a pick then ranks, so not where the pick matters"),- # ------------------------------------------------------------------ image- Route(Role.IMAGE, "gemini:gemini-3.1-flash-image", 0.067,- "per 1024² tile; a texture pass is ~2 tiles + plan + gate ≈ $0.13",- "texture passes only, and only when the before/after gate can ship the result",- default=True),- Route(Role.CAPTIONER, "gemini:gemini-3.7-flash", 0.010,- "captions are post-hoc and cheap; no measured quality difference worth pro",- "always", default=True),-)---def samples_for_precision(model: str, target_std: float, *, noise: dict[str, tuple[float, float]] | None = None) -> int:- """How many samples of ``model`` are needed to reach ``target_std``- (σ_eff = σ / √n). Returns 1 when the model is already precise enough."""- table = noise or JUDGE_NOISE- sigma = table.get(model, (0.0, 0.0))[0]- if sigma <= 0 or target_std <= 0 or sigma <= target_std:- return 1- return int(ceil((sigma / target_std) ** 2))---def pro_break_even(- *,- cheap_model: str = "gemini-3.7-flash",- pro_model: str = "gemini-3.1-pro-preview",- cheap_usd: float = 0.027,- pro_usd: float = 0.060,-) -> dict[str, float]:- """The arithmetic behind "use pro": what matching pro's precision with the- cheap judge would cost, per verdict."""- pro_sigma = JUDGE_NOISE.get(pro_model, (0.03, 0.0))[0]- n = samples_for_precision(cheap_model, pro_sigma)- return {- "samples_needed": float(n),- "cheap_matched_usd": n * cheap_usd,- "pro_usd": pro_usd,- "pro_is_cheaper_by": n * cheap_usd - pro_usd,- "ratio": (n * cheap_usd / pro_usd) if pro_usd else 0.0,- }---def routing_table() -> list[tuple[str, str, str, str, str]]:- """Rows for the report: (role, model, $/call, quality, when)."""- return [(str(r.role), r.model_id + (" *" if r.default else ""), f"${r.usd_per_call:.3f}", r.quality, r.when)- for r in ROUTES]diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex 521672c6..4b53019c 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -163,7 +163,7 @@ codeverse3d/profiles.py (economy|balanced|quality; cli._common.resolve_dial is THE resolver)billing.py (SUBSCRIPTION_BACKENDS/bills_usd — which backends take real dollars,so the ledger bills real money and not list price; docs/COST.md §25)- guard.py routing.py reconstruct.py (old runs)+ guard.py reconstruct.py (old runs)judges/ base.py (JudgeInput; `round_input` + `plan_summary(plan, language)`, the ONE payloadbuilder and plan digest the in-run judge, `3dcode judge`, calibration, the texturegate and eval all use; the pure replay helpers), rubrics.py + rubrics/*.yaml (defect checklists, the wirediff --git a/harness/docs/COST.md b/harness/docs/COST.mdindex 619a6308..b48f1be6 100644--- a/harness/docs/COST.md+++ b/harness/docs/COST.md@@ -354,8 +354,8 @@ matter how many samples you buy. Pro is the cheap option for anything thatpersists. Concretely, the 112 verdicts in this data set cost $6.48 with the projudge and would cost $24.2 as "cheap" flash at n=8.-`codeverse3d/cost/routing.py` holds this table in code-(`ROUTES`, `pro_break_even()`, `samples_for_precision()`).+This table is its one home (the `cost/routing.py` copy of it, which only the markdown cost+report printed, went on 2026-09-22).## 9. Ranked optimisation opportunitiesdiff --git a/harness/tests/cost/test_audit_report.py b/harness/tests/cost/test_audit_report.pyindex 35cf4d80..2dba80d0 100644--- a/harness/tests/cost/test_audit_report.py+++ b/harness/tests/cost/test_audit_report.py@@ -76,7 +76,7 @@ def test_a_lower_scoring_round_is_not_waste_but_a_repair_that_never_built_is(fakdef test_report_renders(fake_run: Path):audit = audit_runs([fake_run])md = markdown(audit)- for heading in ("Per stage", "Per role", "Where a dollar bought nothing", "Routing"):+ for heading in ("Per stage", "Per role", "Where a dollar bought nothing"):assert f"## {heading}" in mdassert "per passing artifact" not in md and "per run" in mdassert "judge" in console(audit)diff --git a/harness/tests/cost/test_guard_caching_routing.py b/harness/tests/cost/test_guard.pysimilarity index 72%rename from harness/tests/cost/test_guard_caching_routing.pyrename to harness/tests/cost/test_guard.pyindex f4a2caa9..bb09ca4a 100644--- a/harness/tests/cost/test_guard_caching_routing.py+++ b/harness/tests/cost/test_guard.py@@ -1,5 +1,4 @@-"""The three optimisation helpers: pre-send estimate, cache-friendly ordering,-model routing."""+"""The pre-send cost estimate."""from __future__ import annotations@@ -7,7 +6,6 @@ import pytestfrom codeverse3d.cost import estimate_callfrom codeverse3d.cost.guard import image_tokens, text_tokens-from codeverse3d.cost.routing import pro_break_even, samples_for_precision# ------------------------------------------------------------------ guard@@ -31,11 +29,3 @@ def test_estimate_from_text_and_images():def test_estimate_of_an_image_model_uses_the_per_image_price():est = estimate_call("gemini:gemini-3.1-flash-image", input_tokens=500, n_images_out=2)assert est.usd == pytest.approx(500 * 0.5 / 1e6 + 2 * 0.067)---# ------------------------------------------------------------------ caching-def test_pro_judge_pays_for_itself_at_equal_precision():- assert samples_for_precision("gemini-3.7-flash", 0.030) == 8- assert samples_for_precision("gemini-3.1-pro-preview", 0.030) == 1- be = pro_break_even()- assert be["ratio"] > 3 and be["pro_is_cheaper_by"] > 0.1