Official Codebase of 3DCodeVerse
Python
CLI/workspace: four user-facing failures that gave no usable explanation
gaoypenga7e47a123f7c
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.pyindex 21382d52..1519bc33 100644--- a/harness/codeverse/cli/main.py+++ b/harness/codeverse/cli/main.py@@ -83,8 +83,8 @@ def make("(sets models, judge samples, rounds, candidates, turn cap, ""montage size and the texture pass together)")] = None,rounds: Annotated[int | None, typer.Option("--rounds", min=0, help="refine rounds after the baseline (default: the profile's)")] = None,- max_usd: Annotated[float | None, typer.Option("--max-usd")] = None,- max_minutes: Annotated[float | None, typer.Option("--max-minutes")] = None,+ max_usd: Annotated[float | None, typer.Option("--max-usd", min=0)] = None,+ max_minutes: Annotated[float | None, typer.Option("--max-minutes", min=0)] = None,candidates: Annotated[int | None, typer.Option("--candidates", min=1, help="best-of-N baseline: N parallel candidates, keep the best (default: settings.default_candidates or 1)")] = None,slug: Annotated[str | None, typer.Option("--slug")] = None,runs_dir: RunsDirOpt = None,@@ -109,12 +109,24 @@ def make(language = TRACK_LANGUAGES[track][0]run_slug = C.make_slug(prompt, track.value, language.value, slug)settings = get_settings()+ texture_arg = texture # the dial folds the profile in below; remember what the USER asked# ONE resolver for the whole dial, so `--profile X` and `CV3D_PROFILE=X` land the same# values (they used to disagree on candidates + texture); an explicit flag beats both.dial = C.resolve_dial(settings, profile, rounds=rounds, candidates=candidates,max_usd=max_usd, max_minutes=max_minutes, texture=texture)rounds, max_usd, max_minutes = dial.rounds, dial.max_usd, dial.max_minutescandidates, texture = dial.candidates, dial.texture+ # A run must not record and display a pass it cannot run. `3dcv texture pass` already+ # refuses non-object tracks; `3dcv make` accepted --texture (and --profile quality,+ # which forces it) on scene/graphics, froze it on the spec, printed "texture True",+ # and then emitted a spurious texture.failed at finalise because there is no GLB.+ from codeverse.texturing.run import texture_supported++ if texture and not texture_supported(track):+ if texture_arg: # the user asked for it explicitly: say no, and say where to go+ hint = " — use `3dcv texture scene-pack`" if track is Track.SCENE else ""+ raise C.CliError(f"--texture is for object tracks; {track.value} runs have no GLB to texture{hint}")+ texture = False # profile-implied: quality simply has no texture pass on this trackbackends = settings.backends(generator=generator, planner=planner, judge=judge, captioner=captioner)# validate the whole Spec BEFORE touching the filesystem: an invalid# track/language combination must not leave an orphan run directory behind.@@ -235,8 +247,8 @@ def resume(slug: str,runs_dir: RunsDirOpt = None,candidates: Annotated[int | None, typer.Option("--candidates", min=1, help="best-of-N baseline width (only matters before round 0 ran)")] = None,- max_usd: Annotated[float | None, typer.Option("--max-usd", help="raise the budget cap before resuming (rewrites spec.json)")] = None,- max_minutes: Annotated[float | None, typer.Option("--max-minutes", help="raise the time cap before resuming")] = None,+ max_usd: Annotated[float | None, typer.Option("--max-usd", min=0, help="raise the budget cap before resuming (rewrites spec.json)")] = None,+ max_minutes: Annotated[float | None, typer.Option("--max-minutes", min=0, help="raise the time cap before resuming")] = None,rounds: Annotated[int | None, typer.Option("--rounds", min=0, help="new max refine rounds (rewrites spec.json)")] = None,force: Annotated[bool, typer.Option("--force", help="re-enter a run that already finished (it will be re-planned and re-scored)")] = False,) -> None:diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.pyindex 8fb13aba..76a23b03 100644--- a/harness/codeverse/contracts/common.py+++ b/harness/codeverse/contracts/common.py@@ -121,12 +121,19 @@ class Usage(BaseModel):class Budget(BaseModel):- """Hard ceilings for a run. The orchestrator stops (cleanly) when any is hit."""+ """Hard ceilings for a run. The orchestrator stops (cleanly) when any is hit.- max_rounds: int = 4- max_usd: float = 5.0- max_minutes: float = 60.0- max_repair_attempts: int = 3 # per build failure before escalating+ The ceilings are non-negative by construction. A negative one is not a small+ budget, it is an unrunnable one: ``BudgetGuard.ok()`` is False before a single+ token is spent, the first charge raises ``BudgetExceeded: cost $0.001 exceeds+ max_usd $-2.50``, and ``grant_grace`` cannot lift a hard ceiling back above zero —+ so the workspace and the git-committed spec are created for a run that can only die.+ """++ max_rounds: int = Field(default=4, ge=0)+ max_usd: float = Field(default=5.0, ge=0)+ max_minutes: float = Field(default=60.0, ge=0)+ max_repair_attempts: int = Field(default=3, ge=0) # per build failure before escalatingclass Backends(BaseModel):diff --git a/harness/codeverse/texturing/run.py b/harness/codeverse/texturing/run.pyindex 73a22972..fac167c7 100644--- a/harness/codeverse/texturing/run.py+++ b/harness/codeverse/texturing/run.py@@ -24,7 +24,7 @@ from typing import Anyfrom pydantic import BaseModel, Fieldfrom codeverse.contracts.artifacts import Measurement, RenderSet-from codeverse.contracts.common import TRACK_INFO, Usage+from codeverse.contracts.common import TRACK_INFO, Track, Usagefrom codeverse.contracts.plan import StaticPlanfrom codeverse.contracts.spec import Specfrom codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset@@ -118,15 +118,35 @@ def _measure(glb: Path) -> Measurement | None:#: ``texture: false`` run still paid for a texture pass (docs/COST.md §15: the quality run's#: ledger was +9.5% over record.total_usage because the pass ran twice, once from inside a#: round-2 agent session). Both now ask this function.+#: the object tracks — the only ones with an ``artifacts/object.glb`` to texture. A scene+#: has no GLB deliverable (languages/scene_threejs/runtime.py: "BuildResult.glb_path stays+#: None") and neither graphics language produces one at all, so ``texture_pass`` on those+#: tracks can only ever raise FileNotFoundError. Scenes have their own command,+#: ``3dcv texture scene-pack``.+TEXTURE_TRACKS = (Track.STATIC_OBJECT, Track.ARTICULATED_OBJECT)+++def texture_supported(track: Track) -> bool:+ """Whether ``texture_pass`` can run on this track at all (is there a GLB?)."""+ return track in TEXTURE_TRACKS++def texture_requested(spec: Spec) -> bool:- """True when the run asked for the derived texture pass.+ """True when the run asked for the derived texture pass AND the track can run one.``Spec.options.texture`` is the switch; the legacy ``texture`` tag is stillhonoured because recorded specs carry it. Nothing else may turn texturingon — an agent calling the ``texture_pass`` tool in a run that did not ask forit is refused, and ``3dcv texture pass <slug>`` is an explicit user- instruction that does not go through here at all."""- return bool(spec.options.texture or "texture" in (spec.tags or []))+ instruction that does not go through here at all.++ The track scope belongs here too, for the same "one owner" reason: without it+ ``--profile quality`` (which forces texture=True) made every scene and graphics run+ call a pass that could only raise FileNotFoundError, swallowed at log.warning into a+ spurious ``texture.failed`` event — quality's advertised "+texture" was a guaranteed+ no-op on half the tracks, and scene runs never reached the command that would work.+ """+ return bool(spec.options.texture or "texture" in (spec.tags or [])) and texture_supported(spec.track)def texture_pass(diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.pyindex 676e9890..739aad46 100644--- a/harness/codeverse/workspace.py+++ b/harness/codeverse/workspace.py@@ -54,6 +54,35 @@ _GITIGNORE_LINES = ()+class WorkspaceGitError(subprocess.CalledProcessError):+ """A git command in a run workspace failed, carrying git's own explanation.++ Subclasses CalledProcessError so existing ``except subprocess.CalledProcessError``+ handlers keep working. The reason it exists: CalledProcessError.__str__ drops+ stderr, and codeverse/cli/main.py reports failures as+ "run failed: {type(e).__name__}: {e}" — so a stale ``.git/index.lock`` surfaced as+ the bare line "Command '['git', 'add', '-A']' returned non-zero exit status 128"+ while git's own "fatal: Unable to create ... index.lock: File exists" sat unread in+ e.stderr. The 4-try/1.2 s retry loop above is built for a LIVE holder and can never+ clear a stale lock, so every subsequent ``3dcv resume <slug>`` repeated the same+ opaque failure with no clue and no named remedy.+ """++ def __init__(self, root: Path, args: tuple[str, ...], returncode: int, stderr: str):+ super().__init__(returncode, ["git", *args], None, stderr)+ self.root = root+ self._detail = (stderr or "").strip()[-800:]++ def __str__(self) -> str:+ msg = f"git {' '.join(self.cmd[1:])} failed in {self.root} (exit {self.returncode})"+ if self._detail:+ msg += f": {self._detail}"+ if "index.lock" in (self.stderr or ""):+ msg += (f"\n a stale lock is left behind when a run is killed mid-commit; "+ f"if no other git is running here, remove it: rm {self.root / '.git' / 'index.lock'}")+ return msg++class Workspace:"""Paths + snapshot helpers for one run. Cheap to construct; no I/O until used."""@@ -258,7 +287,7 @@ class Workspace:breaktime.sleep(0.2 * (attempt + 1)) # another process holds .git/index.lockif check and proc.returncode != 0:- raise subprocess.CalledProcessError(proc.returncode, proc.args, proc.stdout, proc.stderr)+ raise WorkspaceGitError(self.root, args, proc.returncode, proc.stderr or "")return procdef _git_init(self) -> None:diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.pyindex 644752a1..62f93ad6 100644--- a/harness/tests/core/test_run_layout.py+++ b/harness/tests/core/test_run_layout.py@@ -163,3 +163,35 @@ def test_show_prints_the_sheet_that_exists_after_a_move(tmp_path):shown = line.split("sheet:", 1)[1].strip().rstrip("│ ").strip()assert shown.endswith("sheet.png"), f"the panel wrapped the path: {line!r}"assert Path(shown).exists(), f"show printed a sheet that is not there: {shown!r}"+++def test_a_stale_index_lock_names_the_remedy(tmp_path):+ """CP-7: a run killed mid-commit leaves .git/index.lock behind, and every subsequent+ `3dcv resume <slug>` then failed with the bare line "Command '['git', 'add', '-A']'+ returned non-zero exit status 128". git's own explanation sat unread in e.stderr:+ CalledProcessError.__str__ drops it and cli/main.py prints only+ "run failed: {type(e).__name__}: {e}". The 4-try/1.2 s retry loop is built for a+ LIVE holder and can never clear a stale lock, so the failure repeated forever with+ no clue and no named remedy."""+ import subprocess++ import pytest++ from codeverse.workspace import Workspace, WorkspaceGitError++ ws = Workspace(tmp_path / "run").create()+ ws.src.mkdir(parents=True, exist_ok=True)+ (ws.src / "model.py").write_text("x = 1\n")+ ws.commit("round 0")++ (ws.root / ".git" / "index.lock").write_text("") # what a SIGKILL leaves behind+ with pytest.raises(WorkspaceGitError) as ei:+ ws.commit("round 1")++ msg = str(ei.value)+ assert "index.lock" in msg, "git's own explanation must reach the operator"+ assert "File exists" in msg+ assert f"rm {ws.root / '.git' / 'index.lock'}" in msg, "the remedy must be named"+ # still a CalledProcessError, so existing handlers keep working, and stderr is kept+ assert isinstance(ei.value, subprocess.CalledProcessError)+ assert "index.lock" in (ei.value.stderr or "")diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.pyindex 888c618e..8174b3e0 100644--- a/harness/tests/flywheel_cli/test_cli.py+++ b/harness/tests/flywheel_cli/test_cli.py@@ -364,3 +364,85 @@ def test_reference_with_no_run_says_it_is_about_to_spend_money(tmp_path: Path, mhelp_text = typing.get_type_hints(make_cmd, include_extras=True)["no_run"].__metadata__[0].helpassert "with --reference the reference pass still runs first" in help_text+++def test_an_unknown_profile_is_a_clean_error_not_a_traceback(tmp_path: Path):+ """SMOKE5: `--profile <unknown>` exited with a raw ValueError traceback out of+ cost/profiles.py:153, while every other rejected value (a slug collision, a missing+ battery) printed the clean "error: ..." line the CLI uses for user errors."""+ r = runner.invoke(app, ["make", "a chair", "--profile", "turbo", "--no-run",+ "--runs-dir", str(tmp_path / "runs"), "--slug", "prof"])+ assert r.exit_code == 2, "the CLI's typed configuration-error code (see SM-10)"+ assert "unknown profile" in r.output and "economy, balanced, quality" in r.output+ assert "Traceback" not in r.output and "ValueError" not in r.output+ assert not (tmp_path / "runs" / "prof").exists(), "no workspace for a rejected flag"+++def test_a_negative_budget_is_rejected_before_the_workspace_exists(tmp_path: Path):+ """SM-11: --max-usd took any float. A negative ceiling is not a small budget, it is+ an unrunnable one — BudgetGuard.ok() is False before a single token is spent, the+ first charge raises "cost $0.001 exceeds max_usd $-2.50", and grant_grace cannot+ lift a hard ceiling back above zero. `3dcv make` nonetheless printed+ `max_usd -3.0`, created the workspace and git-committed the spec."""+ runs = tmp_path / "runs"+ for flag, value in (("--max-usd", "-3"), ("--max-minutes", "-10")):+ r = runner.invoke(app, ["make", "a chair", flag, value, "--no-run",+ "--runs-dir", str(runs), "--slug", "neg"])+ assert r.exit_code != 0, f"{flag} {value} was accepted"+ assert "range x>=0" in r.output.replace("\n", "")+ assert not (runs / "neg").exists(), "no workspace may be created for a rejected budget"++ # 0 stays legal (documented: a run at 0 degrades from its first check) ...+ r = runner.invoke(app, ["make", "a chair", "--max-usd", "0", "--no-run",+ "--runs-dir", str(runs), "--slug", "zero"])+ assert r.exit_code == 0 and (runs / "zero" / "spec.json").is_file()+ # ... and the contract refuses a negative ceiling even when built directly+ import pytest as _pytest+ from pydantic import ValidationError++ from codeverse.contracts.common import Budget++ with _pytest.raises(ValidationError):+ Budget(max_usd=-3.0)+ assert Budget(max_usd=0.0).max_usd == 0.0+++def test_texture_is_not_offered_on_tracks_that_have_no_glb(tmp_path: Path):+ """SM-08: `--texture` (and `--profile quality`, which forces it) was accepted on the+ scene and graphics tracks, frozen on the spec, and printed as `texture True` — but a+ scene has no GLB deliverable and neither graphics language produces one, so the+ finalise pass could ONLY raise FileNotFoundError('no GLB to texture'), swallowed by+ BaseTrack._texture_pass into a spurious `texture.failed`. quality's advertised+ "+texture" was a guaranteed no-op on half the tracks, and scene runs never reached+ the command that would work. `3dcv texture pass` already guards this; `3dcv make`+ did not."""+ from codeverse.contracts.common import Track+ from codeverse.texturing.run import texture_requested, texture_supported++ runs = tmp_path / "runs"+ # profile-implied: quality still works, it just has no texture pass on this track+ r = runner.invoke(app, ["make", "a plasma shader", "--track", "graphics", "--profile", "quality",+ "--no-run", "--runs-dir", str(runs), "--slug", "gfxq"])+ assert r.exit_code == 0+ opts = json.loads((runs / "gfxq" / "spec.json").read_text())["options"]+ assert opts["texture"] is False, "a run must not record a pass it cannot run"+ assert opts["profile"] == "quality", "the rest of the dial still applies"++ # explicit: refused, and pointed at the command that does work+ r = runner.invoke(app, ["make", "a kitchen", "--track", "scene", "--texture",+ "--no-run", "--runs-dir", str(runs), "--slug", "scnx"])+ assert r.exit_code == 1 and "texture scene-pack" in r.output.replace("\n", "")+ assert not (runs / "scnx").exists()++ # the object tracks are untouched+ r = runner.invoke(app, ["make", "a chair", "--profile", "quality",+ "--no-run", "--runs-dir", str(runs), "--slug", "objq"])+ assert r.exit_code == 0+ assert json.loads((runs / "objq" / "spec.json").read_text())["options"]["texture"] is True++ # and the single owner of the decision knows the track scope, so a spec that already+ # carries texture=True on a scene track (recorded before this fix) is a no-op too+ assert texture_supported(Track.STATIC_OBJECT) and not texture_supported(Track.SCENE)+ stale = Spec.model_validate(json.loads((runs / "objq" / "spec.json").read_text()))+ assert texture_requested(stale)+ assert not texture_requested(stale.model_copy(update={"track": Track.GRAPHICS}))