1
0
Fork 0
polaris-task-force/tests/int/bomperator-prediction.int.spec.ts
Z8MB1E d15beb8e35 fix(minigames): end Bomperator WS jitter with ack-sized envelope and rate-limited trims
Prod telemetry (bompDebug, 783 snapshots): ping RTT of 3-24ms shrank the
correction envelope to ~0.75 cells while the real gap noise floor sat at
p95 1.0, so 13% of snapshots trimmed and each trim closed its whole
excess in one frame - constant micro-teleports.

- size the envelope from transport RTT plus the server-side component of
  measured input-to-ack latency (tick queue + snapshot turnaround),
  which ping/pong cannot see; HTTP behavior stays near the v0.12.6 tuning
- rate-limit trims to 0.35 cells per snapshot (a run-speed glide); the
  >2.5-cell ease branch remains the fallback for genuine divergence
- harness mirror updated: maxJump now capped at 0.35 across all 12
  scenarios, prod-trace pulls 162 -> 47, zero teleports throughout
2026-10-20 02:02:00 -04:00

863 lines
33 KiB
TypeScript

/**
* Offline prediction harness for Ordnance Disposal.
*
* Reproduces the full client/server loop in silico: the real engine ticks at
* TICK_MS with the registry's immediate-apply input semantics, a modeled
* network delays inputs and snapshots (one-way latency, jitter, POST round
* trips feeding the client's RTT EMA, React/rAF pipeline lag on delivery), and
* a frame-by-frame replica of BomperatorGame's prediction + reconcile logic
* (pending ledger, ack drain, timed replay, deadzone pull, hard snap) runs
* against it.
*
* Why this exists: production playtests reported frequent "teleport back to
* where the server last saw me" snaps during heavy movement. Snaps fire when
* |est - pred| > 2.5 cells; the telemetry below separates the two ways that
* can happen - pred genuinely ran away from the server (predErr large) or the
* estimator produced a bad estimate (estErr large) - so fixes target the real
* mechanism instead of guesswork.
*
* Everything is deterministic (seeded PRNG, fixed map, scripted keys), so a
* failing scenario is a reproducible regression target.
*/
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import {
GRID_H,
GRID_W,
TICK_MS,
applyInput,
buildBomperatorView,
createMatchState,
startRound,
tick,
type BomperatorInput,
type BomperatorState,
type Dir,
} from "@/lib/minigames/bomperator";
import {
PRED_DEADZONE,
PRED_ENVELOPE_BUDGET_MS,
predAdvance,
projectServerPosition,
type PredictBomb,
type RenderPos,
} from "@/lib/minigames/bomperator/prediction";
/* ------------------------------------------------------------- test helpers */
/** Deterministic PRNG so jitter never makes a failure unreproducible. */
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function percentile(samples: readonly number[], q: number): number {
if (samples.length === 0) return 0;
const sorted = [...samples].sort((a, b) => a - b);
return sorted[Math.min(sorted.length - 1, Math.floor(q * (sorted.length - 1)))];
}
const SUBSTEP_MS = 5;
const FRAME_MS = 16;
interface SimSnapshot {
version: number;
deliverAt: number;
me: {
x: number;
y: number;
dir: Dir;
speed: number;
kick: boolean;
alive: boolean;
bombsMax: number;
bombsActive: number;
lastInputSeq: number;
};
bombs: { id: string; x: number; y: number; ownerSeat: number }[];
grid: number[];
}
interface ScenarioConfig {
durationMs: number;
seed: number;
/** One-way network latency baseline (ms). */
oneWayMs: number;
/** +/- jitter applied to every arrival and delivery. */
jitterMs: number;
/** Extra snapshot delivery lag: SSE event -> React setState -> rAF frame. */
pipelineMs: number;
/** POST round-trip baseline the client's RTT EMA observes. */
rttTrueMs: number;
/** POSTs that took much longer than baseline (network hiccups). */
spikes?: readonly { atMs: number; extraMs: number }[];
/** Script charge drops while moving. */
drops?: boolean;
/** Patrol leg length; longer legs keep the player clear of its own blasts. */
legMs?: number;
/** Interval between scripted drops (default 1600ms). */
dropEveryMs?: number;
/** Pause (full key release) every N legs (default 8). */
pauseEvery?: number;
/** Correction policy mirror: "envelope" (default: lead-aware envelope trim +
* capped-rate ease) or "v123" (pull only when all inputs acked + instant
* snap past 2.5 cells) for A/B runs against recorded traces. */
policy?: "envelope" | "v123";
/** Replay measured production input RTT samples (tests/fixtures/*.json)
* instead of rttTrueMs+jitter; indexed by send count, so runs stay
* deterministic while the client EMA sees real-world variance. */
rttTrace?: readonly { atMs: number; rttMs: number }[];
/** Override seat 0's speed (speed-powerup state; widens the straddle window). */
speedOverride?: number;
/** Periodic rAF starvation windows: no client frames run while inside one. */
stallEveryMs?: number;
stallMs?: number;
/** Node event-loop stalls on the SERVER: tick callbacks are dropped (no
* catch-up), so server sim time permanently lags wall clock by the stall.
* Suspected true cause of the production teleport-back. */
serverStallEveryMs?: number;
serverStallMs?: number;
/** SSE backpressure windows: snapshots stop arriving, then only the newest
* lands (intermediate events coalesce away). Stale est is the suspected
* rubberband trigger behind the original teleport-back complaint. */
snapStallEveryMs?: number;
snapStallMs?: number;
/** Direction cycle for the patrol legs (default the square cycle). */
dirCycle?: readonly Dir[];
/** Optional intro leg pressed at t=0 and released after introMs (e.g. step
* off the spawn row onto the patrol line before the cycle begins). */
introDir?: Dir;
introMs?: number;
/** Cells where a scripted drop would kill the idle bot (blast reach); the
* script skips drops that would land on them. */
dangerCells?: readonly (readonly [number, number])[];
}
interface SnapEvent {
t: number;
gap: number;
est: RenderPos;
pred: RenderPos;
truth: RenderPos;
pendingLen: number;
rttAvg: number;
ackedDir: Dir | null;
held: Dir | null;
recentGaps: number[];
}
interface Telemetry {
snaps: SnapEvent[];
pulls: number;
resetBranch: number;
/** Decision-alignment nudges applied at input edges, and total distance. */
nudges: number;
nudgeDist: number;
gapSamples: number[];
/** |pred - serverTruth| at each reconcile: did prediction run away? */
predErrSamples: number[];
/** |est - serverTruth| at each reconcile: was the estimate wrong? */
estErrSamples: number[];
/** Ghost charge retired onto a different cell than the server's real one. */
ghostMismatch: number;
ghostDist: number;
/** Corrections that moved the display > 1.5 cells in ONE reconcile (visible
* teleport), vs the capped-rate ease ceiling. maxJump = worst single jump. */
teleports: number;
maxJump: number;
deaths: number;
completedMs: number;
}
function runScenario(cfg: ScenarioConfig): Telemetry {
const rng = mulberry32(cfg.seed);
const jitter = () => (rng() * 2 - 1) * cfg.jitterMs;
/* ---- server ---- */
let state: BomperatorState = createMatchState(
[
{ seat: 0, userId: 101, name: "Hero" },
{ seat: 1, userId: 102, name: "Idle" },
],
3,
cfg.seed,
);
state = startRound(state);
let guard = 0;
while (state.phase !== "battle" && guard < 1000) {
state = tick(state);
guard += 1;
}
if (state.phase !== "battle") throw new Error("battle phase never started");
if (cfg.speedOverride !== undefined) {
state = {
...state,
players: state.players.map((p) =>
p.seat === 0 ? { ...p, speed: cfg.speedOverride as number } : p,
),
};
}
const undelivered: SimSnapshot[] = [];
const arrivals: { at: number; input: BomperatorInput }[] = [];
const completions: { at: number; sentAt: number }[] = [];
let registryStamp = 0;
const emitSnapshot = (now: number) => {
const view = buildBomperatorView(state, {
matchId: "sim",
name: null,
version: state.tickCount,
yourSeat: 0,
});
const me = view.players[0];
undelivered.push({
version: view.version,
deliverAt: now + cfg.oneWayMs + jitter() + cfg.pipelineMs,
me: {
x: me.x,
y: me.y,
dir: me.dir,
speed: me.speed,
kick: me.kick,
alive: me.alive,
bombsMax: me.bombsMax,
bombsActive: me.bombsActive,
// The registry stamps the highest applied seq per viewer (registry.ts).
lastInputSeq: registryStamp,
},
bombs: view.bombs.map((b) => ({ id: b.id, x: b.x, y: b.y, ownerSeat: b.ownerSeat })),
grid: [...view.grid],
});
};
emitSnapshot(0);
/* ---- client state (mirror of BomperatorGame refs) ---- */
let pred: RenderPos | null = null;
let facing: Dir = "down";
let heldStack: Dir[] = [];
const pending: { seq: number; dir: Dir | null; sentAt: number }[] = [];
let lastAck = 0;
let lastAckedDir: Dir | null = null;
let rttAvg = cfg.rttTrueMs;
// Mirror of ackLatRef: input-to-ack latency EMA (includes the tick queue
// and snapshot turnaround); sizes the correction envelope.
let ackLat = cfg.rttTrueMs;
let clientView: SimSnapshot | null = null;
let lastVersionSeen = -1;
let seqCounter = 0;
const ghosts: { x: number; y: number; placedAt: number }[] = [];
let knownBombIds = new Set<string>();
/** Client time the newest snapshot version ARRIVED (mirror of the
* component's lastSnapshotAtRef); decision projections start from it minus
* one-way latency, and stale snapshots skip projection entirely. */
let lastSnapshotAt = -1000;
const sendDir = (dir: Dir | null, now: number) => {
const seq = (seqCounter += 1);
pending.push({ seq, dir, sentAt: now });
if (pending.length > 64) pending.splice(0, pending.length - 64);
const spike = cfg.spikes?.find((s) => Math.abs(s.atMs - now) < 2);
// Trace replay cycles the measured production RTTs (v0.12.4 regression:
// synthetic 90ms latency hid that real TTFB swings 31-463ms).
const traced = cfg.rttTrace?.[seq % cfg.rttTrace.length];
const base = traced ? traced.rttMs : cfg.rttTrueMs + jitter();
const rtt = Math.max(20, base + (spike ? spike.extraMs : 0));
arrivals.push({ at: now + rtt / 2 + jitter(), input: { dir, seq } });
arrivals.sort((a, b) => a.at - b.at);
completions.push({ at: now + rtt, sentAt: now });
completions.sort((a, b) => a.at - b.at);
};
const sendDrop = (now: number) => {
if (!clientView || !pred || !clientView.me.alive) return;
const me = clientView.me;
// Mirror the component (v0.12.3 semantics): ghost at the displayed
// position. Projecting onto the server's future cell shipped in v0.12.4
// and was reverted: under production RTT variance it missed by 1-3 cells
// and read as charges landing nowhere near the preview.
const at = pred;
const cx = Math.round(at.x);
const cy = Math.round(at.y);
// Scenario safety: a charge adjacent to the idle bot's seat would kill it
// and end the round mid-run; skip those drops.
if (cfg.dangerCells?.some(([dx, dy]) => dx === cx && dy === cy)) return;
// Scenario safety: space charges out. A charge dropped within reach of a
// live one can pin the runner against the older bomb's cell when the lap
// brings them back, and the fuse then collects them; real players do not
// stack their own corridors either.
if (
clientView.bombs.some((b) => Math.abs(b.x - cx) + Math.abs(b.y - cy) <= 3) ||
ghosts.some((g) => Math.abs(g.x - cx) + Math.abs(g.y - cy) <= 3)
) {
return;
}
// Scenario safety: only drop while running across open ground - require two
// cells clear ahead in the held direction so the technician always outruns
// its own fuse. A charge dropped while pinned against a wall detonates
// under the player, which is what killed every earlier drops-scenario run.
const held = heldStack[0] ?? null;
if (!held) return;
const advX = held === "left" ? -1 : held === "right" ? 1 : 0;
const advY = held === "up" ? -1 : held === "down" ? 1 : 0;
for (let i = 1; i <= 2; i += 1) {
const gx = cx + advX * i;
const gy = cy + advY * i;
if (gx < 0 || gy < 0 || gx >= GRID_W || gy >= GRID_H) return;
if (clientView.grid[gy * GRID_W + gx] !== 0) return;
}
const cellTaken =
cx < 0 ||
cy < 0 ||
cx >= GRID_W ||
cy >= GRID_H ||
clientView.grid[cy * GRID_W + cx] !== 0 ||
clientView.bombs.some((b) => b.x === cx && b.y === cy) ||
ghosts.some((g) => g.x === cx && g.y === cy);
if (!cellTaken && me.bombsActive + ghosts.length < me.bombsMax && ghosts.length < 4) {
ghosts.push({ x: cx, y: cy, placedAt: now });
}
arrivals.push({ at: now + cfg.rttTrueMs / 2 + jitter(), input: { drop: true } });
arrivals.sort((a, b) => a.at - b.at);
};
/* ---- scripted keys: square patrol, press-then-release turns, pauses ---- */
const legMs = cfg.legMs ?? 700;
const pauseEvery = cfg.pauseEvery ?? 8;
const cycle: readonly Dir[] = cfg.dirCycle ?? ["right", "down", "left", "up"];
const keyEvents: { at: number; type: "down" | "up"; dir: Dir }[] = [];
// Optional intro leg: e.g. step off the spawn row onto the patrol line.
let t0 = 0;
if (cfg.introDir) {
const introMs = cfg.introMs ?? 600;
keyEvents.push({ at: 0, type: "down", dir: cfg.introDir });
keyEvents.push({ at: introMs, type: "up", dir: cfg.introDir });
t0 = introMs;
}
let prevLeg: Dir | null = null;
let prevStopped = false;
for (let t = t0, i = 0; t < cfg.durationMs; t += legMs, i += 1) {
const next = cycle[i % cycle.length];
keyEvents.push({ at: t, type: "down", dir: next });
if (prevLeg && !prevStopped) keyEvents.push({ at: t + 30, type: "up", dir: prevLeg });
const stopping = i % pauseEvery === pauseEvery - 1;
if (stopping) keyEvents.push({ at: t + legMs - 300, type: "up", dir: next });
prevLeg = next;
prevStopped = stopping;
}
keyEvents.sort((a, b) => a.at - b.at);
/* ---- main loop ---- */
const tel: Telemetry = {
snaps: [],
pulls: 0,
resetBranch: 0,
nudges: 0,
nudgeDist: 0,
gapSamples: [],
predErrSamples: [],
estErrSamples: [],
ghostMismatch: 0,
ghostDist: 0,
teleports: 0,
maxJump: 0,
deaths: 0,
completedMs: 0,
};
let edgeIdx = 0;
let nextKeepalive = 400;
let nextDrop = cfg.drops ? 800 : Infinity;
let battleOver = false;
let lastFrameAt = 0;
for (let now = 0; now <= cfg.durationMs && !battleOver; now += SUBSTEP_MS) {
// 1. Scripted key edges, keepalives, drops.
while (edgeIdx < keyEvents.length && keyEvents[edgeIdx].at <= now) {
const ev = keyEvents[edgeIdx];
edgeIdx += 1;
const prevHeld = heldStack[0] ?? null;
if (ev.type === "down") heldStack = [ev.dir, ...heldStack.filter((d) => d !== ev.dir)];
else heldStack = heldStack.filter((d) => d !== ev.dir);
const nextHeld = heldStack[0] ?? null;
void prevHeld; // held-stack bookkeeping only since the nudge revert
sendDir(nextHeld, now);
}
if (now >= nextKeepalive) {
if (heldStack[0]) sendDir(heldStack[0], now);
nextKeepalive += 400;
}
if (now >= nextDrop) {
sendDrop(now);
nextDrop += cfg.dropEveryMs ?? 1600;
}
// 2. Server: inputs apply the instant they arrive (registry semantics).
while (arrivals.length > 0 && arrivals[0].at <= now) {
const arrival = arrivals.shift();
if (!arrival) break;
const seq = arrival.input.seq;
if (typeof seq === "number") {
if (seq <= registryStamp) continue; // stale echo, silently dropped
registryStamp = seq;
}
state = applyInput(state, 0, arrival.input);
}
// 3. Server tick boundary: advance + push a snapshot to the client.
// Node event-loop stalls (serverStall*): setInterval callbacks are DROPPED,
// not caught up, so the server sim permanently loses the stalled wall-clock
// time. est then over-projects past where the server actually is, and the
// correction drags the display BACKWARD - the exact reported complaint.
const serverStalled =
cfg.serverStallEveryMs !== undefined &&
cfg.serverStallMs !== undefined &&
now % cfg.serverStallEveryMs < cfg.serverStallMs;
if (now > 0 && now % TICK_MS === 0 && !serverStalled) {
state = tick(state);
emitSnapshot(now);
}
// 4. POST completions feed the client's RTT EMA.
while (completions.length > 0 && completions[0].at <= now) {
const c = completions.shift();
if (!c) break;
rttAvg = rttAvg * 0.8 + (c.at - c.sentAt) * 0.2;
}
// 5. Client frame (rAF cadence: fires whenever at least FRAME_MS has
// elapsed since the last one, and prediction advances by the real elapsed
// dt - a browser never fires on exact multiples of its refresh interval,
// and the component advances by the measured frame delta, not a constant
// step. Gating on `now % FRAME_MS` under a 5ms substep loop starved frames
// to one per 80ms while still advancing 16ms of movement each: pred then
// crawled at 20% of real-time speed and every sustained leg ratcheted the
// gap open - a harness artifact, not component behavior).
// rAF starvation windows: inside a stall the whole client side freezes
// (no frames, no snapshot intake) while the server keeps moving, mirroring
// a stalled main thread; when it ends the newest snapshot lands at once
// and dt caps at 100ms, so pred under-advances by the component's margin.
if (
cfg.stallEveryMs !== undefined &&
cfg.stallMs !== undefined &&
now % cfg.stallEveryMs < cfg.stallMs
) {
continue;
}
if (now - lastFrameAt < FRAME_MS) continue;
const dtMs = Math.min(now - lastFrameAt, 100);
lastFrameAt = now;
// 5a. Snapshot delivery (Arena applies monotonically; newest wins per
// frame). During SSE backpressure windows nothing lands; when the window
// ends only the newest queued snapshot survives (older ones coalesce).
const snapStalled =
cfg.snapStallEveryMs !== undefined &&
cfg.snapStallMs !== undefined &&
now % cfg.snapStallEveryMs < cfg.snapStallMs;
if (!snapStalled) {
let newest: SimSnapshot | null = null;
for (let i = undelivered.length - 1; i >= 0; i -= 1) {
if (undelivered[i].deliverAt <= now) {
const s = undelivered.splice(i, 1)[0];
if (s && (!newest || s.version > newest.version)) newest = s;
}
}
if (newest && (!clientView || newest.version > clientView.version)) {
clientView = newest;
lastSnapshotAt = now;
}
}
if (!clientView) continue;
// 5b. Local prediction for our own seat.
const me = clientView.me;
const bombsWorking: PredictBomb[] = clientView.bombs.map((b) => ({
id: b.id,
x: b.x,
y: b.y,
}));
for (const g of ghosts) {
bombsWorking.push({ id: `ghost:${g.placedAt}`, x: g.x, y: g.y, ghost: true });
}
if (me.alive) {
if (pred === null) pred = { x: me.x, y: me.y };
const held = heldStack[0] ?? null;
if (held) facing = held;
pred = predAdvance(clientView.grid, bombsWorking, pred, held, facing, me.speed, me.kick, dtMs);
} else {
pred = null;
pending.length = 0;
ghosts.length = 0;
tel.deaths += 1;
battleOver = true;
}
// 5c. Reconcile once per fresh snapshot version.
if (clientView.version === lastVersionSeen) {
tel.completedMs = now;
continue;
}
lastVersionSeen = clientView.version;
const ack = me.lastInputSeq;
if (ack < lastAck) {
tel.resetBranch += 1;
pending.length = 0;
pred = me.alive ? { x: me.x, y: me.y } : null;
facing = me.dir;
lastAckedDir = null;
} else {
let ackedDir: Dir | null = lastAckedDir;
while (pending.length > 0) {
const head = pending[0];
if (!head || head.seq > ack) break;
const lat = now - head.sentAt;
if (lat > 0 && lat < 2000) ackLat = ackLat * 0.8 + lat * 0.2;
ackedDir = head.dir;
pending.shift();
}
lastAckedDir = ackedDir;
if (me.alive && pred) {
const replayBombs: PredictBomb[] = clientView.bombs.map((b) => ({
id: b.id,
x: b.x,
y: b.y,
}));
const projected = projectServerPosition(
clientView.grid,
replayBombs,
{ x: me.x, y: me.y },
me.dir,
ackedDir,
pending,
me.speed,
me.kick,
rttAvg,
// Calibrated snapshot age: lands est on the server's quantized now.
now - rttAvg / 2 - TICK_MS / 2,
now,
);
const est = projected.pos;
const gap = Math.hypot(est.x - pred.x, est.y - pred.y);
const truth: RenderPos = { x: state.players[0].x, y: state.players[0].y };
tel.gapSamples.push(gap);
tel.predErrSamples.push(Math.hypot(pred.x - truth.x, pred.y - truth.y));
tel.estErrSamples.push(Math.hypot(est.x - truth.x, est.y - truth.y));
// Mirror of the component's correction policy: healthy gaps (flight
// lead, tick quantization, estimator error) ride inside the envelope
// untouched; anything beyond is genuine divergence, corrected a little
// on EVERY snapshot so offsets can never stack into a teleport.
const rttEnv = Math.min(300, Math.max(rttAvg, ackLat - rttAvg));
const envelope = Math.max(
PRED_DEADZONE,
(me.speed * (rttEnv / 2 + TICK_MS / 2 + PRED_ENVELOPE_BUDGET_MS)) / 1000,
);
const predBefore = { x: pred.x, y: pred.y };
if (gap > 2.5) {
tel.snaps.push({
t: now,
gap,
est: { ...est },
pred: { ...pred },
truth: { ...truth },
pendingLen: pending.length,
rttAvg,
ackedDir,
held: heldStack[0] ?? null,
recentGaps: tel.gapSamples.slice(-4, -1),
});
if (cfg.policy === "v123") {
// v0.12.3 behavior: instant snap (the teleport-back complaint).
pred.x = est.x;
pred.y = est.y;
} else {
const maxStep = (me.speed * 2.5 * dtMs) / 1000;
const easeT = Math.min(1, maxStep / gap);
pred.x += (est.x - pred.x) * easeT;
pred.y += (est.y - pred.y) * easeT;
}
facing = projected.facing;
} else if (
cfg.policy === "v123"
? pending.length === 0 && gap > PRED_DEADZONE
: gap > envelope
) {
const floor = cfg.policy === "v123" ? PRED_DEADZONE : envelope;
// v123: instant close to floor. Envelope policy: rate-limited trim
// (max 0.35 cells per snapshot, a glide not a jump).
const k =
cfg.policy === "v123"
? Math.min(gap - floor, gap * 0.5) / gap
: Math.min(gap - floor, 0.35) / gap;
pred.x += (est.x - pred.x) * k;
pred.y += (est.y - pred.y) * k;
tel.pulls += 1;
}
const jump = Math.hypot(pred.x - predBefore.x, pred.y - predBefore.y);
if (jump > tel.maxJump) tel.maxJump = jump;
if (jump > 1.5) tel.teleports += 1;
}
}
lastAck = ack;
// Ghost reconciliation (identical rules to the component), recording how
// often the ghost sat on a different cell than the server's real charge.
if (ghosts.length > 0) {
const freshOwnList = clientView.bombs.filter(
(b) => b.ownerSeat === 0 && !knownBombIds.has(b.id),
);
let freshOwn = freshOwnList.length;
for (let i = ghosts.length - 1; i >= 0; i -= 1) {
const g = ghosts[i];
const cellTaken = clientView.bombs.some((b) => b.x === g.x && b.y === g.y);
if (cellTaken) ghosts.splice(i, 1);
else if (freshOwn > 0) {
freshOwn -= 1;
const real = freshOwnList[freshOwn];
const dist = Math.abs(real.x - g.x) + Math.abs(real.y - g.y);
if (dist > 0) tel.ghostMismatch += 1;
tel.ghostDist += dist;
ghosts.splice(i, 1);
} else if (now - g.placedAt > 1200) ghosts.splice(i, 1);
}
}
knownBombIds = new Set(clientView.bombs.map((b) => b.id));
tel.completedMs = now;
}
return tel;
}
function report(label: string, tel: Telemetry): void {
const line = (s: readonly number[]) =>
`p50=${percentile(s, 0.5).toFixed(2)} p95=${percentile(s, 0.95).toFixed(2)} max=${(
s.length ? Math.max(...s) : 0
).toFixed(2)}`;
console.info(
`[pred-harness] ${label}: snaps=${tel.snaps.length} pulls=${tel.pulls} ` +
`nudges=${tel.nudges} (${tel.nudgeDist.toFixed(1)} cells total) ` +
`resets=${tel.resetBranch} deaths=${tel.deaths} ` +
`ghostMismatch=${tel.ghostMismatch} (avg ${
tel.ghostMismatch ? (tel.ghostDist / tel.ghostMismatch).toFixed(2) : "0.00"
} cells) ` +
`teleports=${tel.teleports} maxJump=${tel.maxJump.toFixed(2)} ` +
`ran=${(tel.completedMs / 1000).toFixed(1)}s\n` +
` gap: ${line(tel.gapSamples)}\n` +
` predErr: ${line(tel.predErrSamples)}\n` +
` estErr: ${line(tel.estErrSamples)}`,
);
for (const s of tel.snaps.slice(0, 8)) {
console.info(
` SNAP t=${(s.t / 1000).toFixed(2)}s gap=${s.gap.toFixed(2)} ` +
`pred=(${s.pred.x.toFixed(2)},${s.pred.y.toFixed(2)}) ` +
`est=(${s.est.x.toFixed(2)},${s.est.y.toFixed(2)}) ` +
`truth=(${s.truth.x.toFixed(2)},${s.truth.y.toFixed(2)}) ` +
`pending=${s.pendingLen} rttAvg=${s.rttAvg.toFixed(0)} held=${s.held} ackedDir=${s.ackedDir} ` +
`recentGaps=[${s.recentGaps.map((g) => g.toFixed(2)).join(", ")}]`,
);
}
}
/** Recorded production input round-trips (HAR, two-window playtest, v0.12.4):
* p50 ~104ms with swings to 463ms. Every future prediction change must survive
* this distribution, not just synthetic calm latency. */
function loadProdTrace(): { atMs: number; rttMs: number }[] {
// Vitest serves modules over http URLs, so import.meta.url is not a file
// path here; the suite always runs from the repo root.
return JSON.parse(
readFileSync("tests/fixtures/bomperator-prod-rtt.json", "utf8"),
) as { atMs: number; rttMs: number }[];
}
const BASE: ScenarioConfig = {
durationMs: 90_000,
seed: 1234,
oneWayMs: 45,
jitterMs: 10,
pipelineMs: 20,
rttTrueMs: 90,
};
/* ------------------------------------------------------------------ scenarios */
describe("bomperator prediction harness", () => {
it("clean network: 90s of heavy zigzagging never hard-snaps", () => {
const tel = runScenario(BASE);
report("clean", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.deaths).toBe(0);
expect(tel.completedMs).toBeGreaterThanOrEqual(BASE.durationMs);
expect(tel.snaps).toHaveLength(0);
});
it("ws-grade latency: the arena transport's low end stays teleport-free", () => {
// The other end of the latency range from the prod-trace replay: a
// dedicated-server WebSocket round trip (single-digit RTT, low jitter, no
// Next request pipeline in the snapshot path). The envelope must ride this
// calm distribution untouched too - corrections that only look smooth at
// high latency are still corrections.
const cfg: ScenarioConfig = { ...BASE, oneWayMs: 4, jitterMs: 2, pipelineMs: 5, rttTrueMs: 9 };
const tel = runScenario(cfg);
report("ws-low-latency", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.deaths).toBe(0);
expect(tel.completedMs).toBeGreaterThanOrEqual(cfg.durationMs);
expect(tel.snaps).toHaveLength(0);
});
it("tight zigzag: rapid turns never hard-snap or rubber-band", () => {
const cfg: ScenarioConfig = { ...BASE, legMs: 350 };
const tel = runScenario(cfg);
report("tight-zigzag", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.snaps).toHaveLength(0);
});
it("stop-start heavy: frequent releases never hard-snap", () => {
const cfg: ScenarioConfig = { ...BASE, pauseEvery: 2 };
const tel = runScenario(cfg);
report("stop-go", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.snaps).toHaveLength(0);
});
it("speed powerup: a faster technician never hard-snaps", () => {
const cfg: ScenarioConfig = { ...BASE, speedOverride: 9.5 };
const tel = runScenario(cfg);
report("speed", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.snaps).toHaveLength(0);
});
it("drops while moving: ghost charges never provoke a hard snap", () => {
// Drop safety is enforced by sendDrop's clear-ahead gate (drop only while
// running with two open cells ahead), so the technician outruns its own
// fuse on any map layout. dangerCells additionally skips crosses that would
// reach the idle bot at (13,11) and end the round early. dropEveryMs
// exceeds fuse + flame time, so each charge is gone before the next drop.
// seed 2817: the spawn pocket on seed 1234 is crate-choked (no corridor is
// open for 2 cells, so the clear-ahead gate skips everything); this seed's
// grid has an open ring (1,1)-(11,5) whose ~3.3s lap outlives every fuse.
const cfg: ScenarioConfig = {
...BASE,
seed: 2817,
drops: true,
legMs: 2100,
dropEveryMs: 3000,
dangerCells: [[13, 11], [12, 11], [14, 11], [13, 10], [13, 12]],
};
const tel = runScenario(cfg);
report("drops", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.snaps).toHaveLength(0);
// deaths is reported but not asserted: with ghost-at-displayed-cell
// semantics (shipped v0.12.x behavior), a timer drop landing on a corner
// dwell cell can pin the SCRIPTED patrol inside its own flame column.
// Real players do not drop while pinned; the load-bearing check above is
// that ghosts never provoke a hard snap.
});
it("rtt spikes: a couple of slow POSTs never provoke a hard snap", () => {
const cfg: ScenarioConfig = {
...BASE,
spikes: [
{ atMs: 15_000, extraMs: 260 },
{ atMs: 40_000, extraMs: 300 },
{ atMs: 65_000, extraMs: 240 },
],
};
const tel = runScenario(cfg);
report("spikes", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.snaps).toHaveLength(0);
});
it("slow React pipeline: laggy snapshot delivery never provokes a hard snap", () => {
const cfg: ScenarioConfig = { ...BASE, pipelineMs: 60 };
const tel = runScenario(cfg);
report("pipeline", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.snaps).toHaveLength(0);
});
it("frame stalls: rAF starvation never provokes a hard snap", () => {
// Production rAF stalls under 20Hz React re-render load: frames stop for
// 150ms every 3s. The dt cap (100ms) under-advances pred once per stall;
// the envelope correction must absorb it without any snap-class event.
const cfg: ScenarioConfig = { ...BASE, stallEveryMs: 3000, stallMs: 150 };
const tel = runScenario(cfg);
report("stalls", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.snaps).toHaveLength(0);
});
it("backgrounded tab: a 4s freeze every 20s resumes without teleporting", () => {
// Mobile reality: app switches stop rAF for seconds while the server keeps
// running. On resume the dt cap under-advances pred by nearly the whole
// freeze, so the gap can only close through the correction path. The
// envelope policy must reel in at the capped rate - never teleport. This
// is the guarantee the touch-controls work depends on.
const cfg: ScenarioConfig = {
...BASE,
legMs: 350,
rttTrace: loadProdTrace(),
stallEveryMs: 20000,
stallMs: 4000,
};
const tel = runScenario(cfg);
report("background-resume", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.teleports).toBe(0);
expect(tel.maxJump).toBeLessThanOrEqual(1.5);
expect(tel.completedMs).toBeGreaterThan(85_000);
});
it("prod trace: measured HAR latency replay never hard-snaps", () => {
// The v0.12.4 regression shipped because every scenario here assumed a
// calm 90ms RTT. This replays the actual production input round-trips
// (31-463ms from the playtest HAR) under heavy turning.
const cfg: ScenarioConfig = { ...BASE, legMs: 350, rttTrace: loadProdTrace() };
const tel = runScenario(cfg);
report("prod-trace", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.snaps).toHaveLength(0);
expect(tel.completedMs).toBeGreaterThan(85_000);
});
it("prod trace A/B: the v0.12.3 policy teleports, the envelope policy does not", () => {
// Reproduces the ORIGINAL complaint (teleport-back while moving a lot)
// under real latency + SSE backpressure bursts, then shows the correction
// policy fixes it. If the v123 run ever stops snapping here, our model of
// the prod bug is wrong and this test must fail loudly rather than let a
// fix ship unproven.
const cfg: ScenarioConfig = {
...BASE,
legMs: 350,
rttTrace: loadProdTrace(),
serverStallEveryMs: 3000,
serverStallMs: 400,
};
const before = runScenario({ ...cfg, policy: "v123" });
const after = runScenario({ ...cfg, policy: "envelope" });
report("trace v0.12.3 policy", before);
report("trace envelope policy", after);
// The honest metric is the per-reconcile jump: v0.12.3 discharges the
// accumulated stall gap as an instant teleport; the envelope policy eases
// it in at the capped rate, so no single correction is ever visible.
expect(before.teleports).toBeGreaterThan(0);
expect(after.teleports).toBe(0);
expect(after.maxJump).toBeLessThanOrEqual(1.5);
expect(after.deaths).toBe(0);
});
});