Official Codebase of 3DCodeVerse
Python
config + ab_plan: negative in-flight caps, and children that ignored the cap the budget reserved
gaoypeng215e028378f6
diff --git a/harness/bench/ab_plan.py b/harness/bench/ab_plan.pyindex 613c8687..407a877d 100644--- a/harness/bench/ab_plan.py+++ b/harness/bench/ab_plan.py@@ -79,9 +79,10 @@ DEFAULT_GENERATOR = "api-agent:gemini:gemini-3.7-flash"DEFAULT_JUDGE = "gemini:gemini-3.1-pro-preview"#: the per-child cap. The flat name is a first-class alias of ``CV3D_RATE__MAX_IN_FLIGHT``#: since 2026-08-24 (``Settings._FLAT_ALIASES``; before that it was read by nothing) and-#: wins over the nested spelling when both are set, which is what makes ``setdefault``-#: below a real cap even when the launching shell exported the nested one at 64.+#: wins over the nested spelling when both are set.MAX_IN_FLIGHT_ENV = "CV3D_MAX_IN_FLIGHT"+#: the nested spelling: popped from every child's env so it cannot fight the flat one+NESTED_MAX_IN_FLIGHT_ENV = "CV3D_RATE__MAX_IN_FLIGHT"DEFAULT_MAX_IN_FLIGHT = 16#: only ever 2 — one control + one variant, launched together (see module docstring)PARALLEL = 2@@ -113,6 +114,20 @@ class AbOptions(BaseModel):resume=self.resume, pairwise=False)+def inherited_max_in_flight() -> int:+ """The cap the launching shell asks for, used only when ``--max-in-flight`` is absent.++ Whatever wins here is BOTH what the children run at and what the budget preflight+ reserves; the two must never disagree, which is why the answer is resolved once, into+ ``AbOptions``, instead of once per child out of the ambient environment.+ """+ for name in (MAX_IN_FLIGHT_ENV, NESTED_MAX_IN_FLIGHT_ENV):+ raw = os.environ.get(name, "").strip()+ if raw.isdigit() and int(raw) > 0:+ return int(raw)+ return DEFAULT_MAX_IN_FLIGHT++def parse_variant_env(items: Sequence[str]) -> dict[str, str]:"""``["K=V", "K2=V2"]`` → ``{K: V, K2: V2}``; a bare ``K`` is rejected, not defaulted."""out: dict[str, str] = {}@@ -130,7 +145,12 @@ def child_env(arm: str, opts: AbOptions, base: dict[str, str] | None = None) ->The variant gets ``variant_env`` on top of the driver's env; the control gets thedriver's env with those same keys REMOVED, so a switch that happens to be set inthe launching shell cannot silently turn the control into a second variant. Both- get the in-flight cap unless the driver already set one.+ are PINNED to ``opts.max_in_flight`` (both spellings), never merely defaulted to it:+ ``main`` refuses to start unless ``pool_budget().fits(2 * opts.max_in_flight)``, so a+ child that inherited a different cap from the launching shell would make that+ reservation a fiction — with ``--max-in-flight 8`` under a shell exporting 32 the A/B+ reserved 16 of the 64-call knee and consumed 64 (docs/COST.md §23). ``opts`` already+ carries the inherited value when no flag was passed (:func:`inherited_max_in_flight`).Under ``--aa`` the variant arm gets the CONTROL environment: the two arms then runbyte-identical code and the measured delta is the rig's own noise floor, which is the@@ -141,7 +161,8 @@ def child_env(arm: str, opts: AbOptions, base: dict[str, str] | None = None) ->env.pop(k, None)if arm == VARIANT and not opts.aa:env.update(opts.variant_env)- env.setdefault(MAX_IN_FLIGHT_ENV, str(opts.max_in_flight))+ env[MAX_IN_FLIGHT_ENV] = str(opts.max_in_flight)+ env.pop(NESTED_MAX_IN_FLIGHT_ENV, None)env["PYTHONUNBUFFERED"] = "1"return env@@ -335,7 +356,9 @@ def _parser() -> argparse.ArgumentParser:ap.add_argument("--ids", default="")ap.add_argument("--tiers", default="")ap.add_argument("--limit", type=int, default=None)- ap.add_argument("--max-in-flight", type=int, default=DEFAULT_MAX_IN_FLIGHT, help=f"per child ({MAX_IN_FLIGHT_ENV})")+ ap.add_argument("--max-in-flight", type=int, default=None,+ help=f"per child; wins over an inherited {MAX_IN_FLIGHT_ENV} "+ f"(default: that variable, else {DEFAULT_MAX_IN_FLIGHT}). The preflight reserves 2x it")ap.add_argument("--parallel", type=int, default=PARALLEL, help="accepted for symmetry; must be 2 (one pair)")ap.add_argument("--redo-status", default="", help="comma list, e.g. infra_failed (re-runs both arms of the prompt)")ap.add_argument("--redo-resume", action="store_true",@@ -364,7 +387,8 @@ def main(argv: Sequence[str] | None = None) -> int:rounds=ns.rounds, max_usd=ns.max_usd, max_minutes=ns.max_minutes, n_samples=ns.n_samples,ids=[i for i in ns.ids.split(",") if i], tiers=[t for t in ns.tiers.split(",") if t],limit=ns.limit, resume=not ns.no_resume, redo_status=[s for s in ns.redo_status.split(",") if s],- variant_env=parse_variant_env(ns.variant_env), max_in_flight=ns.max_in_flight,+ variant_env=parse_variant_env(ns.variant_env),+ max_in_flight=ns.max_in_flight if ns.max_in_flight is not None else inherited_max_in_flight(),aa=ns.aa, redo_fresh=not ns.redo_resume)out = Path(ns.out)if ns.report_only:@@ -404,9 +428,9 @@ def main(argv: Sequence[str] | None = None) -> int:return 0-__all__ = ["DEFAULT_GENERATOR", "DEFAULT_JUDGE", "MAX_IN_FLIGHT_ENV", "PARALLEL", "AbOptions", "CellRunner", "Todo",- "archive_cell", "cell_dir", "cell_main", "child_env", "main", "parse_variant_env", "preflight", "run_ab",- "spawn_cell", "worker_argv"]+__all__ = ["DEFAULT_GENERATOR", "DEFAULT_JUDGE", "MAX_IN_FLIGHT_ENV", "NESTED_MAX_IN_FLIGHT_ENV", "PARALLEL",+ "AbOptions", "CellRunner", "Todo", "archive_cell", "cell_dir", "cell_main", "child_env",+ "inherited_max_in_flight", "main", "parse_variant_env", "preflight", "run_ab", "spawn_cell", "worker_argv"]if __name__ == "__main__":raise SystemExit(main())diff --git a/harness/codeverse/config.py b/harness/codeverse/config.pyindex b5f91be6..4f44ac2c 100644--- a/harness/codeverse/config.py+++ b/harness/codeverse/config.py@@ -27,6 +27,16 @@ _LEGACY_KEYS_FILE = Path.home() / ".config" / "astra3d" / "gemini_keys.env"_USER_CONFIG = Path.home() / ".config" / "codeverse" / "config.yaml"+def _lower_bound(model: type[BaseModel], field: str) -> int | None:+ """The ``ge=`` declared on ``model.field`` (None when unbounded). Lets a flat env+ alias enforce exactly the bound its target field declares, in one place."""+ for meta in model.model_fields[field].metadata:+ lo = getattr(meta, "ge", None)+ if lo is not None:+ return int(lo)+ return None++class Binaries(BaseModel):blender: str = Field(default="", description="path to a Blender 4.2+/5.x binary (headless capable)")node: str = "node"@@ -69,10 +79,11 @@ class Limits(BaseModel):# (1 392 builds/min; 24 workers gave 1 168, 32 gave 1 019), so a fan-out of 12# agent tasks x their own builds stays inside the knee and leaves cores for the# render pass, whose tail is minutes long.- max_parallel_agents: int = 12- max_parallel_builds: int = 8+ max_parallel_agents: int = Field(default=12, ge=1, description="thread fan-out for agent tasks (>= 1)")+ max_parallel_builds: int = Field(default=8, ge=1, description="concurrent build subprocesses (>= 1)")agent_max_turns: int = Field(default=0,+ ge=0,description="hard cap on model turns per agent session (0 = the backend's own default, ""which is what ships: a 28-turn cap cost $0.02 more and 0.205 of a score point in its ""own A/B — docs/COST.md §17 — so no profile sets one; name it here if you want one).",@@ -93,10 +104,15 @@ class Rate(BaseModel):cores, model calls are network-bound and sized by the provider. 0 = unlimited."""- rpm_per_key: int = Field(default=1000, description="requests/minute allowed per API key")- tpm_per_key: int = Field(default=1_000_000, description="prompt tokens/minute allowed per API key")+ rpm_per_key: int = Field(default=1000, ge=1, description="requests/minute allowed per API key")+ tpm_per_key: int = Field(default=1_000_000, ge=0, description="prompt tokens/minute allowed per API key (0 = no TPM bucket)")max_in_flight: int = Field(default=64,+ ge=0, # NEGATIVE is not "unlimited" here: 0 is. Without this bound -5 survived config,+ # was reported as FITTING the pool budget by `3dcv doctor`, poisoned the shared+ # in-flight accounting, and finally died as a bare ValueError from+ # threading.BoundedSemaphore inside KeyPool -- at the first model call, long+ # after the workspace and spec.json were written.description="process-wide cap on concurrent model calls (0 = off). Measured knee: a ""128-call burst of 12k-token prompts ran 29.6 calls/min at 16 in-flight, 43.9 at 32, ""72.9 at 64 and fell back to 47.2 at 128 (docs/COST.md Part III).")@@ -140,7 +156,14 @@ class Settings(BaseSettings):value = int(raw)except ValueError as e:raise ValueError(f"{env}={raw!r}: expected an integer") from e- setattr(getattr(self, section), field, value)+ # plain assignment does NOT re-validate (no validate_assignment), so the target+ # field's own bound is enforced here — and the message names the variable the+ # operator actually typed, not the nested field they never heard of.+ sub = getattr(self, section)+ lo = _lower_bound(type(sub), field)+ if lo is not None and value < lo:+ raise ValueError(f"{env}={raw!r}: must be >= {lo}")+ setattr(sub, field, value)return selfruns_dir: Path = Field(default=Path("runs"))diff --git a/harness/tests/compare_bench/test_ab_plan.py b/harness/tests/compare_bench/test_ab_plan.pyindex d995027e..f66fb5d5 100644--- a/harness/tests/compare_bench/test_ab_plan.py+++ b/harness/tests/compare_bench/test_ab_plan.py@@ -26,13 +26,16 @@ from bench._ab_report import ( # noqa: E402)from bench._compare_report import CellResult, load_jsonl # noqa: E402from bench.ab_plan import ( # noqa: E402+ DEFAULT_MAX_IN_FLIGHT,MAX_IN_FLIGHT_ENV,+ NESTED_MAX_IN_FLIGHT_ENV,AbOptions,Todo,_plan_todo,archive_cell,cell_dir,child_env,+ inherited_max_in_flight,main,parse_variant_env,run_ab,@@ -185,11 +188,30 @@ def test_variant_env_is_applied_to_the_variant_arm_only():assert "CV3D_PLAN_BRIEF" not in c, "the control must never inherit the switch under test"assert c["PATH"] == v["PATH"] == "/bin"assert c[MAX_IN_FLIGHT_ENV] == v[MAX_IN_FLIGHT_ENV] == "16"- # a cap set by the driver's own environment is respected, not overwritten- assert child_env(VARIANT, opts, {MAX_IN_FLIGHT_ENV: "4"})[MAX_IN_FLIGHT_ENV] == "4"assert child_env(VARIANT, opts, {})["PYTHONUNBUFFERED"] == "1"+def test_children_run_at_exactly_the_cap_the_budget_reserved(monkeypatch):+ """CQ-3: main() refuses to start unless ``pool_budget().fits(2 * opts.max_in_flight)``,+ so both children must run at THAT number. child_env used ``setdefault``, so a shell+ exporting CV3D_MAX_IN_FLIGHT=32 under ``--max-in-flight 8`` reserved 16 of the 64-call+ knee and then consumed 64 (docs/COST.md §23) — three lines after the function+ deliberately pops every variant key so an inherited switch cannot win."""+ opts = AbOptions(variant_env={"K": "v"}, max_in_flight=8)+ base = {"PATH": "/bin", MAX_IN_FLIGHT_ENV: "32", NESTED_MAX_IN_FLIGHT_ENV: "48"}+ for arm in (CONTROL, VARIANT):+ env = child_env(arm, opts, base)+ assert env[MAX_IN_FLIGHT_ENV] == "8", "an explicit --max-in-flight must beat the shell"+ assert NESTED_MAX_IN_FLIGHT_ENV not in env, "the nested spelling must not fight the flat one"+ # without the flag the inherited cap is still honoured — resolved ONCE, into AbOptions,+ # so the number the children get and the number the preflight reserves are the same one+ monkeypatch.setenv(MAX_IN_FLIGHT_ENV, "6")+ monkeypatch.delenv(NESTED_MAX_IN_FLIGHT_ENV, raising=False)+ assert inherited_max_in_flight() == 6+ monkeypatch.delenv(MAX_IN_FLIGHT_ENV)+ assert inherited_max_in_flight() == DEFAULT_MAX_IN_FLIGHT++def test_the_in_flight_env_name_is_one_settings_reads(monkeypatch):"""A cap that Settings does not read is no cap: the children would run at 64 each."""from codeverse.config import get_settingsdiff --git a/harness/tests/core/test_config_env_aliases.py b/harness/tests/core/test_config_env_aliases.pyindex 3bb80a39..347d0792 100644--- a/harness/tests/core/test_config_env_aliases.py+++ b/harness/tests/core/test_config_env_aliases.py@@ -49,3 +49,34 @@ def test_doctor_prints_a_name_that_is_actually_read():src = (Path(__file__).resolve().parents[2] / "codeverse" / "cli" / "doctor.py").read_text()assert "CV3D_MAX_IN_FLIGHT=" in srcassert "CV3D_MAX_IN_FLIGHT" in Settings._FLAT_ALIASES+++def test_a_negative_cap_is_rejected_by_both_spellings(monkeypatch):+ """SM-07: ``CV3D_MAX_IN_FLIGHT=-5`` used to survive Settings, be reported as *fitting*+ the pool budget by ``3dcv doctor`` (-5 <= headroom), poison the shared in-flight+ accounting every sibling process reads, and finally die as a bare+ 'ValueError: semaphore initial value must be >= 0' from threading.BoundedSemaphore+ inside KeyPool — at the first model call, after the workspace and spec.json were on+ disk. 0 means unlimited here, so -1 / -5 is exactly what an operator reaches for."""+ monkeypatch.delenv("CV3D_RATE__MAX_IN_FLIGHT", raising=False)+ monkeypatch.setenv("CV3D_MAX_IN_FLIGHT", "-5")+ with pytest.raises(ValueError, match="CV3D_MAX_IN_FLIGHT"): # names the variable they typed+ Settings()+ monkeypatch.delenv("CV3D_MAX_IN_FLIGHT")+ monkeypatch.setenv("CV3D_RATE__MAX_IN_FLIGHT", "-5")+ with pytest.raises(ValueError, match="max_in_flight"):+ Settings()+++def test_the_rate_and_limits_dials_carry_their_bounds(monkeypatch):+ """The same class of value elsewhere: a 0 RPM bucket never refills and a 0-worker+ fan-out cannot start a thread, so both are rejected at construction, not at use."""+ from codeverse.config import Limits, Rate++ for kwargs in ({"max_in_flight": -1}, {"rpm_per_key": 0}, {"tpm_per_key": -1}):+ with pytest.raises(ValueError):+ Rate(**kwargs)+ for kwargs in ({"max_parallel_agents": 0}, {"max_parallel_builds": -2}, {"agent_max_turns": -1}):+ with pytest.raises(ValueError):+ Limits(**kwargs)+ assert Rate(max_in_flight=0).max_in_flight == 0, "0 stays legal: it means unlimited"