Files
OpenFrontIO/tests/PackedPlayerUpdates.test.ts
T
Evan bca980f572 Shrink the per-tick worker → main update payload by ~90% (#4244)
Stacked on #4243 (the `perf:client` harness) — first step of fixing the
every-100ms main-thread stutter: make the per-tick burst small before
spreading what remains across frames.

## Problem

The harness showed the main-thread burst was dominated by
`structuredClone` of the `updates` object, and the clone was dominated
by two kinds of per-tick churn that re-sent object payloads every tick:

- `gold` / `troops` / `tilesOwned` change for nearly every alive player
every tick → ~278 partial `PlayerUpdate` objects per tick (world/400
bots), ~508 on giantworldmap.
- Attack troop counts tick down every tick → whole
`outgoingAttacks`/`incomingAttacks` arrays re-cloned for every fighting
player every tick.
- `playerNameViewData` (an all-players record) was cloned every tick but
only recomputed every 30 ticks.

## Change

Three additions to the worker → main protocol (all transferable,
zero-clone):

1. **`packedPlayerUpdates`** — `[smallID, tilesOwned, gold, troops]`
float64 quads for players whose stats changed. These fields no longer
appear in `PlayerUpdate` diffs (first emissions still carry the full
snapshot). Gold is exact in a float64 (game values ≪ 2^53).
2. **`packedAttackUpdates`** — `[ownerSmallID, direction, index,
troops]` quads. Attack arrays are only resent when
membership/order/retreating changes — which is exactly the condition
that keeps the patch indexes valid (a tick either resends an array or
patches it, never both).
3. **`playerNameViewData` is now optional** — attached only on
placement-rebuild ticks (spawn ticks, first ticks, every 30th, spawn
end). The client keeps the last applied values; dead players' name
placements freeze at death (matching the previous effective behavior).

On the client, `GameView.populateFrame` now also rebuilds `names` /
`relationMatrix` / `allianceClusters` only when their inputs changed
that tick — field presence on a partial `PlayerUpdate` marks them dirty.
(`playerStatus`, nuke telegraphs, and attack rings still recompute every
tick; they're tick- or unit-dependent.)

## Results (perf:client, this machine; low-end devices ~5–20× slower)

Default run (world, 400 bots, 1800 ticks):

| stage | before | after |
|---|---|---|
| clone (serialize+deserialize) | 1.02ms | **0.09ms** |
| GameView.update | 0.62ms | **0.29ms** |
| WebGLFrameBuilder.update | 0.04ms | 0.04ms |
| **TOTAL burst mean** | **1.67ms** | **0.42ms** |
| TOTAL p99 / max | 3.47 / 10.3ms | **1.21 / 3.92ms** |

giantworldmap/600t: 2.54 → 0.68ms mean. Player update objects: 278 → 6.5
per tick (world), 508 → 12 (giant). The remaining burst is mostly tile
apply + per-tick derivations — the part that frame-spreading (next step)
addresses.

## Verification

- **Sim final hash unchanged** on all three reference configs
(`5607618202213430`, `29309648281599524`, `39945089450032050`) — no
simulation behavior change.
- **View hash unchanged** on all three configs (`942106e9`, `a3aae227`,
`cbaaf265`) — the rendered view state is provably identical
tick-for-tick, including the name-freeze semantics.
- New tests: `tests/PackedPlayerUpdates.test.ts` (drain + GameRunner
cadence), packed-channel and freeze-at-death cases in
`tests/client/view/GameView.test.ts`, `packAttackTroopDeltas` unit tests
and updated diff contract in `tests/GameUpdateUtils.test.ts` /
`tests/PlayerUpdateDiff.test.ts`.
- `npm test` (1490 tests), `eslint`, `prettier`, `tsc --noEmit` all
pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 16:50:56 -07:00

156 lines
5.1 KiB
TypeScript

/**
* The worker→main tick payload: per-tick numeric stat churn travels on the
* transferable `packedPlayerUpdates` quad buffer (drained from GameImpl),
* and `playerNameViewData` is attached only on ticks where the worker
* recomputed name placements. See GameUpdateViewData in GameUpdates.ts.
*/
import { Executor } from "../src/core/execution/ExecutionManager";
import { SpawnExecution } from "../src/core/execution/SpawnExecution";
import { Game, Player, PlayerInfo, PlayerType } from "../src/core/game/Game";
import {
GameUpdateType,
GameUpdateViewData,
} from "../src/core/game/GameUpdates";
import { GameRunner } from "../src/core/GameRunner";
import { setup } from "./util/Setup";
const gameID = "game_id";
describe("packedPlayerUpdates (GameImpl drain)", () => {
let game: Game;
let alice: Player;
beforeEach(async () => {
game = await setup("plains", {});
const aliceInfo = new PlayerInfo(
"alice",
PlayerType.Human,
"alice_client",
"alice_id",
);
game.addPlayer(aliceInfo);
game.addExecution(new SpawnExecution(gameID, aliceInfo, game.ref(10, 10)));
game.executeNextTick();
game.executeNextTick();
alice = game.player("alice_id");
game.drainPackedPlayerUpdates(); // discard spawn-time churn
});
test("a stat change is drained as a [smallID, tiles, gold, troops] quad", () => {
alice.addGold(500n);
game.executeNextTick();
const packed = game.drainPackedPlayerUpdates();
expect(packed).not.toBeNull();
// Find alice's quad (other players may have churned too).
let quad: number[] | undefined;
for (let i = 0; i + 3 < packed!.length; i += 4) {
if (packed![i] === alice.smallID()) {
quad = Array.from(packed!.subarray(i, i + 4));
}
}
expect(quad).toEqual([
alice.smallID(),
alice.numTilesOwned(),
Number(alice.gold()),
alice.troops(),
]);
});
test("drain returns null when no stats changed and resets between drains", () => {
alice.addGold(500n);
game.executeNextTick();
expect(game.drainPackedPlayerUpdates()).not.toBeNull();
// Drained — a second drain without a tick has nothing.
expect(game.drainPackedPlayerUpdates()).toBeNull();
});
});
describe("GameRunner payload cadence", () => {
let game: Game;
let byTick: Map<number, GameUpdateViewData>;
let tick: () => void;
beforeEach(async () => {
game = await setup(
"plains",
{},
[],
undefined,
undefined,
false, // keep the spawn phase under the test's control
);
const aliceInfo = new PlayerInfo(
"alice",
PlayerType.Human,
"alice_client",
"alice_id",
);
game.addPlayer(aliceInfo);
game.addExecution(new SpawnExecution(gameID, aliceInfo, game.ref(10, 10)));
byTick = new Map();
const runner = new GameRunner(
game,
new Executor(game, gameID, "alice_client"),
(gu) => {
if (!("errMsg" in gu)) byTick.set(gu.tick, gu);
},
);
// No runner.init(): no SpawnTimerExecution — the game stays in the spawn
// phase until the test ends it manually.
let turn = 0;
tick = () => {
runner.addTurn({ turnNumber: turn++, intents: [] });
runner.executeNextTick();
};
});
test("playerNameViewData is attached only on placement-rebuild ticks", () => {
tick(); // 1
tick(); // 2
game.endSpawnPhase();
for (let t = 3; t <= 61; t++) tick();
// ticks < 3 always rebuild; every 30th tick rebuilds; everything else
// omits the record. (The in-tick spawn-end rebuild also sets the flag,
// but ending the spawn phase between ticks doesn't exercise it here.)
expect(byTick.get(1)!.playerNameViewData).toBeDefined();
expect(byTick.get(2)!.playerNameViewData).toBeDefined();
expect(byTick.get(4)!.playerNameViewData).toBeUndefined();
expect(byTick.get(29)!.playerNameViewData).toBeUndefined();
expect(byTick.get(30)!.playerNameViewData).toBeDefined();
expect(byTick.get(31)!.playerNameViewData).toBeUndefined();
expect(byTick.get(60)!.playerNameViewData).toBeDefined();
});
test("stat churn arrives as packedPlayerUpdates quads on the view data", () => {
tick(); // 1
tick(); // 2
game.endSpawnPhase();
tick(); // 3 — flush spawn churn
const alice = game.player("alice_id");
alice.addGold(500n);
tick(); // 4
const gu = byTick.get(game.ticks())!;
const packed = gu.packedPlayerUpdates;
expect(packed).toBeDefined();
expect(packed!.length % 4).toBe(0);
let quad: number[] | undefined;
for (let i = 0; i + 3 < packed!.length; i += 4) {
if (packed![i] === alice.smallID()) {
quad = Array.from(packed!.subarray(i, i + 4));
}
}
expect(quad).toEqual([
alice.smallID(),
alice.numTilesOwned(),
Number(alice.gold()),
alice.troops(),
]);
// And the object channel no longer carries the stat fields: alice must
// not appear in this tick's PlayerUpdates for a gold-only change.
const playerUpdates = gu.updates[GameUpdateType.Player];
expect(playerUpdates.find((u) => u.id === "alice_id")).toBeUndefined();
});
});