Skip to content

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

feat(net): replication finds dirty state by candidate, not by scanning it all

esengine77661a0ef51b
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index c7f5810e4..04524a2eb 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6538,6 +6538,7 @@ beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
detachConnection: (id: number) => void
+dispose: () => void
inputOf: (connectionId: number) => ReplInputMsg | null
netIds: NetIds
sample: (tick: number) => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index dfbc21446..42099df87 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6731,6 +6731,7 @@ beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
detachConnection: (id: number) => void
+dispose: () => void
inputOf: (connectionId: number) => ReplInputMsg | null
netIds: NetIds
sample: (tick: number) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 5246ac36e..55d54e423 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6533,6 +6533,7 @@ beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
detachConnection: (id: number) => void
+dispose: () => void
inputOf: (connectionId: number) => ReplInputMsg | null
netIds: NetIds
sample: (tick: number) => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 6b1cf3c7e..b8af69f87 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6779,6 +6779,7 @@ beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
detachConnection: (id: number) => void
+dispose: () => void
inputOf: (connectionId: number) => ReplInputMsg | null
netIds: NetIds
sample: (tick: number) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 3547923ca..00f182a53 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6540,6 +6540,7 @@ beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
detachConnection: (id: number) => void
+dispose: () => void
inputOf: (connectionId: number) => ReplInputMsg | null
netIds: NetIds
sample: (tick: number) => void
diff --git a/sdk/src/net/replication/ReplicationPlugin.ts b/sdk/src/net/replication/ReplicationPlugin.ts
index 1b9af2524..1e37642b0 100644
--- a/sdk/src/net/replication/ReplicationPlugin.ts
+++ b/sdk/src/net/replication/ReplicationPlugin.ts
@@ -70,6 +70,9 @@ export class NetSession {
stop(): void {
this.client_?.disconnect();
+ // Dropping the reference is not releasing what the server holds: its
+ // removal-history claims and its despawn subscription outlive it.
+ this.server_?.dispose();
this.client_ = null;
this.server_ = null;
this.role_ = 'offline';
diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.ts
index 54aed5690..377217312 100644
--- a/sdk/src/net/replication/server.ts
+++ b/sdk/src/net/replication/server.ts
@@ -18,7 +18,7 @@
*/
import type { World } from '../../ecs/world';
import type { Entity } from '../../types';
-import { Name, Parent, getComponent } from '../../ecs/component';
+import { Name, Parent, getComponent, type AnyComponentDef } from '../../ecs/component';
import { ABI_LAYOUT_HASH } from '../../ecs/component.generated';
import { serializeEntityComponents, type SceneComponentData } from '../../scene/scene';
import { NetChannel, type ReliableOrderedTransport } from '../NetChannel';
@@ -129,10 +129,21 @@ export class ReplicationServer {
private policy_: InterestPolicy | null = null;
private tick_ = 0;
private fixedDelta_ = 0;
+ /** Removal-history claims, one per replicated component. */
+ private readonly observations_: { def: AnyComponentDef; readerId: number }[] = [];
+ /**
+ * The floor every observation reads from, one tick BEHIND the world.
+ * `worldTick` moves once per App frame while a frame may run several fixed
+ * steps, and a write after a sample carries the tick it just closed — a
+ * floor at the current tick drops both. The shadow filters the overlap.
+ */
+ private changeFloor_ = -1;
+ private readonly offDespawn_: () => void;
+ private disposed_ = false;
constructor(world: World) {
this.world_ = world;
- world.onDespawn((e) => {
+ this.offDespawn_ = world.onDespawn((e) => {
// Sampling handles replicated despawns; this catches direct holes.
this.netIds_.unregisterEntity(e);
});
@@ -140,7 +151,54 @@ export class ReplicationServer {
/** Lazily built so components defined after plugin install still count. */
get table(): ReplicationTable {
- return (this.table_ ??= buildReplicationTable());
+ if (!this.table_) {
+ const table = buildReplicationTable();
+ // Installed HERE, with the table: doing it in the constructor would
+ // freeze the table before the game's own components exist, and the
+ // observation set would then describe a smaller world than the table.
+ this.installObservation_(table);
+ this.table_ = table;
+ }
+ return this.table_;
+ }
+
+ /** Track every replicated component, and claim its removal history. */
+ private installObservation_(table: ReplicationTable): void {
+ this.changeFloor_ = this.world_.getWorldTick() - 1;
+ for (const te of table.entries) {
+ this.world_.enableChangeTracking(te.def);
+ // The query is `tick > changeFloor_`, so the claim starts one after.
+ const readerId = this.world_.registerRemovedReaderFrom(te.def, this.changeFloor_ + 1);
+ this.observations_.push({ def: te.def, readerId });
+ }
+ }
+
+ /**
+ * Close the window this sample read, and open the next one. Retention is
+ * given up only after the rows were consumed — the same order a system's
+ * `Removed` reader releases in.
+ */
+ private advanceObservationFloor_(): void {
+ const nextFloor = this.world_.getWorldTick() - 1;
+ for (const o of this.observations_) {
+ this.world_.advanceRemovedReader(o.def, o.readerId, nextFloor);
+ }
+ this.changeFloor_ = nextFloor;
+ }
+
+ /**
+ * Give back everything this server holds outside itself: its channels, its
+ * claims on removal history, and its despawn subscription. Idempotent — the
+ * world would otherwise keep a dead server reachable, and its claims would
+ * pin removal rows for a session nobody is running.
+ */
+ dispose(): void {
+ if (this.disposed_) return;
+ this.disposed_ = true;
+ for (const id of [...this.connections_.keys()]) this.detachConnection(id);
+ for (const o of this.observations_) this.world_.disposeRemovedReader(o.def, o.readerId);
+ this.observations_.length = 0;
+ this.offDespawn_();
}
get netIds(): NetIds {
@@ -284,7 +342,12 @@ export class ReplicationServer {
* one filtered frame per connection with one). Runs in FixedPostUpdate. */
sample(tick: number): void {
this.tick_ = tick;
- if (this.connections_.size === 0) return;
+ if (this.connections_.size === 0) {
+ // No world scan, but the claims still move: a reader parked on an old
+ // floor pins removal history for as long as the server runs empty.
+ this.advanceObservationFloor_();
+ return;
+ }
const { spawnedEntities, despawned } = this.reconcileRegistry_();
@@ -304,6 +367,9 @@ export class ReplicationServer {
conn.ackedSeq = conn.applied.seq;
this.sendTo_(conn, (c) => c.channel.send<ReplAckMsg>(ReplMsg.ack, { tick, seq: conn.ackedSeq }));
}
+
+ // Last: the window is given up only once its rows are on the wire.
+ this.advanceObservationFloor_();
}
/** Fast path (no policy): everything to every ready connection on shared
@@ -485,6 +551,8 @@ export class ReplicationServer {
private rebaseRegistry_(): void {
this.reconcileRegistry_();
for (const e of this.known_) this.seedShadow_(e);
+ // The shadow is now the world, so the observation window starts here too.
+ this.advanceObservationFloor_();
}
private registerEntity_(e: Entity): void {
@@ -540,15 +608,34 @@ export class ReplicationServer {
/** Diff every known entity against its shadow (updating the shadow), and
* return this tick's dirty component entries. */
+ /**
+ * What to put on the wire this sample. History SELECTS candidates; shadow ×
+ * current world DECIDES truth — a component removed and re-added between
+ * samples is one candidate whose shadow and world both hold it, so it
+ * reduces to a field diff, or to nothing if the value came back the same.
+ */
private collectDirty_(): DirtySample {
const out: DirtyEntry[] = [];
const removals: RemovalEntry[] = [];
- for (const e of this.known_) {
- const perComp = this.shadow_.get(e);
- if (!perComp) continue;
- const netId = this.knownNetIds_.get(e);
- if (netId === undefined) continue;
- for (const te of this.table.entries) {
+ const floor = this.changeFloor_;
+ for (const te of this.table.entries) {
+ const candidates = new Set<Entity>();
+ // O(1) gate first: with nothing changed this component is skipped
+ // without walking the population at all.
+ if (this.world_.anyChangedSince(te.def, floor)) {
+ for (const e of this.known_) {
+ if (this.world_.isChangedSince(e, te.def, floor)) candidates.add(e);
+ }
+ }
+ // A Set, so a component lost twice in one window is one candidate.
+ for (const e of this.world_.getRemovedEntitiesSince(te.def, floor)) candidates.add(e);
+
+ for (const e of candidates) {
+ const perComp = this.shadow_.get(e);
+ if (!perComp) continue;
+ const netId = this.knownNetIds_.get(e);
+ if (netId === undefined) continue;
+ const held = perComp.get(te.id);
if (!this.world_.has(e, te.def)) {
// The shadow is the record of what the clients were told
// exists. Its snapshot disappearing IS the removal — there
@@ -557,12 +644,10 @@ export class ReplicationServer {
continue;
}
const data = this.world_.tryGet(e, te.def) as Record<string, unknown>;
- let snap = perComp.get(te.id);
- if (!snap) {
- // Component added after spawn: replicate all fields.
- snap = {};
- perComp.set(te.id, snap);
- }
+ // Absent from the shadow means the client has never been told it
+ // exists, whether it arrived now or came back: send every field.
+ const snap = held ?? {};
+ if (!held) perComp.set(te.id, snap);
let mask = 0;
for (let i = 0; i < te.fields.length; i++) {
const f = te.fields[i];
diff --git a/sdk/tests/replication-candidate.test.ts b/sdk/tests/replication-candidate.test.ts
new file mode 100644
index 000000000..9330bbbfa
--- /dev/null
+++ b/sdk/tests/replication-candidate.test.ts
@@ -0,0 +1,286 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What the candidate collector puts on the wire.
+ *
+ * History selects candidates; shadow × current world decides truth. So the
+ * observation record is never the wire record: a component removed and re-added
+ * between samples is one candidate holding both, and reduces to a field diff or
+ * to silence. These cases are the ones where a collector that trusted the
+ * tracker's history would send something the full-shadow one never did.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { App } from '../src/app/app';
+import { defineComponent, clearUserComponents } from '../src/ecs/component';
+import { MemoryTransport } from '../src/net/MemoryTransport';
+import { replicationPlugin, Net, Replicated } from '../src/net/replication';
+import { defineSystem, Schedule, GetWorld } from '../src/ecs/system';
+import type { ReliableOrderedTransport } from '../src/net/NetChannel';
+import type { Entity } from '../src/types';
+
+const STEP = 1 / 60;
+
+let NetPos: ReturnType<typeof defineComponent<{ x: number; y: number; z: number }>>;
+let Tag: ReturnType<typeof defineComponent<{ v: number }>>;
+
+beforeEach(() => {
+ clearUserComponents();
+ NetPos = defineComponent('NetPos', { x: 0, y: 0, z: 0 }, { replicatedFields: ['x', 'y', 'z'] });
+ Tag = defineComponent('NetTag', { v: 0 }, { replicatedFields: ['v'] });
+});
+
+const makeApp = (): App => { const a = App.new(); a.addPlugin(replicationPlugin); return a; };
+
+/** Everything the server put on the wire, so "sent nothing" is assertable. */
+function spy(inner: ReliableOrderedTransport) {
+ const sent: string[] = [];
+ return {
+ sent,
+ transport: {
+ delivery: 'reliable-ordered' as const,
+ send(d: string | ArrayBuffer) {
+ sent.push(typeof d === 'string' ? d : `[binary:${d.byteLength}]`);
+ inner.send(d);
+ },
+ on: (e: 'message', h: (d: string | ArrayBuffer) => void) => inner.on(e, h),
+ } as ReliableOrderedTransport,
+ };
+}
+
+async function connected() {
+ const serverApp = makeApp();
+ const clientApp = makeApp();
+ const server = serverApp.getResource(Net).startServer();
+ const [ta, tb] = MemoryTransport.pair();
+ const seen = spy(ta);
+ server.attachConnection(seen.transport);
+ const client = await clientApp.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+ const step = async (n = 1) => {
+ for (let i = 0; i < n; i++) { await serverApp.tick(STEP); await clientApp.tick(STEP); }
+ };
+ return { serverApp, clientApp, server, client, seen, step };
+}
+
+const removes = (sent: string[]): number => sent.filter((m) => m.includes('repl:crm')).length;
+const deltas = (sent: string[]): number => sent.filter((m) => m.startsWith('[binary')).length;
+
+function spawn(app: App, x: number): Entity {
+ const e = app.world.spawn();
+ app.world.insert(e, Replicated, { owner: 0 });
+ app.world.insert(e, NetPos, { x, y: 0, z: 0 });
+ return e;
+}
+
+const clientTag = (app: App): number | undefined => {
+ for (const e of app.world.getEntitiesWithComponents([Replicated])) {
+ const t = app.world.tryGet(e, Tag) as { v: number } | null;
+ if (t) return t.v;
+ }
+ return undefined;
+};
+
+describe('the candidate collector reduces to final state', () => {
+ it('A absent → add: the component arrives once, whole', async () => {
+ const { serverApp, clientApp, seen, step } = await connected();
+ const e = spawn(serverApp, 1);
+ await step();
+ seen.sent.length = 0;
+
+ serverApp.world.insert(e, Tag, { v: 7 });
+ await step();
+
+ expect(clientTag(clientApp)).toBe(7);
+ expect(removes(seen.sent)).toBe(0);
+ });
+
+ it('B present → remove: exactly one componentRemove', async () => {
+ const { serverApp, clientApp, seen, step } = await connected();
+ const e = spawn(serverApp, 1);
+ serverApp.world.insert(e, Tag, { v: 7 });
+ await step();
+ seen.sent.length = 0;
+
+ serverApp.world.remove(e, Tag);
+ await step(2);
+
+ expect(clientTag(clientApp)).toBeUndefined();
+ expect(removes(seen.sent)).toBe(1);
+ });
+
+ it('C present → remove → add: no removal, only the value that differs', async () => {
+ const { serverApp, clientApp, seen, step } = await connected();
+ const e = spawn(serverApp, 1);
+ serverApp.world.insert(e, Tag, { v: 7 });
+ await step();
+ seen.sent.length = 0;
+
+ serverApp.world.remove(e, Tag);
+ serverApp.world.insert(e, Tag, { v: 9 });
+ await step();
+
+ expect(removes(seen.sent)).toBe(0);
+ expect(clientTag(clientApp)).toBe(9);
+ });
+
+ it('C2 present → remove → add with the SAME value: nothing at all', async () => {
+ const { serverApp, seen, step } = await connected();
+ const e = spawn(serverApp, 1);
+ serverApp.world.insert(e, Tag, { v: 7 });
+ await step();
+ seen.sent.length = 0;
+
+ serverApp.world.remove(e, Tag);
+ serverApp.world.insert(e, Tag, { v: 7 });
+ await step();
+
+ expect(removes(seen.sent)).toBe(0);
+ expect(deltas(seen.sent)).toBe(0);
+ });
+
+ it('D absent → add → remove: no wire operation', async () => {
+ const { serverApp, seen, step } = await connected();
+ const e = spawn(serverApp, 1);
+ await step();
+ seen.sent.length = 0;
+
+ serverApp.world.insert(e, Tag, { v: 7 });
+ serverApp.world.remove(e, Tag);
+ await step();
+
+ expect(removes(seen.sent)).toBe(0);
+ expect(deltas(seen.sent)).toBe(0);
+ });
+
+ it('E remove → add → remove: exactly one componentRemove', async () => {
+ const { serverApp, clientApp, seen, step } = await connected();
+ const e = spawn(serverApp, 1);
+ serverApp.world.insert(e, Tag, { v: 7 });
+ await step();
+ seen.sent.length = 0;
+
+ serverApp.world.remove(e, Tag);
+ serverApp.world.insert(e, Tag, { v: 8 });
+ serverApp.world.remove(e, Tag);
+ await step(2);
+
+ expect(removes(seen.sent)).toBe(1);
+ expect(clientTag(clientApp)).toBeUndefined();
+ });
+
+ it('field edits still replicate', async () => {
+ const { serverApp, clientApp, step } = await connected();
+ const e = spawn(serverApp, 1);
+ await step();
+
+ serverApp.world.set(e, NetPos, { x: 42, y: 0, z: 0 });
+ await step(2);
+
+ const xs = clientApp.world.getEntitiesWithComponents([Replicated])
+ .map((g) => (clientApp.world.tryGet(g, NetPos) as { x: number } | null)?.x);
+ expect(xs).toContain(42);
+ });
+});
+
+describe('the observation window against the real clock', () => {
+ it('sees BOTH fixed steps of one App frame', async () => {
+ const { serverApp, clientApp, server, client } = await connected();
+ const e = spawn(serverApp, 0);
+ await serverApp.tick(STEP); await clientApp.tick(STEP);
+
+ // worldTick advances once per APP frame; two fixed steps share it. A
+ // floor at the current tick would drop the second step's write.
+ let steps = 0;
+ serverApp.addSystemToSchedule(Schedule.FixedUpdate, defineSystem(
+ [GetWorld()],
+ (world) => {
+ if (steps >= 2) return;
+ steps++;
+ const p = world.get(e, NetPos) as { x: number };
+ world.update(e, NetPos, (d: { x: number }) => { d.x = p.x + 1; });
+ },
+ { name: 'CandStep' },
+ ));
+
+ await serverApp.tick(STEP * 2);
+ await clientApp.tick(STEP); await clientApp.tick(STEP);
+ await serverApp.tick(STEP); await clientApp.tick(STEP);
+
+ expect(steps).toBe(2);
+ expect((serverApp.world.get(e, NetPos) as { x: number }).x).toBe(2);
+ const xs = clientApp.world.getEntitiesWithComponents([Replicated])
+ .map((g) => (clientApp.world.tryGet(g, NetPos) as { x: number } | null)?.x);
+ expect(xs).toContain(2);
+ expect(server.connectionCount).toBe(1);
+ expect(client).toBeTruthy();
+ });
+
+ it('sees a write that lands AFTER the sample, on the next one', async () => {
+ const { serverApp, clientApp, step } = await connected();
+ const e = spawn(serverApp, 0);
+ await step();
+
+ // PostUpdate runs after FixedPostUpdate, where replication samples: this
+ // write carries the tick the sample just closed.
+ let once = true;
+ serverApp.addSystemToSchedule(Schedule.PostUpdate, defineSystem(
+ [GetWorld()],
+ (world) => {
+ if (!once) return;
+ once = false;
+ world.update(e, NetPos, (d: { x: number }) => { d.x = 77; });
+ },
+ { name: 'CandLate' },
+ ));
+
+ await step(3);
+
+ const xs = clientApp.world.getEntitiesWithComponents([Replicated])
+ .map((g) => (clientApp.world.tryGet(g, NetPos) as { x: number } | null)?.x);
+ expect(xs).toContain(77);
+ });
+});
+
+describe('the server owns what it registered', () => {
+ it('gives its removal claims back on stop, and does not stack them on restart', () => {
+ const app = makeApp();
+ const net = app.getResource(Net);
+ const world = app.world;
+
+ const before = world.removedReaderCount(NetPos);
+ const server = net.startServer();
+ void server.table;
+ expect(world.removedReaderCount(NetPos)).toBe(before + 1);
+
+ net.stop();
+ expect(world.removedReaderCount(NetPos)).toBe(before);
+
+ const again = net.startServer();
+ void again.table;
+ expect(world.removedReaderCount(NetPos)).toBe(before + 1);
+ net.stop();
+ net.stop();
+ expect(world.removedReaderCount(NetPos)).toBe(before);
+ });
+
+ it('keeps removal history bounded while nobody is connected', async () => {
+ const { serverApp, server, step } = await connected();
+ const e = spawn(serverApp, 1);
+ serverApp.world.insert(e, Tag, { v: 1 });
+ await step();
+
+ for (let id = 0; id < 8; id++) server.detachConnection(id);
+ expect(server.connectionCount).toBe(0);
+
+ // The world keeps losing components with nobody listening. Retention has
+ // to follow the window, not the length of the quiet period.
+ for (let i = 0; i < 30; i++) {
+ const t = serverApp.world.spawn();
+ serverApp.world.insert(t, Replicated, { owner: 0 });
+ serverApp.world.insert(t, Tag, { v: i });
+ serverApp.world.remove(t, Tag);
+ await serverApp.tick(STEP);
+ }
+
+ expect(serverApp.world.getStorageSizes().changes.removedRows).toBeLessThan(10);
+ });
+});