1
0
Fork 0
polaris-task-force/tests/int/bomperator-prediction.int.spec.ts
Z8MB1E 655407ab7d fix(minigames): stop Bomperator teleport-back with envelope correction and decision nudges
- Extract client prediction helpers to bomperator/prediction.ts (predStep/
  predAdvance port, alignDecisionToServer, projectServerPosition)
- Nudge prediction across cell boundaries at turn/stop edges so client and
  server commit to the same rounding decision; ghosts use the server's
  projected placement cell
- Stamp snapshot arrival time; event projections use measured age, reconcile
  estimate keeps the calibrated half-tick bias
- Replace pending-gated pull and instant 2.5-cell snap with a lead-aware
  correction envelope plus capped-rate ease (2.5x speed); resets still snap
  via the ack-backwards branch
- Add offline deterministic prediction harness (real engine + modeled network
  + frame-by-frame reconcile mirror), 9 scenarios incl. rAF stalls and a
  pre/post-fix ghost-mismatch comparison
2026-10-18 01:09:56 -04:00

771 lines
28 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 { 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,
alignDecisionToServer,
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;
/** Apply the decision-alignment nudge at input edges (default true; false
* reproduces the pre-fix divergence for diagnostics). */
nudges?: boolean;
/** 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;
/** 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;
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;
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;
/** Mirror of the component's projectDecisionPos: project the server's copy of
* our technician forward to `atTime` by replaying every unacknowledged input
* from the latest snapshot (in-flight edges included). */
const projectDecisionPos = (atTime: number, now: number): RenderPos | null => {
if (!clientView || !clientView.me.alive) return null;
if (now - lastSnapshotAt > 300) return null;
if (atTime - now > 400) return null;
const me = clientView.me;
const bombs: PredictBomb[] = clientView.bombs.map((b) => ({ id: b.id, x: b.x, y: b.y }));
return projectServerPosition(
clientView.grid,
bombs,
{ x: me.x, y: me.y },
me.dir,
lastAckedDir,
pending,
me.speed,
me.kick,
rttAvg,
// True server-side age: measured arrival minus one-way latency.
lastSnapshotAt - rttAvg / 2,
atTime,
).pos;
};
/** Mirror of the component's applyDecisionNudge. The rounding decision
* samples the server's staircase at the last tick BEFORE the input arrives
* (half a tick early), not after it - projecting past the arrival slides up
* to a full tick beyond the corner and rounds to the wrong cell. */
const applyDecisionNudge = (prev: Dir | null, next: Dir | null, now: number) => {
if (cfg.nudges === false) return;
if (prev === next || pred === null) return;
const dp = projectDecisionPos(now + rttAvg / 2 - TICK_MS / 2, now);
if (!dp) return;
const res = alignDecisionToServer(pred, dp, next, prev ?? facing);
if (res.nudged) {
pred = res.pos;
tel.nudges += 1;
tel.nudgeDist += res.delta;
}
};
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);
const rtt = Math.max(20, cfg.rttTrueMs + (spike ? spike.extraMs : 0) + jitter());
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: ghost where the SERVER will place the charge (its
// position one way latency plus half a tick from now), not where our display
// currently is.
const at =
(cfg.nudges === false ? null : projectDecisionPos(now + rttAvg / 2 + TICK_MS / 2, now)) ??
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: 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,
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;
// Nudge BEFORE the send (mirror of the component): the decision position
// must not include the very edge being decided.
applyDecisionNudge(prevHeld, nextHeld, now);
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.
if (now > 0 && now % TICK_MS === 0) {
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).
for (let i = undelivered.length - 1; i >= 0; i -= 1) {
if (undelivered[i].deliverAt <= now) {
const s = undelivered.splice(i, 1)[0];
if (!clientView || s.version > clientView.version) {
clientView = s;
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;
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 envelope = Math.max(
PRED_DEADZONE,
(me.speed * (rttAvg / 2 + TICK_MS / 2 + PRED_ENVELOPE_BUDGET_MS)) / 1000,
);
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),
});
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 (gap > envelope) {
const k = Math.min(gap - envelope, gap * 0.5) / gap;
pred.x += (est.x - pred.x) * k;
pred.y += (est.y - pred.y) * k;
tel.pulls += 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) ` +
`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(", ")}]`,
);
}
}
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("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.deaths).toBe(0);
expect(tel.snaps).toHaveLength(0);
});
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("decision placement puts ghost charges on the server's cell far more often", () => {
// Under the fixed cadence the movement distributions of the pre-fix and
// post-fix algorithms are indistinguishable: corrections are rare and
// small either way. The nudge's remaining honest value is the drop: the
// ghost charge appears where the SERVER will place it (its decision
// position, projected through in-flight inputs) instead of where the
// leading display position rounds, so mid-cell drops mismatch the real
// bomb far less often. Same scenario, nudges on vs off, drops enabled.
// 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 before = runScenario({ ...cfg, nudges: false });
const after = runScenario(cfg);
report("drops PRE-FIX", before);
report("drops POST-FIX", after);
expect(after.ghostMismatch).toBeLessThan(before.ghostMismatch);
expect(after.snaps).toHaveLength(0);
expect(after.deaths).toBe(0);
});
});