Skip to content

The agent that grows with you

fix(web): bound the dashboard build's CPU and heap (#63338)

Austin Pickettaf9c7137c8c5
diff --git a/hermes_cli/source_build.py b/hermes_cli/source_build.py
index 427acb1021f..781b5cab02d 100644
--- a/hermes_cli/source_build.py
+++ b/hermes_cli/source_build.py
@@ -94,6 +94,11 @@ def build_source_tui(project_root: Path, *, env: dict) -> None:
def build_source_web(project_root: Path, *, env: dict, icons: Path | None = None) -> None:
+ # Bounded build (#63338): the Vite/Rolldown dashboard build saturates small
+ # hosts; cap the V8 heap and the native bundler's rayon thread pool.
+ from hermes_cli.web_build_limits import apply_web_build_limits
+
+ apply_web_build_limits(env)
# Default-brand icons are committed; installs never render them.
icons = icons or project_root
run_source_script(project_root, "scripts/build/web.mjs", "--source", str(project_root),
diff --git a/hermes_cli/web_build_limits.py b/hermes_cli/web_build_limits.py
new file mode 100644
index 00000000000..34a2edd88f5
--- /dev/null
+++ b/hermes_cli/web_build_limits.py
@@ -0,0 +1,140 @@
+"""Web UI build resource caps (issue #63338).
+
+``npm run build`` in ``web/`` runs the TypeScript solution builder plus Vite 8's
+Rust-native bundler (Rolldown). On small hosts (2–4 vCPU VPS, ~4–10 GB RAM) that
+combination saturates every CPU (200%+ ``top`` readings) and can OOM the box or
+freeze SSH sessions for the ~20 s build window. Rolldown does not expose a JS-level
+worker/thread option, but its native binding parallelizes with rayon, which honours
+``RAYON_NUM_THREADS`` — and V8's heap is capped via ``--max-old-space-size``.
+
+The defaults are deliberately conservative: bounded to half the available cores so
+one build can never monopolize a small host, and a heap ceiling sized from the
+container/cgroup limit (75% of it, same shape as the TUI launcher's sizing) so a
+constrained container gets a graceful V8 allocation failure instead of a silent
+cgroup OOM kill.
+
+User overrides always win: an explicit ``NODE_OPTIONS`` ``--max-old-space-size`` or
+``RAYON_NUM_THREADS`` in the environment is left untouched, and
+``HERMES_WEB_BUILD_MAX_OLD_SPACE_SIZE`` / ``HERMES_WEB_BUILD_THREADS`` allow
+tailoring without code changes.
+"""
+
+from __future__ import annotations
+
+import os
+
+# Never let the heap ceiling drop below this on constrained-but-usable hosts:
+# below ~1 GB V8 spends the build GC-thrashing instead of making progress.
+_MIN_WEB_BUILD_HEAP_MB = 1024
+# Ceiling even on huge machines; the dashboard bundle is small and a larger cap
+# only inflates the resident set (and OOM risk on shared VPS hosts).
+_MAX_WEB_BUILD_HEAP_MB = 4096
+# Likewise for parallelism: rolldown caps its own JS-plugin workers at 8, and
+# beyond ~half-a-dozen threads the small dashboard graph doesn't speed up.
+_MAX_WEB_BUILD_THREADS = 8
+
+_TRUTHY = {"1", "true", "yes", "on"}
+
+
+def _cgroup_memory_limit_mb() -> int | None:
+ """Return the cgroup memory limit in MB, or None when unconstrained."""
+ limit = None
+ for path in (
+ "/sys/fs/cgroup/memory.max", # cgroup v2
+ "/sys/fs/cgroup/memory/memory.limit_in_bytes", # cgroup v1
+ ):
+ try:
+ with open(path, "r", encoding="utf-8-sig") as f:
+ raw = f.read().strip()
+ except OSError:
+ continue
+ if raw == "max":
+ return None
+ try:
+ value = int(raw)
+ except ValueError:
+ continue
+ if value <= 0 or value >= (1 << 50): # the v1 "unlimited" sentinel
+ return None
+ limit = value
+ break
+ if limit is None:
+ return None
+ return limit // (1024 * 1024)
+
+
+def _available_cores() -> int:
+ try:
+ return max(1, len(os.sched_getaffinity(0))) # type: ignore[attr-defined]
+ except AttributeError:
+ return max(1, os.cpu_count() or 1)
+
+
+def _bounded_threads() -> int:
+ """Half the cores, clamped to [1, _MAX_WEB_BUILD_THREADS]."""
+ return max(1, min(_MAX_WEB_BUILD_THREADS, _available_cores() // 2 or 1))
+
+
+def _bounded_heap_mb() -> int:
+ """Heap ceiling from the cgroup limit, clamped to [_MIN, _MAX]."""
+ limit_mb = _cgroup_memory_limit_mb()
+ if not limit_mb:
+ return _MAX_WEB_BUILD_HEAP_MB
+ return max(_MIN_WEB_BUILD_HEAP_MB, min(_MAX_WEB_BUILD_HEAP_MB, int(limit_mb * 0.75)))
+
+
+def _env_flag(env: dict[str, str], name: str) -> bool:
+ return str(env.get(name, "")).strip().lower() in _TRUTHY
+
+
+def web_build_limits(env: dict[str, str] | None = None) -> dict[str, str]:
+ """Return a copy of *env* bounding the web dashboard build's CPU and heap (#63338).
+
+ Never overrides the user: an existing ``NODE_OPTIONS`` containing
+ ``--max-old-space-size`` or an existing ``RAYON_NUM_THREADS`` is preserved.
+ ``HERMES_WEB_BUILD_LIGHT=1`` tightens the caps (1 thread, 1 GB heap) for hosts
+ that cannot spare full CPU during the build.
+ """
+ env = dict(env if env is not None else os.environ)
+ light = light_build_requested(env)
+
+ # --- V8 heap cap ---------------------------------------------------------
+ tokens = env.get("NODE_OPTIONS", "").split()
+ if not any(t.startswith("--max-old-space-size=") for t in tokens):
+ explicit = (env.get("HERMES_WEB_BUILD_MAX_OLD_SPACE_SIZE") or "").strip()
+ try:
+ heap_mb = int(explicit) if explicit else (
+ _MIN_WEB_BUILD_HEAP_MB if light else _bounded_heap_mb()
+ )
+ except ValueError:
+ heap_mb = _MIN_WEB_BUILD_HEAP_MB if light else _bounded_heap_mb()
+ heap_mb = max(_MIN_WEB_BUILD_HEAP_MB, heap_mb)
+ tokens.append(f"--max-old-space-size={heap_mb}")
+ env["NODE_OPTIONS"] = " ".join(t for t in tokens if t).strip()
+
+ # --- Native bundler parallelism cap -------------------------------------
+ if not env.get("RAYON_NUM_THREADS"):
+ explicit = (env.get("HERMES_WEB_BUILD_THREADS") or "").strip()
+ try:
+ threads = int(explicit) if explicit else (1 if light else _bounded_threads())
+ except ValueError:
+ threads = 1 if light else _bounded_threads()
+ env["RAYON_NUM_THREADS"] = str(max(1, threads))
+
+ return env
+
+
+def apply_web_build_limits(env: dict[str, str]) -> dict[str, str]:
+ """Apply :func:`web_build_limits` into *env* (in place) and return it."""
+ env.update(web_build_limits(env))
+ return env
+
+
+def light_build_requested(env: dict[str, str] | None = None) -> bool:
+ """True when the caller asked for the minimal-footprint web build.
+
+ ``HERMES_WEB_BUILD_LIGHT=1``: caps tighten to a single bundler thread and a
+ 1 GB heap — for VPS hosts that cannot spare full CPU during the build
+ (the closed PR #78131's ``build:light`` idea).
+ """
+ return _env_flag(env if env is not None else dict(os.environ), "HERMES_WEB_BUILD_LIGHT")
diff --git a/scripts/build/web.mjs b/scripts/build/web.mjs
index 020b2c832d6..80e0c579b9c 100644
--- a/scripts/build/web.mjs
+++ b/scripts/build/web.mjs
@@ -1,11 +1,97 @@
#!/usr/bin/env node
// Pure dashboard compilation; icon/dependency preparation belongs to callers.
-import { cpSync, existsSync, mkdirSync, statSync } from 'node:fs'
+import { cpSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'
+import os from 'node:os'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { frontendArgs, isMain, productOutput, repoRoot, withProduct, workspaceTool } from './frontend-common.mjs'
import { recordProduct, buildInputs } from './freshness.mjs'
+// --- Bounded build (#63338) -------------------------------------------------
+// `npm run build` drives Vite 8's Rust-native bundler (Rolldown), whose rayon
+// thread pool saturates every CPU on small hosts (200%+ `top` readings, OOMs
+// and frozen SSH sessions on 2–4 vCPU VPS boxes). Vite exposes no worker knob,
+// but Rolldown's native binding honours RAYON_NUM_THREADS, and V8's heap is
+// capped with --max-old-space-size. `--max-old-space-size` cannot affect an
+// already-running process, so the default heap cap is enforced with a single
+// re-exec (spawnSync → exit); the thread cap is set before vite is imported.
+// User-set env (NODE_OPTIONS heap flag, RAYON_NUM_THREADS) always wins, and
+// HERMES_WEB_BUILD_MAX_OLD_SPACE_SIZE / HERMES_WEB_BUILD_THREADS tailor the
+// caps; HERMES_WEB_BUILD_LIGHT=1 tightens them (1 thread, minimum heap) for
+// hosts that cannot spare full CPU during the build.
+const MIN_HEAP_MB = 1024
+const MAX_HEAP_MB = 4096
+const MAX_THREADS = 8
+const TRUTHY = new Set(['1', 'true', 'yes', 'on'])
+
+const webBuildLight = () => TRUTHY.has(String(process.env.HERMES_WEB_BUILD_LIGHT ?? '').toLowerCase())
+
+function availableCores() {
+ try {
+ return Math.max(1, os.availableParallelism?.() ?? (os.cpus().length || 1))
+ } catch {
+ return 1
+ }
+}
+
+// Half the cores (the dashboard graph is small), clamped to [1, MAX_THREADS].
+function boundedThreads() {
+ return Math.max(1, Math.min(MAX_THREADS, Math.ceil(availableCores() / 2)))
+}
+
+// cgroup v2/v1 memory limit in MB, or null when unconstrained.
+function readCgroupLimitMb() {
+ for (const cgroupPath of ['/sys/fs/cgroup/memory.max', '/sys/fs/cgroup/memory/memory.limit_in_bytes']) {
+ try {
+ const raw = String(readFileSync(cgroupPath, 'utf-8')).trim()
+ if (raw === 'max' || !/^\d+$/.test(raw)) continue
+ const value = Number(raw)
+ if (value <= 0 || value >= 2 ** 50) return null // the v1 "unlimited" sentinel
+ return Math.floor(value / (1024 * 1024))
+ } catch { /* unconstrained or unsupported */ }
+ }
+ return null
+}
+
+// 75% of the cgroup limit when constrained (mirrors the TUI launcher's heap
+// sizing), else the conservative ceiling. Never below the GC-thrash floor.
+function boundedHeapMb() {
+ const limitMb = readCgroupLimitMb()
+ const sized = limitMb ? Math.floor(limitMb * 0.75) : MAX_HEAP_MB
+ return Math.max(MIN_HEAP_MB, Math.min(MAX_HEAP_MB, sized))
+}
+
+function applyThreadCap() {
+ if (process.env.RAYON_NUM_THREADS) return
+ const explicit = Number.parseInt(process.env.HERMES_WEB_BUILD_THREADS ?? '', 10)
+ const threads = Number.isFinite(explicit) && explicit > 0 ? explicit
+ : (webBuildLight() ? 1 : boundedThreads())
+ process.env.RAYON_NUM_THREADS = String(Math.max(1, threads))
+}
+
+// Re-exec with the heap cap appended to NODE_OPTIONS unless the user already
+// set one. Runs only for direct invocation (isMain), before vite is imported.
+async function ensureHeapCapForFreshProcess() {
+ const tokens = (process.env.NODE_OPTIONS ?? '').split(/\s+/).filter(Boolean)
+ if (tokens.some(token => token.startsWith('--max-old-space-size='))) return
+ const explicit = Number.parseInt(process.env.HERMES_WEB_BUILD_MAX_OLD_SPACE_SIZE ?? '', 10)
+ const heapMb = Number.isFinite(explicit) && explicit > 0
+ ? Math.max(MIN_HEAP_MB, explicit)
+ : (webBuildLight() ? MIN_HEAP_MB : boundedHeapMb())
+ tokens.push(`--max-old-space-size=${heapMb}`)
+ const { spawnSync } = await import('node:child_process')
+ const result = spawnSync(process.execPath, process.argv.slice(1), {
+ stdio: 'inherit',
+ env: { ...process.env, NODE_OPTIONS: tokens.join(' ') },
+ })
+ process.exit(result.status ?? 1)
+}
+
+if (isMain(import.meta.url)) {
+ applyThreadCap()
+ await ensureHeapCapForFreshProcess()
+}
+
function typecheck(ts, root, scratch) {
const diagnostics = []
const host = ts.createSolutionBuilderHost(ts.sys, undefined, diagnostic => diagnostics.push(diagnostic))
diff --git a/tests/hermes_cli/test_web_build_limits.py b/tests/hermes_cli/test_web_build_limits.py
new file mode 100644
index 00000000000..6b72b061d1d
--- /dev/null
+++ b/tests/hermes_cli/test_web_build_limits.py
@@ -0,0 +1,131 @@
+"""Web dashboard build resource caps (issue #63338).
+
+``npm run build`` under ``web/`` runs Vite 8's Rust-native bundler (Rolldown) plus
+the TypeScript solution builder; on small VPS hosts it saturates every CPU and can
+OOM the machine. These tests cover the env capping helper and its propagation into
+the install/update/dashboard-triggered source build path.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from hermes_cli.web_build_limits import (
+ apply_web_build_limits,
+ web_build_limits,
+)
+
+
+class TestWebBuildLimits:
+ def test_heap_and_thread_caps_applied(self, monkeypatch):
+ monkeypatch.delenv("NODE_OPTIONS", raising=False)
+ monkeypatch.delenv("RAYON_NUM_THREADS", raising=False)
+ monkeypatch.delenv("HERMES_WEB_BUILD_MAX_OLD_SPACE_SIZE", raising=False)
+ monkeypatch.delenv("HERMES_WEB_BUILD_THREADS", raising=False)
+ env = web_build_limits({})
+ assert "--max-old-space-size=" in env["NODE_OPTIONS"]
+ assert int(env["RAYON_NUM_THREADS"]) >= 1
+
+ def test_existing_user_node_options_preserved(self, monkeypatch):
+ monkeypatch.delenv("RAYON_NUM_THREADS", raising=False)
+ env = web_build_limits({"NODE_OPTIONS": "--max-old-space-size=8192"})
+ assert env["NODE_OPTIONS"].count("--max-old-space-size=") == 1
+ assert "8192" in env["NODE_OPTIONS"]
+
+ def test_existing_user_rayon_threads_preserved(self, monkeypatch):
+ monkeypatch.delenv("NODE_OPTIONS", raising=False)
+ env = web_build_limits({"RAYON_NUM_THREADS": "6"})
+ assert env["RAYON_NUM_THREADS"] == "6"
+ # heap cap still applied
+ assert "--max-old-space-size=" in env["NODE_OPTIONS"]
+
+ def test_explicit_env_overrides_win(self, monkeypatch):
+ monkeypatch.delenv("NODE_OPTIONS", raising=False)
+ monkeypatch.delenv("RAYON_NUM_THREADS", raising=False)
+ env = web_build_limits({
+ "HERMES_WEB_BUILD_MAX_OLD_SPACE_SIZE": "3072",
+ "HERMES_WEB_BUILD_THREADS": "1",
+ })
+ assert "--max-old-space-size=3072" in env["NODE_OPTIONS"]
+ assert env["RAYON_NUM_THREADS"] == "1"
+
+ def test_cgroup_limit_shrinks_heap_floor(self, monkeypatch):
+ monkeypatch.delenv("NODE_OPTIONS", raising=False)
+ monkeypatch.setattr(
+ "hermes_cli.web_build_limits._cgroup_memory_limit_mb", lambda: 2048
+ )
+ env = web_build_limits({})
+ # 75% of a 2GB container, above the GC-thrash floor but below the
+ # unconstrained ceiling.
+ assert "--max-old-space-size=1536" in env["NODE_OPTIONS"]
+
+ def test_bounded_threads_half_cores(self, monkeypatch):
+ monkeypatch.setattr("hermes_cli.web_build_limits._available_cores", lambda: 16)
+ env = web_build_limits({})
+ assert env["RAYON_NUM_THREADS"] == "8" # clamped ceiling
+
+ monkeypatch.setattr("hermes_cli.web_build_limits._available_cores", lambda: 4)
+ env = web_build_limits({})
+ assert env["RAYON_NUM_THREADS"] == "2" # half of 4 — the issue's host
+
+ monkeypatch.setattr("hermes_cli.web_build_limits._available_cores", lambda: 1)
+ env = web_build_limits({})
+ assert env["RAYON_NUM_THREADS"] == "1" # single-core host never gets 0
+
+ def test_apply_updates_env_in_place(self, monkeypatch):
+ monkeypatch.delenv("NODE_OPTIONS", raising=False)
+ monkeypatch.delenv("RAYON_NUM_THREADS", raising=False)
+ env = {"PATH": "/bin"}
+ apply_web_build_limits(env)
+ assert "--max-old-space-size=" in env["NODE_OPTIONS"]
+ assert env["RAYON_NUM_THREADS"].isdigit()
+ assert env["PATH"] == "/bin"
+
+ def test_light_mode_tightens_caps(self, monkeypatch):
+ monkeypatch.delenv("NODE_OPTIONS", raising=False)
+ monkeypatch.delenv("RAYON_NUM_THREADS", raising=False)
+ monkeypatch.delenv("HERMES_WEB_BUILD_MAX_OLD_SPACE_SIZE", raising=False)
+ monkeypatch.delenv("HERMES_WEB_BUILD_THREADS", raising=False)
+ monkeypatch.setattr("hermes_cli.web_build_limits._available_cores", lambda: 8)
+ env = web_build_limits({"HERMES_WEB_BUILD_LIGHT": "1"})
+ assert "--max-old-space-size=1024" in env["NODE_OPTIONS"]
+ assert env["RAYON_NUM_THREADS"] == "1"
+
+
+class TestBuildSourceWebPropagatesLimits:
+ """The install/update/``hermes dashboard`` build path must apply the caps."""
+
+ def test_build_source_web_applies_limits(self, tmp_path, monkeypatch):
+ from hermes_cli import source_build
+
+ captured: dict = {}
+
+ def fake_run_source_script(project_root, script, *args, env, label):
+ captured["env"] = env
+ captured["label"] = label
+
+ monkeypatch.setattr(source_build, "run_source_script", fake_run_source_script)
+ monkeypatch.delenv("NODE_OPTIONS", raising=False)
+ monkeypatch.delenv("RAYON_NUM_THREADS", raising=False)
+
+ env = {"PATH": "/bin"}
+ source_build.build_source_web(tmp_path, env=env)
+ assert "--max-old-space-size=" in captured["env"]["NODE_OPTIONS"]
+ assert captured["env"]["RAYON_NUM_THREADS"].isdigit()
+ # original env keys untouched
+ assert captured["env"]["PATH"] == "/bin"
+ assert captured["label"] == "Building the web UI"
+
+
+class TestPackageJsonBuildScriptCapped:
+ """``scripts/build/web.mjs`` must carry the caps for direct npm runs."""
+
+ def test_build_script_has_heap_and_thread_caps(self):
+ from pathlib import Path
+
+ repo_root = Path(__file__).resolve().parents[2]
+ build_script = (repo_root / "scripts/build/web.mjs").read_text(encoding="utf-8")
+ assert "--max-old-space-size=" in build_script
+ assert "RAYON_NUM_THREADS" in build_script
+ # caps apply on direct invocation before vite is imported
+ assert "isMain(import.meta.url)" in build_script