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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
bench(net): the sweep says which build it measured, and what a crossover means
esengine927677581acd
diff --git a/bench/replication-dirty/README.md b/bench/replication-dirty/README.mdindex fea654854..5760109ff 100644--- a/bench/replication-dirty/README.md+++ b/bench/replication-dirty/README.md@@ -24,10 +24,10 @@ justifies nothing.## Running it```sh-node bench/replication-dirty/run.mjs # the 36-point matrix + recall-node bench/replication-dirty/run.mjs --quick # 1k only, for wiring changes-node bench/replication-dirty/completeness.mjs # which write paths report-node bench/replication-dirty/churn.mjs # storage over time+node bench/replication-dirty/run.mjs # the 36-point matrix + recall+node bench/replication-dirty/run.mjs --crossover # the 42-point sweep: where C stops paying+node bench/replication-dirty/run.mjs --quick # 1k only, for wiring changes+node bench/replication-dirty/completeness.mjs # which write paths report```Every point runs in its **own process**. Change tracking cannot be turned off@@ -79,6 +79,27 @@ workload: a shadow reads the final value and does not care how it got there; atracker is an observation and is only usable as an authoritative source if everylegal write path reports.+## What a crossover is, and what it is not++`--crossover` sweeps 1 / 30 / 50 / 70 / 85 / 95 / 100% dirty at 10k and 100k,+arms A/B/C. It answers ONE question: **is a replicated component worth enrolling+in change tracking at all?**++It is not a per-frame switch. Enrolling is not a sample-time flag — the write tax+is paid on every write once a component is tracked, whatever the sampler then+does. So a busy frame chooses between C and B, never back to A, and+`if (dirty > x) fullScan()` recovers nothing. PR6b measured C/B at 0.95–1.04 with+everything dirty: having paid for tracking, candidate pruning is close to free.++Read the tax against a budget as well as against the other arm. The report prints+each total as a share of one core (µs per simulated second, so 1e6 = 100%). Where+both arms are already past one core, `C/A > 1` does not make A usable — neither+arm is.++Both anchors are re-run on the same HEAD as the middle of the curve. Splicing a+1% number from one build onto a 70% number from another is how a benchmark+reports a mechanism change as a workload effect.+## Fidelity notes, and what this does not cover- The shadow is **seeded at registration**, as `registerEntity_` does: an@@ -92,3 +113,12 @@ legal write path reports.C++ mirror, and their tracking behaviour is not measured here.- Physics, UI layout and AOT writeback have their own write paths and are notcovered. None of them is assumed.+- The measurement phase only ever calls `world.set()`: no removal, no despawn,+ no churn. So this says nothing about **topology** discovery — a production+ sampler still finds component removal by comparing against the shadow, and+ owning a `Removed` reader per replicated component is a PR7 question, not one+ these numbers answer.+- `ReplicationServer.sample()` walks every replicated entity to find spawns and+ despawns BEFORE it looks for dirty fields. That scan is not in these arms, so+ a near-zero sample tax here is the dirty-discovery segment vanishing, not the+ whole sample.diff --git a/bench/replication-dirty/churn.mjs b/bench/replication-dirty/churn.mjsdeleted file mode 100644index 7eeb9f6bd..000000000--- a/bench/replication-dirty/churn.mjs+++ /dev/null@@ -1,115 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file Does a tracker-backed consumer have a resource debt in TIME?- *- * The timing matrix runs a fixed population and would never see this. A world- * that spawns, mutates and despawns forever is the ordinary case, and the- * tracker keeps per-entity rows plus a removed-entity buffer that only shrinks- * when a consumer calls `cleanRemovedBuffer`. If storage tracks total churn- * since process start rather than the recent window, no speedup makes the- * mechanism shippable.- *- * Two consumers, same workload:- * naive — reads the tracker, never cleans (what forgetting looks like)- * diligent — cleans behind its own sample tick (what a consumer must do)- *- * node bench/replication-dirty/churn.mjs- */-import path from 'node:path';-import { fileURLToPath } from 'node:url';-import { loadSdk, defineWorkloadComponents } from './workload.mjs';--const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');-const argv = process.argv.slice(2);-const flag = (n, d) => { const i = argv.indexOf(`--${n}`); return i >= 0 && argv[i + 1] !== undefined ? argv[i + 1] : d; };--const LIVE = Number(flag('live', '2000')); // steady-state population-const CHURN = Number(flag('churn', '50')); // entities replaced per sim tick-const TICKS = Number(flag('ticks', '3000'));-const REPL_EVERY = 3;--const sdk = await loadSdk(ROOT);--async function run(label, clean) {- const app = sdk.App.new();- const world = app.world;- const table = defineWorkloadComponents(sdk);- for (const entry of table) world.enableChangeTracking(entry.def);-- const live = [];- const spawnOne = (i) => {- const e = world.spawn();- world.insert(e, table[0].def, { x: i, y: 0, z: 0 });- world.insert(e, table[1].def, { hp: 100, mp: 50 });- return e;- };- for (let i = 0; i < LIVE; i++) live.push(spawnOne(i));-- const samples = [];- let since = -1;- let cursor = 0;-- for (let t = 0; t < TICKS; t++) {- // Retire and replace a slice: population is constant, churn is not.- for (let k = 0; k < CHURN; k++) {- const slot = cursor % live.length;- const old = live[slot];- // A replicated component leaving, then the whole entity leaving —- // both feed the removed buffer.- if (world.has(old, table[1].def)) world.remove(old, table[1].def);- world.despawn(old);- live[slot] = spawnOne(t * CHURN + k);- cursor++;- }- // And ordinary mutation on the survivors.- for (let k = 0; k < CHURN; k++) {- const e = live[(cursor + k * 7) % live.length];- if (world.valid(e)) world.set(e, table[0].def, { x: t, y: k, z: 0 });- }- world.advanceTick();-- if ((t + 1) % REPL_EVERY !== 0) continue;- // A consumer reads what changed…- for (const entry of table) {- if (world.anyChangedSince(entry.def, since)) world.getRemovedEntitiesSince(entry.def, since);- }- // …and, if it is diligent, tells the tracker it is done with them.- if (clean) world.cleanRemovedBuffer(world.getWorldTick());- since = world.getWorldTick() - 1;-- if ((t + 1) % 300 === 0) {- samples.push({ tick: t + 1, ...world.debugInfo?.().changes ?? sizesOf(world) });- }- }- return { label, samples };-}--/** `world.debugInfo()` may not exist on every build; read the tracker directly. */-function sizesOf(world) {- const changes = world.changes_ ?? null;- return changes && typeof changes.sizes === 'function' ? changes.sizes() : {};-}--const runs = [await run('naive (never cleans)', false), await run('diligent (cleans each sample)', true)];--console.log('=== tracker storage under churn ===');-console.log(` ${LIVE} live entities · ${CHURN} replaced per tick · ${TICKS} ticks`);-console.log(' A bounded consumer keeps storage proportional to the RECENT window.');-console.log(' Growth proportional to churn since start is a resource debt, and');-console.log(' disqualifies the mechanism however fast it samples.');-console.log('');-for (const r of runs) {- console.log(` ${r.label}`);- console.log(' tick addedRows changedRows removedRows');- for (const s of r.samples) {- console.log(` ${String(s.tick).padStart(6)} ${String(s.addedRows ?? '?').padStart(10)}`- + ` ${String(s.changedRows ?? '?').padStart(11)} ${String(s.removedRows ?? '?').padStart(12)}`);- }- const first = r.samples[0];- const last = r.samples[r.samples.length - 1];- const grew = (k) => (first?.[k] ?? 0) > 0 ? ((last?.[k] ?? 0) / first[k]).toFixed(2) : '—';- console.log(` growth first→last: added ×${grew('addedRows')}`- + ` changed ×${grew('changedRows')} removed ×${grew('removedRows')}`);- console.log('');-}diff --git a/bench/replication-dirty/run.mjs b/bench/replication-dirty/run.mjsindex 447e918ab..59d1172de 100644--- a/bench/replication-dirty/run.mjs+++ b/bench/replication-dirty/run.mjs@@ -22,21 +22,28 @@ import { writeFileSync } from 'node:fs';import os from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { sdkIdentity } from './workload.mjs';const HERE = path.dirname(fileURLToPath(import.meta.url));const ROOT = path.resolve(HERE, '..', '..');const ARM = path.join(HERE, 'arm.mjs');const QUICK = process.argv.includes('--quick');--const ARMS = ['A', 'B', 'C', 'D'];+// The crossover sweep: where does the candidate architecture stop paying? Two+// sizes worth running and seven dirty rates, with this HEAD's OWN 1% and 100%+// anchors — a curve must not be spliced from two different builds.+const CROSSOVER = process.argv.includes('--crossover');++// D is a counterfactual ceiling and PR6b already disqualified it: the tracker is+// not an authority, so shadow verify stays. It is not run in the sweep.+const ARMS = CROSSOVER ? ['A', 'B', 'C'] : ['A', 'B', 'C', 'D'];const ARM_MEANING = {A: 'tracking OFF, full shadow (today\'s production)',B: 'tracking ON, full shadow (the write tax, alone)',C: 'tracking ON, candidates+verify(the candidate architecture)',D: 'tracking ON, candidates only (COUNTERFACTUAL CEILING)',};-const ENTITY_COUNTS = QUICK ? [1000] : [1000, 10000, 100000];-const DIRTY_RATES = [0, 0.01, 1];+const ENTITY_COUNTS = QUICK ? [1000] : CROSSOVER ? [10000, 100000] : [1000, 10000, 100000];+const DIRTY_RATES = CROSSOVER ? [0.01, 0.3, 0.5, 0.7, 0.85, 0.95, 1] : [0, 0.01, 1];const FIXED = {simHz: 60, replHz: 20,warmup: QUICK ? 60 : 300,@@ -50,7 +57,23 @@ const FIXED = {*/const VERIFY_POINTS = QUICK? [[1000, 0.01]]- : [[1000, 0], [1000, 0.01], [1000, 1], [10000, 0], [10000, 0.01], [10000, 1], [100000, 0.01]];+ : CROSSOVER+ ? [[10000, 0.3], [10000, 0.95], [100000, 0.5]]+ : [[1000, 0], [1000, 0.01], [1000, 1], [10000, 0], [10000, 0.01], [10000, 1], [100000, 0.01]];++/**+ * Build the SDK once, here, rather than letting 42 workers each discover the+ * artifact is stale. The arms still refuse a stale one on their own — this is+ * the convenience, that is the guard.+ */+function buildSdkOnce() {+ const built = spawnSync('pnpm', ['--filter', './sdk', 'build'],+ { encoding: 'utf8', cwd: ROOT, maxBuffer: 1 << 24 });+ if (built.status !== 0) {+ console.error(built.stderr || built.stdout);+ throw new Error('the SDK build failed; nothing was measured');+ }+}function runPoint(arm, entities, dirty, verify) {const args = [@@ -70,6 +93,8 @@ function runPoint(arm, entities, dirty, verify) {return result;}+buildSdkOnce();+const points = [];const total = ENTITY_COUNTS.length * DIRTY_RATES.length * ARMS.length + VERIFY_POINTS.length;let done = 0;@@ -143,7 +168,7 @@ const round = (v) => Math.round(v);for (const entities of ENTITY_COUNTS) {for (const dirty of DIRTY_RATES) {say(` ${entities} entities · ${dirty * 100}% dirty`);- say(` arm write sample total B/A C/B C/A alloc KB/s GC`);+ say(` arm write sample total 1 core B/A C/B C/A alloc KB/s GC`);const a = at('A', entities, dirty);for (const arm of ARMS) {const p = at(arm, entities, dirty);@@ -153,7 +178,9 @@ for (const entities of ENTITY_COUNTS) {: arm === 'B' ? [ratio(p.totalTaxUsPerSimSecond, a.totalTaxUsPerSimSecond), '—', '—']: arm === 'C' ? ['—', ratio(p.totalTaxUsPerSimSecond, b.totalTaxUsPerSimSecond), ratio(p.totalTaxUsPerSimSecond, a.totalTaxUsPerSimSecond)]: ['—', '—', ratio(p.totalTaxUsPerSimSecond, a.totalTaxUsPerSimSecond)];- say(` ${arm} ${pad(round(p.writeTaxUsPerSimSecond), 8)} ${pad(round(p.sampleTaxUsPerSimSecond), 11)} ${pad(round(p.totalTaxUsPerSimSecond), 11)}`+ // Per simulated second, so µs/s IS the share of one core: 1e6 = 100%.+ const core = `${(p.totalTaxUsPerSimSecond / 1e4).toFixed(1)}%`;+ say(` ${arm} ${pad(round(p.writeTaxUsPerSimSecond), 8)} ${pad(round(p.sampleTaxUsPerSimSecond), 11)} ${pad(round(p.totalTaxUsPerSimSecond), 11)} ${pad(core, 7)}`+ ` ${pad(cols[0], 6)} ${pad(cols[1], 6)} ${pad(cols[2], 6)}`+ ` ${pad(round(p.heapDeltaBytes / 1024 / p.simSeconds), 10)} ${pad(p.gcCount, 4)}`);}@@ -166,6 +193,16 @@ say(' B/A what does turning tracking on cost the WRITE path, alone?');say(' C/B having paid that, how much scan does candidate pruning save?');say(' C/A is the whole architecture worth switching production to?');say('');+say(' A crossover is NOT a per-frame switch. Tracking is enrollment, not a');+say(' sample-time flag: once a component is enrolled the write tax is paid');+say(' whatever the sampler then does, so a busy frame chooses between C and B,');+say(' never back to A. `if (dirty > x) fullScan()` does not recover A.');+say(' The question the sweep answers is whether a replicated component is');+say(' worth ENROLLING at all.');+say('');+say(' Read the tax beside the budget, not only the ratio: where both arms are');+say(' already past one core, C/A > 1 does not make A a usable option.');+say('');say(recallClean? 'RECALL: complete at every point measured.': 'RECALL: INCOMPLETE — the tracker missed changes a full scan found.'@@ -173,7 +210,8 @@ say(recallClean// A quick run writes its own file: it is 1k-only and must never be mistaken// for — or overwrite — the matrix everyone reads.-const out = path.join(HERE, QUICK ? 'results.quick.json' : 'results.json');+const out = path.join(HERE, QUICK ? 'results.quick.json'+ : CROSSOVER ? 'results.crossover.json' : 'results.json');// A benchmark artifact that does not say what ran it is a number without units.const machine = {node: process.version,@@ -183,7 +221,9 @@ const machine = {totalMemGB: Math.round(os.totalmem() / 1024 ** 3),ranAt: new Date().toISOString(),};-writeFileSync(out, `${JSON.stringify({ machine, fixed: FIXED, points, verifies, parity, recallClean }, null, 2)}+writeFileSync(out, `${JSON.stringify({+ machine, build: sdkIdentity(ROOT), fixed: FIXED, points, verifies, parity, recallClean,+}, null, 2)}`);say('');say(`raw results: ${path.relative(ROOT, out)}`);diff --git a/bench/replication-dirty/workload.mjs b/bench/replication-dirty/workload.mjsindex d41939769..58e587fdf 100644--- a/bench/replication-dirty/workload.mjs+++ b/bench/replication-dirty/workload.mjs@@ -12,13 +12,49 @@* locality the real thing would not have.*/import { pathToFileURL } from 'node:url';+import { createHash } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { readdirSync, readFileSync, statSync } from 'node:fs';import path from 'node:path';const STRIDE = 7919; // coprime with every entity count used here-/** Load the SDK's headless build from a repo checkout. */+/** The newest hand-written .ts under `dir`, in epoch ms. */+function newestSource(dir) {+ let newest = 0;+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'node_modules' || entry.name === 'dist') continue;+ const full = path.join(dir, entry.name);+ newest = Math.max(newest, entry.isDirectory() ? newestSource(full)+ : entry.name.endsWith('.ts') ? statSync(full).mtimeMs : 0);+ }+ return newest;+}++/**+ * What was actually measured: the commit, and the artifact the arms imported.+ * A benchmark cannot tell a stale build from a fast one — it just reports very+ * stable numbers for yesterday's code — so the identity ships with the result.+ */+export function sdkIdentity(root) {+ const entry = path.join(root, 'sdk', 'dist', 'index.node.js');+ const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();+ const dirty = execFileSync('git', ['status', '--porcelain'], { cwd: root, encoding: 'utf8' }).trim();+ return {+ gitHead: head,+ workingTreeClean: dirty.length === 0,+ sdkArtifactSha256: createHash('sha256').update(readFileSync(entry)).digest('hex').slice(0, 16),+ sdkBuiltAt: new Date(statSync(entry).mtimeMs).toISOString(),+ };+}++/** Load the SDK's headless build, refusing one older than the sources it is built from. */export async function loadSdk(root) {const entry = path.join(root, 'sdk', 'dist', 'index.node.js');+ if (newestSource(path.join(root, 'sdk', 'src')) > statSync(entry).mtimeMs) {+ throw new Error('sdk/dist is older than sdk/src — this run would measure the previous'+ + ' commit. Build it with `pnpm --filter ./sdk build`.');+ }return import(pathToFileURL(entry).href);}