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
probe(net): push and pull are the same truth projected two ways, so choose per sample
esengine47fe715d4c22
diff --git a/bench/replication-routing/README.md b/bench/replication-routing/README.mdindex b6dfaf178..7d6e2e489 100644--- a/bench/replication-routing/README.md+++ b/bench/replication-routing/README.md@@ -100,6 +100,107 @@ leave events per sample across all 32 connections — the interest sets barely monce the world is steady, which is the same fact that makes the enter/leave DIFF(29,547 comparisons to find 12 events) look the way it does.+## N3b: routing the debt, four ways++`node bench/replication-routing/probe.mjs`. The same five workloads, but only the+ROUTING: all four arms consume one canonical truth — this sample's dirty rows,+its removals, and the shipped provider's real visibility — and must produce the+same plan before any time is believed.++| | how it gets a row to a connection |+|---|---|+| **A** | every connection walks every row — what ships |+| **P** | each affected ENTITY is handed to the connections that can see it |+| **L** | each connection asks its own view what happened to it |+| **H** | whichever of the two is smaller, from this sample's own counts |++Debt is merged per entity first: an entity with two dirty components and a+removal is one reverse lookup on the push side and one map probe on the pull+side, not three. The wire still carries removals before the delta.++The reverse index is the server's, not the provider's — `viewersByEntity` is the+projection of `conn.interest`, maintained from the enters and leaves the+visibility pass already produces.++### Visits++| workload | A | P | L | H |+|---|---|---|---|---|+| scattered mixed | 66,920 | **2,710** | 29,566 | 2,710 |+| clustered mixed | 66,920 | **2,385** | 15,683 | 2,385 |+| everything dirty | 3,200,000 | 129,509 | **29,509** | 29,509 |+| removals 10% | 352,000 | **14,078** | 29,481 | 14,078 |+| movement only | 32,000 | **1,243** | 29,444 | 1,243 |++### Microseconds, and what counts as a difference++`L2` is `L` again, by the same call from a second site. Two arms running+identical code came out **31% apart**, so nothing closer than that is a+difference this harness can see — and every conclusion below is outside it.++| workload | A | P | L | L2 | **H** | H picked |+|---|---|---|---|---|---|---|+| scattered mixed | 783.5 | 110.7 | 352.1 | 367.2 | **85.1** | push |+| clustered mixed | 720.8 | 43.5 | 103.4 | 94.8 | **42.2** | push |+| everything dirty | 37,434.2 | 6,353.1 | 3,872.4 | 2,966.1 | **3,090.7** | pull |+| removals 10% | 4,191.5 | 474.3 | 701.8 | 692.6 | **471.4** | push |+| movement only | 382.2 | 37.6 | 397.3 | 399.2 | **34.2** | push |++- **A costs 9 to 12 times the adaptive router at every point.**+- **The choice is worth making.** Push beats pull by 3.2x at the mixed workload;+ pull beats push by 1.6x with everything dirty. Both are outside the floor.+- **H picked the right side every sample of every point** — never the mixed+ workload by pull, never everything-dirty by push — and lands within the noise+ floor of the better arm each time.++### The chooser, and the one thing it must not do++```+U = affected entities F = their exact viewer fanout+S = total interest membership push while U + F < S+```++No rate, no average, no threshold. The 29,000 that N3a's counts crossed at is an+observation about one workload and does not belong in the engine.++But measuring `F` costs `U` reverse lookups, which is push's own dominant term —+so an exact chooser that always measures it pays to decide **not** to push. That+is not hypothetical: the first version ran 4x slower than pull with everything+dirty, having spent 20,000 lookups to conclude it should not do 20,000 lookups.++The fix is exact rather than a guess: `U + F >= U`, so once `U >= S` push cannot+win whatever the fanout turns out to be, and the answer is pull for free. Below+that, `U < S` bounds the probe by the pull it is being compared against. The+`how` column says which branch decided:++| workload | U + F | S | picked | how |+|---|---|---|---|---|+| scattered mixed | 2,703 | 29,558 | push | exact |+| clustered mixed | 2,366 | 15,669 | push | exact |+| everything dirty | 100,000 | 29,510 | pull | `U >= S` |+| removals 10% | 14,077 | 29,479 | push | exact |+| movement only | 1,231 | 29,431 | push | exact |++Scale changes the answer, which is the whole argument for deciding per sample:+at 20k entities and 8 connections the same `removals 10%` workload picks **pull**+(U = 2,000 against S = 1,341), and at 100k with 32 connections it picks push.++### The shapes, checked before any of it is timed++Seven cases where a router can be wrong in a way a total would hide, run as plain+inputs with no world at all — and the probe refuses to report a single time until+all four arms agree on every one:++an entity with several dirty components · dirty and a removal on the same entity ·+an entity that entered this sample (spawn carries its state, so it owes nothing+else) · an entity that left (nobody hears about it) · one entity visible to eight+connections · an entity nobody can see · nothing happened at all.++Plans are compared as row INDICES in order, which is the decoded wire: same+removals, same delta entries, same sequence. Push and pull both build their+buckets out of order and sort them — on the rows actually SENT, which is 598 at+the mixed workload against the 66,848 visits the sort replaces.+## What this does not cover- **Encoding is inside the totals and not separated.** It is proportional to what@@ -115,3 +216,10 @@ once the world is steady, which is the same fact that makes the enter/leave DIFFare arranged: 1.00 spread across the map, 8.10 packed into a thousandth of it.- Client apps are connected but not ticked during measurement. What is timed isthe server's own sample.+- **The N3b probe routes; it does not send.** Its arms are timed over the same+ inputs the server computes, but nothing is installed on a server and no bytes+ are encoded. What it answers is whether JavaScript's maps and sets overturn the+ crossover the counts predict — they do not, at these points.+- The probe's arm A is a transcription of `sampleWithInterest_`'s two filters,+ not the server running them. The absolute numbers for the shipped path are the+ section above, measured on the real server.diff --git a/bench/replication-routing/probe.mjs b/bench/replication-routing/probe.mjsnew file mode 100644index 000000000..1684fb26c--- /dev/null+++ b/bench/replication-routing/probe.mjs@@ -0,0 +1,320 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Does the routing crossover survive JavaScript's Map and Set?+ *+ * N3a said push wins while `U + F < S` and pull past it. That is a count. This+ * runs the two, and a chooser that decides per sample from those exact facts,+ * over the shipped provider's real visibility — and checks all four produce the+ * same plan before believing any of the times.+ *+ * Production is untouched: nothing here is installed on a server.+ *+ * node bench/replication-routing/probe.mjs+ */+import path from 'node:path';+import os from 'node:os';+import { fileURLToPath, pathToFileURL } from 'node:url';+import {+ mergeByEntity, routeCurrent, routePush, routePull, routeAdaptive, fanout,+} from './routers.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');+const { loadSdk, sdkIdentity } = await import(pathToFileURL(+ path.join(ROOT, 'bench/replication-interest/workload.mjs')).href);++// =============================================================================+// The shapes a router has to get right, before any of them is timed+// =============================================================================++/** A plan, as the wire would carry it: removals then delta, in row order. */+const shape = (plan) => `${plan.removals.join(',')}|${plan.delta.join(',')}`;+const plansAgree = (a, b) => {+ if (a.size !== b.size) return false;+ for (const [id, plan] of a) if (shape(plan) !== shape(b.get(id) ?? { removals: [], delta: [] })) return false;+ return true;+};++function runAll(conns, dirty, removals, entered, viewers) {+ const affected = mergeByEntity(dirty, removals);+ let membership = 0;+ for (const c of conns) membership += c.visible.size;+ const { rows } = fanout(affected, viewers);+ return {+ A: routeCurrent(conns, dirty, removals, entered),+ P: routePush(conns, dirty, removals, entered, rows),+ L: routePull(conns, dirty, removals, entered, affected),+ H: routeAdaptive(conns, dirty, removals, entered, affected, viewers, membership),+ };+}++/** The cases where a router can be wrong in a way a total would not show. */+function shapesHold() {+ const failures = [];+ const check = (name, conns, dirty, removals, entered, viewers) => {+ const r = runAll(conns, dirty, removals, entered, viewers);+ for (const arm of ['P', 'L', 'H']) {+ if (!plansAgree(r.A.out, r[arm].out)) failures.push(`${name}: ${arm} disagrees with A`);+ }+ };+ const conn = (id, visible) => ({ id, visible: new Set(visible) });+ const viewersOf = (pairs) => new Map(pairs.map(([e, ids]) => [e, new Set(ids)]));+ const noEnters = (ids) => new Map(ids.map((id) => [id, new Set()]));++ check('one entity, several dirty components',+ [conn(0, [7])],+ [{ entity: 7, netId: 7, componentId: 1 }, { entity: 7, netId: 7, componentId: 2 },+ { entity: 8, netId: 8, componentId: 1 }],+ [], noEnters([0]), viewersOf([[7, [0]], [8, []]]));++ check('dirty and a removal on the same entity',+ [conn(0, [7])],+ [{ entity: 7, netId: 7, componentId: 1 }],+ [{ entity: 7, netId: 7, componentId: 2 }],+ noEnters([0]), viewersOf([[7, [0]]]));++ check('an entity that entered this sample owes nothing extra',+ [conn(0, [7, 9])],+ [{ entity: 7, netId: 7, componentId: 1 }, { entity: 9, netId: 9, componentId: 1 }],+ [{ entity: 7, netId: 7, componentId: 2 }],+ new Map([[0, new Set([7])]]), viewersOf([[7, [0]], [9, [0]]]));++ check('an entity that left is not in anyone view',+ [conn(0, [9])],+ [{ entity: 7, netId: 7, componentId: 1 }],+ [{ entity: 7, netId: 7, componentId: 2 }],+ noEnters([0]), viewersOf([[7, []], [9, [0]]]));++ const eight = Array.from({ length: 8 }, (_, i) => conn(i, [7]));+ check('one entity, eight connections',+ eight,+ [{ entity: 7, netId: 7, componentId: 1 }], [],+ noEnters(eight.map((c) => c.id)), viewersOf([[7, [0, 1, 2, 3, 4, 5, 6, 7]]]));++ check('an entity nobody can see',+ [conn(0, [9])],+ [{ entity: 7, netId: 7, componentId: 1 }], [],+ noEnters([0]), viewersOf([[9, [0]]]));++ check('nothing happened at all', [conn(0, [9])], [], [], noEnters([0]), viewersOf([[9, [0]]]));+ return failures;+}++const failures = shapesHold();+if (failures.length > 0) {+ console.error('The routers do not agree on the shapes that matter:\n');+ for (const f of failures) console.error(` ${f}`);+ process.exit(1);+}++// =============================================================================+// The workload: the shipped provider's real visibility over a real world+// =============================================================================++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 ENTITIES = Number(flag('entities', '100000'));+const CONNECTIONS = Number(flag('connections', '32'));+const VISIBLE = Number(flag('visible', '0.01'));+const SAMPLES = Number(flag('samples', '12'));++const sdk = await loadSdk(ROOT);+const wasmDir = process.env.ESENGINE_WASM_DIR ?? path.join(ROOT, 'build', 'wasm', 'web');+const factory = (await import(pathToFileURL(path.join(wasmDir, 'esengine.js')).href)).default;+const engine = await factory({ locateFile: (f) => path.join(wasmDir, f) });++const app = sdk.App.new();+app.connectCpp(new engine.Registry(), engine, { strict: false });+const world = app.world;+const side = Math.ceil(Math.sqrt(ENTITIES));+const entities = new Array(ENTITIES);+for (let i = 0; i < ENTITIES; i++) {+ const e = world.spawn();+ world.insert(e, sdk.Transform, { position: { x: i % side, y: Math.floor(i / side), z: 0 } });+ entities[i] = e;+}+const RADIUS = Math.sqrt((VISIBLE * ENTITIES) / Math.PI);+const provider = sdk.radiusInterestProvider(RADIUS);++/** One anchor per connection; `cluster` decides how much of the map they share. */+function anchorsFor(cluster) {+ const span = Math.max(1, Math.floor(ENTITIES * cluster));+ const stride = Math.max(1, Math.floor(span / CONNECTIONS));+ return Array.from({ length: CONNECTIONS }, (_, c) => [entities[(c * stride) % ENTITIES]]);+}++/**+ * The reverse projection of `conn.interest`, maintained from enters and leaves —+ * the server's fact, not the provider's. N3a measured twelve events a sample+ * across thirty-two connections, which is what makes this affordable.+ */+function reverseIndex() {+ const viewers = new Map();+ return {+ viewers,+ enter(e, id) {+ let seen = viewers.get(e);+ if (!seen) { seen = new Set(); viewers.set(e, seen); }+ seen.add(id);+ },+ leave(e, id) {+ const seen = viewers.get(e);+ if (!seen) return;+ seen.delete(id);+ if (seen.size === 0) viewers.delete(e);+ },+ };+}++const POINTS = [+ { name: 'scattered mixed — 1% dirty, 0.1% removed', dirty: 0.01, removals: 0.001, cluster: 1 },+ { name: 'clustered mixed — same rates, packed', dirty: 0.01, removals: 0.001, cluster: 0.001 },+ { name: 'everything dirty', dirty: 1, removals: 0, cluster: 1 },+ { name: 'removals 10%', dirty: 0, removals: 0.1, cluster: 1 },+ { name: 'movement only — the floor is made of this', dirty: 0, removals: 0, cluster: 1 },+];+const MOVEMENT = 0.01;++function measure(point) {+ const anchors = anchorsFor(point.cluster);+ const conns = Array.from({ length: CONNECTIONS }, (_, id) => ({ id, visible: new Set(), interest: new Set() }));+ const index = reverseIndex();+ // L2 is L again, by the same call, from a second site. Two arms running+ // identical code are the only honest scale for "is that difference real".+ const arms = { A: { ns: 0, visits: 0, min: Infinity }, P: { ns: 0, visits: 0, min: Infinity },+ L: { ns: 0, visits: 0, min: Infinity }, H: { ns: 0, visits: 0, min: Infinity },+ L2: { ns: 0, visits: 0, min: Infinity } };+ const chose = { push: 0, pull: 0 };+ let mismatches = 0;+ let units = { push: 0, pull: 0 };++ for (let tick = 0; tick < SAMPLES + 4; tick++) {+ // — what the world did —+ const dirty = [];+ const removals = [];+ const touched = new Set();+ for (let k = 0, n = Math.round(ENTITIES * MOVEMENT); k < n; k++) {+ const e = entities[(tick * 7919 + k * 7919) % ENTITIES];+ world.update(e, sdk.Transform, (d) => { d.position.x += ((tick + k) % 3) - 1; });+ if (!touched.has(e)) { touched.add(e); dirty.push({ entity: e, netId: e, componentId: 0 }); }+ }+ for (let k = 0, n = Math.round(ENTITIES * point.dirty); k < n; k++) {+ const e = entities[(tick * 104729 + k * 104729) % ENTITIES];+ if (touched.has(e)) continue;+ touched.add(e);+ dirty.push({ entity: e, netId: e, componentId: 1 });+ }+ for (let k = 0, n = Math.round(ENTITIES * point.removals); k < n; k++) {+ const e = entities[(tick * 15485863 + k * 15485863) % ENTITIES];+ removals.push({ entity: e, netId: e, componentId: 1 });+ }++ // — what each connection can see, from the shipped provider —+ world.ensureTransformsComposed();+ const prepared = provider.prepare({+ world, entities, entityCount: entities.length,+ entered: tick === 0 ? entities : [], left: [], rechecked: [],+ });+ const entered = new Map();+ for (const c of conns) {+ const answer = prepared.query({ connectionId: c.id, owned: anchors[c.id] });+ const visible = answer === 'all' ? new Set(entities) : new Set(answer);+ for (const e of anchors[c.id]) visible.add(e);+ const enters = new Set();+ for (const e of visible) if (!c.interest.has(e)) { enters.add(e); index.enter(e, c.id); }+ for (const e of c.interest) if (!visible.has(e)) index.leave(e, c.id);+ c.visible = visible;+ c.interest = visible;+ entered.set(c.id, enters);+ }+ if (tick < 4) continue; // warm the world, the provider and the index++ // — the four routers over one truth, in a rotating order —+ const affected = mergeByEntity(dirty, removals);+ let membership = 0;+ for (const c of conns) membership += c.visible.size;+ // Rotated by the tick, so no arm always runs last into caches the ones+ // before it warmed. Rotating a fixed four times, as this did first, puts+ // the array back where it started and gave H a 20% head start.+ const order = ['A', 'P', 'L', 'H', 'L2'];+ for (let r = 0; r < tick % order.length; r++) order.push(order.shift());+ const results = {};+ for (const arm of order) {+ const t0 = process.hrtime.bigint();+ let out;+ if (arm === 'A') out = routeCurrent(conns, dirty, removals, entered);+ else if (arm === 'P') out = routePush(conns, dirty, removals, entered, fanout(affected, index.viewers).rows);+ else if (arm === 'L') out = routePull(conns, dirty, removals, entered, affected);+ else if (arm === 'L2') out = routePull(conns, dirty, removals, entered, affected);+ else out = routeAdaptive(conns, dirty, removals, entered, affected, index.viewers, membership);+ const dt = Number(process.hrtime.bigint() - t0);+ arms[arm].ns += dt;+ arms[arm].min = Math.min(arms[arm].min, dt / 1000);+ arms[arm].visits += out.visits;+ results[arm] = out;+ }+ for (const arm of ['P', 'L', 'H', 'L2']) if (!plansAgree(results.A.out, results[arm].out)) mismatches++;+ chose[results.H.chose]++;+ units = { push: results.H.pushUnits, pull: results.H.pullUnits, exact: results.H.exact };+ }++ const n = SAMPLES;+ return {+ name: point.name, mismatches, chose, units,+ arms: Object.fromEntries(Object.entries(arms).map(([k, v]) => [k, {+ usMin: v.min, usMean: v.ns / 1000 / n, visits: v.visits / n,+ }])),+ };+}++const rows = POINTS.map((p) => { process.stderr.write(`${p.name}\n`); return measure(p); });++const say = (s = '') => console.log(s);+const pad = (v, w) => String(v).padStart(w);+say('');+say(`=== routing one sample's debt (${ENTITIES} entities, ${CONNECTIONS} connections, ${VISIBLE * 100}% visible) ===`);+say('');+say(' A every connection walks every row — what ships');+say(' P every affected entity is handed to the connections that see it');+say(' L every connection asks its own view what happened');+say(' H whichever of the two is smaller, decided from this sample\'s own counts');+say('');+const dirtyPlans = rows.every((r) => r.mismatches === 0);+say(dirtyPlans+ ? ' Every arm produced the same plan for every connection, every sample —'+ + ' removals and delta rows, in order.'+ : ' PLANS DISAGREE — the numbers below mean nothing.');+say('');+say(' visits per sample');+say(' workload A P L H');+for (const r of rows) {+ say(` ${r.name.padEnd(42)} ${pad(Math.round(r.arms.A.visits), 8)} ${pad(Math.round(r.arms.P.visits), 9)}`+ + ` ${pad(Math.round(r.arms.L.visits), 9)} ${pad(Math.round(r.arms.H.visits), 9)}`);+}+say('');+say(' us per sample (fastest). L2 is L again — the scale for what counts as a difference.');+say(' workload A P L L2 H H picked');+for (const r of rows) {+ const best = Math.min(r.arms.P.usMin, r.arms.L.usMin);+ const picked = r.chose.push >= r.chose.pull ? 'push' : 'pull';+ const tail = `${picked} ${r.arms.H.usMin <= best * 1.1 ? '' : `(${(r.arms.H.usMin / best).toFixed(1)}x)`}`;+ say(` ${r.name.padEnd(42)} ${pad(r.arms.A.usMin.toFixed(1), 8)} ${pad(r.arms.P.usMin.toFixed(1), 9)}`+ + ` ${pad(r.arms.L.usMin.toFixed(1), 9)} ${pad(r.arms.L2.usMin.toFixed(1), 9)}`+ + ` ${pad(r.arms.H.usMin.toFixed(1), 9)} ${tail}`);+}+say('');+const noise = Math.max(...rows.map((r) => Math.abs(r.arms.L.usMin - r.arms.L2.usMin) / Math.min(r.arms.L.usMin, r.arms.L2.usMin)));+say(` L against L2, the same code twice: up to ${(noise * 100).toFixed(0)}% apart. Nothing`);+say(' closer than that is a difference this harness can see.');+say('');+say(' what H decided on');+say(' workload U + F S push/pull how');+for (const r of rows) {+ say(` ${r.name.padEnd(42)} ${pad(r.units.push, 6)} ${pad(r.units.pull, 6)}`+ + ` ${pad(`${r.chose.push}/${r.chose.pull}`, 8)} ${r.units.exact ? 'exact' : 'U >= S'}`);+}+say('');+say(` ${JSON.stringify({ ...sdkIdentity(ROOT), cpu: os.cpus()[0]?.model })}`);diff --git a/bench/replication-routing/routers.mjs b/bench/replication-routing/routers.mjsnew file mode 100644index 000000000..451c9a948--- /dev/null+++ b/bench/replication-routing/routers.mjs@@ -0,0 +1,147 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Four ways to get one sample's wire debt to the connections that want it.+ *+ * All four consume the SAME canonical truth — this sample's dirty rows, its+ * component removals, and each connection's visibility — and must produce the+ * same plan. What differs is only which side of the cross product they walk.+ *+ * Debt is merged per ENTITY first. An entity with two dirty components and a+ * removal is one reverse lookup, not three, and one `affected` lookup on the+ * pull side too — the wire still carries removals before the delta.+ */++/** This sample's debt, keyed by entity, in first-appearance order. */+export function mergeByEntity(dirty, removals) {+ const affected = new Map();+ const of = (e) => {+ let d = affected.get(e);+ if (!d) { d = { dirty: [], removals: [] }; affected.set(e, d); }+ return d;+ };+ for (let i = 0; i < removals.length; i++) of(removals[i].entity).removals.push(i);+ for (let i = 0; i < dirty.length; i++) of(dirty[i].entity).dirty.push(i);+ return affected;+}++const empty = () => ({ removals: [], delta: [] });+/** Row INDICES, so two plans compare exactly — including the order they went in. */+const order = (plan) => {+ plan.removals.sort((a, b) => a - b);+ plan.delta.sort((a, b) => a - b);+ return plan;+};++/**+ * A — what ships: every connection walks the whole removal list and the whole+ * dirty list, whatever fraction of the world it can see.+ */+export function routeCurrent(conns, dirty, removals, entered) {+ let visits = 0;+ const out = new Map();+ for (const c of conns) {+ const ent = entered.get(c.id);+ const plan = empty();+ for (let i = 0; i < removals.length; i++) {+ visits++;+ const r = removals[i];+ if (c.visible.has(r.entity) && !ent.has(r.entity)) plan.removals.push(i);+ }+ for (let i = 0; i < dirty.length; i++) {+ visits++;+ const d = dirty[i];+ if (!c.visible.has(d.entity) || ent.has(d.entity)) continue;+ plan.delta.push(i);+ }+ out.set(c.id, plan);+ }+ return { out, visits };+}++/**+ * The lookup both the chooser and the push router need: one reverse-index probe+ * per affected entity. Done once and handed on, as production would.+ */+export function fanout(affected, viewers) {+ const rows = [];+ let units = affected.size;+ for (const [e, debt] of affected) {+ const seen = viewers.get(e);+ rows.push([e, debt, seen]);+ units += seen ? seen.size : 0;+ }+ return { rows, units };+}++/**+ * P — push: each affected entity is handed to the connections that can see it.+ * The reverse lookup is paid even for an entity nobody watches, which is why the+ * unit count is `U + F` and not `F`.+ */+export function routePush(conns, dirty, removals, entered, rows) {+ let visits = 0;+ const out = new Map();+ for (const c of conns) out.set(c.id, empty());+ for (const [e, debt, seen] of rows) {+ visits++;+ if (!seen) continue;+ for (const id of seen) {+ visits++;+ if (entered.get(id).has(e)) continue;+ const plan = out.get(id);+ if (!plan) continue;+ for (const i of debt.removals) plan.removals.push(i);+ for (const i of debt.dirty) plan.delta.push(i);+ }+ }+ for (const plan of out.values()) order(plan);+ return { out, visits };+}++/**+ * L — pull: each connection asks its own view whether anything happened to it.+ * Bounded by total interest membership whatever the dirty rate is.+ */+export function routePull(conns, dirty, removals, entered, affected) {+ let visits = 0;+ const out = new Map();+ for (const c of conns) {+ const ent = entered.get(c.id);+ const plan = empty();+ for (const e of c.visible) {+ visits++;+ const debt = affected.get(e);+ if (!debt || ent.has(e)) continue;+ for (const i of debt.removals) plan.removals.push(i);+ for (const i of debt.dirty) plan.delta.push(i);+ }+ out.set(c.id, order(plan));+ }+ return { out, visits };+}++/**+ * H — whichever is smaller, decided from facts this sample already holds: the+ * unique affected entities plus their exact viewer fanout, against the total+ * interest membership. No rate, no average, no threshold.+ */+export function routeAdaptive(conns, dirty, removals, entered, affected, viewers, membership) {+ // Exact and free: `U + F >= U`, so more affected entities than interest+ // memberships means push cannot win whatever the fanout is. Measuring F to+ // learn that costs U reverse lookups, which is push's own dominant term.+ const U = affected.size;+ if (U >= membership) {+ const r = routePull(conns, dirty, removals, entered, affected);+ return { ...r, chose: 'pull', pushUnits: U, pullUnits: membership, exact: false };+ }+ const { rows, units } = fanout(affected, viewers);+ if (units < membership) {+ const r = routePush(conns, dirty, removals, entered, rows);+ return { ...r, chose: 'push', pushUnits: units, pullUnits: membership, exact: true };+ }+ const r = routePull(conns, dirty, removals, entered, affected);+ // The fanout probe is spent either way: it is what the choice is made on,+ // and it is bounded by U, which this branch already knows is under S.+ return { ...r, visits: r.visits + U, chose: 'pull', pushUnits: units, pullUnits: membership, exact: true };+}