Official Codebase of 3DCodeVerse
Python
render: retry once when the BROWSER dies under a driver, on a browser of our own
ziyao6f0019c4b372
diff --git a/harness/codeverse/spatial/node.py b/harness/codeverse/spatial/node.pyindex 316bf126..ee0a82fb 100644--- a/harness/codeverse/spatial/node.py+++ b/harness/codeverse/spatial/node.py@@ -74,6 +74,34 @@ class NodeResult:return self.stderr[-TAIL_CHARS:]+#: A render failure that is the BOX, not the scene: the browser or the page died+#: under the driver — the renderer process crashed, the tab was reaped under memory+#: pressure, the shared browser was retired mid-call. The same workspace renders on+#: the next attempt, so one retry is worth its wall clock. Measured 2026-09-05: four+#: cells of the `scenes_v1` baseline lost every render — and with it the judge, after+#: the models had already been paid for — to "Attempted to use detached Frame" while+#: the box sat at load 93 with swap full.+BROWSER_LOST_MARKERS = (+ "detached frame",+ "target closed",+ "target crashed",+ "session closed",+ "page crashed",+ "browser has disconnected",+ "connection closed",+)++#: Env for a retry after a browser loss: take an OWNED browser, because the shared+#: one advertised in the cache is the suspect (`runtime_js/gpu_launch.cjs`).+OWN_BROWSER_ENV: dict[str, str] = {"CV3D_BROWSER_REUSE": "off"}+++def browser_was_lost(text: object) -> bool:+ """True when ``text`` names a browser or page that died under the driver."""+ lowered = str(text).lower()+ return any(marker in lowered for marker in BROWSER_LOST_MARKERS)++def runtime_js_dir() -> Path:return get_settings().runtime_js_dir()diff --git a/harness/codeverse/spatial/render.py b/harness/codeverse/spatial/render.pyindex 0e55eab7..c8480b0d 100644--- a/harness/codeverse/spatial/render.py+++ b/harness/codeverse/spatial/render.py@@ -25,7 +25,14 @@ from codeverse.contracts.artifacts import RENDER_MODES, RenderSet, RenderViewfrom codeverse.conventions import OBJECT_VIEWS, ViewPresetfrom codeverse.proc import sha256_filefrom codeverse.spatial._render_common import build_sheet, out_directory, view_specs-from codeverse.spatial.node import NodeError, run_node, runtime_js_dir+from codeverse.spatial.node import (+ BROWSER_LOST_MARKERS,+ OWN_BROWSER_ENV,+ NodeError,+ browser_was_lost,+ run_node,+ runtime_js_dir,+)BACKGROUNDS = ("studio", "white", "transparent")CACHE_VERSION = 4 # bump when the rig changes in a way that invalidates cached PNGs@@ -139,9 +146,15 @@ def render_glb(# compare_art_v4 (2026-08-28): under 12 concurrent cells the browser took 7.5 s to# open a page and the viewer's wait expired ("Waiting failed"); the cell lost its# in-loop judge for the round. One retry with twice the time is cheap next to that.- log.warning("render_glb transient failure, retrying once with %.0f s: %s", timeout_s * 2, str(e)[:160])+ # A browser LOSS is retried on a browser of our own: the shared one+ # advertised in the cache is the suspect, so re-using it repeats the failure.+ own = browser_was_lost(e)+ log.warning(+ "render_glb transient failure, retrying once with %.0f s%s: %s",+ timeout_s * 2, " on an owned browser" if own else "", str(e)[:160],+ )time.sleep(RETRY_PAUSE_S)- record = _run_render(glb, out_dir, params, gpu=gpu, timeout_s=timeout_s * 2)+ record = _run_render(glb, out_dir, params, gpu=gpu, timeout_s=timeout_s * 2, own_browser=own)if use_cache:_store_in_cache(cache_dir, out_dir, record)@@ -169,8 +182,10 @@ def render_glb()-#: render failures that are the box, not the model: a retry is worth one more timeout-TRANSIENT_MARKERS = ("waiting failed", "timed out", "timeout", "produced no result", "target closed", "session closed")+#: render failures that are the box, not the model: a retry is worth one more timeout.+#: The browser-loss half is shared with the scene drivers, which had no retry at all+#: until 2026-09-05 and lost four baseline cells to a marker missing from this tuple.+TRANSIENT_MARKERS = ("waiting failed", "timed out", "timeout", "produced no result", *BROWSER_LOST_MARKERS)RETRY_PAUSE_S = 3.0@@ -179,7 +194,9 @@ def _transient(e: Exception) -> bool:return any(m in text for m in TRANSIENT_MARKERS)-def _run_render(glb: Path, out_dir: Path, params: dict[str, Any], *, gpu: str, timeout_s: float) -> dict[str, Any]:+def _run_render(+ glb: Path, out_dir: Path, params: dict[str, Any], *, gpu: str, timeout_s: float, own_browser: bool = False+) -> dict[str, Any]:args = ["--glb", str(glb), "--out", str(out_dir), "--views", json.dumps(params["views"]),"--mode", params["mode"], "--width", str(params["width"]), "--height", str(params["height"]),@@ -191,7 +208,10 @@ def _run_render(glb: Path, out_dir: Path, params: dict[str, Any], *, gpu: str, tif params["anim_time"] is not None:args += ["--anim-time", str(params["anim_time"])]try:- res = run_node(runtime_js_dir() / "render_glb.mjs", args, timeout_s=timeout_s + 30)+ res = run_node(+ runtime_js_dir() / "render_glb.mjs", args, timeout_s=timeout_s + 30,+ env_extra=OWN_BROWSER_ENV if own_browser else None,+ )except NodeError as e:detail = ""if e.result and e.result.last_json:diff --git a/harness/codeverse/spatial/render_scene.py b/harness/codeverse/spatial/render_scene.pyindex a055253f..8bdef187 100644--- a/harness/codeverse/spatial/render_scene.py+++ b/harness/codeverse/spatial/render_scene.py@@ -27,7 +27,14 @@ from codeverse.contracts.plan import BBox, CameraPlanfrom codeverse.conventions import SCENE_VIEWS, ViewPresetfrom codeverse.proc import read_json_or_nonefrom codeverse.spatial._render_common import build_sheet, out_directory, view_specs-from codeverse.spatial.node import NodeError, NodeResult, run_node, runtime_js_dir+from codeverse.spatial.node import (+ OWN_BROWSER_ENV,+ NodeError,+ NodeResult,+ browser_was_lost,+ run_node,+ runtime_js_dir,+)from codeverse.workspace import Workspacelog = logging.getLogger(__name__)@@ -43,11 +50,22 @@ class SceneRenderError(RuntimeError):"""The node driver could not run (missing node/deps, timeout, crash)."""+def _driver_failed(r: NodeResult) -> bool:+ """The DRIVER could not run (exit 2/3, or a non-zero exit with no summary line).+ Exit 1 is a scene that failed, which is a verdict, not a driver failure."""+ return r.rc in (2, 3) or (r.rc != 0 and not r.summary)++def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd: Path | None = None) -> NodeResult:"""Run ``runtime_js/<script>`` via ``codeverse.spatial.node.run_node`` (whichdelegates to ``codeverse.proc.run_subprocess``: own process group, group killon timeout). The driver prints a JSON summary as its LAST stdout line; atimeout or exit code 2/3 means the driver itself failed → ``SceneRenderError``.++ A driver that lost its BROWSER (``node.BROWSER_LOST_MARKERS``) is retried once on+ a browser of its own. That failure is the box, not the workspace, and without the+ retry it costs the round every render and therefore its judge — the object path+ has retried it since 2026-08-28 (``spatial/render.py``), the scene path did not."""rt = runtime_js_dir()path = rt / script@@ -57,14 +75,25 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:gpu = get_settings().render.gpuif gpu and "CV3D_RENDER_GPU" not in os.environ:env_extra["CV3D_RENDER_GPU"] = gpu- try:- r = run_node(path, list(map(str, args)), cwd=cwd or rt, timeout_s=timeout_s, env_extra=env_extra, check=False)- except NodeError as e:- if e.result is not None and e.result.timed_out:- raise SceneRenderError(f"{script} timed out after {timeout_s:.0f}s\n{e.result.stderr_tail}") from e- raise SceneRenderError(f"{script} could not run: {e}") from e+ argv = [str(a) for a in args]++ def attempt(env: dict[str, str]) -> NodeResult:+ try:+ return run_node(path, argv, cwd=cwd or rt, timeout_s=timeout_s, env_extra=env, check=False)+ except NodeError as e:+ if e.result is not None and e.result.timed_out:+ raise SceneRenderError(f"{script} timed out after {timeout_s:.0f}s\n{e.result.stderr_tail}") from e+ raise SceneRenderError(f"{script} could not run: {e}") from e++ r = attempt(env_extra)+ if _driver_failed(r) and browser_was_lost(r.summary.get("error", "")):+ log.warning(+ "%s lost its browser (%s); retrying once on an owned browser",+ script, str(r.summary.get("error"))[:200],+ )+ r = attempt({**env_extra, **OWN_BROWSER_ENV})summary = r.summary- if r.rc in (2, 3) or (r.rc != 0 and not summary):+ if _driver_failed(r):raise SceneRenderError(f"{script} failed (exit {r.rc}): {summary.get('error') if summary else ''}\n"f"stderr tail: {r.stderr_tail}\nstdout tail: {r.stdout[-1000:]}"diff --git a/harness/tests/scene_runtime/test_scene_driver_retry.py b/harness/tests/scene_runtime/test_scene_driver_retry.pynew file mode 100644index 00000000..2f58c98e--- /dev/null+++ b/harness/tests/scene_runtime/test_scene_driver_retry.py@@ -0,0 +1,72 @@+"""A scene driver that LOST ITS BROWSER is retried once on a browser of its own.++Measured 2026-09-05 on `bench/out/scene_baseline`: with the box at load 93 and swap+full, Chrome reaped the render tab of four cells. Each driver exited 2 with+"Attempted to use detached Frame …", `run_scene_script` raised, the round kept zero+renders and the judge was skipped — after the generator had already been paid for.+The object path had retried a transient render since 2026-08-28; the scene path,+which is the only one whose renders the scene judge reads, had no retry at all.+"""++from __future__ import annotations++import pytest++import codeverse.spatial.render_scene as RS+from codeverse.spatial.node import NodeResult+from codeverse.spatial.render_scene import SceneRenderError, run_scene_script++DETACHED = "render failed: Attempted to use detached Frame '10276B428E350BFA074A02AF37D52E6C'."+++def _result(rc: int, summary: dict | None) -> NodeResult:+ return NodeResult(rc=rc, stdout="", stderr="", last_json=summary, duration_ms=1)+++def _record(monkeypatch, results: list[NodeResult]) -> list[dict[str, str]]:+ """Feed `results` to run_scene_script in order; collect each call's env_extra."""+ envs: list[dict[str, str]] = []++ def fake(path, args, *, cwd, timeout_s, env_extra, check):+ envs.append(dict(env_extra or {}))+ return results[len(envs) - 1]++ monkeypatch.setattr(RS, "run_node", fake)+ return envs+++def test_a_lost_browser_is_retried_on_an_owned_browser(monkeypatch):+ envs = _record(monkeypatch, [+ _result(2, {"ok": False, "error": DETACHED}),+ _result(0, {"ok": True, "n_views": 8}),+ ])+ r = run_scene_script("render_scene.mjs", ["--ws", "x"], timeout_s=10)+ assert r.summary["n_views"] == 8, "the second attempt's result is the one returned"+ assert len(envs) == 2, "a browser loss must be retried"+ assert envs[0].get("CV3D_BROWSER_REUSE") is None+ assert envs[1]["CV3D_BROWSER_REUSE"] == "off", "the retry must not reuse the browser that died"+++def test_a_scene_that_failed_is_not_retried(monkeypatch):+ """Exit 1 is a verdict about the scene — console errors, a scene that did not+ boot — not a driver failure. Re-rendering it would only spend the time again."""+ envs = _record(monkeypatch, [_result(1, {"ok": False, "error": "scene did not boot"})])+ r = run_scene_script("render_scene.mjs", ["--ws", "x"], timeout_s=10)+ assert r.rc == 1 and len(envs) == 1+++def test_a_driver_error_that_is_not_a_browser_loss_is_not_retried(monkeypatch):+ envs = _record(monkeypatch, [_result(2, {"ok": False, "error": "--ws and --out are required"})])+ with pytest.raises(SceneRenderError, match="--ws and --out are required"):+ run_scene_script("render_scene.mjs", [], timeout_s=10)+ assert len(envs) == 1+++def test_a_retry_that_loses_the_browser_again_raises(monkeypatch):+ envs = _record(monkeypatch, [+ _result(2, {"ok": False, "error": DETACHED}),+ _result(2, {"ok": False, "error": DETACHED}),+ ])+ with pytest.raises(SceneRenderError, match="detached Frame"):+ run_scene_script("render_scene.mjs", ["--ws", "x"], timeout_s=10)+ assert len(envs) == 2, "exactly one retry — a box out of memory stays out of memory"diff --git a/harness/tests/threejs_render/test_render_retry.py b/harness/tests/threejs_render/test_render_retry.pyindex 62b3eb8a..028fb04f 100644--- a/harness/tests/threejs_render/test_render_retry.py+++ b/harness/tests/threejs_render/test_render_retry.py@@ -30,7 +30,7 @@ def _glb(tmp_path: Path) -> Path:def test_transient_failure_is_retried_with_double_timeout(tmp_path, monkeypatch):calls: list[float] = []- def fake(glb, out_dir, params, *, gpu, timeout_s):+ def fake(glb, out_dir, params, *, gpu, timeout_s, own_browser=False):calls.append(timeout_s)if len(calls) == 1:raise RenderError("render_glb failed: node script render_glb.mjs exited 1: Waiting failed")@@ -44,7 +44,7 @@ def test_transient_failure_is_retried_with_double_timeout(tmp_path, monkeypatch)def test_real_failure_is_not_retried(tmp_path, monkeypatch):calls: list[float] = []- def fake(glb, out_dir, params, *, gpu, timeout_s):+ def fake(glb, out_dir, params, *, gpu, timeout_s, own_browser=False):calls.append(timeout_s)raise RenderError("render_glb failed: Cannot find module 'puppeteer'")@@ -52,3 +52,39 @@ def test_real_failure_is_not_retried(tmp_path, monkeypatch):with pytest.raises(RenderError):render_glb(_glb(tmp_path), tmp_path / "out", use_cache=False, timeout_s=100)assert calls == [100]+++# The string below is verbatim from bench/out/scene_baseline (2026-09-05): with the box+# at load 93 and swap full, Chrome reaped the render tab and every driver reported it+# this way. "detached frame" was not in TRANSIENT_MARKERS, so the object path did not+# retry it either — it only ever matched the "Target closed" spelling.+DETACHED = "render_glb failed: Attempted to use detached Frame '10276B428E350BFA074A02AF37D52E6C'."+++def test_a_lost_browser_is_retried_on_a_browser_of_our_own(tmp_path, monkeypatch):+ seen: list[bool] = []++ def fake(glb, out_dir, params, *, gpu, timeout_s, own_browser=False):+ seen.append(own_browser)+ if len(seen) == 1:+ raise RenderError(DETACHED)+ return {"views": [], "renderer": "fake", "duration_ms": 1}++ monkeypatch.setattr(R, "_run_render", fake)+ rs = render_glb(_glb(tmp_path), tmp_path / "out", use_cache=False, timeout_s=100)+ assert rs.renderer == "fake"+ assert seen == [False, True], "the retry must not go back to the browser that just died"+++def test_a_transient_that_is_not_a_browser_loss_keeps_the_shared_browser(tmp_path, monkeypatch):+ seen: list[bool] = []++ def fake(glb, out_dir, params, *, gpu, timeout_s, own_browser=False):+ seen.append(own_browser)+ if len(seen) == 1:+ raise RenderError("render_glb failed: Waiting failed: 30000 ms exceeded")+ return {"views": [], "renderer": "fake", "duration_ms": 1}++ monkeypatch.setattr(R, "_run_render", fake)+ render_glb(_glb(tmp_path), tmp_path / "out", use_cache=False, timeout_s=100)+ assert seen == [False, False], "a slow box is not a reason to give up browser reuse"