Skip to content

Official Codebase of 3DCodeVerse

Python

spatial, doctor: use the helpers that exist — proc.tail for the build-failure stderr, parse_last_json for the doctor's chrome probe, read_json_or_none for scene metrics

gaoypeng97216c3865fa
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index 1b418b5c..9a1b4a36 100644
--- a/harness/codeverse3d/doctor.py
+++ b/harness/codeverse3d/doctor.py
@@ -118,6 +118,7 @@ _PROBE_JS = (
def check_gpu_probe(timeout_s: int = 120) -> list[Row]:
"""Launch headless Chrome through runtime_js/gpu_launch.cjs and report the WebGL renderer."""
from codeverse3d.proc import run_subprocess
+ from codeverse3d.spatial.node import parse_last_json
s = get_settings()
try:
@@ -134,11 +135,7 @@ def check_gpu_probe(timeout_s: int = 120) -> list[Row]:
return [("chrome webgl", "FAIL", str(e))]
if proc.timed_out:
return [("chrome webgl", "FAIL", f"probe timed out after {timeout_s}s")]
- line = next((ln for ln in reversed(proc.stdout.strip().splitlines()) if ln.startswith("{")), "")
- try:
- res = json.loads(line) if line else {}
- except ValueError:
- res = {}
+ res = parse_last_json(proc.stdout) or {}
if "error" in res or proc.returncode != 0:
detail = str(res.get("error") or (proc.stderr.strip().splitlines() or ["unknown error"])[-1])
return [("chrome webgl", "FAIL", detail[:160])]
diff --git a/harness/codeverse3d/spatial/observe.py b/harness/codeverse3d/spatial/observe.py
index 52ce2b98..6f00643a 100644
--- a/harness/codeverse3d/spatial/observe.py
+++ b/harness/codeverse3d/spatial/observe.py
@@ -2,7 +2,6 @@
* ``fmt_numbers`` – one-line ``k=v`` rendering with sane float precision.
* ``truncate`` – head/tail truncation with a marker (never mid-line when possible).
-* ``tail_lines`` – last ``n`` lines of a log.
* ``image_budget`` – cap image lists (contact sheet kept first).
* ``rel_path`` – workspace-relative display path (never leak host paths in text).
* ``lint_lines`` / ``build_failure_lines`` – the one lint / BUILD FAILED report
@@ -17,6 +16,7 @@ from collections.abc import Iterable, Sequence
from pathlib import Path
from typing import Any
+from codeverse3d import proc
from codeverse3d.contracts.artifacts import BuildResult, GateReport, RenderSet, Severity
from codeverse3d.spatial.registry import Observation
@@ -70,11 +70,6 @@ def truncate(text: str, n: int = MAX_TEXT, tail_ratio: float = 0.3) -> str:
return f"{head}\n… [{len(text) - head_n - tail_n} chars omitted] …\n{tail}"
-def tail_lines(text: str, n: int = 30) -> str:
- lines = text.rstrip("\n").splitlines()
- return "\n".join(lines[-n:])
-
-
def image_budget(images: Sequence[str], max_n: int = MAX_IMAGES) -> list[str]:
"""Keep at most ``max_n`` images; the first (contact sheet) always survives."""
imgs = [str(p) for p in images if p]
@@ -162,7 +157,7 @@ def build_failure_lines(br: BuildResult, root: Path, lint_warns: Sequence[str],
# the location stays on the headline even when the message is multi-line (GLSL)
head, _, rest = sanitize_text(br.error_message, root).partition("\n")
lines = [f"BUILD FAILED: {br.error_type or 'Error'}: {head}{where}"] + ([rest] if rest else [])
- tail = tail_lines(sanitize_text(br.stderr_tail, root), tail_n)
+ tail = proc.tail(sanitize_text(br.stderr_tail, root).rstrip("\n"), max_lines=tail_n)
if tail and tail not in br.error_message:
lines.append("stderr (tail):\n" + tail)
if lint_warns:
diff --git a/harness/codeverse3d/spatial/render_scene.py b/harness/codeverse3d/spatial/render_scene.py
index e7f71ab6..ee450bbf 100644
--- a/harness/codeverse3d/spatial/render_scene.py
+++ b/harness/codeverse3d/spatial/render_scene.py
@@ -351,11 +351,6 @@ def _mark_judge_views(views_json: Path, views: Sequence[RenderView]) -> None:
views_json.write_text(json.dumps(entries, indent=1))
-def read_metrics(out_dir: Path) -> dict[str, Any]:
- """Full instrument payload written by the driver (census, camera_checks, ...)."""
- return read_json_or_none(Path(out_dir) / "metrics.json") or {}
-
-
def metrics_path_for(rs: RenderSet) -> Path | None:
"""``metrics.json`` of a RenderSet: the stamped ``out_dir`` when present, else
guessed as a sibling of the sheet / views (rounds recorded before stamping)."""
diff --git a/harness/codeverse3d/spatial/tools.py b/harness/codeverse3d/spatial/tools.py
index 288eab1e..00632b87 100644
--- a/harness/codeverse3d/spatial/tools.py
+++ b/harness/codeverse3d/spatial/tools.py
@@ -19,6 +19,7 @@ from codeverse3d.config import get_settings
from codeverse3d.contracts.artifacts import RENDER_MODES, BuildResult, GateReport, Measurement
from codeverse3d.contracts.common import Language, Track
from codeverse3d.conventions import OBJECT_VIEWS, OBJECT_VIEWS_QUICK
+from codeverse3d.proc import read_json_or_none
from codeverse3d.spatial.connectivity import check_connectivity as _check_connectivity
from codeverse3d.spatial.contract import check_contract as _check_contract
from codeverse3d.spatial.contract import planned_joins
@@ -42,7 +43,7 @@ from codeverse3d.spatial.observe import (
)
from codeverse3d.spatial.probes import probe_scene, run_probe
from codeverse3d.spatial.registry import NoArgs, Observation, ToolContext, ToolUsageError, tool
-from codeverse3d.spatial.render_scene import read_metrics, render_scene
+from codeverse3d.spatial.render_scene import render_scene
from codeverse3d.spatial.scene_placement import placement_census as _placement_census
from codeverse3d.spatial.scene_placement import placement_gate, placement_table_text
from codeverse3d.spatial.sections import cross_section as _cross_section
@@ -474,7 +475,7 @@ def _frame_table(out_dir: Path) -> str:
measured motion between the times. Without them the agent is asked to LOOK at a sheet and
guess whether its sway is visible or its dusk is too dark; with them it can read the answer."""
try:
- metrics = read_metrics(out_dir)
+ metrics = read_json_or_none(out_dir / "metrics.json")
return frame_summary_text(metrics) if metrics else ""
except Exception: # noqa: BLE001 — a tool observation must never fail on instrumentation
return ""
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 622a988b..e4c9e04a 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -307,7 +307,7 @@ render_scene(ws, out_dir, *, cameras=None, orbit=True, times=(0.0, 1.5), width=1
bounds=None) -> RenderSet
# Δ bounds default from ws plan.json → orbit rig frustum-fits the CONTENT box (not ground/sky);
# contact sheet = judge subset only; views.json entries get judge: true|false
-from codeverse3d.spatial.render_scene import select_judge_views, JUDGE_MAX_VIEWS, read_metrics, plan_bounds
+from codeverse3d.spatial.render_scene import select_judge_views, JUDGE_MAX_VIEWS, plan_bounds
select_judge_views(rs, max_n=10) -> RenderSet # priority: authored@t0, 2 overview@t0, 2 authored@t_last, rest
from codeverse3d.spatial.frame_metrics import frame_gate_from_renders, frame_findings, frame_summary_text, FRAME_GATE
frame_gate_from_renders(renders) -> GateReport # gate "scene_frames"; data.kind ∈ dark_frame | blown_frame | flat_frame |
diff --git a/harness/tests/scene_gates/test_live_frames.py b/harness/tests/scene_gates/test_live_frames.py
index f0351070..172d89d4 100644
--- a/harness/tests/scene_gates/test_live_frames.py
+++ b/harness/tests/scene_gates/test_live_frames.py
@@ -13,10 +13,10 @@ import pytest
from PIL import Image
from codeverse3d.conventions import SCENE_VIEWS
+from codeverse3d.proc import read_json_or_none
from codeverse3d.spatial.frame_metrics import frame_gate_from_renders
from codeverse3d.spatial.render_scene import (
JUDGE_MAX_VIEWS,
- read_metrics,
render_scene,
select_judge_views,
)
@@ -55,7 +55,7 @@ def test_example_scene_passes_frame_gate_and_judge_subset(starter_ws: Workspace)
assert im.size == (640, 360)
px = im.convert("L").resize((32, 18)).tobytes()
assert 20 < sum(px) / len(px) < 235 # lit, neither black nor blown
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
assert m["census"]["totals"]["triangles"] > 1000
chk = {c["name"]: c for c in m["camera_checks"]}
for c in chk.values():
@@ -115,7 +115,7 @@ def test_plan_bounds_guard_orbit_framing(starter_ws: Workspace, tmp_path: Path):
rs = render_scene(starter_ws, out, times=(0.0,), orbit_views=SCENE_VIEWS[:1], width=320, height=180, fps_seconds=0,
bounds=BBox(center=(0, 3, 0), extents=(extents, 10, extents)), sheet=False)
ov = next(v for v in rs.views if v.name == SCENE_VIEWS[0].name)
- return read_metrics(out)["framing_bbox"], ov.camera_position[1]
+ return read_json_or_none(out / "metrics.json")["framing_bbox"], ov.camera_position[1]
wide, y_wide = _run(2, 90.0) # meadow (≈ 84 m) fits → framed as a whole
assert wide["size"][0] == pytest.approx(84.4, abs=0.5)
diff --git a/harness/tests/scene_gates/test_live_hero_in_frame.py b/harness/tests/scene_gates/test_live_hero_in_frame.py
index acaac8a3..54d83863 100644
--- a/harness/tests/scene_gates/test_live_hero_in_frame.py
+++ b/harness/tests/scene_gates/test_live_hero_in_frame.py
@@ -12,8 +12,9 @@ import math
import pytest
+from codeverse3d.proc import read_json_or_none
from codeverse3d.spatial.frame_metrics import HERO_MIN_FRAC, frame_gate_from_renders
-from codeverse3d.spatial.render_scene import read_metrics, render_scene
+from codeverse3d.spatial.render_scene import render_scene
from codeverse3d.workspace import Workspace
from tests.scene_runtime.conftest import needs_browser
from tests.scene_runtime.glb_fixture import write_box_glb
@@ -67,7 +68,7 @@ def test_a_hero_in_an_authored_frame_passes(starter_ws: Workspace):
out = starter_ws.renders_dir(0)
rs = render_scene(starter_ws, out, times=(0.0,), width=640, height=360, fps_seconds=0.2)
assert rs.console_errors == []
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
rows = {r["url"]: r for r in m["census"]["glb_assets"]}
assert rows[URL]["in_scene"] is True and abs(rows[URL]["size_m"] - 4.0) < 0.05, rows[URL]
chk = {c["name"]: c for c in m["camera_checks"]}
@@ -83,7 +84,7 @@ def test_a_hero_behind_a_wall_in_every_authored_frame_is_an_error(starter_ws: Wo
_with_hero(starter_ws, hidden=True)
out = starter_ws.renders_dir(0)
rs = render_scene(starter_ws, out, times=(0.0,), width=640, height=360, fps_seconds=0.2)
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
chk = {c["name"]: c for c in m["camera_checks"]}
assert chk["overview"]["glb_frac"].get(URL, 0.0) < 0.002, chk["overview"]["glb_frac"] # in the scene, behind the wall
gate = frame_gate_from_renders(rs)
@@ -104,7 +105,7 @@ def test_the_overview_rig_lifts_the_room_shells_lid_but_an_authored_camera_keeps
out = starter_ws.renders_dir(0)
rs = render_scene(starter_ws, out, times=(0.0,), width=640, height=360, fps_seconds=0.2)
assert rs.console_errors == []
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
chk = {c["name"]: c for c in m["camera_checks"]}
# the lid is lifted for the rig: a 4 m cube from 100 m up is a few pixels, but it is there
assert chk["overview_top"]["glb_frac"].get(URL, 0.0) > 0.0005, chk["overview_top"]["glb_frac"]
@@ -123,7 +124,7 @@ def test_a_camera_named_for_the_hero_is_re_aimed_when_the_hero_is_out_of_its_fra
out = starter_ws.renders_dir(0)
rs = render_scene(starter_ws, out, times=(0.0,), width=640, height=360, fps_seconds=0.2)
assert rs.console_errors == []
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
chk = {c["name"]: c for c in m["camera_checks"]}
assert chk["HeroCubeDetail"]["glb_frac"].get(URL, 0.0) > 0.01, chk["HeroCubeDetail"]["glb_frac"]
aimed = [r for r in m["census"]["camera_repair"] if r.get("aimed_at")]
diff --git a/harness/tests/scene_runtime/test_post.py b/harness/tests/scene_runtime/test_post.py
index ef212e5b..a850899c 100644
--- a/harness/tests/scene_runtime/test_post.py
+++ b/harness/tests/scene_runtime/test_post.py
@@ -23,7 +23,8 @@ import numpy as np
import pytest
from PIL import Image
-from codeverse3d.spatial.render_scene import post_chain_args, read_metrics, run_scene_script
+from codeverse3d.proc import read_json_or_none
+from codeverse3d.spatial.render_scene import post_chain_args, run_scene_script
from codeverse3d.workspace import Workspace
from tests.scene_runtime.conftest import needs_browser, needs_node
@@ -115,8 +116,8 @@ def test_bloom_is_selective_not_a_brightness_threshold(tmp_path):
e_raw, e_post = render(emissive, tmp_path / "e_raw", "--no-post"), render(emissive, tmp_path / "e_post")
p_raw, p_post = render(plain, tmp_path / "p_raw", "--no-post"), render(plain, tmp_path / "p_post")
- assert read_metrics(tmp_path / "e_post")["census"]["post"]["bloom_sources"] >= 1
- assert read_metrics(tmp_path / "p_post")["census"]["post"]["bloom_sources"] == 0
+ assert read_json_or_none(tmp_path / "e_post" / "metrics.json")["census"]["post"]["bloom_sources"] >= 1
+ assert read_json_or_none(tmp_path / "p_post" / "metrics.json")["census"]["post"]["bloom_sources"] == 0
assert mean_lum(e_post) - mean_lum(e_raw) > 0.004, "emissive box did not bloom"
assert abs(mean_lum(p_post) - mean_lum(p_raw)) < 0.005, "a merely bright box must not bloom"
@@ -130,10 +131,10 @@ def test_scene_grade_hint_reaches_the_shader_and_is_clamped(tmp_path):
ws = make_ws(tmp_path, "graded", BRIGHT, extra="scene.userData.grade = { exposure: 99, warmth: 0.4 };")
out = tmp_path / "graded_out"
render(ws, out, "--post-options", '{"ao":0,"bloom":0}')
- grade = read_metrics(out)["census"]["post"]["grade"]
+ grade = read_json_or_none(out / "metrics.json")["census"]["post"]["grade"]
assert grade["exposure"] == 8.0 # clamped from 99
assert grade["warmth"] == pytest.approx(0.4)
- assert read_metrics(out)["census"]["post"]["grade_neutral"] is False
+ assert read_json_or_none(out / "metrics.json")["census"]["post"]["grade_neutral"] is False
@needs_node
@@ -142,7 +143,7 @@ def test_no_post_leaves_the_chain_off(tmp_path):
ws = make_ws(tmp_path, "off", BRIGHT)
out = tmp_path / "off_out"
render(ws, out, "--no-post")
- assert read_metrics(out)["census"]["post"] == {"enabled": False}
+ assert read_json_or_none(out / "metrics.json")["census"]["post"] == {"enabled": False}
@needs_node
@@ -151,6 +152,6 @@ def test_ungraded_scene_reports_a_neutral_grade(tmp_path):
ws = make_ws(tmp_path, "ungraded", BRIGHT)
out = tmp_path / "ungraded_out"
render(ws, out)
- post = read_metrics(out)["census"]["post"]
+ post = read_json_or_none(out / "metrics.json")["census"]["post"]
assert post["enabled"] is True and post["grade_neutral"] is True
assert post["warnings"] == [] and json.dumps(post) # serialisable into metrics.json
diff --git a/harness/tests/scene_runtime/test_render_scene.py b/harness/tests/scene_runtime/test_render_scene.py
index 6116cfe3..d03b03a0 100644
--- a/harness/tests/scene_runtime/test_render_scene.py
+++ b/harness/tests/scene_runtime/test_render_scene.py
@@ -11,11 +11,11 @@ from PIL import Image
from codeverse3d.contracts.plan import CameraPlan
from codeverse3d.conventions import SCENE_VIEWS
+from codeverse3d.proc import read_json_or_none
from codeverse3d.spatial import render_scene as rs_mod
from codeverse3d.spatial.render_scene import (
SceneRenderError,
probe_env_args,
- read_metrics,
render_scene,
run_scene_script,
)
@@ -71,7 +71,7 @@ def test_render_scene_parses_driver_output(fake_runtime, ws, tmp_path):
assert rs.console_errors[0] == "oops" and rs.console_errors[1].startswith("shader[fragment]")
assert rs.contact_sheet and Path(rs.contact_sheet).is_file()
assert Image.open(rs.contact_sheet).size[0] > 100
- assert read_metrics(out)["census"]["totals"]["meshes"] == 1
+ assert read_json_or_none(out / "metrics.json")["census"]["totals"]["meshes"] == 1
@needs_node
@@ -96,7 +96,7 @@ def test_camera_in_geometry_is_detected(starter_ws, monkeypatch):
cams = [CameraPlan(name="buried", position=(12.0, 2.0, -2.0), look_at=(12.0, 2.0, -10.0), fov=50)] # inside the windmill tower
out = starter_ws.renders_dir(1)
render_scene(starter_ws, out, cameras=cams, orbit=False, times=(0.0,), fps_seconds=0, sheet=False)
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
chk = m["camera_checks"][0]
assert chk["camera_in_geometry"] is True
# repair off → everything renders from the AUTHORED camera and no repair is recorded
@@ -114,7 +114,7 @@ def test_camera_repair_is_observable_in_census_and_views(starter_ws, monkeypatch
cams = [CameraPlan(name="buried", position=(12.0, 2.0, -2.0), look_at=(12.0, 2.0, -10.0), fov=50)] # inside the windmill tower
out = starter_ws.renders_dir(2)
render_scene(starter_ws, out, cameras=cams, orbit=False, times=(0.0,), fps_seconds=0, sheet=False)
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
reps = (m.get("census") or {}).get("camera_repair")
assert reps and reps[0]["name"] == "buried" and reps[0]["moved_back_m"] + reps[0]["moved_up_m"] > 0
view = next(v for v in m["views"] if v["name"] == "buried")
@@ -141,7 +141,7 @@ def test_camera_repair_telemetry_survives_the_python_reader(fake_runtime, ws, tm
rs = render_scene(ws, out, cameras=[CameraPlan(name="cam_a", position=(1, 2, 3), look_at=(0, 0, 0), fov=45)],
orbit=False, times=(0.0,), sheet=False)
assert rs.views[0].camera_position == (1.0, 2.0, 3.0)
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
assert m["census"]["camera_repair"][0]["name"] == "authored_a"
assert m["views"][0]["repaired_position"] == [1, 2.6, 4.1]
# the judge-flag rewrite of views.json must not strip the telemetry rider
@@ -204,7 +204,7 @@ def test_host_warnings_reach_metrics_and_the_log(ws, caplog):
out = ws.renders_dir(0)
with caplog.at_level(logging.WARNING, logger=rs_mod.__name__):
rs = render_scene(ws, out, orbit=False, times=(0.0,), width=320, height=180, fps_seconds=0, sheet=False)
- warnings = read_metrics(out)["host_warnings"]
+ warnings = read_json_or_none(out / "metrics.json")["host_warnings"]
assert any(w.startswith("post chain unavailable") and "grade unreadable" in w for w in warnings), warnings
assert any(w.startswith("coverage failed for cam") and "no masks" in w for w in warnings), warnings
logged = [r.getMessage() for r in caplog.records]
@@ -231,7 +231,7 @@ def test_update_throw_mid_render_yields_frames_and_console_error(starter_ws):
assert len(rs.views) == 2 * 4, [v.name for v in rs.views]
assert all(Path(v.path).is_file() for v in rs.views)
assert any(e.startswith("update(t=") and "intensity" in e for e in rs.console_errors), rs.console_errors
- m = read_metrics(out)
+ m = read_json_or_none(out / "metrics.json")
assert m["update_errors"] and "update() disabled" in m["update_errors"][0]
diff --git a/harness/tests/spatial_tools/test_observe.py b/harness/tests/spatial_tools/test_observe.py
index 60548629..8b601838 100644
--- a/harness/tests/spatial_tools/test_observe.py
+++ b/harness/tests/spatial_tools/test_observe.py
@@ -19,7 +19,6 @@ from codeverse3d.spatial.observe import (
rel_path,
render_observation,
sanitize_text,
- tail_lines,
truncate,
)
@@ -34,7 +33,6 @@ def test_truncate_keeps_head_and_tail() -> None:
t = truncate(text, 400)
assert t.startswith("line 0") and t.endswith("line 499") and "chars omitted" in t
assert truncate("short") == "short"
- assert tail_lines("a\nb\nc\nd", 2) == "c\nd"
def test_image_budget_keeps_sheet_first() -> None: