Official Codebase of 3DCodeVerse
Python
spatial/runtime_js: host warnings reach metrics + the log; a malformed URL is a 404; the shader probe runs raw; ablation measures the judge's frames
gaoypeng11001833fc46
diff --git a/harness/codeverse3d/spatial/ablation.py b/harness/codeverse3d/spatial/ablation.pyindex 1b417494..eee8f757 100644--- a/harness/codeverse3d/spatial/ablation.py+++ b/harness/codeverse3d/spatial/ablation.py@@ -36,7 +36,12 @@ from typing import Anyfrom pydantic import BaseModel, Fieldfrom codeverse3d.proc import read_json_or_none-from codeverse3d.spatial.render_scene import SceneRenderError, run_scene_script+from codeverse3d.spatial.render_scene import (+ SceneRenderError,+ post_chain_args,+ probe_env_args,+ run_scene_script,+)from codeverse3d.workspace import Workspace#: census.json key the compact report lands under@@ -169,6 +174,7 @@ def ablate_scene(]if frames:args.append("--frames")+ args += probe_env_args() + post_chain_args() # the judge's frames: same repair / settle / post policyres = run_scene_script("ablate_scene.mjs", args, timeout_s=timeout_s + 20)return _report(res.summary, out, duration_ms=int((time.time() - t0) * 1000))diff --git a/harness/codeverse3d/spatial/render_scene.py b/harness/codeverse3d/spatial/render_scene.pyindex 296d74fb..f20ff174 100644--- a/harness/codeverse3d/spatial/render_scene.py+++ b/harness/codeverse3d/spatial/render_scene.py@@ -226,6 +226,8 @@ def render_scene(driver_error = str(e).splitlines()[0][:500]res = NodeResult(rc=2, stdout="", stderr="", last_json={"error": driver_error}, duration_ms=0)metrics = read_json_or_none(out_dir / "metrics.json") or {}+ for w in metrics.get("host_warnings") or []: # e.g. a post chain that could not be built: judged RAW+ log.warning("render_scene host warning: %s", w)_store_motion(out_dir, metrics)views: list[RenderView] = []for v in metrics.get("views", []):diff --git a/harness/runtime_js/ablate_scene.mjs b/harness/runtime_js/ablate_scene.mjsindex bde31cd1..5d24ebbc 100644--- a/harness/runtime_js/ablate_scene.mjs+++ b/harness/runtime_js/ablate_scene.mjs@@ -5,6 +5,7 @@** node ablate_scene.mjs --ws <ws> [--out <dir>] [--t 1.5] [--frames] [--max-materials 8]* [--gpu auto] [--timeout-ms 120000]+ * [--no-settle] [--camera-repair] [--auto-exposure] [--no-post] (render_scene's switches)** Boots the host once (512x288) and calls `window.__c3v.ablation()` (lib/host_ablation.mjs):* every authored camera is rendered as authored and again with every ShaderMaterial /@@ -23,6 +24,8 @@ import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, safeName,import { createTimeoutMs, errorSummary, openHost } from './lib/host_page.mjs';const args = parseCli({+ 'no-settle': { type: 'boolean', default: false }, 'camera-repair': { type: 'boolean', default: false },+ 'auto-exposure': { type: 'boolean', default: false }, 'no-post': { type: 'boolean', default: false },ws: {}, out: { default: '' }, t: { default: '1.5' }, 'max-materials': { default: '8' },frames: { type: 'boolean', default: false }, gpu: { default: process.env.C3D_RENDER_GPU || 'auto' },'timeout-ms': { default: '120000' },@@ -42,6 +45,8 @@ async function main() {host = await openHost(args.ws, {width: 512, height: 288, gpu: args.gpu,createSceneTimeoutMs: createTimeoutMs(timeoutMs),+ settle: !args['no-settle'], cameraRepair: !!args['camera-repair'],+ autoExposure: !!args['auto-exposure'], post: !args['no-post'],});} catch (e) {return fail(`host failed: ${e.message}`);diff --git a/harness/runtime_js/check_shaders.mjs b/harness/runtime_js/check_shaders.mjsindex b69adfe0..c9814d76 100644--- a/harness/runtime_js/check_shaders.mjs+++ b/harness/runtime_js/check_shaders.mjs@@ -37,7 +37,8 @@ async function main() {let host = null;try {- host = await openHost(ws, { width: 256, height: 144, gpu: args.gpu });+ // raw, like the build's `probe_scene --compile`: the post chain's own programs are not the scene's+ host = await openHost(ws, { width: 256, height: 144, gpu: args.gpu, post: false });await compileIntoReport(report, files, host);await host.close();} catch (e) {diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjsindex ba6d5303..d47c52d1 100644--- a/harness/runtime_js/lib/scene_host.mjs+++ b/harness/runtime_js/lib/scene_host.mjs@@ -700,6 +700,7 @@ window.__c3v = {ablation,fps,post: () => (state.postInfo ? { ...state.postInfo } : null),+ hostWarnings: () => state.hostWarnings.slice(),shaderErrors: () => state.shaderErrors.slice(),updateErrors: () => state.updateErrors.slice(),cameras: () => state.cameras.slice(),diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjsindex 3482ae27..54f00886 100644--- a/harness/runtime_js/render_scene.mjs+++ b/harness/runtime_js/render_scene.mjs@@ -142,6 +142,8 @@ async function main() {} catch (e) { sceneErr('post readback failed', e); }metrics.shader_errors = (await page.evaluate(() => window.__c3v.shaderErrors())).map(({ _key, ...e }) => e);metrics.update_errors = await page.evaluate(() => window.__c3v.updateErrors());+ // the whole run's, not boot's: coverage failures are pushed while camera checks run+ metrics.host_warnings = await page.evaluate(() => window.__c3v.hostWarnings());Object.assign(metrics, errorSummary(host.errors, boot));for (const e of sceneErrors) if (!metrics.console_errors.includes(e)) metrics.console_errors.push(e);metrics.ok = metrics.console_errors.length === 0 && metrics.shader_errors.length === 0;diff --git a/harness/runtime_js/serve.cjs b/harness/runtime_js/serve.cjsindex ab611efc..b8598bd3 100644--- a/harness/runtime_js/serve.cjs+++ b/harness/runtime_js/serve.cjs@@ -109,7 +109,15 @@ async function serveDirs(opts = {}) {const routes = opts.routes || {};const server = http.createServer((req, res) => {- const urlPath = decodeURIComponent((req.url || '/').split('?')[0]);+ let urlPath;+ try {+ urlPath = decodeURIComponent((req.url || '/').split('?')[0]);+ } catch (_e) {+ // a malformed escape (`/assets/100%.png`) is a missing file, not a crashed driver+ res.statusCode = 404;+ res.end(`not found: ${req.url}`);+ return;+ }res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Cache-Control', 'no-store');diff --git a/harness/tests/scene_runtime/test_driver_flags.py b/harness/tests/scene_runtime/test_driver_flags.pyindex f95795c7..bf71c5ea 100644--- a/harness/tests/scene_runtime/test_driver_flags.py+++ b/harness/tests/scene_runtime/test_driver_flags.py@@ -22,7 +22,7 @@ pytestmark = [pytest.mark.node, needs_node]FLAGS = ["--no-settle", "--camera-repair", "--auto-exposure", "--no-post"][email protected]("driver", ["render_scene.mjs", "probe_scene.mjs"])[email protected]("driver", ["render_scene.mjs", "probe_scene.mjs", "ablate_scene.mjs"])def test_every_documented_flag_parses(driver):s = get_settings()node = s.binaries.node or "node"diff --git a/harness/tests/scene_runtime/test_probes.py b/harness/tests/scene_runtime/test_probes.pyindex c00e2dff..5015c612 100644--- a/harness/tests/scene_runtime/test_probes.py+++ b/harness/tests/scene_runtime/test_probes.py@@ -57,6 +57,29 @@ def test_probe_scene_catches_update_throw_and_console_errors(starter_ws):assert "update boom" in msgs and "custom failure 42" in msgs+def test_check_shaders_runs_raw_like_the_build_probe(ws, tmp_path, monkeypatch):+ """The shader_probe tool booted with the post chain ON (openHost's default) while the+ build's probe_scene --compile runs raw, so it compiled — and counted, and would have+ blamed on the scene — the harness's own GTAO / bloom / grade programs. Only the chain+ reads `scene.userData.grade`, so a read of it means the chain was built."""+ from codeverse3d.spatial.render_scene import render_scene++ ws.src.mkdir(parents=True, exist_ok=True)+ (ws.src / "scene.js").write_text(+ "import * as THREE from 'three';\n"+ "export function createScene() { const scene = new THREE.Scene(); scene.add(new THREE.AmbientLight());\n"+ " scene.add(new THREE.Mesh(new THREE.BoxGeometry(1,1,1), new THREE.MeshStandardMaterial()));\n"+ " Object.defineProperty(scene.userData, 'grade', { get() { console.error('post chain built'); return undefined; } });\n"+ " return { scene, cameras: [{ name: 'x', position: [3, 3, 3], lookAt: [0, 0, 0], fov: 50 }], update() {} }; }\n"+ )+ rep = check_shaders(ws)+ assert rep.passed and not [f for f in rep.findings if "post chain built" in f.message], [f.message for f in rep.findings]+ # control: a scene render DOES build the chain, and the read shows up+ monkeypatch.delenv("C3D_POST", raising=False)+ rs = render_scene(ws, tmp_path / "control", orbit=False, times=(0.0,), width=160, height=90, fps_seconds=0, sheet=False)+ assert any("post chain built" in e for e in rs.console_errors), rs.console_errors++def test_check_shaders_clean_on_example(starter_ws):rep = check_shaders(starter_ws)assert rep.gate == "shader_preflight" and rep.passed, [(f.target, f.message) for f in rep.findings]diff --git a/harness/tests/scene_runtime/test_render_scene.py b/harness/tests/scene_runtime/test_render_scene.pyindex 3406316e..348d2410 100644--- a/harness/tests/scene_runtime/test_render_scene.py+++ b/harness/tests/scene_runtime/test_render_scene.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import loggingfrom pathlib import Pathimport pytest@@ -174,6 +175,43 @@ def test_render_scene_clears_stale_metrics(fake_runtime, ws, tmp_path):assert all(v.name != "stale" for v in rs.views)+# The post chain cannot read this grade, so it is never built and every frame renders RAW+# (a boot-time host warning); the box refuses the coverage instrument's flat-white mask pass+# (a warning pushed while the camera checks run, i.e. AFTER boot).+_HOST_WARNING_SCENE = """+import * as THREE from 'three';+export function createScene() {+ const scene = new THREE.Scene();+ scene.add(new THREE.AmbientLight(0xffffff, 1.0));+ Object.defineProperty(scene.userData, 'grade', { get() { throw new Error('grade unreadable'); } });+ const box = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());+ box.name = 'Box';+ box.onBeforeRender = (r, s) => { if (s.overrideMaterial && s.overrideMaterial.isMeshBasicMaterial) throw new Error('no masks'); };+ scene.add(box);+ return { scene, cameras: [{ name: 'cam', position: [0, 1, 4], lookAt: [0, 0, 0], fov: 50 }], update() {} };+}+"""+++@needs_browser+def test_host_warnings_reach_metrics_and_the_log(ws, caplog):+ """Host warnings were copied into boot.host_warnings once, at the END of boot, and nothing+ read even that copy: a scene rendered and judged without its post chain, or with the+ coverage instrument (content_small / hero_unseen) switched off, left no trace at all."""+ ws.src.mkdir(parents=True, exist_ok=True)+ (ws.src / "scene.js").write_text(_HOST_WARNING_SCENE)+ 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"]+ 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]+ assert any("post chain unavailable" in m for m in logged) and any("coverage failed for cam" in m for m in logged)+ assert [v.name for v in rs.views] == ["cam"] # the frame itself still renders++@pytest.mark.node@needs_browserdef test_update_throw_mid_render_yields_frames_and_console_error(starter_ws):@@ -257,6 +295,7 @@ def test_every_driver_invocation_carries_the_env_flags(monkeypatch, ws, tmp_pathsettle / camera-repair / auto-exposure flags as the standalone probe andrender paths — it used to pass none of them."""import codeverse3d.languages.scene_threejs as st+ import codeverse3d.spatial.ablation as ablation_modimport codeverse3d.spatial.probes as probes_modcaptured: dict[str, list[str]] = {}@@ -267,7 +306,8 @@ def test_every_driver_invocation_carries_the_env_flags(monkeypatch, ws, tmp_pathmonkeypatch.setattr(probes_mod, "run_scene_script", fake_run)monkeypatch.setattr(rs_mod, "run_scene_script", fake_run)- for k in ("C3D_SETTLE", "C3D_CAMERA_REPAIR", "C3D_AUTO_EXPOSURE"):+ monkeypatch.setattr(ablation_mod, "run_scene_script", fake_run)+ for k in ("C3D_SETTLE", "C3D_CAMERA_REPAIR", "C3D_AUTO_EXPOSURE", "C3D_POST"):monkeypatch.delenv(k, raising=False)# defaults: camera repair ON everywhere, settle on (no flag), exposure off@@ -279,11 +319,20 @@ def test_every_driver_invocation_carries_the_env_flags(monkeypatch, ws, tmp_pathrender_scene(ws, tmp_path / "out_flags", cameras=[CameraPlan(name="c", position=(1, 2, 3), look_at=(0, 0, 0), fov=45)],orbit=False, times=(0.0,), sheet=False)assert _flags(captured["render_scene.mjs"]) == ["--camera-repair"]+ # effect_ablation measures the frames the judge sees: it used to run with repair OFF+ # and the post chain ON whatever C3D_POST said+ with pytest.raises(SceneRenderError):+ ablation_mod.ablate_scene(ws)+ assert _flags(captured["ablate_scene.mjs"]) == ["--camera-repair"] and "--no-post" not in captured["ablate_scene.mjs"]# the A/B words reach every path, including the combined buildmonkeypatch.setenv("C3D_SETTLE", "0")monkeypatch.setenv("C3D_CAMERA_REPAIR", "false")+ monkeypatch.setenv("C3D_POST", "0")st._probe_and_preflight(ws, timeout_s=5.0)assert _flags(captured["probe_scene.mjs"]) == ["--no-settle"]probes_mod.probe_scene(ws)assert _flags(captured["probe_scene.mjs"]) == ["--no-settle"]+ with pytest.raises(SceneRenderError):+ ablation_mod.ablate_scene(ws)+ assert _flags(captured["ablate_scene.mjs"]) == ["--no-settle"] and "--no-post" in captured["ablate_scene.mjs"]diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.pyindex cd81583f..e3b81d72 100644--- a/harness/tests/threejs_render/test_runtime_js.py+++ b/harness/tests/threejs_render/test_runtime_js.py@@ -73,6 +73,7 @@ const {{ serveDirs, importMapHtml }} = require({json.dumps(str(runtime_js_dir()glb: await get('/a.glb'), json: await get('/sub/b.json'), page: await get('/__p.html'),three: await get('/__runtime/node_modules/three/build/three.module.js'),escape: await get('/../s.cjs'), missing: await get('/nope.png'), fav: await get('/favicon.ico'),+ malformed: await get('/100%.png'), after: await get('/a.glb'), // decodeURIComponent throws on '%.p'importmap: importMapHtml(),}};await srv.close();@@ -85,6 +86,7 @@ const {{ serveDirs, importMapHtml }} = require({json.dumps(str(runtime_js_dir()assert out["page"]["status"] == 200 and "text/html" in out["page"]["type"]assert out["three"]["status"] == 200 and out["three"]["len"] > 100000 and out["three"]["type"] == "text/javascript"assert out["escape"]["status"] == 404 and out["missing"]["status"] == 404 and out["fav"]["status"] == 204+ assert out["malformed"]["status"] == 404 and out["after"]["status"] == 200 # the server survived itim = json.loads(out["importmap"].split(">", 1)[1].rsplit("<", 1)[0])["imports"]assert im["three"].startswith("/__runtime/") and im["three/addons/"].endswith("/examples/jsm/")assert "http" not in json.dumps(im)