Skip to content

Official Codebase of 3DCodeVerse

Python

fixes from the 2026-09-21 review: eight bugs, three regression tests

gaoypengcfe9f721ebe8
diff --git a/harness/codeverse/agents/backends.py b/harness/codeverse/agents/backends.py
index 4d20f6f9..f10f49ca 100644
--- a/harness/codeverse/agents/backends.py
+++ b/harness/codeverse/agents/backends.py
@@ -431,7 +431,7 @@ class ClaudeCodeAgent(_CliAgent):
reason, ok = "error", False
errors.append(f"rc={proc.rc}; no result envelope; stderr tail: {tail(proc.stderr, 1500)}")
if is_transient_failure(proc.stderr, proc.stdout):
- reason = "budget" if "rate" in proc.stderr.lower() else "error"
+ reason = "budget" if is_quota_failure(proc.stderr) else "error"
elif env.get("is_error") or str(env.get("subtype", "")).startswith("error"):
ok = False
sub = str(env.get("subtype", ""))
diff --git a/harness/codeverse/cost/report.py b/harness/codeverse/cost/report.py
index 3a9a6fa9..72adccc8 100644
--- a/harness/codeverse/cost/report.py
+++ b/harness/codeverse/cost/report.py
@@ -25,6 +25,12 @@ def _usd(x: float) -> str:
return f"${x:,.4f}" if abs(x) < 1 else f"${x:,.2f}"
+def _share(part: float, whole: float) -> float:
+ """``part`` as a percentage of ``whole``; 0 when the whole is 0 (a run that booked no money — every
+ session killed before it reported usage — is still a run to report)."""
+ return 100 * part / whole if whole else 0.0
+
+
def _tok(n: int) -> str:
if n >= 1_000_000:
return f"{n / 1e6:.2f}M"
@@ -83,10 +89,10 @@ def runs_table(audit: Audit, *, limit: int = 20) -> str:
def waste_table(audit: Audit) -> str:
- rows = [[k, n, _usd(usd), f"{100 * usd / audit.total_usd:.1f}%"]
+ rows = [[k, n, _usd(usd), f"{_share(usd, audit.total_usd):.1f}%"]
for k, (n, usd) in audit.waste_by_kind().items()]
rows.append(["**total**", sum(n for n, _ in audit.waste_by_kind().values()),
- _usd(audit.waste_total()), f"{100 * audit.waste_total() / audit.total_usd:.1f}%"])
+ _usd(audit.waste_total()), f"{_share(audit.waste_total(), audit.total_usd):.1f}%"])
return table(("waste", "n", "USD", "share of spend"), rows)
@@ -96,14 +102,14 @@ def summary_lines(audit: Audit) -> list[str]:
return [
f"- runs: **{audit.n_runs}** ({audit.n_passed} passed) — total **{_usd(audit.total_usd)}**, "
f"{_usd(audit.usd_per_run)} per run, **{_usd(audit.usd_per_passing_artifact)} per passing artifact**",
- f"- tokens: {_tok(total_in)} input of which **{100 * cached / total_in:.0f}% cached** "
+ f"- tokens: {_tok(total_in)} input of which **{_share(cached, total_in):.0f}% cached** "
f"({_tok(audit.summary.total.output_tokens)} output, {_tok(audit.summary.total.thoughts_tokens)} thoughts)",
f"- prompt caching already saves **{_usd(no_cache - audit.total_usd)}** "
- f"({100 * (1 - audit.total_usd / no_cache):.0f}% of what this traffic would cost uncached); "
+ f"({_share(no_cache - audit.total_usd, no_cache):.0f}% of what this traffic would cost uncached); "
f"cache reads still cost {_usd(cache_usd)}",
f"- clock: {audit.wall_s / 3600:.1f} h of run time, {audit.model_s / 3600:.1f} h of it waiting on models",
f"- calls: {audit.summary.total.n_calls:,} model calls, {audit.calls_per_round():.0f} per round",
- f"- identified waste: **{_usd(audit.waste_total())}** ({100 * audit.waste_total() / audit.total_usd:.0f}% of spend)",
+ f"- identified waste: **{_usd(audit.waste_total())}** ({_share(audit.waste_total(), audit.total_usd):.0f}% of spend)",
]
@@ -139,11 +145,11 @@ def console(audit: Audit) -> str:
lines = [line.replace("**", "") for line in summary_lines(audit)]
lines += ["", "stage:"]
for b in audit.summary.ranked("stage"):
- lines.append(f" {b.key:<12} {_usd(b.cost_usd):>10} {100 * b.cost_usd / audit.total_usd:5.1f}% "
+ lines.append(f" {b.key:<12} {_usd(b.cost_usd):>10} {_share(b.cost_usd, audit.total_usd):5.1f}% "
f"{b.n_calls:>6,} calls cached {100 * b.cached_fraction:3.0f}%")
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}%")
+ lines.append(f" {b.key:<12} {_usd(b.cost_usd):>10} {_share(b.cost_usd, audit.total_usd):5.1f}%")
if keyed := keyed_buckets(audit):
lines += ["", "key (last 4 chars):"]
for b in keyed:
diff --git a/harness/codeverse/languages/blender/__init__.py b/harness/codeverse/languages/blender/__init__.py
index ef8035e2..919cceea 100644
--- a/harness/codeverse/languages/blender/__init__.py
+++ b/harness/codeverse/languages/blender/__init__.py
@@ -376,9 +376,8 @@ def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | Non
f"rename to src/{PARTS_DIR}/{to_snake(stem)}.py (the harness maps plan part "
f"'{stem}' → that file) and fix the import in model.py"))
continue
- try:
- tree = ast.parse(p.read_text(), filename=target)
- except SyntaxError:
+ tree, _ = safe_parse(p.read_text(), target)
+ if tree is None:
continue # reported by the per-file lint
fn = f"build_{stem}"
if fn not in _exported_functions(tree):
@@ -416,11 +415,7 @@ def lint_workspace(ws: Workspace) -> GateReport:
expect_names=not (is_helper or (is_entry and bool(parts))),
expect_bpy=not is_helper)
findings.extend(rep.findings)
- entry_tree: ast.Module | None
- try:
- entry_tree = ast.parse(entry.read_text(), filename=ENTRY_REL)
- except SyntaxError:
- entry_tree = None
+ entry_tree, _ = safe_parse(entry.read_text(), ENTRY_REL)
findings.extend(_layout_rules(ws, parts, entry_tree))
passed = not any(f.severity == Severity.ERROR for f in findings)
return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
diff --git a/harness/codeverse/languages/threejs/__init__.py b/harness/codeverse/languages/threejs/__init__.py
index 341bb8da..51dce1b2 100644
--- a/harness/codeverse/languages/threejs/__init__.py
+++ b/harness/codeverse/languages/threejs/__init__.py
@@ -238,10 +238,11 @@ def lint_workspace(ws: Workspace) -> GateReport:
elif path.parent == ws.src / "parts":
expected = "build" + to_pascal(path.stem)
if expected not in exports:
+ named = sorted(e for e in exports if e != "build")
sev = Severity.WARN if any(e != "build" for e in exports) else Severity.ERROR
findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
message=f"{rel}: expected `export function {expected}(THREE)` (found {sorted(exports) or 'no build export'})",
- fix_hint=f"rename the export to {expected} or the file to parts/{to_snake(exports.pop()[5:]) if exports else path.stem}.js"))
+ fix_hint=f"rename the export to {expected} or the file to parts/{to_snake(named[0][5:]) if named else path.stem}.js"))
part_files = [p for p in sources if p.parent == ws.src / "parts"]
for p in part_files:
diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.py
index 360304f3..ac072fba 100644
--- a/harness/codeverse/tracks/generation.py
+++ b/harness/codeverse/tracks/generation.py
@@ -408,6 +408,7 @@ def generate_files(
# here would discard it before transcript/parse/write_files. The ceiling is
# enforced at the round's phase boundary instead (steps._run_phase).
_charge(budget, usage, task=task, enforce=False)
+ retry = False
if _is_truncated(resp):
# cut off by max_output_tokens: the envelope is unterminated — one retry with a
# DOUBLED budget beats writing a half-file. Already at the 65,536 model ceiling
@@ -435,7 +436,7 @@ def generate_files(
(traj / "prompt.md").write_text(f"# system\n{system}\n\n# user\n{task.prompt}\n")
(traj / "response.md").write_text(resp.text or "")
if _is_truncated(resp):
- if events is not None:
+ if events is not None and retry: # the RETRY was cut off too; the first cut is already in the log
events.emit(
"generate.truncated",
label=task.label,
diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.py
index a8d72d80..705b9dc4 100644
--- a/harness/codeverse/tracks/scene_assets.py
+++ b/harness/codeverse/tracks/scene_assets.py
@@ -481,7 +481,7 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
for f, body in src.items():
if body:
(sub_ws.root / f).write_text(body)
- sub_ws.commit("asset fix reverted (judged worse)")
+ sub_ws.commit("asset fix reverted")
_stamp_glb(result, ctx, dest)
return _restore
@@ -694,6 +694,8 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
return result
result.fixed = after_fix(gen) if after_fix is not None else True
if not result.fixed:
+ if restore is not None:
+ restore() # a fix that does not build is undone too: the asset that was judged stays the asset
return result
again = _verdict(1)
if again is None:
diff --git a/harness/runtime_js/ablate_scene.mjs b/harness/runtime_js/ablate_scene.mjs
index 73dd4059..1210d6bf 100644
--- a/harness/runtime_js/ablate_scene.mjs
+++ b/harness/runtime_js/ablate_scene.mjs
@@ -95,7 +95,7 @@ async function main() {
/** The report shape a caller can rely on even when the scene never booted. */
function emptyReport() {
return { custom_materials: 0, cameras: [], materials: [], max_changed_frac: 0,
- content_changed_frac: 0, per_material_measured: false, per_material_camera: '' };
+ content_changed_frac: 0, per_material_measured: false, per_material_cameras: [] };
}
main().catch((e) => fail(e.stack || String(e)));
diff --git a/harness/runtime_js/lib/host_placement.mjs b/harness/runtime_js/lib/host_placement.mjs
index b78a4dcd..3acddcf3 100644
--- a/harness/runtime_js/lib/host_placement.mjs
+++ b/harness/runtime_js/lib/host_placement.mjs
@@ -410,7 +410,7 @@ function pairs(checked) {
if (c.frac > OVERLAP_MIN_FRAC) out.push({ a: small.name, b: large.name, zone_a: small.zone, zone_b: large.zone, aabb_overlap: r3(aabb), inside_frac: r3(c.frac), samples: c.sampled });
}
}
- return out.sort((x, y) => y.overlap - x.overlap).slice(0, 40);
+ return out.sort((x, y) => y.aabb_overlap - x.aabb_overlap).slice(0, 40);
}
/**
diff --git a/harness/tests/blender_cadquery/test_blender_layout.py b/harness/tests/blender_cadquery/test_blender_layout.py
index 6f7b5a5c..fb01cbe5 100644
--- a/harness/tests/blender_cadquery/test_blender_layout.py
+++ b/harness/tests/blender_cadquery/test_blender_layout.py
@@ -74,6 +74,16 @@ def test_lint_workspace_passes_clean_multi_file_layout(tmp_ws) -> None:
assert {f.target for f in rep.findings} <= {"src/model.py", "src/parts/seat.py", "src/parts/leg.py", "src/parts/_common.py"}
+def test_lint_workspace_reports_a_source_too_deep_to_parse_instead_of_crashing(tmp_ws) -> None:
+ """The layout rules re-parsed every file with a bare ``ast.parse`` — a literal nested past the
+ parser's stack raised ``MemoryError`` out of the lint and killed the round."""
+ deep = "x = " + "-" * 20_000 + "1\n"
+ _write(tmp_ws, "src/model.py", deep)
+ _write(tmp_ws, "src/parts/seat.py", deep)
+ rep = lint_workspace(tmp_ws)
+ assert not rep.passed and {f.target for f in rep.errors} >= {"src/model.py", "src/parts/seat.py"}
+
+
def test_lint_workspace_layout_rules(tmp_ws) -> None:
_write(tmp_ws, "src/model.py", MODEL)
_write(tmp_ws, "src/parts/seat.py", SEAT.replace("def build_seat", "def build_seat_cushion")) # wrong export
diff --git a/harness/tests/cost/test_audit_report.py b/harness/tests/cost/test_audit_report.py
index 14152ef6..c275680f 100644
--- a/harness/tests/cost/test_audit_report.py
+++ b/harness/tests/cost/test_audit_report.py
@@ -30,6 +30,23 @@ def test_audit_of_one_run(fake_run: Path):
assert stage_latency(audit)
+def test_a_run_that_booked_no_money_still_reports(tmp_path: Path):
+ """Every session killed before it reported usage books $0 (a killed gemini-cli says nothing);
+ the report divided by the run's total and `3dcv cost` died of ZeroDivisionError on it."""
+ ws = tmp_path / "free_run"
+ ws.mkdir()
+ (ws / "record.json").write_text(json.dumps({
+ "spec": {"track": "static_object", "language": "blender", "backends": {"generator": "gemini-cli:gemini-3.7-flash"}},
+ "status": "failed", "rounds": [], "total_usage": {}, "extra": {}}))
+ ledger = ws / "telemetry" / "cost.jsonl"
+ ledger.parent.mkdir()
+ ledger.write_text(json.dumps({"run": ws.name, "round": 0, "stage": "baseline", "role": "generator", "backend": "gemini-cli",
+ "provider": "gemini", "model": "gemini-3.7-flash", "cost_usd": 0.0}) + "\n")
+ audit = audit_runs([tmp_path])
+ assert audit.n_runs == 1 and audit.total_usd == 0
+ assert "0%" in console(audit) and "# Cost audit" in markdown(audit)
+
+
def test_waste_finds_a_regression(fake_run: Path, tmp_path: Path):
"""A refine round that scores below the best is money spent on a worse artifact."""
import shutil
diff --git a/harness/tests/orchestrator_tracks/test_fix_generation.py b/harness/tests/orchestrator_tracks/test_fix_generation.py
index f9f7ec78..3e313d4b 100644
--- a/harness/tests/orchestrator_tracks/test_fix_generation.py
+++ b/harness/tests/orchestrator_tracks/test_fix_generation.py
@@ -59,9 +59,11 @@ def test_generate_files_truncation_policy(tmp_path):
ws = Workspace(tmp_path / "ceiling").create()
model = ScriptedModel([(TRUNCATED, "MAX_TOKENS")])
task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"])
- res = generate_files(ws, model=model, task=task, events=EventLog(tmp_path / "ceiling.jsonl"))
+ events = EventLog(tmp_path / "ceiling.jsonl")
+ res = generate_files(ws, model=model, task=task, events=events)
assert not res.ok and res.notes.startswith("truncated")
assert len(model.requests) == 1
+ assert [e["event"] for e in events.read()].count("generate.truncated") == 1 # one cut, one event
# --------------------------------------------------------------------- finding: out-of-root path aborted the whole write
diff --git a/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py b/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py
index 77e07da6..c6676d42 100644
--- a/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py
+++ b/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py
@@ -270,6 +270,22 @@ def test_a_fix_that_judges_worse_is_undone(tmp_ws, settings):
assert (tmp_ws.public / "assets" / f"{snake}.glb").is_file()
+def test_a_fix_that_does_not_build_is_undone(tmp_ws, settings):
+ """The restore only ran when the fix JUDGED worse; a fix that broke the build left the broken
+ src in the hero's workspace next to the GLB of the version before it."""
+ judge = FakeJudge(scores=(0.6,))
+ snake = "crate"
+ agent = FakeAgent(lambda job, ws: {"src/model.py": GOOD_MODEL + ("" if job.label == f"asset_{snake}" else FAIL_MARK) # the fix AND its repair break
+ + f"# session {job.label}\n"})
+ ctx, hero = _scene(tmp_ws, settings, services=CardedServices(judge=judge), agent=agent)
+ assert SA.to_snake(hero.name) == snake
+ res = SA.build_blender_asset(ctx, hero, judge=True)
+ assert res.ok and res.judged and not res.fixed and res.score == 0.6
+ model = (tmp_ws.root / "_assets" / snake / "src" / "model.py").read_text()
+ assert FAIL_MARK not in model and f"session asset_{snake}\n" in model, "src is back at the version that built"
+ assert (tmp_ws.public / "assets" / f"{snake}.glb").is_file()
+
+
def test_the_largest_module_is_judged_and_the_small_ones_are_not(tmp_ws, settings):
"""`render_asset` makes a threejs verdict possible; the share rule alone judged nothing
(no prop reaches 5 % of a scene's volume), so the plan's largest module keeps its