Speed up the core sim: inline sfc32 PRNG and allocation-free player updates (#4233)

## Summary

Follow-up to #4230. Two more core-sim optimizations — these are
**behavior-affecting in controlled ways** (unlike #4230, which was
hash-identical), so both come with dedicated test coverage written
before the change.

Combined results (`npm run perf:game`, same machine, before → after):

| run | mean tick | ticks/sec | p99 | peak heap |
|---|---|---|---|---|
| default (world, 400 bots, 1800 ticks) | 7.98 → **6.96 ms** | 125 →
**144** | 21.2 → **19.0 ms** | 438 → **294 MB** |
| giantworldmap, 600 ticks | 17.4 → **15.2 ms** | 58 → **66** | 32.6 →
30.5 ms | |

Cumulative with #4230 vs. the original baseline: default run mean 9.04 →
6.96 ms (111 → 144 ticks/sec); giantworldmap 22.5 → 15.2 ms (44 → 66
ticks/sec, max tick 52.8 → 40.1 ms).

### 1. `PseudoRandom`: seedrandom ARC4 → inline sfc32

- ARC4 was ~4% of profiled self time. The new engine is sfc32 with
splitmix32 seed expansion and a warmup, using only 32-bit integer ops —
sequences are identical across platforms. The class API is unchanged.
- This **removes the `seedrandom` dependency entirely**, making
`src/core` actually dependency-free (the import was the only violation
of that rule).
- ⚠️ **The random stream differs, so the deterministic game-state hash
changes.** All clients run the same code, so cross-client sync is
unaffected; the harness reproduces the same hash on repeated runs per
seed. New reference hashes:
  - `--map world --ticks 200 --bots 100` → `5607618202213430`
  - default run → `29309648281599524`
  - `--map giantworldmap --ticks 600` → `39945089450032050`
- New `tests/PseudoRandom.test.ts` (15 tests) pins the engine-agnostic
contract: per-seed determinism, ranges, uniformity, adjacent-seed
decorrelation, and every API method. The tests were verified green
against the old engine first, then the swap.
- The stream change exposed a test that passed **by RNG luck**: in
`AiAttackBehavior.test.ts`, "nation cannot attack allied player" was
actually being blocked by the difficulty dice gate in `shouldAttack`,
not the alliance check — hiding that the test's `AiAttackBehavior` was
constructed without its `NationEmojiBehavior`. The test now supplies one
and verifies the real protection layer (`AttackExecution`'s alliance
check), robust to any dice outcome.

### 2. `PlayerImpl.toFullUpdate`: allocation-free empty collections

- `toFullUpdate` runs for every player every tick and allocated ~10
collections each (allies, embargoes Set, attacks, alliance views, …)
even when all were empty — the common case for most of 472 players.
Because `lastSentUpdate` retains each snapshot for a full tick, these
objects survived minor GC, got promoted, and accumulated as old-space
garbage between major GCs — that's the peak-heap drop.
- Empty collections now reuse shared **frozen** module-level singletons,
so `diffPlayerUpdate`'s existing `a === b` fast paths skip structural
comparison entirely. Non-empty collections build in single passes.
Freezing makes accidental in-worker mutation throw loudly instead of
silently corrupting every player; consumers across the worker boundary
get mutable structured clones as before. (`Set` cannot be frozen —
`EMPTY_EMBARGOES` is documented as never-mutate.)
- Value-identical: the game-state hash is unchanged by this part
(verified against the post-PRNG baseline).
- New `tests/PlayerUpdateDiff.test.ts` (8 tests): full-snapshot shape,
null-when-unchanged, embargo/alliance/target/attack diffs through the
real tick pipeline, and the freeze contract.

### Verification

- Full suite passes: 124 files / 1408 tests (23 new) + server tests;
lint and prettier clean.
- Hash reproducibility confirmed: repeated runs with identical args
produce identical hashes on all three configs.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Evan
2026-06-12 08:15:01 -07:00
committed by GitHub
co-authored by Claude Fable 5
parent 1ef3fca2ac
commit 2e6f70c098
7 changed files with 505 additions and 66 deletions
+36 -8
View File
@@ -1,34 +1,62 @@
import seedrandom from "seedrandom";
export class PseudoRandom {
private rng: seedrandom.PRNG;
// sfc32 state. All operations are 32-bit integer ops, so sequences are
// identical across platforms.
private s0: number;
private s1: number;
private s2: number;
private s3: number;
private static readonly POW36_8 = Math.pow(36, 8); // Pre-compute 36^8
constructor(seed: number) {
this.rng = seedrandom(String(seed));
// The seed is truncated to 32 bits: seeds congruent mod 2^32 produce
// identical streams, and fractional parts are discarded.
// Expand the numeric seed into four state words with splitmix32.
let h = seed | 0;
const split = () => {
h = (h + 0x9e3779b9) | 0;
let t = h ^ (h >>> 16);
t = Math.imul(t, 0x21f0aaad);
t = t ^ (t >>> 15);
t = Math.imul(t, 0x735a2d97);
return (t ^ (t >>> 15)) | 0;
};
this.s0 = split();
this.s1 = split();
this.s2 = split();
this.s3 = split();
// Warm up to diffuse low-entropy seeds (sequential ints, small numbers).
for (let i = 0; i < 12; i++) {
this.next();
}
}
// Generates the next pseudorandom number between 0 and 1.
next(): number {
return this.rng();
const t = (((this.s0 + this.s1) | 0) + this.s3) | 0;
this.s3 = (this.s3 + 1) | 0;
this.s0 = this.s1 ^ (this.s1 >>> 9);
this.s1 = (this.s2 + (this.s2 << 3)) | 0;
this.s2 = (this.s2 << 21) | (this.s2 >>> 11);
this.s2 = (this.s2 + t) | 0;
return (t >>> 0) / 4294967296;
}
// Generates a random integer between min (inclusive) and max (exclusive).
nextInt(min: number, max: number): number {
const lo = Math.floor(min);
const hi = Math.floor(max);
return Math.floor(this.rng() * (hi - lo)) + lo;
return Math.floor(this.next() * (hi - lo)) + lo;
}
// Generates a random float between min (inclusive) and max (exclusive).
nextFloat(min: number, max: number): number {
return this.rng() * (max - min) + min;
return this.next() * (max - min) + min;
}
// Generates a random ID (8 characters, alphanumeric).
nextID(): string {
return Math.floor(this.rng() * PseudoRandom.POW36_8)
return Math.floor(this.next() * PseudoRandom.POW36_8)
.toString(36)
.padStart(8, "0");
}
+112 -38
View File
@@ -66,6 +66,25 @@ class Donation {
) {}
}
// Shared singletons for empty collections in toFullUpdate. Sharing
// references lets diffPlayerUpdate's `a === b` fast paths skip structural
// comparison and avoids per-player-per-tick allocations. The arrays are
// frozen so accidental in-worker mutation throws instead of silently
// corrupting every player's updates; updates crossing to the main thread
// are structured-cloned (clones are mutable). Sets cannot be frozen
// (Set.add ignores freeze) — EMPTY_EMBARGOES must never be mutated.
const EMPTY_NUMBER_ARRAY: number[] = [];
const EMPTY_STRING_ARRAY: string[] = [];
const EMPTY_ATTACK_UPDATES: AttackUpdate[] = [];
const EMPTY_ALLIANCE_VIEWS: AllianceView[] = [];
const EMPTY_EMOJIS: EmojiMessage[] = [];
const EMPTY_EMBARGOES = new Set<string>();
Object.freeze(EMPTY_NUMBER_ARRAY);
Object.freeze(EMPTY_STRING_ARRAY);
Object.freeze(EMPTY_ATTACK_UPDATES);
Object.freeze(EMPTY_ALLIANCE_VIEWS);
Object.freeze(EMPTY_EMOJIS);
export class PlayerImpl implements Player {
public _lastTileChange: number = 0;
public _pseudo_random: PseudoRandom;
@@ -146,9 +165,92 @@ export class PlayerImpl implements Player {
}
private toFullUpdate(): PlayerUpdate {
const outgoingAllianceRequests = this.outgoingAllianceRequests().map((ar) =>
ar.recipient().id(),
);
// Empty collections reuse shared singletons (EMPTY_*) so
// diffPlayerUpdate's reference fast paths hit and nothing is allocated.
// This runs for every player every tick; most collections are empty for
// most players. The singletons are never mutated — updates are
// structured-cloned before leaving the worker.
let outgoingAllianceRequests = EMPTY_STRING_ARRAY;
for (const ar of this.mg.allianceRequests) {
if (ar.requestor() === this) {
if (outgoingAllianceRequests === EMPTY_STRING_ARRAY) {
outgoingAllianceRequests = [];
}
outgoingAllianceRequests.push(ar.recipient().id());
}
}
const alliances = this.alliances();
let allies = EMPTY_NUMBER_ARRAY;
let allianceViews = EMPTY_ALLIANCE_VIEWS;
if (alliances.length > 0) {
allies = alliances.map((a) => a.other(this).smallID());
const extensionCutoff =
this.mg.ticks() + this.mg.config().allianceExtensionPromptOffset();
allianceViews = alliances.map(
(a) =>
({
id: a.id(),
other: a.other(this).id(),
createdAt: a.createdAt(),
expiresAt: a.expiresAt(),
hasExtensionRequest: a.expiresAt() <= extensionCutoff,
}) satisfies AllianceView,
);
}
let embargoes = EMPTY_EMBARGOES;
if (this.embargoes.size > 0) {
embargoes = new Set<string>();
for (const id of this.embargoes.keys()) {
embargoes.add(id.toString());
}
}
let targets = EMPTY_NUMBER_ARRAY;
if (this.targets_.length > 0) {
const t = this.targets();
if (t.length > 0) {
targets = t.map((p) => p.smallID());
}
}
let outgoingEmojis = EMPTY_EMOJIS;
if (this.outgoingEmojis_.length > 0) {
const e = this.outgoingEmojis();
if (e.length > 0) {
outgoingEmojis = e;
}
}
const outgoingAttacks =
this._outgoingAttacks.length === 0
? EMPTY_ATTACK_UPDATES
: this._outgoingAttacks.map((a) => {
return {
attackerID: a.attacker().smallID(),
targetID: a.target().smallID(),
troops: a.troops(),
id: a.id(),
retreating: a.retreating(),
} satisfies AttackUpdate;
});
let incomingAttacks = EMPTY_ATTACK_UPDATES;
if (this._incomingAttacks.length > 0) {
const incoming = this.incomingAttacks();
if (incoming.length > 0) {
incomingAttacks = incoming.map((a) => {
return {
attackerID: a.attacker().smallID(),
targetID: a.target().smallID(),
troops: a.troops(),
id: a.id(),
retreating: a.retreating(),
} satisfies AttackUpdate;
});
}
}
return {
type: GameUpdateType.Player,
@@ -164,44 +266,16 @@ export class PlayerImpl implements Player {
tilesOwned: this.numTilesOwned(),
gold: this._gold,
troops: this.troops(),
allies: this.alliances().map((a) => a.other(this).smallID()),
embargoes: new Set([...this.embargoes.keys()].map((p) => p.toString())),
allies: allies,
embargoes: embargoes,
isTraitor: this.isTraitor(),
traitorRemainingTicks: this.getTraitorRemainingTicks(),
targets: this.targets().map((p) => p.smallID()),
outgoingEmojis: this.outgoingEmojis(),
outgoingAttacks: this.outgoingAttacks().map((a) => {
return {
attackerID: a.attacker().smallID(),
targetID: a.target().smallID(),
troops: a.troops(),
id: a.id(),
retreating: a.retreating(),
} satisfies AttackUpdate;
}),
incomingAttacks: this.incomingAttacks().map((a) => {
return {
attackerID: a.attacker().smallID(),
targetID: a.target().smallID(),
troops: a.troops(),
id: a.id(),
retreating: a.retreating(),
} satisfies AttackUpdate;
}),
targets: targets,
outgoingEmojis: outgoingEmojis,
outgoingAttacks: outgoingAttacks,
incomingAttacks: incomingAttacks,
outgoingAllianceRequests: outgoingAllianceRequests,
alliances: this.alliances().map(
(a) =>
({
id: a.id(),
other: a.other(this).id(),
createdAt: a.createdAt(),
expiresAt: a.expiresAt(),
hasExtensionRequest:
a.expiresAt() <=
this.mg.ticks() +
this.mg.config().allianceExtensionPromptOffset(),
}) satisfies AllianceView,
),
alliances: allianceViews,
hasSpawned: this.hasSpawned(),
spawnTile: this._spawnTile,
betrayals: this._betrayalCount,