Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(tooling): a performance snapshot, guarded the way the API surface is

esenginecc5e51f98c45
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 678a054c6..05078a924 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -174,7 +174,9 @@ jobs:
name: Tests (engine-coupled)
runs-on: ubuntu-latest
needs: build-emscripten
- timeout-minutes: 25
+ # Room for the benchmark sweep at the end: ~3 min on a fast laptop, and this
+ # runner has two cores.
+ timeout-minutes: 40
steps:
- uses: actions/checkout@v7
@@ -200,6 +202,15 @@ jobs:
ESTELLA_REQUIRE_WASM: '1'
run: pnpm --filter @estella/editor exec vitest run
+ # The performance counterpart of the API-surface snapshot, and it belongs in
+ # this job for the same reason the job exists: it needs the built wasm, and
+ # its own failure mode is a benchmark that quietly stops measuring. Asserts
+ # ratios between benchmarks in one run, so the runner's speed cancels out.
+ - name: Check performance snapshot
+ env:
+ ESENGINE_WASM_DIR: ${{ github.workspace }}/build/wasm/web
+ run: node tools/perf-guard.mjs --check
+
# Headless pixel verification: real scenes rendered by the editor's electron
# host under xvfb (SwiftShader WebGL), asserted pixel-by-pixel.
verify-render:
diff --git a/package.json b/package.json
index 1c4de8bfa..b51000fd7 100644
--- a/package.json
+++ b/package.json
@@ -18,6 +18,7 @@
"asset-meta": "node tools/asset-meta.js",
"migrate-asset-refs": "node tools/migrate-asset-refs.js",
"verify": "pnpm --filter ./sdk exec tsc --noEmit && node tools/api-surface.mjs --check && node tools/check-cycles.mjs && node tools/check-layers.mjs && node tools/check-workflows.mjs",
+ "perf": "node tools/perf-guard.mjs --check",
"prepare": "git config core.hooksPath .githooks || true"
},
"dependencies": {
diff --git a/sdk/etc/perf.snapshot.json b/sdk/etc/perf.snapshot.json
new file mode 100644
index 000000000..c75feacb7
--- /dev/null
+++ b/sdk/etc/perf.snapshot.json
@@ -0,0 +1,13 @@
+{
+ "note": "Generated by tools/perf-guard.mjs — run --update to accept changes.",
+ "tolerance": 0.3,
+ "cases": 174,
+ "ratios": {
+ "ui-layout: editing a field vs adding a node": 0.228,
+ "ui-layout: editing a field vs an idle frame": 10.9,
+ "query: count vs iterating": 0.00613,
+ "change-tracking: tracked vs untracked write-back": 1.02,
+ "uiMath: reusing a result vs allocating one": 0.296,
+ "system: three params vs none": 3.32
+ }
+}
diff --git a/tools/perf-guard.mjs b/tools/perf-guard.mjs
new file mode 100644
index 000000000..422304542
--- /dev/null
+++ b/tools/perf-guard.mjs
@@ -0,0 +1,214 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+// =============================================================================
+// Performance guard
+//
+// The same bargain as the API surface guard, for the properties that make the
+// engine fast rather than the ones that make it correct: a snapshot in the repo,
+// drift becomes a reviewed diff instead of an accident.
+//
+// WHY THIS EXISTS. The UI layout re-derived every node's box every frame for
+// months — editing one field cost the whole tree. Nothing was wrong; nobody had
+// ever measured it. "Never optimised" and "quietly regressed" are the same thing
+// when there is no baseline, and this repo had none: fifteen benchmark files and
+// no CI job running any of them. Worse, eleven of them had been importing
+// pre-move ECS paths since `src/world.ts` became `src/ecs/world.ts` — and
+// `vitest bench` skips a file it cannot resolve and still exits 0, so they read
+// as passing while measuring nothing.
+//
+// WHAT IT ASSERTS. Two things, both chosen because they survive being run on a
+// different machine:
+//
+// RATIOS, not milliseconds. Every metric is one benchmark divided by another
+// from the same run, so the CPU cancels out. Each one states an architectural
+// invariant — "editing a field is far cheaper than adding a node" is the
+// incremental layout still working, and it reads the same on any laptop.
+//
+// COVERAGE. How many cases produced a number. A benchmark that stops running
+// is the failure this guard was written after, and it is invisible in every
+// other signal.
+//
+// TOLERANCE is deliberately loose. Measured run-to-run noise on one machine is
+// ~1% median but reaches 14% on the smallest cases, and a ratio compounds two of
+// those. At 30% this cannot see a 5% slowdown — it is not meant to. It is meant
+// to catch the 2x-and-up kind, which is what an architectural property looks
+// like when it breaks.
+//
+// Run: node tools/perf-guard.mjs --check (CI: exit 1 on regression)
+// node tools/perf-guard.mjs --update (accept the new numbers)
+// =============================================================================
+
+import { readFileSync, writeFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { resolve, dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { tmpdir } from 'node:os';
+import { spawnSync } from 'node:child_process';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const SDK = join(ROOT, 'sdk');
+const SNAPSHOT = join(SDK, 'etc', 'perf.snapshot.json');
+
+/** Ratio metrics. `over` is the denominator; both must be in the same group. */
+const METRICS = [
+ {
+ name: 'ui-layout: editing a field vs adding a node',
+ why: 'The incremental solve. Equal cost means the tree is being re-derived.',
+ group: 'UI layout — 2000 nodes',
+ of: 'one node resized',
+ over: 'one node added',
+ },
+ {
+ name: 'ui-layout: editing a field vs an idle frame',
+ why: 'What one edit costs above the floor the gate already skips to.',
+ group: 'UI layout — 2000 nodes',
+ of: 'one node resized',
+ over: 'static frame (nothing changed)',
+ },
+ {
+ name: 'query: count vs iterating',
+ why: 'count() answers from the query cache; it must not walk the entities.',
+ group: 'Query - Iteration (5000 entities, 2 components)',
+ of: 'count',
+ over: 'forEach',
+ },
+ {
+ name: 'change-tracking: tracked vs untracked write-back',
+ why: 'Recording a change tick is a map write, not a second pass.',
+ group: 'Mut() write-back over 5000 builtin components',
+ of: 'Mut write-back, component tracked',
+ over: 'Mut write-back, component NOT tracked',
+ },
+ {
+ name: 'uiMath: reusing a result vs allocating one',
+ why: 'The out-param path exists to not allocate; it has to stay ahead.',
+ group: 'uiMath - Matrix operations',
+ of: 'invertMatrix4 x100 (result reuse)',
+ over: 'invertMatrix4 x100 (no result reuse)',
+ },
+ {
+ name: 'system: three params vs none',
+ why: 'Param resolution per dispatch — bounded, not proportional to work.',
+ group: 'System - Dispatch overhead (empty system)',
+ of: '3 params (Query + Res + Commands)',
+ over: '0 params',
+ },
+];
+
+const DEFAULT_TOLERANCE = 0.30;
+
+const mode = process.argv[2] ?? '--check';
+if (mode !== '--check' && mode !== '--update') {
+ console.error('usage: node tools/perf-guard.mjs --check | --update');
+ process.exit(2);
+}
+
+// ---------------------------------------------------------------------------
+// Run the benchmarks
+// ---------------------------------------------------------------------------
+
+const tmp = mkdtempSync(join(tmpdir(), 'estella-perf-'));
+const out = join(tmp, 'bench.json');
+try {
+ const run = spawnSync('npx', ['vitest', 'bench', '--run', '--outputJson', out], {
+ cwd: SDK, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ if (!existsSync(out)) {
+ console.error('perf: benchmarks produced no report.');
+ console.error(run.stderr?.slice(-2000) ?? '');
+ process.exit(1);
+ }
+ main(JSON.parse(readFileSync(out, 'utf8')));
+} finally {
+ rmSync(tmp, { recursive: true, force: true });
+}
+
+function main(report) {
+ // group + case -> mean ms. A case with no `mean` never ran; it is counted
+ // as missing rather than read as a zero.
+ const means = new Map();
+ let cases = 0;
+ for (const file of report.files ?? []) {
+ for (const group of file.groups ?? []) {
+ const groupName = group.fullName.replace(/^.*bench\.ts > /, '');
+ for (const b of group.benchmarks ?? []) {
+ if (b.mean === undefined) continue;
+ cases++;
+ means.set(`${groupName} :: ${b.name}`, b.mean);
+ }
+ }
+ }
+
+ const measured = { cases, ratios: {} };
+ const missing = [];
+ for (const m of METRICS) {
+ const num = means.get(`${m.group} :: ${m.of}`);
+ const den = means.get(`${m.group} :: ${m.over}`);
+ if (num === undefined || den === undefined || den === 0) {
+ missing.push(m.name);
+ continue;
+ }
+ measured.ratios[m.name] = round(num / den);
+ }
+
+ if (mode === '--update') {
+ if (missing.length) {
+ console.error('perf: cannot update — these metrics measured nothing:');
+ for (const n of missing) console.error(` - ${n}`);
+ process.exit(1);
+ }
+ writeFileSync(SNAPSHOT, `${JSON.stringify({
+ note: 'Generated by tools/perf-guard.mjs — run --update to accept changes.',
+ tolerance: DEFAULT_TOLERANCE,
+ ...measured,
+ }, null, 2)}\n`);
+ console.log(`perf: wrote ${SNAPSHOT.replace(`${ROOT}/`, '')} (${cases} cases, ${Object.keys(measured.ratios).length} metrics)`);
+ return;
+ }
+
+ if (!existsSync(SNAPSHOT)) {
+ console.error('perf: no snapshot. Create one: node tools/perf-guard.mjs --update');
+ process.exit(1);
+ }
+ const snap = JSON.parse(readFileSync(SNAPSHOT, 'utf8'));
+ const tol = snap.tolerance ?? DEFAULT_TOLERANCE;
+ const problems = [];
+ const improved = [];
+
+ // A benchmark that stopped running is the failure this guard exists for, so
+ // it is an error and not a note. More cases than the snapshot is someone
+ // adding benchmarks — worth accepting, never worth failing.
+ if (cases < snap.cases) {
+ problems.push(`coverage fell: ${cases} cases produced a number, snapshot has ${snap.cases}`
+ + ' — a benchmark file that fails to resolve is skipped silently by vitest');
+ }
+ for (const name of missing) problems.push(`metric measured nothing: ${name}`);
+
+ for (const [name, now] of Object.entries(measured.ratios)) {
+ const was = snap.ratios?.[name];
+ if (was === undefined) { improved.push(`new metric: ${name} = ${now}`); continue; }
+ const why = METRICS.find((m) => m.name === name)?.why ?? '';
+ if (now > was * (1 + tol)) {
+ problems.push(`${name}: ${was} → ${now} (+${pct(now / was - 1)})\n ${why}`);
+ } else if (now < was * (1 - tol)) {
+ improved.push(`${name}: ${was} → ${now} (${pct(now / was - 1)})`);
+ }
+ }
+
+ if (improved.length) {
+ console.log('perf: better than the snapshot (accept with --update):');
+ for (const i of improved) console.log(` ${i}`);
+ }
+ if (problems.length) {
+ console.error(`perf: ${problems.length} regression(s):`);
+ for (const p of problems) console.error(` - ${p}`);
+ console.error('\nIf this is intended, accept it: node tools/perf-guard.mjs --update');
+ process.exit(1);
+ }
+ console.log(`perf: ${Object.keys(measured.ratios).length} metrics within ${pct(tol)} of the snapshot; ${cases} cases measured.`);
+}
+
+// Declarations, not consts: main() runs at module top level (above), so an
+// arrow bound later would still be in its temporal dead zone.
+function round(n) { return Number(n.toPrecision(3)); }
+function pct(n) { return `${(n * 100).toFixed(0)}%`; }