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.

perf(net): a snapshot that did not move is not proved again

esengine3d6aa6ad9a5e
diff --git a/bench/replication-routing/README.md b/bench/replication-routing/README.md
index 5fce70f27..ff32a588e 100644
--- a/bench/replication-routing/README.md
+++ b/bench/replication-routing/README.md
@@ -235,18 +235,75 @@ above: 783 µs to 85 at the mixed workload, 37,434 to 3,091 with everything dirt
The shape is the result. What used to grow with `connections × rows` now grows
with the smaller of `affected + fanout` and `total interest membership`.
+## N3e: the sample nothing moved in
+
+The floor above is `C x V` because every connection is asked, every sample, to
+prove a view whose inputs nobody touched. A provider that KEEPS its index knows
+better than that, and can now say so: it publishes what snapshot it is, and a
+connection holding an answer stamped with the same snapshot, the same installed
+source and the same owned set is holding the answer.
+
+So the server does not ask. Not a cheaper query — no query, no copy of the
+result, and neither the enter nor the leave scan over it.
+
+```
+same interest source
+AND same prepared generation -> keep conn.interest
+AND same owned generation
+```
+
+Visibility unchanged is not "this connection has nothing coming": routing and
+sending run exactly as before, off the reverse index that is already the
+projection of what the connection holds. A field that changed on a ghost still
+reaches it.
+
+A/B on one machine, pristine sources against these, same harness, `usPerSampleMin`:
+
+| workload | before | after |
+|---|---|---|
+| **still — nothing moves at all** | 3,863 | **17** |
+| still, 8 connections | 650 | **11** |
+| still, 2% visible | 8,175 | **18** |
+| still, quarter the population | 2,833 | **14** |
+| floor: 1% movement, nothing else | 9,539 / 9,598 | 9,561 / 9,855 |
+| mixed — 1% dirty, 0.1% removed | 13,269 | 13,735 |
+
+**The still column stopped being a function of anything.** Eleven to eighteen
+microseconds whether it is 8 connections or 32, 1% visible or 2%, 25k entities or
+100k — 0.06% to 0.11% of a core, against 4% to 49%. What is left is the prepare
+that consumes the composition delta, and it is the microsecond the idle-
+maintenance probe measured.
+
+The two moving rows are the point of the table as much as the still ones: they
+must not have moved, and two runs of the before column already differ by 0.6%.
+
+> These absolute numbers are lower than the top of this page for the still row
+> and higher for the moving ones because they were taken on a different day —
+> the moving arms run about 9% slower here than they did then. Read the A/B,
+> not one column against the earlier table.
+
+**1% movement is unchanged on purpose.** One entity moving bumps the one spatial
+generation the snapshot publishes, and all 32 connections are proved again. What
+this buys is the sample where nothing moved; a generation per region, so that a
+connection is only re-proved when something moved near IT, is a different and
+larger question.
+
+The rebuilt lane — a custom `position()` — publishes no generation at all, and is
+queried every sample. Nothing can know when an arbitrary function would answer
+differently, so nothing certifies it.
+
## What this does not cover
- **Encoding is inside the totals and not separated.** It is proportional to what
is actually SENT — 598 entries at the mixed point — so it is the floor a
perfect router leaves behind, not part of the wall. Separating it needs the
frame writer, which is not on the SDK's entry.
-- **The still floor is C × V and nothing else.** 3,573 µs with nothing moving,
- and `µs per (connection × visible entity)` comes out 0.112 to 0.121 across
- every point of the sweep — a quarter of the population at the same C × V costs
- the same, and eight connections cost a quarter of thirty-two. There is no
- population term and no constant. The constant the broken harness appeared to
- have was the `'all'` connection.
+- **The still floor WAS C × V and nothing else** — 3,573 µs with nothing moving,
+ and `µs per (connection × visible entity)` 0.112 to 0.121 across every point of
+ the sweep, with no population term and no constant. That measurement is what
+ the section above acted on; the tables in this page up to it describe the shape
+ before it. The constant the broken harness appeared to have was the `'all'`
+ connection.
- One anchor per connection, and a uniform grid world. `viewers per entity` is
the number the push/pull choice turns on, and it is a property of how players
are arranged: 1.00 spread across the map, 8.10 packed into a thousandth of it.
diff --git a/docs/astro/src/content/docs/scripting/networking.mdx b/docs/astro/src/content/docs/scripting/networking.mdx
index 6e5a75a33..962f0d4b4 100644
--- a/docs/astro/src/content/docs/scripting/networking.mdx
+++ b/docs/astro/src/content/docs/scripting/networking.mdx
@@ -187,6 +187,14 @@ At 100,000 entities and 32 connections the kept index costs **18% of one core**
against 195% for rebuilding it every sample, and reads 668 positions per sample
instead of 100,000. With nothing moving it reads none.
+And when nothing entered, left or moved, **no connection is queried at all**. The
+kept index says it is the same snapshot it was; a connection whose owned entities
+have not changed hands either is already holding the answer, so it keeps it. A
+stationary sample at that scale costs microseconds instead of a fifth of a core.
+
+That is about visibility, not about traffic: a field changing on an entity you
+can see still reaches you, whether or not your view moved.
+
Two things follow from the kept index, and neither is a limitation you can work
around by writing the reader differently:
diff --git a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
index ca09a40aa..7bd979404 100644
--- a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
+++ b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
@@ -172,6 +172,13 @@ server.setInterestProvider(radiusInterestProvider(800));
10 万实体、32 个连接时,保留索引占 **18% 单核**,而每采样重建是 195%;每采样读
668 次位置而不是 10 万次。完全没有东西移动时读 0 次。
+而且当没有实体进入、离开或移动时,**任何连接都不会被查询**。保留索引会说明自己
+仍是同一份快照;拥有实体也没有易主的连接,手上握着的就是答案,于是原样留着。这个
+规模下的静止采样从五分之一个核降到几微秒。
+
+这说的是可见性,不是流量:你看得见的实体上有字段变了,照样会送到你手上,与你的
+视野动没动无关。
+
保留索引带来两条结论,都不是换个写法就能绕开的:
- 你传了 `position`,就走每采样重建。对任意函数来说这是正确答案,而且仍然远比
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index d277552f3..1f0c640ed 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6215,6 +6215,7 @@ static prototype: PrefabsPlugin
## PreparedInterest — interface @experimental
```
+generation: number | undefined
query: (view: InterestProviderQueryView) => ReadonlySet<Entity> | "all"
```
@@ -6634,6 +6635,7 @@ static prototype: ReplicationPlugin
@internal fullScans: number
@internal ownerScanVisits: number
@internal viewerLinks: number
+@internal visibilityRecomputes: 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 4da09c4d0..d65fdbb07 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6398,6 +6398,7 @@ static prototype: PrefabsPlugin
## PreparedInterest — interface @experimental
```
+generation: number | undefined
query: (view: InterestProviderQueryView) => ReadonlySet<Entity> | "all"
```
@@ -6827,6 +6828,7 @@ static prototype: ReplicationPlugin
@internal fullScans: number
@internal ownerScanVisits: number
@internal viewerLinks: number
+@internal visibilityRecomputes: 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 df027b72b..be7828e34 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6210,6 +6210,7 @@ static prototype: PrefabsPlugin
## PreparedInterest — interface @experimental
```
+generation: number | undefined
query: (view: InterestProviderQueryView) => ReadonlySet<Entity> | "all"
```
@@ -6629,6 +6630,7 @@ static prototype: ReplicationPlugin
@internal fullScans: number
@internal ownerScanVisits: number
@internal viewerLinks: number
+@internal visibilityRecomputes: 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 d5c70dab4..6906eb180 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6456,6 +6456,7 @@ static prototype: PrefabsPlugin
## PreparedInterest — interface @experimental
```
+generation: number | undefined
query: (view: InterestProviderQueryView) => ReadonlySet<Entity> | "all"
```
@@ -6875,6 +6876,7 @@ static prototype: ReplicationPlugin
@internal fullScans: number
@internal ownerScanVisits: number
@internal viewerLinks: number
+@internal visibilityRecomputes: 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 b86f3608c..f6a0933a6 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6217,6 +6217,7 @@ static prototype: PrefabsPlugin
## PreparedInterest — interface @experimental
```
+generation: number | undefined
query: (view: InterestProviderQueryView) => ReadonlySet<Entity> | "all"
```
@@ -6636,6 +6637,7 @@ static prototype: ReplicationPlugin
@internal fullScans: number
@internal ownerScanVisits: number
@internal viewerLinks: number
+@internal visibilityRecomputes: number
attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
diff --git a/sdk/src/ecs/ChangeTracker.ts b/sdk/src/ecs/ChangeTracker.ts
index 3315bb84d..31cc92e3d 100644
--- a/sdk/src/ecs/ChangeTracker.ts
+++ b/sdk/src/ecs/ChangeTracker.ts
@@ -13,6 +13,10 @@ import { AnyComponentDef } from './component';
* reader holds the component, pruned to the LOWEST claim on it. Two of these
* exist — removal history and membership topology — because a consumer of one
* must not keep the other alive; the ownership rule is written once.
+ *
+ * A reader is a LEASE: it must advance or be disposed. Nothing prunes past a
+ * parked one, deliberately — it is indistinguishable from one about to catch up
+ * — so a holder that can go idle advances anyway.
*/
class ReaderOwnedJournal {
private rows_ = new Map<symbol, Array<{ entity: Entity; tick: number }>>();
diff --git a/sdk/src/net/replication/interest.ts b/sdk/src/net/replication/interest.ts
index 9eeb3a329..65d4ecdf3 100644
--- a/sdk/src/net/replication/interest.ts
+++ b/sdk/src/net/replication/interest.ts
@@ -80,6 +80,14 @@ export interface InterestProviderQueryView {
/** One snapshot, queried by every connection evaluated against it. @experimental */
export interface PreparedInterest {
+ /**
+ * This snapshot's identity, in the provider's own numbering. The same number
+ * twice certifies the same answer to the same query inputs, so the host does
+ * not ask again; absent, every connection is queried.
+ *
+ * @experimental
+ */
+ readonly generation?: number;
query(view: InterestProviderQueryView): ReadonlySet<Entity> | 'all';
}
@@ -181,6 +189,10 @@ function defaultPosition(world: World, entity: Entity): InterestPoint | null {
* composition says changed. A custom `position` rebuilds every sample, because
* nothing can know when an arbitrary function would answer differently.
*
+ * The kept lane also publishes a {@link PreparedInterest.generation}, so a
+ * sample in which nothing entered, left or MOVED is one no connection has to be
+ * queried for. The rebuilt lane publishes none.
+ *
* @experimental
* @see radiusInterest
*/
@@ -205,6 +217,12 @@ export function radiusInterestProvider(
/** Whether this core can report what a composition changed. Null until asked. */
let reports: boolean | null = null;
let heldWorld: World | null = null;
+ /**
+ * Bumped by every change to the answers below — membership, a move, a
+ * rebuild. Monotonic and never reset: a disposed index coming back must not
+ * hand out a number a caller is still holding.
+ */
+ let generation = 0;
function place(world: World, e: Entity): void {
const p = positionOf(world, e);
@@ -231,16 +249,24 @@ export function radiusInterestProvider(
where.delete(e);
}
- /** Read an entity's place again, and move it if the cell changed. */
+ /**
+ * Read an entity's place again, and move it if the cell changed. Bumps the
+ * generation only when the PLACE changed: the change feed reports a
+ * composition, and a rotation composes without moving anybody in or out of
+ * anybody's radius.
+ */
function refresh(world: World, e: Entity): void {
const p = positionOf(world, e);
const slot = where.get(e);
if (!p) {
- if (slot || at.has(e)) displace(e);
+ if (slot || at.has(e)) { displace(e); generation++; }
+ else if (!placeless.has(e)) generation++;
placeless.add(e);
return;
}
- placeless.delete(e);
+ if (placeless.delete(e)) generation++;
+ const was = at.get(e);
+ if (!was || was.x !== p.x || was.y !== p.y || (was.z ?? 0) !== (p.z ?? 0)) generation++;
const k = key(p.x, p.y, p.z ?? 0);
if (slot && slot.key === k) { at.set(e, p); return; }
displace(e);
@@ -262,6 +288,7 @@ export function radiusInterestProvider(
clear();
for (const e of entities) place(world, e);
seeded = true;
+ generation++;
}
/**
@@ -274,6 +301,7 @@ export function radiusInterestProvider(
const delta = world.compositionChanges();
if (!delta || delta.overflowed) return false;
+ if (left.length > 0 || entered.length > 0) generation++;
for (const e of left) displace(e);
for (const e of entered) { placeless.delete(e); displace(e); place(world, e); }
// Duplicates cost a second read and nothing else; ids for entities this
@@ -289,43 +317,51 @@ export function radiusInterestProvider(
return true;
}
- const prepared: PreparedInterest = {
- query({ owned }) {
- const anchors: InterestPoint[] = [];
- for (const e of owned) {
- const p = at.get(e);
- if (p) anchors.push(p);
- }
- // No place to look from: the same fail-open the policy has.
- if (anchors.length === 0) return 'all';
+ function answer({ owned }: InterestProviderQueryView): ReadonlySet<Entity> | 'all' {
+ const anchors: InterestPoint[] = [];
+ for (const e of owned) {
+ const p = at.get(e);
+ if (p) anchors.push(p);
+ }
+ // No place to look from: the same fail-open the policy has.
+ if (anchors.length === 0) return 'all';
- const visible = new Set<Entity>(placeless);
- for (const a of anchors) {
- const cx = Math.floor(a.x / cell);
- const cy = Math.floor(a.y / cell);
- const cz = Math.floor((a.z ?? 0) / cell);
- for (let dx = -1; dx <= 1; dx++) {
- for (let dy = -1; dy <= 1; dy++) {
- for (let dz = -1; dz <= 1; dz++) {
- const bucket = cells.get(`${cx + dx},${cy + dy},${cz + dz}`);
- if (!bucket) continue;
- for (const e of bucket) {
- if (visible.has(e)) continue;
- const p = at.get(e)!;
- // A cell is a box and the rule is a sphere: being
- // in the neighbourhood is not being in range.
- const ddx = p.x - a.x;
- const ddy = p.y - a.y;
- const ddz = (p.z ?? 0) - (a.z ?? 0);
- if (ddx * ddx + ddy * ddy + ddz * ddz <= r2) visible.add(e);
- }
+ const visible = new Set<Entity>(placeless);
+ for (const a of anchors) {
+ const cx = Math.floor(a.x / cell);
+ const cy = Math.floor(a.y / cell);
+ const cz = Math.floor((a.z ?? 0) / cell);
+ for (let dx = -1; dx <= 1; dx++) {
+ for (let dy = -1; dy <= 1; dy++) {
+ for (let dz = -1; dz <= 1; dz++) {
+ const bucket = cells.get(`${cx + dx},${cy + dy},${cz + dz}`);
+ if (!bucket) continue;
+ for (const e of bucket) {
+ if (visible.has(e)) continue;
+ const p = at.get(e)!;
+ // A cell is a box and the rule is a sphere: being
+ // in the neighbourhood is not being in range.
+ const ddx = p.x - a.x;
+ const ddy = p.y - a.y;
+ const ddz = (p.z ?? 0) - (a.z ?? 0);
+ if (ddx * ddx + ddy * ddy + ddz * ddz <= r2) visible.add(e);
}
}
}
}
- return visible;
- },
- };
+ }
+ return visible;
+ }
+
+ /**
+ * The kept lane publishes its generation; the rebuilt one cannot. Nothing
+ * can know when an arbitrary reader would answer differently, so a caller
+ * offered a number for it would be told the world stood still while it
+ * moved.
+ */
+ const prepared: PreparedInterest = custom
+ ? { query: answer }
+ : { get generation() { return generation; }, query: answer };
return {
prepare(view): PreparedInterest {
diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.ts
index fb2e9c81c..cffc57b08 100644
--- a/sdk/src/net/replication/server.ts
+++ b/sdk/src/net/replication/server.ts
@@ -59,6 +59,26 @@ interface Connection {
droppedInputs: number;
/** Entities this connection currently knows (has been sent a spawn for). */
interest: Set<Entity>;
+ /**
+ * What `interest` was last PROVED from. When every part of it still holds,
+ * the same source would answer the same set, so it is not asked: no query,
+ * no copy of the answer, and no scan for what entered or left. Null while
+ * nothing certified it — the connection is queried.
+ */
+ provenance: VisibilityStamp | null;
+}
+
+/**
+ * The three facts one connection's visibility is a function of. Equal on all
+ * three across two samples and the answer cannot have moved.
+ *
+ * @note `source` is here because generations are each provider's own numbering:
+ * two providers both on their fifth snapshot are not the same snapshot.
+ */
+interface VisibilityStamp {
+ source: number;
+ snapshot: number;
+ owned: number;
}
/** Queued-but-unconsumed input cap. Beyond it the NEW command is refused, not
@@ -103,6 +123,14 @@ function removeBatch(tick: number, removals: readonly RemovalEntry[]): ReplCompo
return { tick, entries: [...byNetId].map(([netId, componentIds]) => ({ netId, componentIds })) };
}
+/** The plan of a connection that was not asked again: nothing entered it. */
+const NOBODY: ReadonlySet<Entity> = new Set<Entity>();
+
+function sameVisibility(held: VisibilityStamp | null, now: VisibilityStamp): boolean {
+ return held !== null && held.source === now.source
+ && held.snapshot === now.snapshot && held.owned === now.owned;
+}
+
function fieldEqual(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
@@ -142,6 +170,12 @@ export class ReplicationServer {
private interest_: { kind: 'policy'; value: InterestPolicy }
| { kind: 'provider'; value: InterestProvider }
| null = null;
+ /**
+ * Which source the stamps in flight belong to. Bumped by every install, so
+ * a new provider whose numbering happens to land on the outgoing one's
+ * cannot be mistaken for it.
+ */
+ private interestEpoch_ = 0;
private tick_ = 0;
private fixedDelta_ = 0;
/** Removal-history claims, one per replicated component. */
@@ -172,10 +206,20 @@ export class ReplicationServer {
/** The index's own record of who owned each entity: a write says the NEW
* owner, and the old one is needed to take the entity off its set. */
private readonly ownerOfEntity_ = new Map<Entity, number>();
+ /** How many times a connection's owned set changed. The other half of what
+ * a spatial answer is a function of: the snapshot can stand still while
+ * the anchors a connection looks from change hands. */
+ private readonly ownedEpoch_ = new Map<number, number>();
private ownerFloor_ = -1;
private ownerReader_: number | null = null;
/** @internal Full-world reconciliations run — a steady-state sample must do none. */
fullScans = 0;
+ /**
+ * @internal Connections whose visibility was proved again — queried, copied
+ * and diffed. A sample in which no relevance input moved must do none, and
+ * that is the whole claim of the stamp.
+ */
+ visibilityRecomputes = 0;
/**
* How many (entity, connection) links the reverse-interest index holds.
@@ -321,6 +365,7 @@ export class ReplicationServer {
private setInterest_(next: typeof this.interest_): void {
const previous = this.interest_;
+ this.interestEpoch_++;
if (previous?.kind === 'provider' && previous.value !== (next as { value?: unknown })?.value) {
previous.value.dispose?.();
}
@@ -379,12 +424,21 @@ export class ReplicationServer {
const now = repl ? repl.owner : undefined;
const before = this.ownerOfEntity_.get(e);
if (before === now) return;
- if (before !== undefined) this.ownedByConnection_?.get(before)?.delete(e);
+ if (before !== undefined) {
+ this.ownedByConnection_?.get(before)?.delete(e);
+ this.bumpOwned_(before);
+ }
if (now === undefined) { this.ownerOfEntity_.delete(e); return; }
let set = index.get(now);
if (!set) { set = new Set(); index.set(now, set); }
set.add(e);
this.ownerOfEntity_.set(e, now);
+ this.bumpOwned_(now);
+ }
+
+ /** This connection looks from somewhere else now than it did. */
+ private bumpOwned_(connectionId: number): void {
+ this.ownedEpoch_.set(connectionId, (this.ownedEpoch_.get(connectionId) ?? 0) + 1);
}
/** Drop `e` from the index entirely — it has left replication. */
@@ -393,6 +447,7 @@ export class ReplicationServer {
if (before === undefined) return;
this.ownedByConnection_?.get(before)?.delete(e);
this.ownerOfEntity_.delete(e);
+ this.bumpOwned_(before);
}
/**
@@ -422,7 +477,7 @@ export class ReplicationServer {
id, channel, ready: false,
input: null, queue: [], applied: null, ackedSeq: 0,
lastSeq: 0, droppedInputs: 0,
- interest: new Set(),
+ interest: new Set(), provenance: null,
};
this.connections_.set(id, conn);
@@ -478,6 +533,8 @@ export class ReplicationServer {
this.forgetViewer_(conn);
conn.channel.dispose();
this.connections_.delete(id);
+ // Ids are never reused, so this is the whole lifetime of the count.
+ this.ownedEpoch_.delete(id);
}
/** The latest input command a connection sent (null before the first).
@@ -625,7 +682,7 @@ export class ReplicationServer {
const despawnedNetIds = new Map(despawned.map((d) => [d.entity, d.netId]));
// One snapshot for every connection this sample: a provider prepares
// here, and never on the per-connection path below.
- const visibleFor = this.resolveVisibility_({
+ const visibility = this.resolveVisibility_({
entered: spawnedEntities,
left: despawned.map((d) => d.entity),
// A component going away is not something that component's value feed
@@ -636,12 +693,27 @@ export class ReplicationServer {
// 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>;
+ conn: Connection; visible: ReadonlySet<Entity>; enters: Entity[];
+ leaveIds: number[]; entered: ReadonlySet<Entity>;
}[] = [];
for (const conn of [...this.connections_.values()]) {
if (!conn.ready) continue;
- const visible = visibleFor(conn.id);
+ const stamp = visibility.snapshot === null ? null : {
+ source: this.interestEpoch_,
+ snapshot: visibility.snapshot,
+ owned: this.ownedEpoch_.get(conn.id) ?? 0,
+ };
+ // Nothing this answer is a function of moved: no query, no copy of
+ // a result, neither scan over it. Routing needs no help — the
+ // reverse index is already what this connection holds.
+ if (stamp && sameVisibility(conn.provenance, stamp)) {
+ plans.push({
+ conn, visible: conn.interest, enters: [], leaveIds: [], entered: NOBODY,
+ });
+ continue;
+ }
+ this.visibilityRecomputes++;
+ const visible = visibility.visible(conn.id);
const enters: Entity[] = [];
for (const e of visible) {
if (conn.interest.has(e)) continue;
@@ -656,6 +728,7 @@ export class ReplicationServer {
if (netId !== undefined) leaveIds.push(netId);
}
conn.interest = visible;
+ conn.provenance = stamp;
plans.push({ conn, visible, enters, leaveIds, entered: new Set(enters) });
}
@@ -724,7 +797,7 @@ export class ReplicationServer {
* would cost push's dominant term to decide against push.
*/
private route_(
- plans: { conn: Connection; visible: Set<Entity>; entered: Set<Entity> }[],
+ plans: { conn: Connection; visible: ReadonlySet<Entity>; entered: ReadonlySet<Entity> }[],
dirty: DirtyEntry[],
removals: RemovalEntry[],
): Map<number, { dirty: number[]; removals: number[] }> {
@@ -788,12 +861,19 @@ export class ReplicationServer {
* connection from it. A provider prepares ONCE — that is the whole reason
* it exists — and never sees a materialized candidate array, which is the
* other O(population) the policy shape forces.
+ *
+ * `snapshot` is what the source says this snapshot IS, when it says
+ * anything. Null means the answers below have to be asked for; a number
+ * means a connection whose stamp already carries it holds the same answer.
*/
private resolveVisibility_(membership: {
entered: readonly Entity[];
left: readonly Entity[];
rechecked: readonly Entity[];
- } = { entered: [], left: [], rechecked: [] }): (connectionId: number) => Set<Entity> {
+ } = { entered: [], left: [], rechecked: [] }): {
+ snapshot: number | null;
+ visible: (connectionId: number) => Set<Entity>;
+ } {
// Relevance is decided in world space, so the composition has to be
// current before a snapshot is taken — here rather than inside a position
// reader, so a caller's own reader sees the same composed fact.
@@ -801,7 +881,7 @@ export class ReplicationServer {
const source = this.interest_;
if (!source) {
const all = [...this.known_];
- return () => new Set(all);
+ return { snapshot: null, visible: () => new Set(all) };
}
if (source.kind === 'provider') {
const known = this.known_;
@@ -813,17 +893,22 @@ export class ReplicationServer {
entityCount: known.size,
...membership,
});
- return (connectionId) => {
- const owned = this.ownedByConnection_?.get(connectionId);
- const ownedList = owned ? [...owned] : [];
- const result = prepared.query({ connectionId, owned: ownedList });
- const visible = result === 'all' ? new Set(this.known_) : new Set(result);
- for (const e of ownedList) visible.add(e);
- return visible;
+ return {
+ snapshot: prepared.generation ?? null,
+ visible: (connectionId) => {
+ const owned = this.ownedByConnection_?.get(connectionId);
+ const ownedList = owned ? [...owned] : [];
+ const result = prepared.query({ connectionId, owned: ownedList });
+ const visible = result === 'all' ? new Set(this.known_) : new Set(result);
+ for (const e of ownedList) visible.add(e);
+ return visible;
+ },
};
}
const candidates = [...this.known_];
- return (connectionId) => this.visibleFor_(connectionId, candidates);
+ // A policy is handed the population and asked; there is nothing for it
+ // to certify a repeat answer with.
+ return { snapshot: null, visible: (connectionId) => this.visibleFor_(connectionId, candidates) };
}
/** The policy's answer for one connection, with the server's invariant
@@ -1082,7 +1167,7 @@ export class ReplicationServer {
if (!anyReady) this.rebaseRegistry_();
// Everything relevant right now, full component payloads (current state
// included — no separate baseline frame needed).
- const visible = this.resolveVisibility_()(conn.id);
+ const visible = this.resolveVisibility_().visible(conn.id);
const entities: ReplSpawnEntity[] = [];
for (const e of visible) {
const netId = this.knownNetIds_.get(e);
diff --git a/sdk/tests/replication-interest-reuse.test.ts b/sdk/tests/replication-interest-reuse.test.ts
new file mode 100644
index 000000000..8135c4638
--- /dev/null
+++ b/sdk/tests/replication-interest-reuse.test.ts
@@ -0,0 +1,394 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The sample in which nobody's view could have moved.
+ *
+ * A provider that keeps its index can say what snapshot it IS. When that number,
+ * the installed source and a connection's owned set all still hold, the answer
+ * the connection is already holding is the answer — so it is not queried, the
+ * result is not copied, and neither the enter nor the leave scan runs.
+ *
+ * Everything here is about the ways that certificate can be wrong. A stale
+ * answer is silent by construction: the connection keeps receiving deltas for
+ * exactly the ghosts it holds, and only what should have entered or left is
+ * missing.
+ */
+import { describe, it, expect, afterEach, beforeAll, beforeEach } from 'vitest';
+import { App } from '../src/app/app';
+import { clearUserComponents, defineComponent, Name, Transform } from '../src/ecs/component';
+import { MemoryTransport } from '../src/net/MemoryTransport';
+import { replicationPlugin, Net, Replicated, radiusInterestProvider } from '../src/net/replication';
+import type { InterestProvider, PreparedInterest } from '../src/net/replication/interest';
+import type { Entity } from '../src/types';
+import type { World } from '../src/ecs/world';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+
+const STEP = 1 / 60;
+const RADIUS = 20;
+
+let Health: ReturnType<typeof defineComponent<{ hp: number }>>;
+
+beforeEach(() => {
+ clearUserComponents();
+ Health = defineComponent('ReuseHealth', { hp: 0 }, { replicatedFields: ['hp'] });
+});
+
+const ghosts = (app: App): string[] =>
+ app.world.getEntitiesWithComponents([Replicated])
+ .map((e) => (app.world.tryGet(e, Name) as { value: string } | null)?.value ?? '')
+ .sort();
+
+/**
+ * The provider the server drives, with every `query` on the snapshot it hands
+ * back counted. The generation is FORWARDED, not dropped: a wrapper that ate it
+ * would put the server back on the path this file is about.
+ */
+function counting(inner: InterestProvider) {
+ let queries = 0;
+ const provider: InterestProvider = {
+ prepare(view) {
+ const prepared = inner.prepare(view);
+ return {
+ get generation() { return prepared.generation; },
+ query: (q) => { queries++; return prepared.query(q); },
+ } as PreparedInterest;
+ },
+ dispose: () => inner.dispose?.(),
+ };
+ return { provider, get queries() { return queries; } };
+}
+
+describe.skipIf(!HAS_WASM)('a snapshot nothing moved in is not queried again', () => {
+ let module: ESEngineModule;
+ beforeAll(async () => { module = await loadWasmModule(); });
+ // Change tracking is the ENGINE's, one flag per module — a provider left
+ // installed by one test would otherwise report into the next one's.
+ const opened: App[] = [];
+ afterEach(() => {
+ for (const app of opened.splice(0)) {
+ app.world.setTransformChangeTracking(false);
+ app.world.disconnectCpp();
+ }
+ });
+
+ async function serverWith(connections: number) {
+ 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 clients: { app: App; id: number }[] = [];
+ for (let i = 0; i < connections; i++) {
+ const app = App.new();
+ app.connectCpp(new module.Registry() as unknown as CppRegistry, module, { strict: false });
+ app.addPlugin(replicationPlugin);
+ const [ta, tb] = MemoryTransport.pair();
+ const id = server.attachConnection(ta);
+ await app.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+ opened.push(app);
+ clients.push({ app, id });
+ }
+ 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, Transform, { position: { x, y: 0, z: 0 } });
+ return e;
+ };
+ const move = (e: Entity, x: number) => {
+ serverApp.world.update(e, Transform, (t) => {
+ (t as { position: { x: number } }).position.x = x;
+ });
+ };
+ const give = (e: Entity, owner: number) => {
+ serverApp.world.update(e, Replicated, (d) => { (d as { owner: number }).owner = owner; });
+ };
+ return { serverApp, server, clients, step, place, move, give };
+ }
+
+ /** A settled world: seeded, caught up, and nobody's view still arriving. */
+ async function settled(connections = 1) {
+ const h = await serverWith(connections);
+ const kept = counting(radiusInterestProvider(RADIUS));
+ h.server.setInterestProvider(kept.provider);
+ return { ...h, kept };
+ }
+
+ it('asks nobody while nothing enters, leaves or moves', async () => {
+ const h = await settled(3);
+ for (const c of h.clients) h.place(`anchor${c.id}`, c.id * 1000, c.id);
+ for (let i = 0; i < 6; i++) h.place(`e${i}`, i * 3);
+ await h.step(6);
+
+ const before = h.kept.queries;
+ const recomputes = h.server.visibilityRecomputes;
+ const seen = h.clients.map((c) => ghosts(c.app));
+ await h.step(5);
+
+ // Not a cheaper query: no query at all, and so no copy of its result and
+ // neither scan over it.
+ expect(h.kept.queries - before).toBe(0);
+ expect(h.server.visibilityRecomputes - recomputes).toBe(0);
+ expect(h.clients.map((c) => ghosts(c.app))).toEqual(seen);
+ });
+
+ it('still routes a field that changed to the connections holding the ghost', async () => {
+ const h = await settled(1);
+ const c = h.clients[0]!;
+ h.place('anchor', 0, c.id);
+ const near = h.place('near', 5);
+ h.serverApp.world.insert(near, Health, { hp: 100 });
+ await h.step(6);
+
+ const before = h.kept.queries;
+ h.serverApp.world.update(near, Health, (d) => { (d as { hp: number }).hp = 42; });
+ await h.step(3);
+
+ // Visibility unchanged is not "this connection has nothing coming".
+ expect(h.kept.queries - before).toBe(0);
+ const ghost = c.app.world.getEntitiesWithComponents([Replicated])
+ .find((e) => (c.app.world.tryGet(e, Name) as { value: string } | null)?.value === 'near');
+ expect(ghost).toBeDefined();
+ expect((c.app.world.tryGet(ghost!, Health) as { hp: number } | null)?.hp).toBe(42);
+ });
+
+ it('asks again when something moved, and the move reaches the wire', async () => {
+ const h = await settled(1);
+ const c = h.clients[0]!;
+ h.place('anchor', 0, c.id);
+ const far = h.place('wanderer', 500);
+ await h.step(6);
+ expect(ghosts(c.app)).not.toContain('wanderer');
+
+ const before = h.kept.queries;
+ h.move(far, 4);
+ await h.step(3);
+ expect(h.kept.queries - before).toBeGreaterThan(0);
+ expect(ghosts(c.app)).toContain('wanderer');
+ });
+
+ it('asks again when a spawn joins the world a connection fails open to', async () => {
+ // Owning no positioned anchor, this one's last answer was 'all' — the
+ // population growing is exactly what it cannot be told twice.
+ const h = await settled(1);
+ const c = h.clients[0]!;
+ h.place('somewhere', 5000);
+ await h.step(6);
+ expect(ghosts(c.app)).toEqual(['somewhere']);
+
+ const before = h.kept.queries;
+ h.place('newcomer', 9000);
+ await h.step(3);
+ expect(h.kept.queries - before).toBeGreaterThan(0);
+ expect(ghosts(c.app)).toEqual(['newcomer', 'somewhere']);
+ });
+
+ it('asks again when a despawn takes something out of the world', async () => {
+ const h = await settled(1);
+ const c = h.clients[0]!;
+ h.place('anchor', 0, c.id);
+ const near = h.place('near', 5);
+ await h.step(6);
+ expect(ghosts(c.app)).toContain('near');
+
+ const before = h.kept.queries;
+ h.serverApp.world.despawn(near);
+ await h.step(3);
+ expect(h.kept.queries - before).toBeGreaterThan(0);
+ expect(ghosts(c.app)).not.toContain('near');
+ });
+
+ it('asks again when an entity loses the component its place came from', async () => {
+ const h = await settled(1);
+ const c = h.clients[0]!;
+ h.place('anchor', 0, c.id);
+ const far = h.place('far', 500);
+ await h.step(6);
+ expect(ghosts(c.app)).not.toContain('far');
+
+ // Placeless entities cannot be culled by distance, so this one becomes
+ // relevant to everybody — and no position feed reports it.
+ const before = h.kept.queries;
+ h.serverApp.world.remove(far, Transform);
+ await h.step(3);
+ expect(h.kept.queries - before).toBeGreaterThan(0);
+ expect(ghosts(c.app)).toContain('far');
+ });
+
+ it('asks the two connections an anchor changed hands between, and no others', async () => {
+ const h = await settled(3);
+ const [a, b, idle] = h.clients as [{ app: App; id: number }, { app: App; id: number }, { app: App; id: number }];
+ h.place('a-home', 0, a.id);
+ h.place('b-home', 2000, b.id);
+ h.place('idle-home', 4000, idle.id);
+ const outpost = h.place('outpost', 1000, a.id);
+ h.place('by-outpost', 1004);
+ await h.step(6);
+ expect(ghosts(a.app)).toContain('by-outpost');
+ expect(ghosts(b.app)).not.toContain('by-outpost');
+
+ // The index does not move a byte: the same entities stand in the same
+ // cells. What changed is which of them each connection looks FROM.
+ const recomputes = h.server.visibilityRecomputes;
+ const idleSaw = ghosts(idle.app);
+ h.give(outpost, b.id);
+ await h.step(3);
+
+ expect(h.server.visibilityRecomputes - recomputes).toBe(2);
+ expect(ghosts(a.app)).not.toContain('by-outpost');
+ expect(ghosts(b.app)).toContain('by-outpost');
+ expect(ghosts(idle.app)).toEqual(idleSaw);
+ });
+
+ it('asks a connection that has never been answered, and no one else', async () => {
+ const h = await settled(1);
+ const first = h.clients[0]!;
+ h.place('anchor', 0, first.id);
+ h.place('near', 5);
+ await h.step(6);
+
+ const recomputes = h.server.visibilityRecomputes;
+ const late = App.new();
+ late.connectCpp(new module.Registry() as unknown as CppRegistry, module, { strict: false });
+ late.addPlugin(replicationPlugin);
+ opened.push(late);
+ const [ta, tb] = MemoryTransport.pair();
+ h.server.attachConnection(ta);
+ await late.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+ await late.tick(STEP);
+ await h.step(3);
+
+ // The joiner holds no certificate, so it is proved; the settled one is
+ // not re-proved because somebody else arrived.
+ expect(h.server.visibilityRecomputes - recomputes).toBe(1);
+ expect(ghosts(late)).toEqual(['anchor', 'near']);
+ });
+});
+
+describe('what does not certify a repeat', () => {
+ let NetPos: ReturnType<typeof defineComponent<{ x: number; y: number; z: number }>>;
+ beforeEach(() => { NetPos = defineComponent('ReusePos', { 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;
+
+ async function serverWith(connections: number) {
+ const serverApp = App.new();
+ serverApp.addPlugin(replicationPlugin);
+ const server = serverApp.getResource(Net).startServer();
+ const clients: { app: App; id: 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 });
+ }
+ 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;
+ };
+ return { serverApp, server, clients, step, place };
+ }
+
+ /** A provider whose snapshot identity the test states outright: the subject
+ * is what the SERVER does with a number, not how a grid arrives at one. */
+ function stating(generation: number, visible: () => ReadonlySet<Entity>) {
+ let queries = 0;
+ const provider: InterestProvider = {
+ prepare: () => ({ generation, query: () => { queries++; return visible(); } }),
+ };
+ return { provider, get queries() { return queries; } };
+ }
+
+ it('publishes a snapshot identity only from the lane that can keep one', () => {
+ const world = App.new().world;
+ const view = {
+ world, entities: [] as Entity[], entityCount: 0,
+ entered: [] as Entity[], left: [] as Entity[], rechecked: [] as Entity[],
+ };
+ // Behaviour cannot tell these apart while the rebuilt lane reseeds — and
+ // so bumps — every sample. The contract is what stops a later cheaper
+ // reseed from quietly certifying a function nothing can certify.
+ expect(radiusInterestProvider(RADIUS).prepare(view).generation).toBeTypeOf('number');
+ expect(radiusInterestProvider(RADIUS, { position: posOf }).prepare(view).generation)
+ .toBeUndefined();
+ });
+
+ it('keeps an arbitrary position reader on the per-sample query', async () => {
+ const h = await serverWith(2);
+ for (const c of h.clients) h.place(`anchor${c.id}`, c.id * 500, c.id);
+ h.place('near', 3);
+ const kept = counting(radiusInterestProvider(RADIUS, { position: posOf }));
+ h.server.setInterestProvider(kept.provider);
+ await h.step(4);
+
+ // Nothing can know when an arbitrary function would answer differently,
+ // so a stationary sample buys nothing here — and must not pretend to.
+ const before = kept.queries;
+ await h.step(2);
+ expect(kept.queries - before).toBe(4);
+ });
+
+ it('does not read one provider\'s generation as another\'s', async () => {
+ const h = await serverWith(1);
+ const c = h.clients[0]!;
+ const near = h.place('near', 0);
+ const far = h.place('far', 900);
+ const a = stating(5, () => new Set([near]));
+ h.server.setInterestProvider(a.provider);
+ await h.step(4);
+ expect(ghosts(c.app)).toEqual(['near']);
+
+ // The same number from a different source is a different snapshot.
+ const b = stating(5, () => new Set([far]));
+ h.server.setInterestProvider(b.provider);
+ await h.step(4);
+ expect(b.queries).toBeGreaterThan(0);
+ expect(ghosts(c.app)).toEqual(['far']);
+ });
+
+ it('leaves nothing reusable behind when the initial send is refused', async () => {
+ const h = await serverWith(1);
+ const survivor = h.clients[0]!;
+ const near = h.place('near', 0);
+ const source = stating(7, () => new Set([near]));
+ h.server.setInterestProvider(source.provider);
+ await h.step(4);
+ const settled = h.server.visibilityRecomputes;
+
+ 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 one.
+ 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(3);
+
+ // The corpse holds no view and forces no one else to be re-proved: the
+ // stamp died with the connection rather than outliving it in a Map.
+ expect(h.server.viewerLinks).toBe(1);
+ expect(h.server.visibilityRecomputes - settled).toBe(0);
+ expect(ghosts(survivor.app)).toEqual(['near']);
+ });
+});