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): a sample's rows go to the connections that want them, by the cheaper side

esenginec0f1bbb1f3f9
diff --git a/bench/replication-routing/README.md b/bench/replication-routing/README.md
index 7d6e2e489..46ec771ec 100644
--- a/bench/replication-routing/README.md
+++ b/bench/replication-routing/README.md
@@ -201,6 +201,32 @@ 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.
+### Shipped, and re-measured on the same bench
+
+`route_` chooses per sample now, from `U + F` against `S`, with `U >= S` deciding
+for free. The reverse index is the server's — the projection of `conn.interest`,
+maintained from the enters and leaves the visibility pass already produces.
+
+| workload | before | after |
+|---|---|---|
+| floor: 1% movement | 14,477 | 14,105 |
+| dirty 1% | 19,343 | 19,541 |
+| dirty 10% | 33,756 | **30,324** |
+| **dirty 100%** | 90,828 | **66,742** (545% → 400% of a core) |
+| removals 10% | 21,587 | **19,068** |
+| mixed | 19,563 | **17,921** |
+
+Unambiguous where routing was the cost and inside the noise where it was not,
+which is what N3a said would happen: the two filters were 26% of a realistic
+sample, so removing almost all of them moves that sample by under a tenth. The
+floor itself varies by 3% between runs, so nothing smaller than that in the top
+rows is a claim.
+
+The shape of the win is the point rather than its size today. What used to grow
+with `connections x rows` now grows with the smaller of `affected + fanout` and
+`total interest membership` — so a game that dirties a tenth of its world stopped
+paying 352,000 visits a sample to send 3,201 rows.
+
## What this does not cover
- **Encoding is inside the totals and not separated.** It is proportional to what
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 061ab552b..9ac725cde 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6570,6 +6570,7 @@ static prototype: ReplicationPlugin
```
@internal fullScans: number
@internal ownerScanVisits: number
+@internal viewerLinks: number
attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 95ffd14f7..ec0cdd2ee 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6763,6 +6763,7 @@ static prototype: ReplicationPlugin
```
@internal fullScans: number
@internal ownerScanVisits: number
+@internal viewerLinks: number
attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 0c459c9a7..08ff740bb 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6565,6 +6565,7 @@ static prototype: ReplicationPlugin
```
@internal fullScans: number
@internal ownerScanVisits: number
+@internal viewerLinks: number
attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 2f1d3a4f6..182f31a52 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6811,6 +6811,7 @@ static prototype: ReplicationPlugin
```
@internal fullScans: number
@internal ownerScanVisits: number
+@internal viewerLinks: number
attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index dd553a139..1e3ea1005 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6572,6 +6572,7 @@ static prototype: ReplicationPlugin
```
@internal fullScans: number
@internal ownerScanVisits: number
+@internal viewerLinks: number
attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.ts
index bef31729e..fb2e9c81c 100644
--- a/sdk/src/net/replication/server.ts
+++ b/sdk/src/net/replication/server.ts
@@ -123,6 +123,14 @@ export class ReplicationServer {
/** Last broadcast value per entity × table entry: entity → componentId → field record. */
private readonly shadow_ = new Map<Entity, Map<number, Record<string, unknown>>>();
private readonly known_ = new Set<Entity>();
+
+ /**
+ * Which connections can see an entity — the reverse projection of every
+ * `conn.interest`, maintained from the enters and leaves the visibility pass
+ * produces. Null with no interest source: broadcasting would rebuild, as a
+ * Map, exactly the O(C x E) this exists to avoid.
+ */
+ private viewersByEntity_: Map<Entity, Set<number>> | null = null;
/** known entity → netId, owned by sampling. Survives the onDespawn hook
* clearing netIds_, so a despawn can still broadcast its id. */
private readonly knownNetIds_ = new Map<Entity, number>();
@@ -168,6 +176,20 @@ export class ReplicationServer {
private ownerReader_: number | null = null;
/** @internal Full-world reconciliations run — a steady-state sample must do none. */
fullScans = 0;
+
+ /**
+ * How many (entity, connection) links the reverse-interest index holds.
+ * A diagnostic, and the only way to see that a detached connection or a
+ * failed initial send left nothing behind — routing guards against a stale
+ * link, so one costs memory and bandwidth rather than correctness.
+ *
+ * @internal
+ */
+ get viewerLinks(): number {
+ let n = 0;
+ for (const seen of this.viewersByEntity_?.values() ?? []) n += seen.size;
+ return n;
+ }
/** @internal Candidates read to answer "who owns this" — zero once indexed. */
ownerScanVisits = 0;
@@ -304,6 +326,40 @@ export class ReplicationServer {
}
if (next && !this.ownedByConnection_) this.installOwnerIndex_();
this.interest_ = next;
+ if (!next) { this.viewersByEntity_ = null; return; }
+ // Seeded from what the connections already hold: coming from broadcast,
+ // `interest` is a superset of `visible`, so nothing would ever ENTER and
+ // the index would stay empty while every connection watched everything.
+ if (!this.viewersByEntity_) {
+ this.viewersByEntity_ = new Map();
+ for (const conn of this.connections_.values()) {
+ for (const e of conn.interest) this.watch_(e, conn.id);
+ }
+ }
+ }
+
+ /** @internal One connection now sees this entity. */
+ private watch_(entity: Entity, connectionId: number): void {
+ const index = this.viewersByEntity_;
+ if (!index) return;
+ let seen = index.get(entity);
+ if (!seen) { seen = new Set(); index.set(entity, seen); }
+ seen.add(connectionId);
+ }
+
+ /** @internal It no longer does. */
+ private unwatch_(entity: Entity, connectionId: number): void {
+ const seen = this.viewersByEntity_?.get(entity);
+ if (!seen) return;
+ seen.delete(connectionId);
+ if (seen.size === 0) this.viewersByEntity_!.delete(entity);
+ }
+
+ /** Everything a leaving connection was watching. O(its view), and a detach
+ * is not a steady-state path — twelve enters and leaves a sample are. */
+ private forgetViewer_(conn: Connection): void {
+ if (!this.viewersByEntity_) return;
+ for (const e of conn.interest) this.unwatch_(e, conn.id);
}
/** Claim the write journal, then seed from what is already known — in that
@@ -419,6 +475,7 @@ export class ReplicationServer {
detachConnection(id: number): void {
const conn = this.connections_.get(id);
if (!conn) return;
+ this.forgetViewer_(conn);
conn.channel.dispose();
this.connections_.delete(id);
}
@@ -552,9 +609,13 @@ export class ReplicationServer {
}
}
- /** Interest path: evaluate the policy per ready connection; spawn entering
- * entities (full current state), despawn leaving ones, and write that
- * connection's delta frame from the shared dirty list. */
+ /**
+ * Interest path in three parts: visibility, routing, sending.
+ *
+ * @note Routing is separate because one of the two ways needs every
+ * connection's visibility settled first. A failed send is not rolled
+ * back — that connection is a dead participant (see sendTo_).
+ */
private sampleWithInterest_(
tick: number,
spawnedEntities: Entity[],
@@ -571,34 +632,49 @@ export class ReplicationServer {
// reports, and a provider caching a fact READ from one has to hear.
rechecked: removals.map((r) => r.entity),
});
- // Spawn payloads serialize once per entity per tick, however many
- // connections it enters.
- const payloads = new Map<Entity, ReplSpawnEntity>();
- const payloadOf = (e: Entity): ReplSpawnEntity => {
- let p = payloads.get(e);
- if (!p) {
- p = this.spawnPayload_(e, this.knownNetIds_.get(e)!);
- payloads.set(e, p);
- }
- return p;
- };
+ // What each connection can see, and the index that answers the reverse
+ // question.
+ const plans: {
+ conn: Connection; visible: Set<Entity>; enters: Entity[];
+ leaveIds: number[]; entered: Set<Entity>;
+ }[] = [];
for (const conn of [...this.connections_.values()]) {
if (!conn.ready) continue;
const visible = visibleFor(conn.id);
-
const enters: Entity[] = [];
for (const e of visible) {
- if (!conn.interest.has(e)) enters.push(e);
+ if (conn.interest.has(e)) continue;
+ enters.push(e);
+ this.watch_(e, conn.id);
}
const leaveIds: number[] = [];
for (const e of conn.interest) {
if (visible.has(e)) continue;
+ this.unwatch_(e, conn.id);
const netId = this.knownNetIds_.get(e) ?? despawnedNetIds.get(e);
if (netId !== undefined) leaveIds.push(netId);
}
conn.interest = visible;
+ plans.push({ conn, visible, enters, leaveIds, entered: new Set(enters) });
+ }
+
+ // Whose debt is whose.
+ const routed = this.route_(plans, dirty, removals);
+ // The wire. Spawn payloads serialize once per entity per tick, however
+ // many connections it enters.
+ const payloads = new Map<Entity, ReplSpawnEntity>();
+ const payloadOf = (e: Entity): ReplSpawnEntity => {
+ let p = payloads.get(e);
+ if (!p) {
+ p = this.spawnPayload_(e, this.knownNetIds_.get(e)!);
+ payloads.set(e, p);
+ }
+ return p;
+ };
+ for (const { conn, enters, leaveIds } of plans) {
+ const mine = routed.get(conn.id)!;
this.sendTo_(conn, (c) => {
if (enters.length > 0) {
c.channel.send<ReplSpawnBatch>(ReplMsg.spawn, { tick, entities: enters.map(payloadOf) });
@@ -606,28 +682,107 @@ export class ReplicationServer {
if (leaveIds.length > 0) {
c.channel.send<ReplDespawnBatch>(ReplMsg.despawn, { tick, netIds: leaveIds });
}
- const entered = new Set(enters);
- // Same rule as the delta below: an entity that just entered was
- // serialized without the component, so it owes no removal.
- const mine = removals.filter((r) => visible.has(r.entity) && !entered.has(r.entity));
- if (mine.length > 0) {
- c.channel.send<ReplComponentRemoveBatch>(ReplMsg.componentRemove, removeBatch(tick, mine));
- }
- // Entities that just entered skip the delta — their spawn
- // payload already carries this tick's state.
- let frame: FrameWriter | null = null;
- for (const d of dirty) {
- if (!visible.has(d.entity) || entered.has(d.entity)) continue;
- frame ??= new FrameWriter(tick);
- frame.entry(d.netId, d.te, d.mask, d.data, this.refs_);
+ if (mine.removals.length > 0) {
+ c.channel.send<ReplComponentRemoveBatch>(
+ ReplMsg.componentRemove, removeBatch(tick, mine.removals.map((i) => removals[i]!)));
}
- if (frame && frame.entryCount > 0) {
- c.channel.sendBinary(REPLICATION_CHANNEL, frame.finish());
+ if (mine.dirty.length > 0) {
+ const frame = new FrameWriter(tick);
+ for (const i of mine.dirty) {
+ const d = dirty[i]!;
+ frame.entry(d.netId, d.te, d.mask, d.data, this.refs_);
+ }
+ if (frame.entryCount > 0) c.channel.sendBinary(REPLICATION_CHANNEL, frame.finish());
}
});
}
}
+ /**
+ * This sample's debt, merged per ENTITY. An entity with two dirty components
+ * and a removal is one reverse lookup and one map probe, not three, and the
+ * wire still carries removals before the delta.
+ */
+ private static byEntity(dirty: DirtyEntry[], removals: RemovalEntry[]):
+ Map<Entity, { dirty: number[]; removals: number[] }> {
+ const affected = new Map<Entity, { dirty: number[]; removals: number[] }>();
+ const of = (e: Entity) => {
+ let debt = affected.get(e);
+ if (!debt) { debt = { dirty: [], removals: [] }; affected.set(e, debt); }
+ return debt;
+ };
+ 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;
+ }
+
+ /**
+ * Which rows each connection owes, by whichever projection of the same truth
+ * is smaller THIS sample: pushing costs `U + F`, pulling `S`. No threshold.
+ *
+ * @note `U + F >= U`, so `U >= S` settles it without measuring F, which
+ * would cost push's dominant term to decide against push.
+ */
+ private route_(
+ plans: { conn: Connection; visible: Set<Entity>; entered: Set<Entity> }[],
+ dirty: DirtyEntry[],
+ removals: RemovalEntry[],
+ ): Map<number, { dirty: number[]; removals: number[] }> {
+ const out = new Map<number, { dirty: number[]; removals: number[] }>();
+ for (const { conn } of plans) out.set(conn.id, { dirty: [], removals: [] });
+ if (dirty.length === 0 && removals.length === 0) return out;
+
+ const affected = ReplicationServer.byEntity(dirty, removals);
+ let membership = 0;
+ for (const { visible } of plans) membership += visible.size;
+
+ const viewers = this.viewersByEntity_;
+ if (viewers && affected.size < membership) {
+ const rows: [Entity, { dirty: number[]; removals: number[] }, Set<number> | undefined][] = [];
+ 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;
+ }
+ if (units < membership) {
+ const entered = new Map(plans.map((p) => [p.conn.id, p.entered]));
+ for (const [e, debt, seen] of rows) {
+ if (!seen) continue;
+ for (const id of seen) {
+ const mine = out.get(id);
+ // An entity that entered this sample was serialized with
+ // its current state, so it owes no delta and no removal.
+ if (!mine || entered.get(id)!.has(e)) continue;
+ for (const i of debt.removals) mine.removals.push(i);
+ for (const i of debt.dirty) mine.dirty.push(i);
+ }
+ }
+ // Back into the order the rows were discovered in: the frame a
+ // connection receives is the same one either way, and this costs
+ // only what is actually SENT.
+ for (const mine of out.values()) {
+ mine.removals.sort((a, b) => a - b);
+ mine.dirty.sort((a, b) => a - b);
+ }
+ return out;
+ }
+ }
+
+ for (const { conn, visible, entered } of plans) {
+ const mine = out.get(conn.id)!;
+ for (const e of visible) {
+ const debt = affected.get(e);
+ if (!debt || entered.has(e)) continue;
+ for (const i of debt.removals) mine.removals.push(i);
+ for (const i of debt.dirty) mine.dirty.push(i);
+ }
+ mine.removals.sort((a, b) => a - b);
+ mine.dirty.sort((a, b) => a - b);
+ }
+ return out;
+ }
+
/**
* One snapshot of the interest source, and a function answering per
* connection from it. A provider prepares ONCE — that is the whole reason
@@ -941,6 +1096,10 @@ export class ReplicationServer {
}
conn.interest = visible;
conn.ready = true;
+ // After the send, not before: a connection that never heard about the
+ // world is not a viewer of it, and the early return above is the only
+ // other way out of this function.
+ for (const e of visible) this.watch_(e, conn.id);
}
private broadcast_(fn: (conn: Connection) => void): void {
diff --git a/sdk/tests/replication-routing.test.ts b/sdk/tests/replication-routing.test.ts
new file mode 100644
index 000000000..859f8bc8e
--- /dev/null
+++ b/sdk/tests/replication-routing.test.ts
@@ -0,0 +1,284 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Getting one sample's rows to the connections that want them.
+ *
+ * The server routes a sample's dirty rows and removals by whichever projection
+ * of the same truth is smaller: hand each affected entity to the connections
+ * that see it, or ask each connection's view what happened to it. Which one runs
+ * is decided per sample and must not be visible on the wire — so the shape of
+ * these is "the same world, routed both ways, ends up saying the same thing".
+ *
+ * A stale reverse index is the way this goes wrong quietly: a connection that is
+ * still listed as a viewer receives rows for a ghost it no longer holds, and one
+ * that is missing from the list simply stops hearing.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { App } from '../src/app/app';
+import { clearUserComponents, defineComponent, Name } from '../src/ecs/component';
+import { MemoryTransport } from '../src/net/MemoryTransport';
+import {
+ replicationPlugin, Net, Replicated, radiusInterestProvider,
+} from '../src/net/replication';
+import type { Entity } from '../src/types';
+import type { World } from '../src/ecs/world';
+
+const STEP = 1 / 60;
+/** Wide enough that everything below is in view unless it is moved far away. */
+const RADIUS = 50;
+let NetPos: ReturnType<typeof defineComponent<{ x: number; y: number; z: number }>>;
+
+beforeEach(() => {
+ clearUserComponents();
+ NetPos = defineComponent('NetPos', { x: 0, y: 0, z: 0 }, { replicatedFields: ['x', 'y', 'z'] });
+});
+
+const posOf = (world: World, e: Entity) =>
+ world.tryGet(e, NetPos) as { x: number; y: number; z: number } | null;
+/** Every ghost a client holds, by name and x — the wire's visible result. */
+const held = (app: App): string =>
+ app.world.getEntitiesWithComponents([Replicated])
+ .map((e) => `${(app.world.tryGet(e, Name) as { value: string } | null)?.value}@${posOf(app.world, e)?.x}`)
+ .sort().join(' ');
+
+/** The server end, with a tally of what actually went down the wire. */
+function counted(transport: MemoryTransport) {
+ let frames = 0;
+ const send = transport.send.bind(transport);
+ (transport as unknown as { send(d: string | ArrayBuffer): void }).send = (d) => { frames++; send(d); };
+ return { get frames() { return frames; } };
+}
+
+async function serverWith(connections: number) {
+ const serverApp = App.new();
+ serverApp.addPlugin(replicationPlugin);
+ const server = serverApp.getResource(Net).startServer();
+ const clients: { app: App; id: number; sent: { frames: number } }[] = [];
+ for (let i = 0; i < connections; i++) {
+ const app = App.new();
+ app.addPlugin(replicationPlugin);
+ const [ta, tb] = MemoryTransport.pair();
+ const id = server.attachConnection(ta);
+ await app.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+ clients.push({ app, id, sent: counted(ta as MemoryTransport) });
+ }
+ const step = async (n = 1) => {
+ for (let i = 0; i < n; i++) {
+ await serverApp.tick(STEP);
+ for (const c of clients) await c.app.tick(STEP);
+ }
+ };
+ const place = (name: string, x: number, owner = -1): Entity => {
+ const e = serverApp.world.spawn(name);
+ serverApp.world.insert(e, Replicated, { owner });
+ serverApp.world.insert(e, NetPos, { x, y: 0, z: 0 });
+ return e;
+ };
+ const move = (e: Entity, x: number) => {
+ serverApp.world.update(e, NetPos, (d) => { (d as { x: number }).x = x; });
+ };
+ return { serverApp, server, clients, step, place, move };
+}
+
+const provider = () => radiusInterestProvider(RADIUS, {
+ position: (world: World, e: Entity) => posOf(world, e),
+});
+
+describe('a sample routed either way says the same thing', () => {
+ /**
+ * The same script, run so that the router takes each branch. Few affected
+ * entities and the push side wins; every entity affected and the pull side
+ * does — the decision is `U + F` against total interest membership.
+ */
+ async function play(dirtyAll: boolean): Promise<string[]> {
+ const h = await serverWith(3);
+ h.server.setInterestProvider(provider());
+ for (const c of h.clients) h.place(`anchor${c.id}`, 0, c.id);
+ const crowd = Array.from({ length: 12 }, (_, i) => h.place(`e${i}`, i));
+ await h.step(4);
+
+ for (let round = 0; round < 3; round++) {
+ if (dirtyAll) for (const [i, e] of crowd.entries()) h.move(e, 100 + round * 10 + i);
+ else h.move(crowd[0]!, 100 + round * 10);
+ // One leaves the radius, one comes back.
+ h.move(crowd[1]!, round % 2 === 0 ? 900 : 3);
+ await h.step(3);
+ }
+ return h.clients.map((c) => held(c.app));
+ }
+
+ it('agrees ghost for ghost whichever side did the routing', async () => {
+ const pushed = await play(false);
+ const pulled = await play(true);
+ // Different scripts move different entities, so what is compared is that
+ // each ROUTE produced a consistent world for all three connections.
+ expect(new Set(pushed).size).toBe(1);
+ expect(new Set(pulled).size).toBe(1);
+ });
+
+ it('sends an entity that just entered its spawn and no delta on top', async () => {
+ const h = await serverWith(1);
+ h.server.setInterestProvider(provider());
+ h.place('anchor', 0, h.clients[0]!.id);
+ for (let i = 0; i < 20; i++) h.place(`e${i}`, i % 10);
+ // Known to the server for a while, and out of this connection's view.
+ const arriving = h.place('arriving', 900);
+ await h.step(4);
+ expect(held(h.clients[0]!.app)).not.toContain('arriving');
+
+ // The move that brings it into view is also what makes it dirty, and its
+ // spawn carries the new position — so a delta beside it is a second copy
+ // of the same value, which only the frame count can see.
+ const before = h.clients[0]!.sent.frames;
+ h.move(arriving, 4);
+ await h.step(3);
+ expect(held(h.clients[0]!.app)).toContain('arriving@4');
+ expect(h.clients[0]!.sent.frames - before).toBe(1);
+ });
+
+ it('skips an entity that just entered on the pull side too', async () => {
+ const h = await serverWith(1);
+ h.server.setInterestProvider(provider());
+ h.place('anchor', 0, h.clients[0]!.id);
+ // Three away, so more entities are affected than are visible anywhere and
+ // the PULL side runs — the other branch has its own fixture above.
+ const away = [h.place('a', 900), h.place('b', 901), h.place('c', 902)];
+ await h.step(4);
+
+ const before = h.clients[0]!.sent.frames;
+ h.move(away[0]!, 4);
+ h.move(away[1]!, 903);
+ h.move(away[2]!, 904);
+ await h.step(3);
+ expect(held(h.clients[0]!.app)).toContain('a@4');
+ // The spawn batch alone: the two that stayed away are nobody's, and the
+ // one that arrived carries its value in the spawn.
+ expect(h.clients[0]!.sent.frames - before).toBe(1);
+ });
+
+ it('stops sending to a connection an entity has left', async () => {
+ const h = await serverWith(1);
+ h.server.setInterestProvider(provider());
+ h.place('anchor', 0, h.clients[0]!.id);
+ // A crowd, so total interest membership is well above the one affected
+ // entity and the push side is the one that runs — the side a viewer left
+ // behind in the index would show up on.
+ for (let i = 0; i < 20; i++) h.place(`e${i}`, i % 10);
+ const wanderer = h.place('wanderer', 5);
+ await h.step(4);
+ expect(held(h.clients[0]!.app)).toContain('wanderer@5');
+
+ h.move(wanderer, 900);
+ await h.step(4);
+ expect(held(h.clients[0]!.app)).not.toContain('wanderer');
+
+ // Still being moved, and no longer anybody's business. Counted rather
+ // than read off the client: a row sent for a ghost it no longer holds is
+ // ignored on arrival, so only the wire shows it.
+ const before = h.clients[0]!.sent.frames;
+ h.move(wanderer, 901);
+ h.move(wanderer, 902);
+ await h.step(6);
+ expect(held(h.clients[0]!.app)).not.toContain('wanderer');
+ expect(h.clients[0]!.sent.frames).toBe(before);
+ });
+
+ it('leaves nothing in the index behind a detached connection', async () => {
+ const h = await serverWith(2);
+ h.server.setInterestProvider(provider());
+ for (const c of h.clients) h.place(`anchor${c.id}`, 0, c.id);
+ h.place('shared', 2);
+ await h.step(4);
+ const both = h.server.viewerLinks;
+ expect(both).toBeGreaterThan(0);
+
+ h.server.detachConnection(h.clients[1]!.id);
+ // Halved, not merely still working: a link nothing guards against is a
+ // leak that grows with every connection a session ever had.
+ expect(h.server.viewerLinks).toBe(both / 2);
+ await h.step(3);
+ expect(h.server.viewerLinks).toBe(both / 2);
+ });
+
+ it('makes a viewer of nobody the initial send never reached', async () => {
+ const h = await serverWith(0);
+ h.server.setInterestProvider(provider());
+ h.place('anchor', 0, 0);
+ h.place('near', 3);
+ await h.step(2);
+
+ const [ta, tb] = MemoryTransport.pair();
+ const app = App.new();
+ app.addPlugin(replicationPlugin);
+ // Refuses the initial state and nothing else, so the handshake still
+ // completes: a connection that never heard about the world is not a
+ // viewer of any of it.
+ const send = ta.send.bind(ta);
+ (ta as unknown as { send(d: string | ArrayBuffer): void }).send = (d) => {
+ if (typeof d === 'string' && d.includes('repl:spawn')) throw new Error('refused');
+ send(d);
+ };
+ h.server.attachConnection(ta);
+ await app.getResource(Net).connect(tb, { interpolationDelayTicks: 0 }).catch(() => {});
+ await h.step(2);
+ expect(h.server.viewerLinks).toBe(0);
+ });
+
+ it('reaches every connection that can see one entity', async () => {
+ const h = await serverWith(4);
+ h.server.setInterestProvider(provider());
+ for (const c of h.clients) h.place(`anchor${c.id}`, 0, c.id);
+ const shared = h.place('shared', 2);
+ await h.step(4);
+
+ h.move(shared, 9);
+ await h.step(3);
+ for (const c of h.clients) expect(held(c.app)).toContain('shared@9');
+ });
+
+ it('keeps the survivors current when a connection detaches', async () => {
+ const h = await serverWith(3);
+ h.server.setInterestProvider(provider());
+ for (const c of h.clients) h.place(`anchor${c.id}`, 0, c.id);
+ const shared = h.place('shared', 2);
+ await h.step(4);
+
+ h.server.detachConnection(h.clients[1]!.id);
+ h.move(shared, 42);
+ await h.step(3);
+ expect(held(h.clients[0]!.app)).toContain('shared@42');
+ expect(held(h.clients[2]!.app)).toContain('shared@42');
+ });
+
+ it('picks up a world it was not watching when interest is installed later', async () => {
+ const h = await serverWith(1);
+ // Broadcast first: every connection already holds everything, so nothing
+ // ENTERS when a provider arrives — the reverse index has to be seeded
+ // from what the connection already has or it stays empty for good.
+ h.place('anchor', 0, h.clients[0]!.id);
+ const near = h.place('near', 3);
+ await h.step(4);
+ expect(held(h.clients[0]!.app)).toContain('near@3');
+
+ h.server.setInterestProvider(provider());
+ await h.step(2);
+ h.move(near, 8);
+ await h.step(3);
+ expect(held(h.clients[0]!.app)).toContain('near@8');
+ });
+
+ it('goes back to broadcasting without carrying the index into it', async () => {
+ const h = await serverWith(1);
+ h.server.setInterestProvider(provider());
+ h.place('anchor', 0, h.clients[0]!.id);
+ const far = h.place('far', 900);
+ await h.step(4);
+ expect(held(h.clients[0]!.app)).not.toContain('far');
+
+ h.server.setInterestProvider(null);
+ await h.step(3);
+ h.move(far, 901);
+ await h.step(3);
+ expect(held(h.clients[0]!.app)).toContain('far@901');
+ });
+});