Files
OpenFrontIO/tests/PseudoRandom.test.ts
T
Evan 2e6f70c098 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>
2026-06-12 08:15:01 -07:00

156 lines
4.6 KiB
TypeScript

import { PseudoRandom } from "../src/core/PseudoRandom";
describe("PseudoRandom", () => {
test("same seed produces an identical sequence", () => {
const a = new PseudoRandom(42);
const b = new PseudoRandom(42);
for (let i = 0; i < 1000; i++) {
expect(a.next()).toBe(b.next());
}
});
test("same seed produces identical derived values", () => {
const a = new PseudoRandom(987654);
const b = new PseudoRandom(987654);
for (let i = 0; i < 100; i++) {
expect(a.nextInt(0, 1000)).toBe(b.nextInt(0, 1000));
}
expect(a.nextID()).toBe(b.nextID());
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
expect(a.shuffleArray(arr)).toEqual(b.shuffleArray(arr));
});
test("different seeds produce different sequences", () => {
const a = new PseudoRandom(1);
const b = new PseudoRandom(2);
let same = 0;
for (let i = 0; i < 100; i++) {
if (a.next() === b.next()) same++;
}
expect(same).toBeLessThan(5);
});
test("consecutive integer seeds are not correlated", () => {
// Weak seeding schemes make adjacent seeds (common: tick numbers,
// sequential hashes) produce similar streams.
const values: number[] = [];
for (let seed = 1000; seed < 1100; seed++) {
values.push(new PseudoRandom(seed).nextInt(0, 100));
}
const distinct = new Set(values).size;
expect(distinct).toBeGreaterThan(50);
});
test("next() stays within [0, 1)", () => {
const r = new PseudoRandom(7);
for (let i = 0; i < 10000; i++) {
const v = r.next();
expect(v).toBeGreaterThanOrEqual(0);
expect(v).toBeLessThan(1);
}
});
test("next() is roughly uniform", () => {
const r = new PseudoRandom(1234);
const n = 20000;
let sum = 0;
const buckets = new Array(10).fill(0);
for (let i = 0; i < n; i++) {
const v = r.next();
sum += v;
buckets[Math.floor(v * 10)]++;
}
expect(sum / n).toBeGreaterThan(0.48);
expect(sum / n).toBeLessThan(0.52);
for (const count of buckets) {
// Expected 2000 per bucket; allow generous slack.
expect(count).toBeGreaterThan(1700);
expect(count).toBeLessThan(2300);
}
});
test("nextInt returns integers in [min, max)", () => {
const r = new PseudoRandom(99);
const seen = new Set<number>();
for (let i = 0; i < 10000; i++) {
const v = r.nextInt(3, 8);
expect(Number.isInteger(v)).toBe(true);
expect(v).toBeGreaterThanOrEqual(3);
expect(v).toBeLessThan(8);
seen.add(v);
}
expect([...seen].sort()).toEqual([3, 4, 5, 6, 7]);
});
test("nextInt with a single-value range always returns it", () => {
const r = new PseudoRandom(5);
for (let i = 0; i < 100; i++) {
expect(r.nextInt(4, 5)).toBe(4);
}
});
test("nextInt floors non-integer bounds", () => {
const r = new PseudoRandom(5);
for (let i = 0; i < 100; i++) {
const v = r.nextInt(1.9, 4.7);
expect(v).toBeGreaterThanOrEqual(1);
expect(v).toBeLessThan(4);
}
});
test("nextFloat stays within [min, max)", () => {
const r = new PseudoRandom(11);
for (let i = 0; i < 1000; i++) {
const v = r.nextFloat(2.5, 3.5);
expect(v).toBeGreaterThanOrEqual(2.5);
expect(v).toBeLessThan(3.5);
}
});
test("nextID returns 8 alphanumeric characters", () => {
const r = new PseudoRandom(123);
for (let i = 0; i < 100; i++) {
expect(r.nextID()).toMatch(/^[0-9a-z]{8}$/);
}
});
test("randElement picks members and throws on empty", () => {
const r = new PseudoRandom(77);
const arr = ["a", "b", "c"];
for (let i = 0; i < 100; i++) {
expect(arr).toContain(r.randElement(arr));
}
expect(() => r.randElement([])).toThrow();
});
test("randFromSet picks members and throws on empty", () => {
const r = new PseudoRandom(78);
const set = new Set(["x", "y", "z"]);
for (let i = 0; i < 100; i++) {
expect(set.has(r.randFromSet(set))).toBe(true);
}
expect(() => r.randFromSet(new Set())).toThrow();
});
test("chance(1) is always true, chance(large) is mostly false", () => {
const r = new PseudoRandom(31);
for (let i = 0; i < 100; i++) {
expect(r.chance(1)).toBe(true);
}
let hits = 0;
for (let i = 0; i < 1000; i++) {
if (r.chance(1000)) hits++;
}
expect(hits).toBeLessThan(10);
});
test("shuffleArray returns a permutation and leaves the input unchanged", () => {
const r = new PseudoRandom(55);
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const copy = [...input];
const shuffled = r.shuffleArray(input);
expect(input).toEqual(copy);
expect([...shuffled].sort((a, b) => a - b)).toEqual(copy);
});
});