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): what the interest path's C x E is actually spent on
esenginead6cab3bae28
diff --git a/bench/replication-interest/.gitignore b/bench/replication-interest/.gitignorenew file mode 100644index 000000000..fb02f00c8--- /dev/null+++ b/bench/replication-interest/.gitignore@@ -0,0 +1,2 @@+results.quick.json+.sweep-*.jsonldiff --git a/bench/replication-interest/README.md b/bench/replication-interest/README.mdnew file mode 100644index 000000000..9b6d925bb--- /dev/null+++ b/bench/replication-interest/README.md@@ -0,0 +1,79 @@+# Interest path decomposition++With the registry's O(E) gone (N1.5b), `sampleWithInterest_` is what is left. It+costs C × E, and this measures **which of its passes spends that** — production+is untouched.++## The three passes, and why two of them are the same question++Per ready connection, over every replicated entity:++| pass | what it asks | where it lives |+|---|---|---|+| **anchor** | which entities does this connection own, so its view has a place? | `radiusInterest` |+| **radius** | which candidates are near those anchors? | `radiusInterest` |+| **owner** | which owned entities did the policy cull that the server must put back? | `visibleFor_` |++`anchor` and `owner` are the same question — *what does this connection own* —+asked twice, each time by walking the whole population. The server asks it+again because the ownership invariant is its own and it does not delegate it.++## The arms++| | ownership | radius |+|---|---|---|+| **A** | scanned, twice, as shipped | full scan |+| **B** | answered from an index | full scan, unchanged |++B changes nothing else, so `B/A` is the price of not having an ownership index,+and what remains in B is the spatial problem alone.++## What it costs++`node bench/replication-interest/run.mjs`. B saw exactly what A saw, every+connection, every sample, at all three differential points.++| population | connections | A (share of one core) | B | B/A |+|---|---|---|---|---|+| 10k | 1 | 3% | 1% | 0.48 |+| 10k | 8 | 24% | 11% | 0.48 |+| 10k | 32 | 95% | 47% | 0.49 |+| 10k | 128 | **379%** | 189% | 0.50 |+| 100k | 1 | 53% | 18% | 0.33 |+| 100k | 8 | **428%** | 144% | 0.34 |+| 100k | 32 | **1700%** | 579% | 0.34 |++Entities visited per sample, which is the mechanism without this machine in it:++| | anchor | radius | owner |+|---|---|---|---|+| A @ 100k × 32 | 3,200,000 | 3,200,000 | 3,200,000 |+| B @ 100k × 32 | **32** | 3,200,000 | **32** |++## What that says about N2b++**Half the cost at 10k, two thirds at 100k, is ownership lookup — and none of it+needs a spatial index.** An index answers it in O(owned): 3.2 million visits+become 32.++So the order is settled: **ownership index first, spatial provider after.** Going+straight to a provider would remove anchors, radius and ownership in one change+and leave nobody able to say which part paid.++What is left in B is the real spatial problem, and it is still the larger half —+5.8 seconds per simulated second at 100k × 32. That is what a provider has to+attack, and it is worth attacking on its own terms rather than as a side effect.++## What this does not cover++- Position lives in a script component, not the builtin `Transform` the shipped+ default reads. A builtin read crosses the wasm boundary, so arm A is+ UNDERSTATED here and every ratio is conservative.+- One anchor per connection. `radiusInterest` allows several, and the radius+ pass is then `candidates × anchors` — this measures the floor of that pass.+- The per-connection dirty and removal filters are timed and counted but stay+ tiny at these rates. If a provider removes the interest query, `C × (D + R)`+ is the next thing to look at — measured, not guessed.+- Custom `position()` readers are why a provider cannot simply index everything:+ the server has no way to know when a caller's arbitrary function would return+ something new. That is a design constraint for N2b, not a cost measured here.diff --git a/bench/replication-interest/arm.mjs b/bench/replication-interest/arm.mjsnew file mode 100644index 000000000..71041fd5a--- /dev/null+++ b/bench/replication-interest/arm.mjs@@ -0,0 +1,121 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file One arm at one workload point, printing one JSON object.+ *+ * node bench/replication-interest/arm.mjs --arm A --entities 100000 --connections 32+ */+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ loadSdk, buildWorld, applyMovement, newStats, visibleForA, visibleForB, diffAndFilter,+} from './workload.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');+const argv = process.argv.slice(2);+const flag = (name, fallback) => {+ const i = argv.indexOf(`--${name}`);+ return i >= 0 && argv[i + 1] !== undefined ? argv[i + 1] : fallback;+};++const ARM = flag('arm', 'A');+const ENTITIES = Number(flag('entities', '100000'));+const CONNECTIONS = Number(flag('connections', '32'));+const ANCHORS = Number(flag('anchors', '1'));+/** Fraction of the population a connection should see; radius is solved for it. */+const VISIBLE = Number(flag('visible', '0.01'));+const MOVEMENT = Number(flag('movement', '0.01'));+const SIM_HZ = Number(flag('simHz', '60'));+const REPL_HZ = Number(flag('replHz', '20'));+const WARMUP = Number(flag('warmup', '60'));+const MEASURE = Number(flag('measure', '240'));+/** Arm B only: compare its visible set against arm A's, every connection, every sample. */+const VERIFY = argv.includes('--verify');++const REPL_EVERY = Math.round(SIM_HZ / REPL_HZ);+const sdk = await loadSdk(ROOT);+const app = sdk.App.new();+const world = app.world;+const ctx = buildWorld(sdk, world, {+ population: ENTITIES, connections: CONNECTIONS, anchorsPerConn: ANCHORS,+});++// The grid is `side × side` at one unit per cell, so a disc of radius r covers+// πr² cells: solve that for the requested fraction of the population.+const RADIUS = VISIBLE >= 1+ ? ctx.side * 2+ : Math.sqrt((VISIBLE * ENTITIES) / Math.PI);+const R2 = RADIUS * RADIUS;+const MOVE_COUNT = Math.round(ENTITIES * MOVEMENT);++const stats = newStats();+const previous = new Map();+for (let c = 0; c < CONNECTIONS; c++) previous.set(c, new Set());+const oracle = VERIFY ? new Map() : null;+if (oracle) for (let c = 0; c < CONNECTIONS; c++) oracle.set(c, new Set());++let mismatches = 0;+let samples = 0;+let totalNs = 0n;+let movedTotal = 0;++function sampleOnce(measuring) {+ const t0 = process.hrtime.bigint();+ const mt = process.hrtime.bigint();+ const candidates = [...ctx.entities];+ if (measuring) {+ stats.ns.materialize += process.hrtime.bigint() - mt;+ stats.visited.candidates += candidates.length;+ }+ // A sample's worth of dirty/removal rows, sized like a sparse world.+ const dirty = candidates.slice(0, Math.max(1, Math.round(ENTITIES * 0.01)));+ const removals = [];++ for (let c = 0; c < CONNECTIONS; c++) {+ const use = measuring ? stats : newStats();+ const visible = ARM === 'B'+ ? visibleForB(world, ctx, c, candidates, R2, use, ctx.owned)+ : visibleForA(world, ctx, c, candidates, R2, use, ctx.owned);+ if (VERIFY) {+ const truth = visibleForA(world, ctx, c, candidates, R2, newStats());+ if (truth.size !== visible.size) mismatches++;+ else { for (const e of truth) if (!visible.has(e)) { mismatches++; break; } }+ }+ diffAndFilter(visible, previous.get(c), dirty, removals, use);+ previous.set(c, visible);+ }+ if (measuring) {+ totalNs += process.hrtime.bigint() - t0;+ samples++;+ }+}++function run(count, measuring) {+ for (let t = 0; t < count; t++) {+ const tick = measuring ? WARMUP + t : t;+ movedTotal += applyMovement(world, ctx, tick, MOVE_COUNT);+ world.advanceTick();+ if ((tick + 1) % REPL_EVERY !== 0) continue;+ sampleOnce(measuring);+ }+}++run(WARMUP, false);+run(MEASURE, true);++const simSeconds = MEASURE / SIM_HZ;+const us = (ns) => Number(ns) / 1000;+const per = (v) => v / simSeconds;+process.stdout.write(`${JSON.stringify({+ arm: ARM, entities: ENTITIES, connections: CONNECTIONS, anchors: ANCHORS,+ visible: VISIBLE, movement: MOVEMENT, radius: RADIUS, verify: VERIFY,+ simSeconds, samples, mismatches, movedTotal,+ totalUsPerSimSecond: per(us(totalNs)),+ segmentUsPerSimSecond: Object.fromEntries(+ Object.entries(stats.ns).map(([k, v]) => [k, per(us(v))]),+ ),+ visitedPerSample: Object.fromEntries(+ Object.entries(stats.visited).map(([k, v]) => [k, samples > 0 ? v / samples : 0]),+ ),+ visiblePerConnection: samples > 0 ? stats.visibleTotal / (samples * CONNECTIONS) : 0,+})}\n`);diff --git a/bench/replication-interest/results.json b/bench/replication-interest/results.jsonnew file mode 100644index 000000000..cacef12ca--- /dev/null+++ b/bench/replication-interest/results.json@@ -0,0 +1,658 @@+{+ "machine": {+ "node": "v24.15.0",+ "platform": "darwin 25.5.0",+ "cpu": "Apple M4",+ "cores": 10,+ "ranAt": "2026-09-05T02:37:42.333Z"+ },+ "build": {+ "gitHead": "7a26a773fd3002d871cccde1f1d75dd404273bde",+ "workingTreeClean": false,+ "sdkArtifactSha256": "335caf1aab1fbde7",+ "sdkBuiltAt": "2026-09-05T02:35:04.402Z"+ },+ "fixed": {+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "simHz": 60,+ "replHz": 20,+ "warmup": 60,+ "measure": 120+ },+ "points": [+ {+ "arm": "A",+ "entities": 10000,+ "connections": 1,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 29224.416,+ "segmentUsPerSimSecond": {+ "materialize": 109.3965,+ "anchor": 6684.0625,+ "radius": 13090.2715,+ "owner": 9145.9365,+ "enter": 27.7505,+ "leave": 22.105,+ "removeFilter": 2.581,+ "dirtyFilter": 65.4385+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 10000,+ "radius": 10000,+ "distanceTests": 10000,+ "owner": 10000,+ "enter": 25.3,+ "leave": 25.275,+ "removals": 0,+ "dirty": 100+ },+ "visiblePerConnection": 25.3+ },+ {+ "arm": "B",+ "entities": 10000,+ "connections": 1,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 14027.248,+ "segmentUsPerSimSecond": {+ "materialize": 147.7075,+ "anchor": 6.29,+ "radius": 13715.832,+ "owner": 6.126,+ "enter": 25.23,+ "leave": 18.186,+ "removeFilter": 1.377,+ "dirtyFilter": 64.957+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 1,+ "radius": 10000,+ "distanceTests": 10000,+ "owner": 1,+ "enter": 25.3,+ "leave": 25.275,+ "removals": 0,+ "dirty": 100+ },+ "visiblePerConnection": 25.3+ },+ {+ "arm": "A",+ "entities": 10000,+ "connections": 8,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 239482.3125,+ "segmentUsPerSimSecond": {+ "materialize": 142.959,+ "anchor": 48982.7035,+ "radius": 120946.833,+ "owner": 68337.5885,+ "enter": 293.4625,+ "leave": 217.689,+ "removeFilter": 6.372,+ "dirtyFilter": 347.873+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 80000,+ "radius": 80000,+ "distanceTests": 80000,+ "owner": 80000,+ "enter": 568.6,+ "leave": 568.65,+ "removals": 0,+ "dirty": 800+ },+ "visiblePerConnection": 71.075+ },+ {+ "arm": "B",+ "entities": 10000,+ "connections": 8,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 114669.165,+ "segmentUsPerSimSecond": {+ "materialize": 217.873,+ "anchor": 39.6905,+ "radius": 113383.122,+ "owner": 35.3335,+ "enter": 282.6935,+ "leave": 275.7535,+ "removeFilter": 4.811,+ "dirtyFilter": 294.52+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 8,+ "radius": 80000,+ "distanceTests": 80000,+ "owner": 8,+ "enter": 568.6,+ "leave": 568.65,+ "removals": 0,+ "dirty": 800+ },+ "visiblePerConnection": 71.075+ },+ {+ "arm": "A",+ "entities": 10000,+ "connections": 32,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 945579.8535,+ "segmentUsPerSimSecond": {+ "materialize": 650.7915,+ "anchor": 194014.6655,+ "radius": 472196.2115,+ "owner": 275682.957,+ "enter": 965.0975,+ "leave": 737.141,+ "removeFilter": 20.666,+ "dirtyFilter": 850.5325+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 320000,+ "radius": 320000,+ "distanceTests": 320000,+ "owner": 320000,+ "enter": 2884.675,+ "leave": 2887.7,+ "removals": 0,+ "dirty": 3200+ },+ "visiblePerConnection": 90.14609375+ },+ {+ "arm": "B",+ "entities": 10000,+ "connections": 32,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 466000.3105,+ "segmentUsPerSimSecond": {+ "materialize": 181.6445,+ "anchor": 146.5195,+ "radius": 462907.325,+ "owner": 119.7275,+ "enter": 859.605,+ "leave": 639.336,+ "removeFilter": 17.767,+ "dirtyFilter": 737.395+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 32,+ "radius": 320000,+ "distanceTests": 320000,+ "owner": 32,+ "enter": 2884.675,+ "leave": 2887.7,+ "removals": 0,+ "dirty": 3200+ },+ "visiblePerConnection": 90.14609375+ },+ {+ "arm": "A",+ "entities": 10000,+ "connections": 128,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 3786135.7485,+ "segmentUsPerSimSecond": {+ "materialize": 221.8125,+ "anchor": 781074.9235,+ "radius": 1901248.0455,+ "owner": 1090993.0055,+ "enter": 4116.001,+ "leave": 3218.257,+ "removeFilter": 87.3265,+ "dirtyFilter": 3582.117+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 1280000,+ "radius": 1280000,+ "distanceTests": 1280000,+ "owner": 1280000,+ "enter": 11707.575,+ "leave": 11712.375,+ "removals": 0,+ "dirty": 12800+ },+ "visiblePerConnection": 91.4654296875+ },+ {+ "arm": "B",+ "entities": 10000,+ "connections": 128,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 1885122.6245,+ "segmentUsPerSimSecond": {+ "materialize": 379.2285,+ "anchor": 653.808,+ "radius": 1871585.1415,+ "owner": 466.235,+ "enter": 3990.219,+ "leave": 3115.107,+ "removeFilter": 68.8425,+ "dirtyFilter": 3519.712+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 128,+ "radius": 1280000,+ "distanceTests": 1280000,+ "owner": 128,+ "enter": 11707.575,+ "leave": 11712.375,+ "removals": 0,+ "dirty": 12800+ },+ "visiblePerConnection": 91.4654296875+ },+ {+ "arm": "A",+ "entities": 100000,+ "connections": 1,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 17.841241161527712,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 180000,+ "totalUsPerSimSecond": 531316.6045,+ "segmentUsPerSimSecond": {+ "materialize": 2426.0405,+ "anchor": 154036.188,+ "radius": 188491.501,+ "owner": 185446.9375,+ "enter": 130.417,+ "leave": 105.6885,+ "removeFilter": 4.8515,+ "dirtyFilter": 450.6445+ },+ "visitedPerSample": {+ "candidates": 100000,+ "anchor": 100000,+ "radius": 100000,+ "distanceTests": 100000,+ "owner": 100000,+ "enter": 248.575,+ "leave": 248.55,+ "removals": 0,+ "dirty": 1000+ },+ "visiblePerConnection": 248.575+ },+ {+ "arm": "B",+ "entities": 100000,+ "connections": 1,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 17.841241161527712,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 180000,+ "totalUsPerSimSecond": 175157.48,+ "segmentUsPerSimSecond": {+ "materialize": 2380.938,+ "anchor": 25.792,+ "radius": 172035.417,+ "owner": 33.0625,+ "enter": 96.458,+ "leave": 77.998,+ "removeFilter": 2.187,+ "dirtyFilter": 362.3955+ },+ "visitedPerSample": {+ "candidates": 100000,+ "anchor": 1,+ "radius": 100000,+ "distanceTests": 100000,+ "owner": 1,+ "enter": 248.575,+ "leave": 248.55,+ "removals": 0,+ "dirty": 1000+ },+ "visiblePerConnection": 248.575+ },+ {+ "arm": "A",+ "entities": 100000,+ "connections": 8,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 17.841241161527712,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 180000,+ "totalUsPerSimSecond": 4279556.477,+ "segmentUsPerSimSecond": {+ "materialize": 2620.499,+ "anchor": 1205966.1,+ "radius": 1701799.848,+ "owner": 1361254.73,+ "enter": 2393.0425,+ "leave": 2106.497,+ "removeFilter": 22.7905,+ "dirtyFilter": 2436.5+ },+ "visitedPerSample": {+ "candidates": 100000,+ "anchor": 800000,+ "radius": 800000,+ "distanceTests": 800000,+ "owner": 800000,+ "enter": 7003.9,+ "leave": 7004.3,+ "removals": 0,+ "dirty": 8000+ },+ "visiblePerConnection": 875.4875+ },+ {+ "arm": "B",+ "entities": 100000,+ "connections": 8,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 17.841241161527712,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 180000,+ "totalUsPerSimSecond": 1443150.561,+ "segmentUsPerSimSecond": {+ "materialize": 2574.396,+ "anchor": 152.791,+ "radius": 1433315.374,+ "owner": 189.4245,+ "enter": 2157.189,+ "leave": 1887.125,+ "removeFilter": 16.6885,+ "dirtyFilter": 2269.165+ },+ "visitedPerSample": {+ "candidates": 100000,+ "anchor": 8,+ "radius": 800000,+ "distanceTests": 800000,+ "owner": 8,+ "enter": 7003.9,+ "leave": 7004.3,+ "removals": 0,+ "dirty": 8000+ },+ "visiblePerConnection": 875.4875+ },+ {+ "arm": "A",+ "entities": 100000,+ "connections": 32,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 17.841241161527712,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 180000,+ "totalUsPerSimSecond": 16995103.707,+ "segmentUsPerSimSecond": {+ "materialize": 2604.354,+ "anchor": 4617592.8325,+ "radius": 6734243.512,+ "owner": 5608367.383,+ "enter": 10209.3545,+ "leave": 8817.707,+ "removeFilter": 110.0845,+ "dirtyFilter": 9738.846+ },+ "visitedPerSample": {+ "candidates": 100000,+ "anchor": 3200000,+ "radius": 3200000,+ "distanceTests": 3200000,+ "owner": 3200000,+ "enter": 29498.15,+ "leave": 29500.35,+ "removals": 0,+ "dirty": 32000+ },+ "visiblePerConnection": 921.8171875+ },+ {+ "arm": "B",+ "entities": 100000,+ "connections": 32,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 17.841241161527712,+ "verify": false,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 180000,+ "totalUsPerSimSecond": 5787510.7505,+ "segmentUsPerSimSecond": {+ "materialize": 2944.686,+ "anchor": 371.215,+ "radius": 5753446.935,+ "owner": 452.8105,+ "enter": 9844.168,+ "leave": 8796.4055,+ "removeFilter": 77.83,+ "dirtyFilter": 9738.522+ },+ "visitedPerSample": {+ "candidates": 100000,+ "anchor": 32,+ "radius": 3200000,+ "distanceTests": 3200000,+ "owner": 32,+ "enter": 29498.15,+ "leave": 29500.35,+ "removals": 0,+ "dirty": 32000+ },+ "visiblePerConnection": 921.8171875+ }+ ],+ "verifies": [+ {+ "arm": "B",+ "entities": 10000,+ "connections": 8,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": true,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 361977.1245,+ "segmentUsPerSimSecond": {+ "materialize": 218.0825,+ "anchor": 87.8305,+ "radius": 120327.145,+ "owner": 44.484,+ "enter": 351.9975,+ "leave": 284.9925,+ "removeFilter": 7.7735,+ "dirtyFilter": 458.6525+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 8,+ "radius": 80000,+ "distanceTests": 80000,+ "owner": 8,+ "enter": 568.6,+ "leave": 568.65,+ "removals": 0,+ "dirty": 800+ },+ "visiblePerConnection": 71.075+ },+ {+ "arm": "B",+ "entities": 10000,+ "connections": 128,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 5.641895835477563,+ "verify": true,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 18000,+ "totalUsPerSimSecond": 5719760.856,+ "segmentUsPerSimSecond": {+ "materialize": 214.813,+ "anchor": 1205.1725,+ "radius": 1900284.463,+ "owner": 501.386,+ "enter": 4270.3745,+ "leave": 3225.854,+ "removeFilter": 96.433,+ "dirtyFilter": 3650.7565+ },+ "visitedPerSample": {+ "candidates": 10000,+ "anchor": 128,+ "radius": 1280000,+ "distanceTests": 1280000,+ "owner": 128,+ "enter": 11707.575,+ "leave": 11712.375,+ "removals": 0,+ "dirty": 12800+ },+ "visiblePerConnection": 91.4654296875+ },+ {+ "arm": "B",+ "entities": 100000,+ "connections": 8,+ "anchors": 1,+ "visible": 0.01,+ "movement": 0.01,+ "radius": 17.841241161527712,+ "verify": true,+ "simSeconds": 2,+ "samples": 40,+ "mismatches": 0,+ "movedTotal": 180000,+ "totalUsPerSimSecond": 5945148.4395,+ "segmentUsPerSimSecond": {+ "materialize": 2664.0425,+ "anchor": 564.2105,+ "radius": 1554616.209,+ "owner": 302.795,+ "enter": 2384.454,+ "leave": 2113.6865,+ "removeFilter": 22.602,+ "dirtyFilter": 2500.673+ },+ "visitedPerSample": {+ "candidates": 100000,+ "anchor": 8,+ "radius": 800000,+ "distanceTests": 800000,+ "owner": 8,+ "enter": 7003.9,+ "leave": 7004.3,+ "removals": 0,+ "dirty": 8000+ },+ "visiblePerConnection": 875.4875+ }+ ],+ "differentialClean": true+}diff --git a/bench/replication-interest/run.mjs b/bench/replication-interest/run.mjsnew file mode 100644index 000000000..8920a662c--- /dev/null+++ b/bench/replication-interest/run.mjs@@ -0,0 +1,173 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Where the interest path's C × E actually goes.+ *+ * Phase 1 of N2a: decomposition, not optimisation. Production is untouched —+ * this reproduces `sampleWithInterest_` segment by segment so each pass can be+ * timed and counted on its own, and adds ONE alternative (an ownership index)+ * to price the two passes that exist only to answer "what does this connection+ * own".+ *+ * node bench/replication-interest/run.mjs+ * node bench/replication-interest/run.mjs --quick+ */+import { spawnSync } from 'node:child_process';+import { appendFileSync, existsSync, readFileSync, unlinkSync, 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'];+const ARM_MEANING = {+ A: 'as shipped: anchors, radius and ownership all scan every candidate',+ B: 'ownership index: only the two owner passes change',+};+/** 100k stops at 32 connections: arm A there is already 30 billion visits. */+const POINTS = QUICK+ ? [[10000, 1], [10000, 8]]+ : [[10000, 1], [10000, 8], [10000, 32], [10000, 128],+ [100000, 1], [100000, 8], [100000, 32]];+const FIXED = {+ anchors: 1, visible: 0.01, movement: 0.01,+ simHz: 60, replHz: 20, warmup: QUICK ? 12 : 60, measure: QUICK ? 30 : 120,+};+const VERIFY_POINTS = QUICK ? [[10000, 8]] : [[10000, 8], [10000, 128], [100000, 8]];++const CACHE = path.join(HERE, `.sweep-${QUICK ? 'quick' : 'matrix'}.jsonl`);+const buildId = () => sdkIdentity(ROOT).sdkArtifactSha256;++function loadCache() {+ const done = new Map();+ if (!existsSync(CACHE)) return done;+ for (const line of readFileSync(CACHE, 'utf8').split('\n').filter(Boolean)) {+ const row = JSON.parse(line);+ if (row.build !== buildId()) { unlinkSync(CACHE); return new Map(); }+ done.set(row.key, row.result);+ }+ return done;+}++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, connections, verify) {+ const args = [+ ARM, '--arm', arm, '--entities', String(entities), '--connections', String(connections),+ '--anchors', String(FIXED.anchors), '--visible', String(FIXED.visible),+ '--movement', String(FIXED.movement), '--simHz', String(FIXED.simHz),+ '--replHz', String(FIXED.replHz), '--warmup', String(FIXED.warmup),+ '--measure', String(FIXED.measure),+ ];+ if (verify) args.push('--verify');+ const run = spawnSync(process.execPath, args, { encoding: 'utf8', cwd: ROOT, maxBuffer: 1 << 24 });+ if (run.status !== 0) {+ console.error(run.stderr || run.stdout);+ throw new Error(`arm ${arm} @ ${entities}/${connections} exited ${run.status}`);+ }+ return JSON.parse(run.stdout);+}++const measured = loadCache();+function measure(arm, entities, connections, verify) {+ const key = `${arm}/${entities}/${connections}/${verify ? 'v' : 'p'}`;+ const cached = measured.get(key);+ if (cached) return { result: cached, fresh: false };+ const result = runPoint(arm, entities, connections, verify);+ appendFileSync(CACHE, `${JSON.stringify({ build: buildId(), key, result })}\n`);+ measured.set(key, result);+ return { result, fresh: true };+}++buildSdkOnce();++const points = [];+const total = POINTS.length * ARMS.length + VERIFY_POINTS.length;+let done = 0;+for (const [entities, connections] of POINTS) {+ for (const arm of ARMS) {+ const { result, fresh } = measure(arm, entities, connections, false);+ process.stderr.write(`[${++done}/${total}] arm ${arm} ${entities} ${connections} conn`+ + `${fresh ? '' : ' (cached)'}\n`);+ points.push(result);+ }+}+const verifies = [];+for (const [entities, connections] of VERIFY_POINTS) {+ const { result, fresh } = measure('B', entities, connections, true);+ process.stderr.write(`[${++done}/${total}] differential ${entities} ${connections} conn`+ + `${fresh ? '' : ' (cached)'}\n`);+ verifies.push(result);+}++const at = (arm, e, c) => points.find((p) => p.arm === arm && p.entities === e && p.connections === c);+const lines = [];+const say = (s = '') => { lines.push(s); console.log(s); };+const round = (v) => Math.round(v);+const pad = (v, w) => String(v).padStart(w);++say('=== interest path: where C x E goes ===');+say('');+for (const arm of ARMS) say(` ${arm} ${ARM_MEANING[arm]}`);+say('');+const clean = verifies.every((v) => v.mismatches === 0);+say(clean+ ? ` DIFFERENTIAL: B saw exactly what A saw, every connection, every sample (${verifies.length} point(s)).`+ : ' DIFFERENTIAL: MISMATCHED — the ownership index changed what a connection sees.');+say('');+say(' us per simulated second, and the share of one core');+say(' pop conn arm total 1 core anchor radius owner B/A');+for (const [entities, connections] of POINTS) {+ const a = at('A', entities, connections);+ for (const arm of ARMS) {+ const p = at(arm, entities, connections);+ const s = p.segmentUsPerSimSecond;+ const ratio = arm === 'B' ? (p.totalUsPerSimSecond / a.totalUsPerSimSecond).toFixed(2) : '—';+ say(` ${pad(entities, 7)} ${pad(connections, 5)} ${arm} ${pad(round(p.totalUsPerSimSecond), 11)}`+ + ` ${pad(`${(p.totalUsPerSimSecond / 1e4).toFixed(0)}%`, 7)}`+ + ` ${pad(round(s.anchor), 8)} ${pad(round(s.radius), 9)} ${pad(round(s.owner), 9)} ${pad(ratio, 6)}`);+ }+}+say('');+say(' entities visited per sample (the mechanism, without this machine in it)');+say(' pop conn arm anchor radius owner distance');+for (const [entities, connections] of POINTS) {+ for (const arm of ARMS) {+ const v = at(arm, entities, connections).visitedPerSample;+ say(` ${pad(entities, 7)} ${pad(connections, 5)} ${arm} ${pad(round(v.anchor), 10)}`+ + ` ${pad(round(v.radius), 10)} ${pad(round(v.owner), 10)} ${pad(round(v.distanceTests), 10)}`);+ }+}+say('');+say('--- WHAT THIS DECOMPOSES ---');+say(' anchor finding the entities this connection owns, to place its view');+say(' radius testing every candidate against those anchors');+say(' owner the server putting owned entities back, not trusting the policy');+say('');+say(' anchor and owner are the same question asked twice, both O(population).');+say(' B answers it from an index and changes nothing else — so B/A is the price');+say(' of NOT having one, and what is left in B is the spatial problem alone.');++const out = path.join(HERE, QUICK ? 'results.quick.json' : 'results.json');+writeFileSync(out, `${JSON.stringify({+ machine: {+ node: process.version, platform: `${os.platform()} ${os.release()}`,+ cpu: os.cpus()[0]?.model ?? 'unknown', cores: os.cpus().length,+ ranAt: new Date().toISOString(),+ },+ build: sdkIdentity(ROOT), fixed: FIXED, points, verifies, differentialClean: clean,+}, null, 2)}\n`);+say('');+say(`raw results: ${path.relative(ROOT, out)}`);diff --git a/bench/replication-interest/workload.mjs b/bench/replication-interest/workload.mjsnew file mode 100644index 000000000..73898eae0--- /dev/null+++ b/bench/replication-interest/workload.mjs@@ -0,0 +1,236 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The interest path, reproduced segment by segment.+ *+ * `sampleWithInterest_` costs C × E and the question is which of its passes+ * spends that. So each one is timed and COUNTED separately rather than wrapped+ * in one timer: a visited count says what the mechanism does, where a wall time+ * says what this machine did today.+ *+ * Position lives in a script component rather than the builtin `Transform` the+ * shipped default reads. That understates arm A — a builtin read crosses the+ * wasm boundary — so every ratio here is conservative about how much the full+ * scans cost.+ */+import { pathToFileURL } from 'node:url';+import { readdirSync, statSync } from 'node:fs';+import path from 'node:path';++export { sdkIdentity } from '../replication-dirty/workload.mjs';++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') && !entry.name.endsWith('.generated.ts')+ ? statSync(full).mtimeMs : 0);+ }+ return newest;+}++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);+}++export function defineComponents(sdk) {+ return {+ Pos: sdk.defineComponent('IPos', { x: 0, y: 0, z: 0 }, { replicatedFields: ['x', 'y', 'z'] }),+ Owned: sdk.defineComponent('IOwned', { owner: -1 }, { replicatedFields: ['owner'] }),+ };+}++/** Every segment's clock and its visit count, in one place so nothing is untimed. */+export function newStats() {+ return {+ ns: {+ materialize: 0n, anchor: 0n, radius: 0n, owner: 0n,+ enter: 0n, leave: 0n, removeFilter: 0n, dirtyFilter: 0n,+ },+ visited: {+ candidates: 0, anchor: 0, radius: 0, distanceTests: 0, owner: 0,+ enter: 0, leave: 0, removals: 0, dirty: 0,+ },+ visibleTotal: 0,+ };+}++/**+ * A square world of `population` entities on a uniform grid, and `connections`+ * each owning `anchorsPerConn` of them. Owners are spread across the grid so a+ * connection's view is a real neighbourhood rather than a corner.+ */+export function buildWorld(sdk, world, { population, connections, anchorsPerConn }) {+ const { Pos, Owned } = defineComponents(sdk);+ const side = Math.ceil(Math.sqrt(population));+ const entities = new Array(population);+ for (let i = 0; i < population; i++) {+ const e = world.spawn();+ world.insert(e, Pos, { x: i % side, y: Math.floor(i / side), z: 0 });+ world.insert(e, Owned, { owner: -1 });+ entities[i] = e;+ }+ const owned = new Map();+ const stride = Math.max(1, Math.floor(population / (connections * anchorsPerConn)));+ let at = 0;+ for (let c = 0; c < connections; c++) {+ const mine = [];+ for (let k = 0; k < anchorsPerConn; k++) {+ const e = entities[(at * stride) % population];+ at++;+ world.set(e, Owned, { owner: c });+ mine.push(e);+ }+ owned.set(c, mine);+ }+ return { entities, owned, side, Pos, Owned };+}++/** Move `count` entities one step. Deterministic in `tick`, as every probe here is. */+export function applyMovement(world, ctx, tick, count) {+ const { entities, Pos } = ctx;+ const n = entities.length;+ if (count <= 0) return 0;+ let moved = 0;+ let idx = (tick * 7919) % n;+ for (let k = 0; k < Math.min(count, n); k++) {+ const e = entities[idx];+ const p = world.get(e, Pos);+ world.update(e, Pos, (d) => { d.x = p.x + ((tick + k) % 3) - 1; });+ moved++;+ idx = (idx + 7919) % n;+ }+ return moved;+}++const positionOf = (world, Pos, e) => world.tryGet(e, Pos);++/**+ * Arm A: exactly what ships. Anchors are found by scanning the whole candidate+ * list, the radius test walks it again, and the server walks it a THIRD time to+ * put back entities the connection owns.+ */+export function visibleForA(world, ctx, connId, candidates, r2, stats) {+ const { Pos, Owned } = ctx;+ let t = process.hrtime.bigint();+ const anchors = [];+ for (const e of candidates) {+ stats.visited.anchor++;+ const own = world.tryGet(e, Owned);+ if (own?.owner !== connId) continue;+ const p = positionOf(world, Pos, e);+ if (p) anchors.push(p);+ }+ stats.ns.anchor += process.hrtime.bigint() - t;++ if (anchors.length === 0) return new Set(candidates);++ t = process.hrtime.bigint();+ const visible = radiusScan(world, ctx, candidates, anchors, r2, stats);+ stats.ns.radius += process.hrtime.bigint() - t;++ t = process.hrtime.bigint();+ for (const e of candidates) {+ stats.visited.owner++;+ if (visible.has(e)) continue;+ const own = world.tryGet(e, Owned);+ if (own?.owner === connId) visible.add(e);+ }+ stats.ns.owner += process.hrtime.bigint() - t;+ return visible;+}++/**+ * Arm B: the same radius scan, with an ownership index. Only the two passes+ * that exist to answer "what does this connection own" change — so B/A prices+ * exactly those, and nothing else.+ */+export function visibleForB(world, ctx, connId, candidates, r2, stats, ownedIndex) {+ const { Pos } = ctx;+ let t = process.hrtime.bigint();+ const anchors = [];+ for (const e of ownedIndex.get(connId) ?? []) {+ stats.visited.anchor++;+ const p = positionOf(world, Pos, e);+ if (p) anchors.push(p);+ }+ stats.ns.anchor += process.hrtime.bigint() - t;++ if (anchors.length === 0) return new Set(candidates);++ t = process.hrtime.bigint();+ const visible = radiusScan(world, ctx, candidates, anchors, r2, stats);+ stats.ns.radius += process.hrtime.bigint() - t;++ t = process.hrtime.bigint();+ for (const e of ownedIndex.get(connId) ?? []) {+ stats.visited.owner++;+ visible.add(e);+ }+ stats.ns.owner += process.hrtime.bigint() - t;+ return visible;+}++/** The radius pass both arms share: every candidate against every anchor. */+function radiusScan(world, ctx, candidates, anchors, r2, stats) {+ const { Pos } = ctx;+ const visible = new Set();+ for (const e of candidates) {+ stats.visited.radius++;+ const p = positionOf(world, Pos, e);+ if (!p) { visible.add(e); continue; }+ for (const a of anchors) {+ stats.visited.distanceTests++;+ const dx = p.x - a.x;+ const dy = p.y - a.y;+ const dz = (p.z ?? 0) - (a.z ?? 0);+ if (dx * dx + dy * dy + dz * dz <= r2) { visible.add(e); break; }+ }+ }+ return visible;+}++/** The per-connection work that follows the visibility set, timed separately. */+export function diffAndFilter(visible, previous, dirty, removals, stats) {+ let t = process.hrtime.bigint();+ const enters = [];+ for (const e of visible) {+ stats.visited.enter++;+ if (!previous.has(e)) enters.push(e);+ }+ stats.ns.enter += process.hrtime.bigint() - t;++ t = process.hrtime.bigint();+ const leaves = [];+ for (const e of previous) {+ stats.visited.leave++;+ if (!visible.has(e)) leaves.push(e);+ }+ stats.ns.leave += process.hrtime.bigint() - t;++ t = process.hrtime.bigint();+ let mineRemovals = 0;+ for (const r of removals) {+ stats.visited.removals++;+ if (visible.has(r)) mineRemovals++;+ }+ stats.ns.removeFilter += process.hrtime.bigint() - t;++ t = process.hrtime.bigint();+ let mineDirty = 0;+ for (const d of dirty) {+ stats.visited.dirty++;+ if (visible.has(d)) mineDirty++;+ }+ stats.ns.dirtyFilter += process.hrtime.bigint() - t;++ stats.visibleTotal += visible.size;+ return { enters, leaves, mineRemovals, mineDirty };+}