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.

probe(net): a spawn payload answers three questions with one projection

esengine8636228c6431
diff --git a/bench/spawn-contract/README.md b/bench/spawn-contract/README.md
new file mode 100644
index 000000000..c8cef93fe
--- /dev/null
+++ b/bench/spawn-contract/README.md
@@ -0,0 +1,94 @@
+# What a spawn payload carries, and under which contract
+
+`spawnPayload_` builds its payload with `serializeEntityComponents` — the SCENE
+projection. Scene serialization answers *how is this entity restored in full*.
+Replication answers a different question: *which facts is this client authorized
+and declared to know*. They have been one function, so a third question has been
+answered by accident: *what does a ghost need in order to exist*.
+
+This probe measures nothing. It takes real spawn payloads off the wire and sorts
+their components into the contracts they would belong to, so the construction
+recipe that is currently implicit can be read.
+
+```
+node bench/spawn-contract/probe.mjs
+```
+
+It bundles `examples/multiplayer-arena/src/main.ts` against the same SDK
+instance and runs the certified example's own provisioning — not a transcription
+of its pawn, which would be a probe of this file rather than of the game.
+
+## The census: two pawns, eight components
+
+| component | contract | declared fields | fields sent |
+|---|---|---|---|
+| `Transform` | **replication table** | position, rotation, scale | position, rotation, scale, **worldPosition, worldRotation, worldScale** |
+| `Replicated` | **protocol metadata** | — | netId, owner |
+| `Sprite` | **undeclared** | — | **15** — texture, color, size, pivot, uvOffset, uvScale, layer, lit, flipX, flipY, tileSize, tileSpacing, parallax, material, enabled |
+| `Pawn` | **undeclared** | — | player, speed |
+
+Half the payload declares nothing, and the half that does sends twice the fields
+it declared. The public contract says an empty `replicatedFields` means the
+component is never replicated; on this path it is not true.
+
+## The four buckets, and which is which
+
+1. **Replication table** — `Transform`. This is the only part that is under a
+ declared contract, and even it over-sends: `worldPosition` and friends are the
+ composition's OUTPUT, which the client recomputes from the inputs it was sent.
+2. **Protocol metadata** — `Replicated`. `owner` is not a replicated field and
+ must not become one; it is protocol identity, like `netId`, which is already
+ a top-level field of the payload rather than a component.
+3. **Construction, and the client really does need it** — `Sprite`, `Pawn`. The
+ arena's own source says so out loud: *"full component payload — sprite color
+ included"* and *"`player` rides the spawn payload, so ghosts know who they
+ are"*. **The certified example depends on the hole.** These need an explicit
+ construction contract, not a silent one.
+4. **Server-only, and nothing should have sent it** — nothing in the arena, and
+ that is the point: there is no rule stopping it. An AI blackboard, a physics
+ scratch component, an unrevealed objective — none declares a replicated field,
+ none appears in the handshake schema, and every one of them transits today.
+
+## The gold: `sdk/tests/replication-spawn-contract.test.ts`
+
+One fixture separates all three layers at once:
+
+```
+Replicated protocol identity netId, owner
+Transform replication baseline declared fields only
+Sprite ghost construction client needs it; the authority's VALUE is not its source
+ServerSecret neither must never leave the authority
+```
+
+Two assertions hold today. Three are `it.fails` — they state the contract and
+record that it is currently broken, so a fix that lands without flipping them to
+`it` turns them red:
+
+| assertion | how it fails today |
+|---|---|
+| a component that declares nothing is not handed over | `ServerSecret` is on the ghost — `expected true to be false` |
+| fields a component did not declare are not handed over | `hidden: 9` arrived — `expected 9 to be +0` |
+| the ghost is built from a construction contract | the ghost took the authority's `Sprite.layer` 3, not a declared 7 |
+
+The third is what makes "the ghost has a Sprite" mean something: the archetype's
+value is deliberately not the authority's, so the assertion cannot pass by the
+payload having copied the server's one.
+
+## What this implies for N5b, before it is written
+
+**The arena has to change.** Today its pawn colours reach clients because the
+whole `Sprite` transits. Under an explicit contract the ghost's Sprite comes from
+its archetype, so the example must either key colour off the player index in the
+archetype, or declare `Sprite.color` replicated and mean it. Same for
+`Pawn.player`. That is a migration, and it is the correct one — it turns an
+accident the source already documents into a declaration.
+
+## What this does not cover
+
+- One project. The arena is the certified multiplayer example and the only game
+ in the tree that replicates entities it spawns at runtime.
+- Bucket 3 against bucket 4 is a judgement, not a measurement. The probe reports
+ `undeclared` and says which fields; deciding that `Sprite` is construction and
+ a blackboard is a leak is the design work this exists to inform.
+- It reads the JSON control plane. The binary delta plane already sends declared
+ fields only — the hole is the spawn, not the stream.
diff --git a/bench/spawn-contract/probe.mjs b/bench/spawn-contract/probe.mjs
new file mode 100644
index 000000000..a575ca514
--- /dev/null
+++ b/bench/spawn-contract/probe.mjs
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a spawn payload actually carries, and under which contract.
+ *
+ * `spawnPayload_` builds its payload with `serializeEntityComponents` — the
+ * SCENE projection, which answers "how is this entity restored in full". A wire
+ * projection answers a different question: "which facts is this client
+ * authorized and declared to know". The two have been the same code, so every
+ * non-transient component a server happens to hang on a replicated entity has
+ * been transiting, whether or not it declares a single replicated field.
+ *
+ * This does not measure anything. It takes real spawn payloads off the wire and
+ * sorts their components into the contracts they would belong to, so the
+ * construction recipe that is currently implicit can be read.
+ *
+ * node bench/spawn-contract/probe.mjs
+ */
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+const PROJECT = path.join(ROOT, 'examples', 'multiplayer-arena');
+const SDK = path.join(ROOT, 'sdk', 'dist', 'index.node.js');
+const WASM = process.env.ESENGINE_WASM_DIR ?? path.join(ROOT, 'build', 'wasm', 'web');
+const posix = (p) => p.split(path.sep).join('/');
+const work = mkdtempSync(path.join(tmpdir(), 'estella-spawn-'));
+
+/**
+ * The certified example's own gameplay, bundled against the same SDK instance:
+ * two component registries would make the handshake reject the server's own
+ * client, and a transcription of the pawn would be a probe of this file rather
+ * than of the game.
+ */
+writeFileSync(path.join(work, 'entry.ts'), `
+export * from 'esengine';
+import ${JSON.stringify(posix(path.join(PROJECT, 'src', 'main.ts')))};
+`);
+const out = path.join(work, 'bundle.mjs');
+const { build } = await import('esbuild');
+await build({
+ entryPoints: [path.join(work, 'entry.ts')],
+ outfile: out, bundle: true, format: 'esm', platform: 'node', target: 'node20',
+ logLevel: 'silent', alias: { esengine: SDK, 'esengine/node': SDK },
+});
+const sdk = await import(pathToFileURL(out).href);
+
+const factory = (await import(pathToFileURL(path.join(WASM, 'esengine.js')).href)).default;
+const engine = await factory({ locateFile: (f) => path.join(WASM, f) });
+
+const serverApp = sdk.App.new();
+serverApp.connectCpp(new engine.Registry(), engine, { strict: false });
+serverApp.addPlugin(sdk.replicationPlugin);
+sdk.flushPendingRegistrations(serverApp);
+serverApp.getResource(sdk.Net).startServer();
+
+const clientApp = sdk.App.new();
+clientApp.connectCpp(new engine.Registry(), engine, { strict: false });
+clientApp.addPlugin(sdk.replicationPlugin);
+const [ta, tb] = sdk.MemoryTransport.pair();
+
+/** Every spawn the authority actually put on the wire. */
+const spawned = [];
+const send = ta.send.bind(ta);
+ta.send = (d) => {
+ if (typeof d === 'string' && d.includes('repl:spawn')) {
+ try {
+ const msg = JSON.parse(d);
+ for (const e of msg?.d?.entities ?? []) spawned.push(e);
+ } catch { /* not ours */ }
+ }
+ send(d);
+};
+serverApp.getResource(sdk.Net).server.attachConnection(ta);
+await clientApp.getResource(sdk.Net).connect(tb, { interpolationDelayTicks: 0 });
+
+const STEP = 1 / 60;
+for (let i = 0; i < 20; i++) { await serverApp.tick(STEP); await clientApp.tick(STEP); }
+if (process.env.SPAWN_DEBUG) {
+ const net = serverApp.getResource(sdk.Net);
+ process.stderr.write(`role=${net.role} clients=${JSON.stringify(net.server?.clientIds ?? [])} ` +
+ `pawns=${serverApp.world.getEntitiesWithComponents([sdk.Replicated]).length}
+`);
+}
+
+if (spawned.length === 0) {
+ process.stderr.write('no spawn reached the wire — the arena provisioned nothing to classify\n');
+ rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ process.exit(1);
+}
+
+/** The three contracts a payload component could belong to. */
+const PROTOCOL = new Set(['Replicated']);
+const rows = [];
+for (const s of spawned) {
+ for (const c of s.components) {
+ const declared = sdk.getReplicatedFields(c.type) ?? [];
+ rows.push({
+ entity: s.name || `netId ${s.netId}`,
+ component: c.type,
+ contract: declared.length > 0 ? 'replication table'
+ : PROTOCOL.has(c.type) ? 'protocol metadata'
+ : 'undeclared — construction or leak',
+ declaredFields: [...declared],
+ sentFields: Object.keys(c.data ?? {}),
+ });
+ }
+}
+
+const byContract = {};
+for (const r of rows) (byContract[r.contract] ??= []).push(r);
+/** Fields a table component sent BEYOND what it declares: the same hole, per field. */
+const overSent = rows.filter((r) => r.contract === 'replication table'
+ && r.sentFields.some((f) => !r.declaredFields.includes(f)));
+
+process.stdout.write(`${JSON.stringify({
+ source: 'examples/multiplayer-arena',
+ spawns: spawned.length,
+ payloadComponents: rows.length,
+ byContract: Object.fromEntries(Object.entries(byContract).map(([k, v]) => [k, v.length])),
+ rows,
+ componentsSentBeyondTheirDeclaration: overSent.map((r) => ({
+ component: r.component,
+ declared: r.declaredFields,
+ sent: r.sentFields,
+ })),
+}, null, 2)}\n`);
+rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
diff --git a/sdk/tests/replication-spawn-contract.test.ts b/sdk/tests/replication-spawn-contract.test.ts
new file mode 100644
index 000000000..b64dd0383
--- /dev/null
+++ b/sdk/tests/replication-spawn-contract.test.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The three contracts a spawn payload confuses for one.
+ *
+ * A spawn currently carries `serializeEntityComponents` — the SCENE projection,
+ * which answers "how is this entity restored in full". Replication answers a
+ * different question: "which facts is this client authorized and declared to
+ * know". While the two are one function, every non-transient component a server
+ * hangs on a replicated entity transits, and the documented contract that an
+ * empty `replicatedFields` means never-replicated is not true on this path.
+ *
+ * One fixture separates the three layers:
+ *
+ * Replicated protocol identity — netId, owner
+ * Transform replication baseline — declared fields only
+ * Sprite ghost construction — the client needs it, the server's
+ * value is not authority for it
+ * ServerSecret neither — must never leave the authority
+ *
+ * `it.fails` marks what is broken TODAY. Each becomes `it` when the spawn
+ * contract splits; a fix that lands without flipping them turns them red.
+ */
+import { describe, it, expect, afterEach, beforeAll, beforeEach } from 'vitest';
+import { App } from '../src/app/app';
+import { clearUserComponents, defineComponent, Name, Transform, Sprite } from '../src/ecs/component';
+import { MemoryTransport } from '../src/net/MemoryTransport';
+import { replicationPlugin, Net, Replicated } from '../src/net/replication';
+import type { Entity } from '../src/types';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+
+const STEP = 1 / 60;
+/** What an explicit construction contract would give the ghost — deliberately
+ * NOT what the authority holds, so "the ghost has a Sprite" cannot pass by
+ * the payload having copied the server's one. */
+const ARCHETYPE_LAYER = 7;
+const AUTHORITY_LAYER = 3;
+
+let ServerSecret: ReturnType<typeof defineComponent<{ plan: string }>>;
+/** Two fields, one declared: the same hole a component at a time. */
+let PartlyShared: ReturnType<typeof defineComponent<{ shown: number; hidden: number }>>;
+
+describe.skipIf(!HAS_WASM)('a spawn carries three contracts, not one', () => {
+ let module: ESEngineModule;
+ beforeAll(async () => { module = await loadWasmModule(); });
+ const opened: App[] = [];
+ beforeEach(() => {
+ clearUserComponents();
+ ServerSecret = defineComponent('ServerSecret', { plan: '' });
+ PartlyShared = defineComponent('PartlyShared', { shown: 0, hidden: 0 },
+ { replicatedFields: ['shown'] });
+ });
+ afterEach(() => { for (const app of opened.splice(0)) app.world.disconnectCpp(); });
+
+ async function arena() {
+ const serverApp = App.new();
+ serverApp.connectCpp(new module.Registry() as unknown as CppRegistry, module, { strict: false });
+ serverApp.addPlugin(replicationPlugin);
+ opened.push(serverApp);
+ const server = serverApp.getResource(Net).startServer();
+
+ const clientApp = App.new();
+ clientApp.connectCpp(new module.Registry() as unknown as CppRegistry, module, { strict: false });
+ clientApp.addPlugin(replicationPlugin);
+ opened.push(clientApp);
+ const [ta, tb] = MemoryTransport.pair();
+ const connId = server.attachConnection(ta);
+ await clientApp.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+
+ const pawn = serverApp.world.spawn('pawn');
+ serverApp.world.insert(pawn, Transform, { position: { x: 11, y: 0, z: 0 } });
+ serverApp.world.insert(pawn, Sprite, { layer: AUTHORITY_LAYER });
+ serverApp.world.insert(pawn, PartlyShared, { shown: 5, hidden: 9 });
+ serverApp.world.insert(pawn, ServerSecret, { plan: 'flank at 30s' });
+ serverApp.world.insert(pawn, Replicated, { owner: connId });
+
+ for (let i = 0; i < 6; i++) { await serverApp.tick(STEP); await clientApp.tick(STEP); }
+ const ghost = clientApp.world.getEntitiesWithComponents([Replicated])
+ .find((e) => (clientApp.world.tryGet(e, Name) as { value: string } | null)?.value === 'pawn');
+ expect(ghost, 'the pawn never reached the client at all').toBeDefined();
+ return { serverApp, clientApp, server, connId, pawn, ghost: ghost! };
+ }
+
+ it('gives the ghost the replication baseline', async () => {
+ const h = await arena();
+ const t = h.clientApp.world.tryGet(h.ghost, Transform) as { position: { x: number } } | null;
+ expect(t?.position.x).toBe(11);
+ });
+
+ it('gives the ghost its protocol identity, so ownership resolves', async () => {
+ const h = await arena();
+ const repl = h.clientApp.world.tryGet(h.ghost, Replicated) as { owner: number } | null;
+ expect(repl?.owner).toBe(h.connId);
+ expect(h.clientApp.getResource(Net).client?.ownsEntity(h.ghost)).toBe(true);
+ });
+
+ it.fails('does not hand the client a component that declares nothing', async () => {
+ // ServerSecret has no `replicatedFields`, and the public contract says
+ // that means never replicated. The scene projection sends it anyway.
+ const h = await arena();
+ expect(h.clientApp.world.has(h.ghost, ServerSecret)).toBe(false);
+ });
+
+ it.fails('does not hand the client the fields a component did not declare', async () => {
+ const h = await arena();
+ const p = h.clientApp.world.tryGet(h.ghost, PartlyShared) as
+ { shown: number; hidden: number } | null;
+ expect(p?.shown).toBe(5);
+ expect(p?.hidden, 'undeclared field arrived from the authority').toBe(0);
+ });
+
+ it.fails('builds the ghost from a construction contract, not the authority dump', async () => {
+ // Sprite is not in the table, and a ghost still needs one. Where it comes
+ // from is the whole question: an explicit archetype, or whatever the
+ // server happened to be holding.
+ const h = await arena();
+ const s = h.clientApp.world.tryGet(h.ghost, Sprite) as { layer: number } | null;
+ expect(s, 'the ghost has no Sprite at all').not.toBeNull();
+ expect(s?.layer, 'the ghost took the authority Sprite, not a declared one')
+ .toBe(ARCHETYPE_LAYER);
+ });
+});