Official Codebase of 3DCodeVerse
Python
runtime_js: key the shared-browser endpoint by the runtime_js that spawned it
ziyao89f09a690f20
diff --git a/harness/runtime_js/browser_daemon.cjs b/harness/runtime_js/browser_daemon.cjsindex 100b9ccc..71a3fa05 100644--- a/harness/runtime_js/browser_daemon.cjs+++ b/harness/runtime_js/browser_daemon.cjs@@ -13,7 +13,6 @@'use strict';const fs = require('fs');-const path = require('path');const { _internal } = require('./gpu_launch.cjs');const IDLE_REAP_MS = 90 * 1000;@@ -34,7 +33,7 @@ async function main() {if (!['gpu', 'cpu'].includes(backend)) throw new Error(`--backend must be gpu|cpu, got ${backend}`);const puppeteer = _internal.loadPuppeteer();const epPath = _internal.endpointPath(backend);- const lockPath = path.join(_internal.CACHE_DIR, `browser_${backend}.lock`);+ const lockPath = _internal.spawnLockPath(backend); // one spelling, in gpu_launch.cjsfs.mkdirSync(_internal.CACHE_DIR, { recursive: true });let browser = null;diff --git a/harness/runtime_js/gpu_launch.cjs b/harness/runtime_js/gpu_launch.cjsindex 70a639a5..c63a84f4 100644--- a/harness/runtime_js/gpu_launch.cjs+++ b/harness/runtime_js/gpu_launch.cjs@@ -24,6 +24,7 @@'use strict';const { spawn } = require('child_process');+const crypto = require('crypto');const fs = require('fs');const os = require('os');const path = require('path');@@ -132,12 +133,33 @@ async function tryGpu(puppeteer) {}// --------------------------------------------------------------------- sharing+// A git worktree and the main checkout each run THEIR OWN runtime_js but share+// ~/.cache/codeverse unless the operator remembers CV3D_CACHE_DIR, so both daemons+// used to advertise into one `browser_<backend>.json`: the second overwrote the+// first, the first exited on its superseded-endpoint check, and clients of both+// trees landed on a single browser whose page budget and canary were sized for one.+// Measured 2026-09-05 — two live daemons from two trees, `Session closed` across the+// scene suite, passing again the moment the trees were given separate cache dirs.+// Keying the endpoint by the runtime_js that spawned it makes that structural: two+// trees never share a browser, and neither can retire the other's.+const RUNTIME_KEY = crypto.createHash('sha1').update(__dirname).digest('hex').slice(0, 8);++/** Base name for this runtime's per-backend daemon files (endpoint, lock, failure). */+function endpointBase(backend) {+ return path.join(CACHE_DIR, `browser_${backend}_${RUNTIME_KEY}`);+}+function endpointPath(backend) {- return path.join(CACHE_DIR, `browser_${backend}.json`);+ return `${endpointBase(backend)}.json`;}function daemonFailPath(backend) {- return path.join(CACHE_DIR, `browser_${backend}.failed.json`);+ return `${endpointBase(backend)}.failed.json`;+}++/** Single-flight spawn lock; the daemon deletes it once it has advertised. */+function spawnLockPath(backend) {+ return `${endpointBase(backend)}.lock`;}function reuseEnabled() {@@ -226,7 +248,7 @@ async function connectShared(puppeteer, backend) {/** Spawn the detached daemon for `backend` (single flight via a lock file). */function spawnDaemon(backend) {fs.mkdirSync(CACHE_DIR, { recursive: true });- const lock = path.join(CACHE_DIR, `browser_${backend}.lock`);+ const lock = spawnLockPath(backend);try {const st = fs.statSync(lock);if (Date.now() - st.mtimeMs < SPAWN_LOCK_STALE_MS) return; // someone else is spawning@@ -322,5 +344,8 @@ async function launchBrowser(opts = {}) {module.exports = {launchBrowser, rendererInfo, GPU_ARGS, CPU_ARGS, GPU_ENV, CACHE_PATH,// internals shared with browser_daemon.cjs (not a public surface)- _internal: { launchCpu, tryGpu, loadPuppeteer, endpointPath, daemonFailPath, CACHE_DIR, SOFTWARE_RE },+ _internal: {+ launchCpu, tryGpu, loadPuppeteer, endpointPath, daemonFailPath, spawnLockPath,+ CACHE_DIR, RUNTIME_KEY, SOFTWARE_RE,+ },};diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.pyindex 11bc9727..50c187c2 100644--- a/harness/tests/threejs_render/test_runtime_js.py+++ b/harness/tests/threejs_render/test_runtime_js.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import shutilfrom pathlib import Pathimport pytest@@ -120,6 +121,39 @@ const {{ launchBrowser, rendererInfo }} = require({json.dumps(str(runtime_js_dir_reap_daemons(tmp_path / "cache")+def test_two_runtime_trees_never_share_one_browser_endpoint(tmp_path: Path):+ """A git worktree and the main checkout run their own runtime_js but share+ ~/.cache/codeverse unless the operator remembers CV3D_CACHE_DIR. Measured+ 2026-09-05: two daemons, one endpoint file, `Session closed` across the scene+ suite. The endpoint name carries the runtime_js that spawned it, so the two+ trees keep separate browsers inside the SAME cache dir — no env var required."""+ cache = tmp_path / "cache"+ paths = []+ for tree in ("worktree", "checkout"):+ d = tmp_path / tree+ d.mkdir()+ shutil.copy(runtime_js_dir() / "gpu_launch.cjs", d / "gpu_launch.cjs")+ script = tmp_path / f"{tree}.cjs"+ script.write_text(f"""+const {{ _internal }} = require({json.dumps(str(d / 'gpu_launch.cjs'))});+console.log(JSON.stringify({{+ endpoint: _internal.endpointPath('cpu'),+ lock: _internal.spawnLockPath('cpu'),+ failed: _internal.daemonFailPath('cpu'),+}}));+""")+ paths.append(run_node(script, [], timeout_s=60, env_extra={"CV3D_CACHE_DIR": str(cache)}).last_json)++ a, b = paths+ for key in ("endpoint", "lock", "failed"):+ assert a[key] != b[key], f"both trees would advertise into the same {key}"+ # the separation must be the NAME: one cache dir is still one cache dir+ assert Path(a[key]).parent == Path(b[key]) .parent == cache+ # the reaper and the daemon-failure skip both key off these shapes+ assert Path(a["endpoint"]).name.startswith("browser_cpu_")+ assert a["failed"].endswith(".failed.json")++def _reap_daemons(cache_dir: Path) -> None:"""Kill any shared browser advertised under an ephemeral test cache dir."""import contextlib@@ -160,7 +194,10 @@ const {{ launchBrowser }} = require({json.dumps(str(runtime_js_dir() / 'gpu_launout = run_node(script, [], timeout_s=120, env_extra=env).last_jsonassert out["a_shared"] is True and out["b_shared"] is True and out["alive"]assert out["reconnect_ms"] < 1000 # connect, not a fresh ~550ms+ launch- assert (tmp_path / "cache" / "browser_cpu.json").is_file()+ # the endpoint is keyed by the runtime_js that spawned the daemon, so a worktree+ # and the main checkout sharing one cache dir cannot advertise over each other+ endpoints = list((tmp_path / "cache").glob("browser_cpu_*.json"))+ assert len(endpoints) == 1 and not endpoints[0].name.endswith(".failed.json")off = run_node(script, [], timeout_s=120, env_extra={**env, "CV3D_BROWSER_REUSE": "off"}).last_jsonassert off["a_shared"] is False and off["b_shared"] is False_reap_daemons(tmp_path / "cache")