mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-01 14:43:25 +00:00
2e6f70c098
## 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>
107 lines
3.0 KiB
TypeScript
107 lines
3.0 KiB
TypeScript
export class PseudoRandom {
|
|
// 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) {
|
|
// 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 {
|
|
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.next() * (hi - lo)) + lo;
|
|
}
|
|
|
|
// Generates a random float between min (inclusive) and max (exclusive).
|
|
nextFloat(min: number, max: number): number {
|
|
return this.next() * (max - min) + min;
|
|
}
|
|
|
|
// Generates a random ID (8 characters, alphanumeric).
|
|
nextID(): string {
|
|
return Math.floor(this.next() * PseudoRandom.POW36_8)
|
|
.toString(36)
|
|
.padStart(8, "0");
|
|
}
|
|
|
|
// Selects a random element from an array.
|
|
randElement<T>(arr: T[]): T {
|
|
if (arr.length === 0) {
|
|
throw new Error("array must not be empty");
|
|
}
|
|
return arr[this.nextInt(0, arr.length)];
|
|
}
|
|
|
|
// Selects a random element from a set.
|
|
randFromSet<T>(set: Set<T>): T {
|
|
const size = set.size;
|
|
if (size === 0) {
|
|
throw new Error("set must not be empty");
|
|
}
|
|
|
|
const index = this.nextInt(0, size);
|
|
let i = 0;
|
|
for (const item of set) {
|
|
if (i === index) {
|
|
return item;
|
|
}
|
|
i++;
|
|
}
|
|
|
|
// This should never happen
|
|
throw new Error("Unexpected error selecting element from set");
|
|
}
|
|
|
|
// Returns true with probability 1/odds.
|
|
chance(odds: number): boolean {
|
|
return this.nextInt(0, odds) === 0;
|
|
}
|
|
|
|
// Returns a shuffled copy of the array using Fisher-Yates algorithm.
|
|
shuffleArray<T>(array: T[]): T[] {
|
|
const result = [...array];
|
|
for (let i = result.length - 1; i > 0; i--) {
|
|
const j = this.nextInt(0, i + 1);
|
|
[result[i], result[j]] = [result[j], result[i]];
|
|
}
|
|
return result;
|
|
}
|
|
}
|