From 98d5ec63f80fc3d7b6ec3e4abe05801ad97ea380 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Wed, 21 Oct 2026 11:42:32 -0400 Subject: [PATCH] feat(minigames): make Bomperator own-seat movement server-authoritative Four prediction generations shipped and production still disagreed with the server: v0.12.16's ack-sized envelope, wall-clock catch-up with a 1s cap, ghost parity in both sims, and a forward-only replay clock. The last playtest (n=645, rtt 41-69ms) still read gapP50 1.26, gapP95 7.05, 30% of snapshots easing, with frameMax 17ms and zero server-side jumps. A second simulation cannot be kept in agreement with the server by tuning. Remove the second simulation instead: - own seat renders the server's snapshot position through the same one-pole ease as remote players (shorter constant, 0.6 vs 0.4 per frame, because easing reads as input lag), snapping only past 1.5 cells (respawn/reset) - drop the pending ledger, ack drain, input-to-ack EMA, envelope, trim and ease correction, optimistic kick overlay, and the local movement copy - drop ghosts stay as visual feedback, placed at the server's own copy of our cell so they align with where the charge will appear - telemetry now reports the ease's own-seat trail, own/remote snaps, snapshot cadence, frame max, ghost rows and RTT - delete bomperator/prediction.ts, its offline harness and the prod-RTT fixture: they covered a mechanism that no longer exists Input stays level-triggered on the monotonic seq + 400ms keepalive path. Cost is one tick of queue (~25ms) plus one-way latency, the explicit trade for a render that cannot diverge from the server. tsc clean; bomperator-registry 19/19. --- .../minigames/bomperator/BomperatorGame.tsx | 473 ++------- .../bomperator/BomperatorTouchControls.tsx | 4 +- src/lib/minigames/AGENTS.md | 6 +- src/lib/minigames/bomperator/prediction.ts | 277 ------ tests/fixtures/bomperator-prod-rtt.json | 1 - tests/int/bomperator-prediction.int.spec.ts | 907 ------------------ 6 files changed, 74 insertions(+), 1594 deletions(-) delete mode 100644 src/lib/minigames/bomperator/prediction.ts delete mode 100644 tests/fixtures/bomperator-prod-rtt.json delete mode 100644 tests/int/bomperator-prediction.int.spec.ts diff --git a/src/components/frontend/minigames/bomperator/BomperatorGame.tsx b/src/components/frontend/minigames/bomperator/BomperatorGame.tsx index 1b9d771d..67991b95 100644 --- a/src/components/frontend/minigames/bomperator/BomperatorGame.tsx +++ b/src/components/frontend/minigames/bomperator/BomperatorGame.tsx @@ -6,11 +6,6 @@ import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import type { BomperatorView, Dir, PlayerView } from "@/lib/minigames/bomperator/types"; import { BOMB_FUSE_TICKS, FLAME_LIFETIME_TICKS, GRID_H, GRID_W, MAX_SEATS, MIN_TO_START, TICK_MS, TICKS_PER_SECOND } from "@/lib/minigames/bomperator/constants"; -import { - PRED_DEADZONE, - PRED_ENVELOPE_BUDGET_MS, - projectServerPosition, -} from "@/lib/minigames/bomperator/prediction"; import type { BomperatorTransport } from "./transport"; import { BomperatorHud, seatColor } from "./BomperatorHud"; import { BomperatorTouchControls } from "./BomperatorTouchControls"; @@ -32,7 +27,6 @@ const KEY_DIR: Record = { KeyD: "right", }; -/** Direction unit vectors for client-side prediction. */ const POWERUP_COLORS: Record = { bomb: "#f87171", range: "#fb923c", @@ -42,11 +36,13 @@ const POWERUP_COLORS: Record = { const POWERUP_GLYPH: Record = { bomb: "●", range: "✸", speed: "»", kick: "⇥" }; const POWERUP_NAME: Record = { bomb: "BOMB", range: "RANGE", speed: "SPEED", kick: "KICK" }; -/* ---- opt-in prediction telemetry (localStorage.bompDebug = "1") ------------- - * Records one row per reconciled snapshot so a playtest can answer, with data, - * whether visible jitter comes from correction trims (b=1/2), round resets - * (b=3), remote-player snaps (rs), bursty snapshot delivery (s), or a jumpy - * RTT estimate (r). Dump with __bompDbg.stats() / .table() in devtools. */ +/* ---- opt-in render telemetry (localStorage.bompDebug = "1") ----------------- + * Records one row per fresh snapshot so a playtest can answer, with data, how + * far the rendered own seat trails the server (g), whether the server position + * itself jumped (b=3), how remote players snap (rs), whether snapshots arrive + * unevenly (s), and whether the RTT estimate is jumpy (r). Movement is + * server-authoritative: there is nothing to correct, so no trim/ease codes. + * Dump with __bompDbg.stats() / .table() in devtools. */ const BOMP_DEBUG = typeof window !== "undefined" && (() => { @@ -61,13 +57,13 @@ interface DbgRow { /** ms since page epoch (performance.now at record). */ t: number; v: number; - /** |pred - est| at reconcile, cells (-1 when no estimate was possible). */ + /** Rendered own seat vs server position, cells (the ease's trail). */ g: number; - /** correction envelope for that snapshot, cells. */ + /** Reserved (was the correction envelope); always 0. */ e: number; - /** 0 none, 1 envelope trim, 2 capped ease (>2.5 cells), 3 ack-backwards reset. */ + /** 0 none, 3 own-seat render snap (>1.5 cells: respawn / round reset). */ b: number; - /** rttAvg feeding the envelope, ms. */ + /** transport RTT EMA, ms. */ r: number; /** ms since the previously reconciled snapshot version (delivery cadence). */ s: number; @@ -113,150 +109,6 @@ interface RenderPos { y: number; } -/* ----- client-side prediction: replicate the engine's grid-locked movement ----- */ - -const PRED_DIR_VEC: Record = { - up: [0, -1], - down: [0, 1], - left: [-1, 0], - right: [1, 0], -}; -const PRED_EPS = 1e-6; - -interface PredictBomb { - id: string; - x: number; - y: number; - /** Optimistic local charge the server has not confirmed yet. Blocks movement - * like a real one but cannot be kick-pushed (the server has not placed it). */ - ghost?: boolean; -} - -function predCellCentered(x: number, y: number): boolean { - return Math.abs(x - Math.round(x)) < PRED_EPS && Math.abs(y - Math.round(y)) < PRED_EPS; -} - -function predApproach(current: number, target: number, step: number): number { - const delta = target - current; - if (Math.abs(delta) <= step) return target; - return current + Math.sign(delta) * step; -} - -function predBombAt(bombs: readonly PredictBomb[], x: number, y: number): PredictBomb | undefined { - return bombs.find((b) => b.x === x && b.y === y); -} - -function predOpen(grid: readonly number[], x: number, y: number): boolean { - return x >= 0 && y >= 0 && x < GRID_W && y < GRID_H && grid[y * GRID_W + x] === 0; -} - -function predCanStand(grid: readonly number[], bombs: readonly PredictBomb[], x: number, y: number): boolean { - return predOpen(grid, x, y) && !predBombAt(bombs, x, y); -} - -/** - * One small advance step mirroring the engine's advancePlayer exactly: finish - * aligning the perpendicular axis first, then move toward the adjacent cell - * center; a charge blocks unless kick-capable (then it slides one cell forward, - * recorded into the mutable bombs list). - */ -function predStep( - grid: readonly number[], - bombs: PredictBomb[], - x0: number, - y0: number, - dir: Dir, - kick: boolean, - step: number, -): RenderPos { - const [dx, dy] = PRED_DIR_VEC[dir]; - let x = x0; - let y = y0; - if (dx !== 0) { - if (Math.abs(y - Math.round(y)) > PRED_EPS) { - const ty = Math.round(y); - y += Math.sign(ty - y) * Math.min(Math.abs(ty - y), step); - if (Math.abs(ty - y) < PRED_EPS) y = ty; - return { x, y }; - } - const cy = Math.round(y); - const entering = dx > 0 ? Math.floor(x) + 1 : Math.ceil(x) - 1; - const home = dx > 0 ? Math.floor(x + PRED_EPS) : Math.ceil(x - PRED_EPS); - const bomb = predBombAt(bombs, entering, cy); - if (bomb) { - if (kick && !bomb.ghost) { - const bx = entering + dx; - if (predOpen(grid, bx, cy) && !predBombAt(bombs, bx, cy)) { - bomb.x = bx; - bomb.y = cy; - return { x: predApproach(x, entering, step), y }; - } - } - return { x: home, y }; - } - if (!predCanStand(grid, bombs, entering, cy)) return { x: home, y }; - return { x: predApproach(x, entering, step), y }; - } - if (Math.abs(x - Math.round(x)) > PRED_EPS) { - const tx = Math.round(x); - x += Math.sign(tx - x) * Math.min(Math.abs(tx - x), step); - if (Math.abs(tx - x) < PRED_EPS) x = tx; - return { x, y }; - } - const cx = Math.round(x); - const entering = dy > 0 ? Math.floor(y) + 1 : Math.ceil(y) - 1; - const home = dy > 0 ? Math.floor(y + PRED_EPS) : Math.ceil(y - PRED_EPS); - const bomb = predBombAt(bombs, cx, entering); - if (bomb) { - if (kick && !bomb.ghost) { - const by = entering + dy; - if (predOpen(grid, cx, by) && !predBombAt(bombs, cx, by)) { - bomb.x = cx; - bomb.y = by; - return { x, y: predApproach(y, entering, step) }; - } - } - return { x, y: home }; - } - if (!predCanStand(grid, bombs, cx, entering)) return { x, y: home }; - return { x, y: predApproach(y, entering, step) }; -} - -/** - * Advance over `durationMs` in small slices, honoring the engine's slip-to-rest: - * with no active direction the technician keeps traveling in `facing` until it - * lands exactly on a cell center; a blocked cell settles it back to the one it - * was leaving, where it then stays. - */ -function predAdvance( - grid: readonly number[], - bombs: PredictBomb[], - start: RenderPos, - dir: Dir | null, - facing: Dir, - speed: number, - kick: boolean, - durationMs: number, -): RenderPos { - let { x, y } = start; - let remaining = Math.min(durationMs, 1500); - let guard = 0; - while (remaining > 0.5 && guard < 120) { - guard += 1; - const slice = Math.min(remaining, 16); - const step = (speed * slice) / 1000; - const effDir = dir ?? (predCellCentered(x, y) ? null : facing); - if (!effDir) break; - const res = predStep(grid, bombs, x, y, effDir, kick, step); - const moved = Math.abs(res.x - x) > 1e-9 || Math.abs(res.y - y) > 1e-9; - x = res.x; - y = res.y; - if (!moved) break; // settled against a blocked cell - remaining -= slice; - } - return { x, y }; -} - /* ------------------------------------------------------------- draw helpers */ function drawFloor(ctx: CanvasRenderingContext2D) { @@ -452,28 +304,12 @@ export function BomperatorGame({ const renderPosRef = useRef>(new Map()); const heldKeysRef = useRef([]); const [starting, setStarting] = useState(false); - /* ---- client-side prediction state (own seat only) ---- */ - const predRef = useRef(null); - const facingRef = useRef("down"); + /* ---- render state (own seat and remotes both render server positions) ---- */ const inputSeqRef = useRef(0); - const pendingRef = useRef>([]); - const pushOverlayRef = useRef>(new Map()); const ghostBombsRef = useRef>([]); const knownBombIdsRef = useRef>(new Set()); - const lastAckRef = useRef(0); - const lastAckedDirRef = useRef(null); const lastVersionSeenRef = useRef(-1); const rttAvgRef = useRef(100); - /** - * Input-to-ack latency EMA: measured from send time until the server's - * snapshot confirms the input. Unlike the transport RTT (ping/pong on WS, - * POST timing on HTTP), it includes the server tick queue and snapshot - * turnaround - the full loop delay prediction must tolerate. The envelope - * sizes itself from this; production telemetry showed ping-only RTT (3-24ms) - * shrinking the envelope below the natural gap noise floor, so ~13% of - * snapshots trimmed and each trim read as a micro-teleport. - */ - const ackLatRef = useRef(100); const dbgRef = useRef<{ ring: DbgRow[]; lastAt: number; remoteSnaps: number; lastRs: number } | null>( null, ); @@ -498,9 +334,10 @@ export function BomperatorGame({ const r = st.ring; const out = { n: r.length, - trims: r.filter((x) => x.b === 1).length, - eases: r.filter((x) => x.b === 2).length, - resets: r.filter((x) => x.b === 3).length, + // Own-seat render snaps (server position jumped >1.5 cells: respawn, + // round reset). Corrections do not exist any more: the render follows + // the server, so trims/eases are gone. + ownSnaps: r.filter((x) => x.b === 3).length, remoteSnaps: st.remoteSnaps, gapP50: pct(r.map((x) => x.g), 0.5), gapP95: pct(r.map((x) => x.g), 0.95), @@ -535,29 +372,24 @@ export function BomperatorGame({ const sendDrop = useCallback(async () => { playPlace(); // Optimistic placement: the ghost charge appears at our cell the same instant - // space goes down. The server places the real one about one round trip later - // at its own (slightly trailing) position; the snapshot that shows our fresh - // bomb retires the ghost. Every server rejection rule is mirrored here - // against our freshest state, so a ghost almost never expires unfulfilled. + // space goes down. The cell comes from the server's own copy of our position, + // because that is where the server will place the real charge; the snapshot + // that shows it retires the ghost. Every server rejection rule is mirrored + // here against our freshest state, so a ghost almost never expires unfulfilled. const view = matchRef.current; const seat = view.yourSeat; const me = seat !== null ? (view.players[seat] ?? null) : null; if (view.phase === "battle" && me && me.alive) { - const at = predRef.current ?? { x: me.x, y: me.y }; - const cx = Math.round(at.x); - const cy = Math.round(at.y); + const cx = Math.round(me.x); + const cy = Math.round(me.y); const ghosts = ghostBombsRef.current; - const overlay = pushOverlayRef.current; const cellTaken = cx < 0 || cy < 0 || cx >= GRID_W || cy >= GRID_H || view.grid[cy * GRID_W + cx] !== 0 || - view.bombs.some((b) => { - const to = overlay.get(b.id); - return (b.x === cx && b.y === cy) || (to !== undefined && to.x === cx && to.y === cy); - }) || + view.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: performance.now() }); @@ -598,9 +430,6 @@ export function BomperatorGame({ const sendDir = useCallback( (dir: Dir | null) => { const seq = (inputSeqRef.current += 1); - const pending = pendingRef.current; - pending.push({ seq, dir, sentAt: performance.now() }); - if (pending.length > 64) pending.splice(0, pending.length - 64); void transport.sendInput(dir, seq).catch(() => undefined); }, [transport], @@ -610,8 +439,8 @@ export function BomperatorGame({ * Shared edge-send plumbing for EVERY input source (keyboard, D-pad, swipe). * The held-stack owns priority (newest first); each edge sends the current * top so the server always holds our latest intent. Touch handlers in - * BomperatorTouchControls call exactly these, keeping prediction, keepalives - * and the pending ledger source-agnostic. + * BomperatorTouchControls call exactly these, keeping keepalives and the + * held-direction stack source-agnostic. */ const pressDir = useCallback( (dir: Dir) => { @@ -713,7 +542,7 @@ export function BomperatorGame({ if (performance.now() - s.t < 300) stopAll(); }; - /* ---- render loop: predict our own seat, ease the rest toward snapshots ---- */ + /* ---- render loop: server-authoritative positions, eased for smoothness ---- */ useEffect(() => { if (!hasBoard) return; @@ -724,7 +553,7 @@ export function BomperatorGame({ canvas.height = CANVAS_H * dpr; // CSS owns the display size (responsive wrapper + h-auto keeps the // intrinsic aspect ratio); the internal buffer stays CANVAS_* * dpr so - // rendering and prediction never depend on the viewport. + // rendering never depends on the viewport. const ctx = canvas.getContext("2d"); if (!ctx) return; ctx.scale(dpr, dpr); @@ -737,212 +566,34 @@ export function BomperatorGame({ const rawDt = now - last; last = now; const dt = Math.min(rawDt / 16.6667, 3); - // Prediction advances by REAL elapsed time: the engine runs on wall clock, - // so clamping the local slice (was 100ms) permanently loses whatever a - // main-thread hitch swallowed. A 300ms frame then left a ~2-cell gap that - // had to be eased back, which is exactly the episodic rubber-banding the - // telemetry showed (gapMax 4.19 with a p50 of 0.18). The 1s cap only - // guards against a backgrounded tab; predAdvance still slices at 16ms. - const dtMs = Math.min(rawDt, 1000); - // Correction easing keeps the old 100ms slice so a single catch-up frame - // cannot discharge a whole gap at once. - const easeDtMs = Math.min(rawDt, 100); if (rawDt > maxFrameMs) maxFrameMs = rawDt; const view = matchRef.current; const pos = renderPosRef.current; + // One-pole ease toward the server's position: the 20Hz snapshot steps + // read as continuous motion. The own seat uses a shorter constant because + // every millisecond of easing shows up as input lag on top of the network. const ease = Math.min(1, 0.4 * dt); + const ownEase = Math.min(1, 0.6 * dt); const mySeat = view.yourSeat; const me = mySeat !== null ? (view.players[mySeat] ?? null) : null; - const overlay = pushOverlayRef.current; - // Working bomb set for prediction + drawing: server truth plus optimistic - // kick-pushes we have made that the server has not confirmed yet. - const bombsWorking: PredictBomb[] = view.bombs.map((b) => { - const to = overlay.get(b.id); - return { id: b.id, x: to?.x ?? b.x, y: to?.y ?? b.y }; - }); - for (const g of ghostBombsRef.current) { - bombsWorking.push({ id: `ghost:${g.placedAt}`, x: g.x, y: g.y, ghost: true }); - } - - /* -- local prediction: our own technician answers the keyboard immediately -- */ - if (view.phase === "battle" && me && me.alive) { - if (predRef.current === null) predRef.current = { x: me.x, y: me.y }; - const held = heldKeysRef.current[0] ?? null; - if (held) facingRef.current = held; - predRef.current = predAdvance( - view.grid, - bombsWorking, - predRef.current, - held, - facingRef.current, - me.speed, - me.kick, - dtMs, - ); - // Record any optimistic push so collision and drawing agree next frame. - for (const b of bombsWorking) { - const orig = view.bombs.find((vb) => vb.id === b.id); - if (orig && (orig.x !== b.x || orig.y !== b.y)) overlay.set(b.id, { x: b.x, y: b.y, at: now }); - } - } else { - // Not controlling (between rounds, dead, or spectating): no prediction, - // and no stale inputs may replay into the next round's spawn position. - predRef.current = null; - pendingRef.current = []; - overlay.clear(); + // Not in control (between rounds, dead, spectating): pending drop ghosts + // must not leak into the next round's spawn. + if (view.phase !== "battle" || !me || !me.alive) { ghostBombsRef.current = []; } - /* -- reconcile against the server once per fresh snapshot -- */ + /* -- per-snapshot bookkeeping: retire confirmed drop ghosts, sample telemetry -- */ if (view.version !== lastVersionSeenRef.current) { lastVersionSeenRef.current = view.version; if (me) { - const ack = me.lastInputSeq ?? 0; - if (ack < lastAckRef.current) { - // Ack moved backwards: the server rebuilt state (round reset). Snap. - pendingRef.current = []; - overlay.clear(); - predRef.current = me.alive ? { x: me.x, y: me.y } : null; - facingRef.current = me.dir; - lastAckedDirRef.current = null; - if (BOMP_DEBUG) - dbgRecord( - dbgRef.current, - now, - view.version, - -1, - 0, - 3, - rttAvgRef.current, - maxFrameMs, - ghostBombsRef.current.length, - ); - } else { - // Drop acknowledged inputs; the newest one is the dir the server is - // now applying. Note a release (null) counts as a real direction. - let ackedDir = lastAckedDirRef.current; - const pending = pendingRef.current; - while (pending.length > 0) { - const head = pending[0]; - if (!head || head.seq > ack) break; - // Sample input-to-ack latency for the envelope (see ackLatRef). - const lat = now - head.sentAt; - if (lat > 0 && lat < 2000) ackLatRef.current = ackLatRef.current * 0.8 + lat * 0.2; - ackedDir = head.dir; - pending.shift(); - } - lastAckedDirRef.current = ackedDir; - // Prune optimistic pushes the server has caught up to, plus any a - // rejected push left stranded (server never agreed within 1.5s). - for (const [id, to] of overlay) { - const b = view.bombs.find((vb) => vb.id === id); - if (!b || (b.x === to.x && b.y === to.y) || now - to.at > 1500) overlay.delete(id); - } - if (me.alive && predRef.current) { - const pred = predRef.current; - // Estimate where the server really is NOW: start from its snapshot - // position and replay every input it has not yet acknowledged, - // timed by our send times plus the measured one-way latency. - const rtt = rttAvgRef.current; - const replayBombs: PredictBomb[] = view.bombs.map((b) => { - const to = overlay.get(b.id); - return { id: b.id, x: to?.x ?? b.x, y: to?.y ?? b.y }; - }); - // Our own unconfirmed charges must exist in BOTH simulations. The - // reference position is meant to reproduce the server's copy, but - // comparing it against a local one that sees a ghost the server - // does not yet know about reads as divergence: pred stops at the - // charge while est walks through it, and the difference has to be - // pulled back. The ghost is retired within a tick or two anyway. - for (const g of ghostBombsRef.current) { - replayBombs.push({ id: `ghost:${g.placedAt}`, x: g.x, y: g.y, ghost: true }); - } - const projected = projectServerPosition( - view.grid, - replayBombs, - { x: me.x, y: me.y }, - me.dir, - ackedDir, - pending, - me.speed, - me.kick, - rtt, - // Calibrated snapshot age: lands the estimate on the server's - // quantized "now" (half a tick of projection bias). - now - rtt / 2 - TICK_MS / 2, - now, - ); - const est = projected.pos; - const facing = projected.facing; - const gap = Math.hypot(est.x - pred.x, est.y - pred.y); - // Lead-aware correction envelope. The old policy corrected only - // once EVERY input was acked, so when the server's tick loop - // stalls (Node event-loop blocks drop setInterval callbacks and - // the sim permanently loses that wall-clock time) the gap grew - // unattended past the snap threshold and discharged as the - // reported "teleported back to where the server saw me". Now: - // gaps inside the envelope ride untouched, anything beyond is - // trimmed toward the envelope on EVERY snapshot, and even large - // gaps close at a capped rate (2.5x run speed) instead of - // teleporting. Verified against the recorded production latency - // trace plus server-stall replay in tests/int/bomperator-prediction. - // int.spec.ts. Round resets still snap via the ack-backwards branch. - // Sizing uses transport RTT plus the SERVER-SIDE component of - // the measured input-to-ack loop (tick queue + snapshot - // turnaround), which ping/pong RTT does not see: prod telemetry - // over the WS arena showed ping RTT (3-24ms) understating the - // real input->effect delay, so the envelope sat below the - // natural gap noise floor (p95 1.0 cells) and every held run - // trimmed visibly. On HTTP the ack loop minus POST RTT is just - // the snapshot wait, so this stays near the v0.12.6 tuning. - const rttEnv = Math.min(300, Math.max(rtt, ackLatRef.current - rtt)); - const envelope = Math.max( - PRED_DEADZONE, - (me.speed * (rttEnv / 2 + TICK_MS / 2 + PRED_ENVELOPE_BUDGET_MS)) / 1000, - ); - if (gap > 2.5) { - const maxStep = (me.speed * 2.5 * easeDtMs) / 1000; - const easeT = Math.min(1, maxStep / gap); - pred.x += (est.x - pred.x) * easeT; - pred.y += (est.y - pred.y) * easeT; - facingRef.current = facing; - } else if (gap > envelope) { - // Rate-limited trim: close at most 0.35 cells per snapshot - // (~7 cells/s at 20Hz, i.e. a run-speed glide, not a jump). - // The old policy closed the whole excess in one frame; once - // trims got frequent on the WS arena that read as constant - // micro-teleports (the reported jitter), and slower - // proportional convergence let sustained divergence stack - // past the ease threshold in trace replay. - const k = Math.min(gap - envelope, 0.35) / gap; - pred.x += (est.x - pred.x) * k; - pred.y += (est.y - pred.y) * k; - } - if (BOMP_DEBUG) { - dbgRecord( - dbgRef.current, - now, - view.version, - gap, - envelope, - gap > 2.5 ? 2 : gap > envelope ? 1 : 0, - rttAvgRef.current, - maxFrameMs, - ghostBombsRef.current.length, - ); - } - } - } - lastAckRef.current = ack; - - // Reconcile optimistic ghost charges. The server placed our drop when - // a bomb we have not seen before shows up owned by our seat (it may - // sit a cell away from the ghost: the server trails our displayed - // position), or when anything occupies the ghost's cell. A ghost - // still unmatched past the round-trip budget expired because the - // server rejected the placement; retire it silently. + // Reconcile optimistic ghost charges. The ghost sits on the server's + // own copy of our cell, so the real charge usually lands exactly on + // it; a fresh bomb owned by our seat, or anything occupying the + // ghost's cell, retires the ghost. One still unmatched past the + // round-trip budget expired because the server rejected the + // placement; retire it silently. const ghosts = ghostBombsRef.current; if (ghosts.length > 0) { let freshOwn = 0; @@ -962,16 +613,34 @@ export function BomperatorGame({ } } } + if (BOMP_DEBUG) { + // Own-seat render lag behind the server's authoritative position. + // This is the ease's steady-state trail, not a divergence to + // correct: nothing here ever pulls the render anywhere. + const rendered = pos.get(me.seat) ?? { x: me.x, y: me.y }; + const lag = Math.hypot(rendered.x - me.x, rendered.y - me.y); + dbgRecord( + dbgRef.current, + now, + view.version, + lag, + 0, + lag > 1.5 ? 3 : 0, + rttAvgRef.current, + maxFrameMs, + ghostBombsRef.current.length, + ); + } knownBombIdsRef.current = new Set(view.bombs.map((b) => b.id)); maxFrameMs = 0; } } - // Ease every OTHER technician toward its authoritative server position. - // Monotonic (never overshoots a collision-valid target); a large gap snaps - // instead of sliding across the map (round resets / teleports). + // Every technician renders the server's authoritative position, eased so + // the 20Hz steps read as continuous motion. A gap beyond 1.5 cells snaps + // (respawn, round reset) instead of sliding across the map. for (const player of view.players) { - if (predRef.current && mySeat !== null && player.seat === mySeat) continue; + const isMe = mySeat !== null && player.seat === mySeat; const target = { x: player.x, y: player.y }; const current = pos.get(player.seat); if (!current) { @@ -981,10 +650,11 @@ export function BomperatorGame({ if (Math.hypot(target.x - current.x, target.y - current.y) > 1.5) { current.x = target.x; current.y = target.y; - if (BOMP_DEBUG && dbgRef.current) dbgRef.current.remoteSnaps += 1; + if (BOMP_DEBUG && dbgRef.current && !isMe) dbgRef.current.remoteSnaps += 1; } else { - current.x += (target.x - current.x) * ease; - current.y += (target.y - current.y) * ease; + const k = isMe ? ownEase : ease; + current.x += (target.x - current.x) * k; + current.y += (target.y - current.y) * k; } } @@ -999,8 +669,7 @@ export function BomperatorGame({ } for (const drop of view.drops) drawDrop(ctx, drop.x, drop.y, drop.kind, now); for (const bomb of view.bombs) { - const w = bombsWorking.find((wb) => wb.id === bomb.id); - drawBomb(ctx, w?.x ?? bomb.x, w?.y ?? bomb.y, bomb.fuseTicks, now); + drawBomb(ctx, bomb.x, bomb.y, bomb.fuseTicks, now); } // Ghost charges: optimistic placements awaiting server confirmation. The // fuse burns on the local clock so the blink cadence matches real ones. @@ -1010,11 +679,7 @@ export function BomperatorGame({ } for (const flame of view.flames) drawFlame(ctx, flame.x, flame.y, flame.ticksLeft, now); for (const player of view.players) { - const isMe = mySeat !== null && player.seat === mySeat; - const rp = - isMe && predRef.current - ? predRef.current - : (pos.get(player.seat) ?? { x: player.x, y: player.y }); + const rp = pos.get(player.seat) ?? { x: player.x, y: player.y }; drawPlayer(ctx, rp, player, String(player.userId) === String(currentUserId)); } }; diff --git a/src/components/frontend/minigames/bomperator/BomperatorTouchControls.tsx b/src/components/frontend/minigames/bomperator/BomperatorTouchControls.tsx index 5d11cb4b..553e6115 100644 --- a/src/components/frontend/minigames/bomperator/BomperatorTouchControls.tsx +++ b/src/components/frontend/minigames/bomperator/BomperatorTouchControls.tsx @@ -19,8 +19,8 @@ interface BomperatorTouchControlsProps { * coarse pointers (phones/tablets); keyboard users never see it. * * The buttons feed the SAME press/release edge path as the keyboard handlers - * (pressDir/releaseDir in BomperatorGame), so prediction, keepalives and the - * pending ledger stay input-source agnostic. Hold semantics mirror keys: + * (pressDir/releaseDir in BomperatorGame), so keepalives and the + * held-direction stack stay input-source agnostic. Hold semantics mirror keys: * pressing a direction moves, releasing stops at the next cell center. Each * button captures its own pointer so holding a direction while tapping plant * works; cancel/lost-capture release paths keep the held stack honest when an diff --git a/src/lib/minigames/AGENTS.md b/src/lib/minigames/AGENTS.md index 10ab5bef..7492ccee 100644 --- a/src/lib/minigames/AGENTS.md +++ b/src/lib/minigames/AGENTS.md @@ -11,9 +11,9 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved - **Call for Fire (artillery observer)**: `/minigames/call-for-fire`, game rules in `src/lib/minigames/call-for-fire.ts` (patrol/checkpoint/compound difficulties, compass bearing observer reports, ADD/DROP + RIGHT/LEFT corrections, scoring/accuracy/XP, injected rng, pure). Components: `src/components/frontend/minigames/call-for-fire/` (`CallForFireArena`, `FireMissionBoard`, `CallForFireLeaderboard`). Action `submitCallForFireResult` validates result bounds, updates profile stats, awards XP + chips, emits `minigame:call-for-fire`, and records the ledger entry (accuracy is distance-to-target on a win, null on a loss). - **Call for Fire: Versus (multiplayer)**: `/minigames/call-for-fire-versus`, category `multiplayer` (out of periods). Pure engine in `src/lib/minigames/call-for-fire-versus/` (`engine.ts`, `views.ts`, `types.ts`, `constants.ts`; client-safe) plus a server-only in-memory match registry in `registry.ts` (mirrors `blackjack/tables.ts`: `globalThis`-anchored Map, lobby, per-turn timeout, expiry sweep, SINGLE-INSTANCE ONLY). Each player hides a FOB fleet, then alternates fire corrections (first shot is a grid designation, later shots adjust from the last impact). `views.ts` builds per-viewer snapshots that never serialize the opponent's fleet. Client polls `fetchVersusMatch` (the in-memory SSE bus is unreliable across dev module copies, same as blackjack). Rewards on completion via `stats.ts` (`minigame:call-for-fire-versus`, profile group `callForFireVersus`). - **Ordnance Disposal (multiplayer, real-time)**: `/minigames/bomperator` (internal key `bomperator`, label "Ordnance Disposal"), category `multiplayer` (out of periods), a 2-8 player free-for-all Bomberman-style charge-clearing drill. Same pure-engine + in-memory-registry split as CFF versus, but upgraded from turn-based to a **fixed ~20 Hz tick loop** (was ~10 Hz until v0.12.3; every tick-denominated constant doubles with the rate so real-world durations stay identical): `src/lib/minigames/bomperator/{constants,types,engine,views}.ts` are pure/client-safe (seeded RNG via `state.rngState`/`gridSeed`; `generateGrid`, `createMatchState`, `startRound`, `applyInput`, `tick`), and `registry.ts` runs one `setInterval(TICK_MS)` per live match (started on `startMatch`, cleared on complete/dissolve; `globalThis.__bomperatorMatches`; SINGLE-INSTANCE ONLY: a restart/redeploy kills live matches). Grid is 15x13 (border + even/even pillars + seeded crates with one hidden power-up each; four classic pickups bomb/range/speed/kick). Movement is grid-locked with sub-cell interpolation; charges fuse ~2.5s, cross-flames stop at walls, destroy crates, chain-detonate, and kick-push; round ends at <=1 alive; sudden death spawns random-cell explosions after the 150s timer, with a draw guard. FFA has no hidden info so `buildBomperatorView` serves every viewer the same board (`yourSeat: null` = spectator). Clients POST inputs (`sendBomperatorInput`, rate-limited 40/s) and poll `fetchBomperatorMatch` (~500ms fallback behind the SSE stream); a rolling event buffer (monotonic ids) drives client SFX without diffing. Disconnects hold the seat for `RECONNECT_WINDOW_MS` then eliminate; below two active seats the match dissolves. Rewards on completion via `stats.ts` (`minigame:bomperator`, profile group `bomperator`: matchesPlayed/matchWins/roundsWon/kills/xpEarned; XP win/loss base + per-kill bounty, chips auto-derived). Registry row ships `status: "upcoming"` (page renders `MinigameComingSoon` until an admin flips it active). - - **Client prediction & correction**: `BomperatorGame.tsx` predicts its own seat between snapshots and reconciles with a lead-aware envelope policy (helpers in `bomperator/prediction.ts`): gaps inside `max(PRED_DEADZONE, speed*(rttEnv/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)` ride untouched, anything beyond is trimmed by at most 0.35 cells per snapshot (a run-speed glide, never a one-frame pull), and gaps past 2.5 cells ease toward the estimate at up to 2.5x run speed instead of teleporting (round resets still snap via the ack-backwards branch). `rttEnv` is `min(300, max(rtt, ackLat - rtt))`: transport RTT plus the server-side share of the measured input-to-ack EMA, because ping/pong alone omits the tick queue and snapshot turnaround (sizing from ping alone put the envelope under the real gap noise floor). Prediction advances by real elapsed time with a 1s sanity cap, so a main-thread hitch does not leave a permanent gap (the engine runs on wall clock); correction easing keeps its own 100ms slice so one catch-up frame cannot discharge a whole gap. A hidden tab releases held keys (input is level-triggered, so the server would otherwise keep running the player). Optimistic ghost charges are replayed in BOTH the local prediction and the server estimate. The estimator's replay clock only moves FORWARD: an unacknowledged input older than the snapshot contributes its direction, never its age (rewinding the clock let a stale 400ms keepalive inflate the estimate by up to 4 cells, which the reconcile then chased). Root cause of the old teleport-back: Node event-loop stalls make the server's 20Hz tick loop DROP setInterval callbacks (no catch-up), so the sim permanently lags wall clock; the old all-inputs-acked pull let that gap stack and discharge at once. `tests/int/bomperator-prediction.int.spec.ts` is an offline deterministic harness (real engine + modeled network + frame-by-frame reconcile mirror) including production-latency replay (`tests/fixtures/bomperator-prod-rtt.json`, from HAR) and a server-stall A/B proof; change client prediction in BOTH component and mirror, and run the trace scenarios before shipping. v0.12.4 lesson (reverted in v0.12.5): do not add mechanisms that trust precise latency estimates (decision nudges, projected ghost placement); real TTFB swings 31-463ms and they glitch under it. - - **Arena transport (WebSocket match replication)**: when `NEXT_PUBLIC_ARENA_URL` is baked into the bundle, the client tries a dedicated arena process first (`src/arena/`, Node 22 + `ws`, Coolify service #2, Docker target `runner-arena`): its own event loop runs the 20 Hz tick via a drift-corrected `setTimeout` chain (capped catch-up, `tick-drift` log every 30s), inputs/snapshots ride one socket (`src/arena/protocol.ts`), and RTT comes from 2s ping/pong instead of POST timing. Transport selection lives in `components/frontend/minigames/bomperator/transport.ts`: WS first, automatic fallback to the unchanged HTTP path (registry actions + SSE + slow poll) after 2 connection failures or a 5s setup timeout; absent `NEXT_PUBLIC_ARENA_URL` = pure HTTP (kill switch/rollback). Server side, `ARENA_SECRET` + `ARENA_INTERNAL_URL` make the bomperator actions proxy the lifecycle to the arena (match ownership moves); the arena holds NO Payload dependency: auth is 30s jose tickets `{uid, matchId, iat}` minted by `createArenaTicket` (query string on the WS handshake; no replay store by design), awards go back through `POST /api/minigames/bomperator/results` (secret header, idempotent by matchId). **Restarting the arena kills live matches** (process memory, like the SSE bus before it; acceptable for ~90s matches). The seq/lastInputSeq pending ledger and envelope reconcile work over both transports; the prediction harness pins the low-latency end too ("ws-grade latency" scenario). - - **Mobile / touch input**: `BomperatorTouchControls.tsx` renders a D-pad (+ stop) and plant button on coarse pointers only (`(pointer: coarse)`); the board itself accepts swipes (dominant-axis cardinal, sets direction) and taps (stop). ALL input sources feed the same `pressDir`/`releaseDir`/`stopAll` edge callbacks in `BomperatorGame.tsx` that keyboard uses, so prediction/keepalive/pending logic stays source-agnostic; held-stack priority makes D-pad + swipe coexist. Canvas is CSS-scaled (`w-full h-auto`, max 520px wrapper) with fixed internal resolution. Backgrounded-tab safety is harness-proven ("backgrounded tab" scenario: 4s rAF freeze under prod trace replay, teleports=0). E2E smoke: `tests/e2e/bomperator-mobile.e2e.spec.ts` (phone viewport, no horizontal overflow); run with `E2E_BROWSER_PATH=` when Vivaldi crashes. + - **Client rendering (server-authoritative)**: `BomperatorGame.tsx` does NOT simulate the own seat. Every player, own included, renders the server's snapshot position through a one-pole ease (own seat `min(1, 0.6*dt)`, remotes `min(1, 0.4*dt)`), and a >1.5-cell jump snaps (respawn, round reset). Input stays level-triggered on the existing monotonic-seq plus 400ms keepalive path; the deliberate cost is one tick of queue (~25ms) plus one-way latency. History: four prediction generations shipped (ack-sized envelope trims; wall-clock catch-up with a 1s cap; ghost parity; forward-only replay clock) and production still jittered, because the rendered position and the server position were separate simulations that had to agree by tuning instead of by construction. The prediction module, its offline harness, and the prod-RTT fixture were removed with the mechanism; do not reintroduce client-side movement without a server-side authority story. Drop ghosts remain visual only: placed at the server's own copy of our cell, retired by the first snapshot that shows the charge, and never used for collision. Hidden tabs release held keys (input is level-triggered, so the server would otherwise keep running a backgrounded player). Telemetry (`localStorage.bompDebug = "1"` then `__bompDbg.stats()`) reports own-seat render trail, own/remote snaps, snapshot cadence, frame max, ghost rows, and RTT. + - **Arena transport (WebSocket match replication)**: when `NEXT_PUBLIC_ARENA_URL` is baked into the bundle, the client tries a dedicated arena process first (`src/arena/`, Node 22 + `ws`, Coolify service #2, Docker target `runner-arena`): its own event loop runs the 20 Hz tick via a drift-corrected `setTimeout` chain (capped catch-up, `tick-drift` log every 30s), inputs/snapshots ride one socket (`src/arena/protocol.ts`), and RTT comes from 2s ping/pong instead of POST timing. Transport selection lives in `components/frontend/minigames/bomperator/transport.ts`: WS first, automatic fallback to the unchanged HTTP path (registry actions + SSE + slow poll) after 2 connection failures or a 5s setup timeout; absent `NEXT_PUBLIC_ARENA_URL` = pure HTTP (kill switch/rollback). Server side, `ARENA_SECRET` + `ARENA_INTERNAL_URL` make the bomperator actions proxy the lifecycle to the arena (match ownership moves); the arena holds NO Payload dependency: auth is 30s jose tickets `{uid, matchId, iat}` minted by `createArenaTicket` (query string on the WS handshake; no replay store by design), awards go back through `POST /api/minigames/bomperator/results` (secret header, idempotent by matchId). **Restarting the arena kills live matches** (process memory, like the SSE bus before it; acceptable for ~90s matches). The seq/lastInputSeq input path works over both transports, and both render server snapshots identically, so the arena and the HTTP fallback share one movement policy. + - **Mobile / touch input**: `BomperatorTouchControls.tsx` renders a D-pad (+ stop) and plant button on coarse pointers only (`(pointer: coarse)`); the board itself accepts swipes (dominant-axis cardinal, sets direction) and taps (stop). ALL input sources feed the same `pressDir`/`releaseDir`/`stopAll` edge callbacks in `BomperatorGame.tsx` that keyboard uses, so keepalive and held-stack logic stays source-agnostic; held-stack priority makes D-pad + swipe coexist. Canvas is CSS-scaled (`w-full h-auto`, max 520px wrapper) with fixed internal resolution. Backgrounded-tab safety: `visibilitychange` releases held keys. E2E smoke: `tests/e2e/bomperator-mobile.e2e.spec.ts` (phone viewport, no horizontal overflow); run with `E2E_BROWSER_PATH=` when Vivaldi crashes. - Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong. ## Periods, achievements & the game registry diff --git a/src/lib/minigames/bomperator/prediction.ts b/src/lib/minigames/bomperator/prediction.ts deleted file mode 100644 index 524b7e5d..00000000 --- a/src/lib/minigames/bomperator/prediction.ts +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Client-side movement prediction for Ordnance Disposal. Pure and client-safe: - * no React, no I/O, no Date.now - the render loop and the offline prediction - * harness (tests/int/bomperator-prediction.int.spec.ts) both drive it. - * - * predStep is a line-level port of the engine's advancePlayer (engine.ts): - * align the perpendicular axis first, then move toward the adjacent cell - * center; a charge blocks unless kick-capable (then it slides one cell - * forward, recorded into the mutable bombs list). Keep the two in lockstep; - * divergence between them is felt as rubber-banding. - */ - -import { GRID_H, GRID_W } from "./constants"; -import type { Dir } from "./types"; - -export interface RenderPos { - x: number; - y: number; -} - -export const PRED_DIR_VEC: Record = { - up: [0, -1], - down: [0, 1], - left: [-1, 0], - right: [1, 0], -}; -export const PRED_EPS = 1e-6; - -export interface PredictBomb { - id: string; - x: number; - y: number; - /** Optimistic local charge the server has not confirmed yet. Blocks movement - * like a real one but cannot be kick-pushed (the server has not placed it). */ - ghost?: boolean; -} - -/** - * Correction deadzone in cells. Gaps explainable by input flight time or - * snapshot-projection bias live inside this band; pulling on them is what made - * movement feel heavy, so they are left alone. - */ -export const PRED_DEADZONE = 0.4; - -/** Correction-envelope budget (ms). The correction envelope is - * max(PRED_DEADZONE, speed x (rttAvg/2 + TICK_MS/2 + this)/1000): a display - * leading the server by one-way flight plus half a tick plus this budget is - * healthy prediction, not divergence - only gaps beyond it get pulled. Sized - * to absorb estimator error and tick quantization at 7 cells/s (~1.3 cells). */ -export const PRED_ENVELOPE_BUDGET_MS = 76; - -export function predCellCentered(x: number, y: number): boolean { - return Math.abs(x - Math.round(x)) < PRED_EPS && Math.abs(y - Math.round(y)) < PRED_EPS; -} - -export function predApproach(current: number, target: number, step: number): number { - const delta = target - current; - // Same tolerance as the engine's approach(): accumulated float dust must not - // make the final slice overshoot or stall one step short of the center. - if (Math.abs(delta) <= step + 1e-6) return target; - return current + Math.sign(delta) * step; -} - -export function predBombAt( - bombs: readonly PredictBomb[], - x: number, - y: number, -): PredictBomb | undefined { - return bombs.find((b) => b.x === x && b.y === y); -} - -export function predOpen(grid: readonly number[], x: number, y: number): boolean { - return x >= 0 && y >= 0 && x < GRID_W && y < GRID_H && grid[y * GRID_W + x] === 0; -} - -export function predCanStand( - grid: readonly number[], - bombs: readonly PredictBomb[], - x: number, - y: number, -): boolean { - return predOpen(grid, x, y) && !predBombAt(bombs, x, y); -} - -/** - * One small advance step mirroring the engine's advancePlayer exactly: finish - * aligning the perpendicular axis first, then move toward the adjacent cell - * center; a charge blocks unless kick-capable (then it slides one cell forward, - * recorded into the mutable bombs list). - */ -export function predStep( - grid: readonly number[], - bombs: PredictBomb[], - x0: number, - y0: number, - dir: Dir, - kick: boolean, - step: number, -): RenderPos { - const [dx, dy] = PRED_DIR_VEC[dir]; - let x = x0; - let y = y0; - if (dx !== 0) { - if (Math.abs(y - Math.round(y)) > PRED_EPS) { - const ty = Math.round(y); - y += Math.sign(ty - y) * Math.min(Math.abs(ty - y), step); - if (Math.abs(ty - y) < PRED_EPS) y = ty; - return { x, y }; - } - const cy = Math.round(y); - const entering = dx > 0 ? Math.floor(x) + 1 : Math.ceil(x) - 1; - const home = dx > 0 ? Math.floor(x + PRED_EPS) : Math.ceil(x - PRED_EPS); - const bomb = predBombAt(bombs, entering, cy); - if (bomb) { - if (kick && !bomb.ghost) { - const bx = entering + dx; - if (predOpen(grid, bx, cy) && !predBombAt(bombs, bx, cy)) { - bomb.x = bx; - bomb.y = cy; - return { x: predApproach(x, entering, step), y }; - } - } - return { x: home, y }; - } - if (!predCanStand(grid, bombs, entering, cy)) return { x: home, y }; - return { x: predApproach(x, entering, step), y }; - } - if (Math.abs(x - Math.round(x)) > PRED_EPS) { - const tx = Math.round(x); - x += Math.sign(tx - x) * Math.min(Math.abs(tx - x), step); - if (Math.abs(tx - x) < PRED_EPS) x = tx; - return { x, y }; - } - const cx = Math.round(x); - const entering = dy > 0 ? Math.floor(y) + 1 : Math.ceil(y) - 1; - const home = dy > 0 ? Math.floor(y + PRED_EPS) : Math.ceil(y - PRED_EPS); - const bomb = predBombAt(bombs, cx, entering); - if (bomb) { - if (kick && !bomb.ghost) { - const by = entering + dy; - if (predOpen(grid, cx, by) && !predBombAt(bombs, cx, by)) { - bomb.x = cx; - bomb.y = by; - return { x, y: predApproach(y, entering, step) }; - } - } - return { x, y: home }; - } - if (!predCanStand(grid, bombs, cx, entering)) return { x, y: home }; - return { x, y: predApproach(y, entering, step) }; -} - -/** - * Advance over `durationMs` in small slices, honoring the engine's slip-to-rest: - * with no active direction the technician keeps traveling in `facing` until it - * lands exactly on a cell center; a blocked cell settles it back to the one it - * was leaving, where it then stays. - */ -export function predAdvance( - grid: readonly number[], - bombs: PredictBomb[], - start: RenderPos, - dir: Dir | null, - facing: Dir, - speed: number, - kick: boolean, - durationMs: number, -): RenderPos { - let { x, y } = start; - let remaining = Math.min(durationMs, 1500); - let guard = 0; - while (remaining > 0.5 && guard < 120) { - guard += 1; - const slice = Math.min(remaining, 16); - const step = (speed * slice) / 1000; - const effDir = dir ?? (predCellCentered(x, y) ? null : facing); - if (!effDir) break; - const res = predStep(grid, bombs, x, y, effDir, kick, step); - const moved = Math.abs(res.x - x) > 1e-9 || Math.abs(res.y - y) > 1e-9; - x = res.x; - y = res.y; - if (!moved) break; // settled against a blocked cell - remaining -= slice; - } - return { x, y }; -} - -/* ------------------------------------------------------- decision alignment */ - -/** One unacknowledged client input, as tracked by the pending ledger. */ -export interface ServerReplayInput { - seq: number; - dir: Dir | null; - sentAt: number; -} - -/** - * Estimate where the server's copy of our technician is (or will be) by - * replaying every unacknowledged input from the latest snapshot position, - * timed by send time plus the measured one-way latency. - * - * `targetMs` is the instant to project to: the reconcile passes the current - * frame time (estimating the server NOW); input edges pass the server's - * decision instant for a key just pressed (one-way latency plus half a tick - * out), so the replay must include inputs already in flight - the previous - * edge may not have been applied server-side yet, and projecting through its - * receive time is what keeps corner turns from overshooting. - * - * Segments are clamped to the target: an input whose receive time lies beyond - * `targetMs` has not been applied by then, so the replay stops before it - * instead of sliding past the target in the old direction. - * - * `snapshotAtMs` is when the snapshot position was current server-side. The - * reconcile derives it from a calibrated age bias that lands the estimate on - * the server's quantized "now"; input edges derive it from the snapshot's - * MEASURED arrival minus one-way latency - assuming the same bias there - * under-projects systematically by the delivery cadence and drags the - * projection behind corners. - */ -export function projectServerPosition( - grid: readonly number[], - bombs: PredictBomb[], - snapshotPos: RenderPos, - snapshotFacing: Dir, - ackedDir: Dir | null, - pending: readonly ServerReplayInput[], - speed: number, - kick: boolean, - rttAvg: number, - snapshotAtMs: number, - targetMs: number, -): { pos: RenderPos; dir: Dir | null; facing: Dir } { - // Replay forward from the moment the snapshot position was current. - let t = snapshotAtMs; - let pos: RenderPos = { ...snapshotPos }; - let dir = ackedDir; - let facing = snapshotFacing; - for (const p of pending) { - const recv = p.sentAt + rttAvg / 2; - if (recv >= targetMs) break; - // Advance time FORWARD only. An unacknowledged input older than the - // snapshot's own clock was already received before that snapshot was built - // (its seq just has not come back in the ack yet), so its direction is - // current but replaying it must not rewind `t`. Rewinding made the trailing - // segment below span the input's whole age, so every stale keepalive - // inflated the estimate by up to the 400ms re-assert cadence: a phantom - // lead of 1-4 cells that the reconcile then chased (prod telemetry showed - // gap p50 1.0, p95 4.1, 22% of snapshots easing, with zero frame hitches). - if (recv > t) { - pos = predAdvance( - grid, - bombs, - pos, - dir, - facing, - speed, - kick, - Math.min(recv - t, 1000), - ); - t = recv; - } - dir = p.dir; - if (p.dir) facing = p.dir; - } - pos = predAdvance( - grid, - bombs, - pos, - dir, - facing, - speed, - kick, - Math.max(0, Math.min(targetMs - t, 1000)), - ); - return { pos, dir, facing }; -} - diff --git a/tests/fixtures/bomperator-prod-rtt.json b/tests/fixtures/bomperator-prod-rtt.json deleted file mode 100644 index fa87d8a1..00000000 --- a/tests/fixtures/bomperator-prod-rtt.json +++ /dev/null @@ -1 +0,0 @@ -[{"atMs": 0, "rttMs": 280}, {"atMs": 416, "rttMs": 169}, {"atMs": 576, "rttMs": 338}, {"atMs": 888, "rttMs": 195}, {"atMs": 1081, "rttMs": 90}, {"atMs": 1172, "rttMs": 95}, {"atMs": 1435, "rttMs": 371}, {"atMs": 1782, "rttMs": 171}, {"atMs": 1937, "rttMs": 230}, {"atMs": 2131, "rttMs": 385}, {"atMs": 2500, "rttMs": 206}, {"atMs": 2698, "rttMs": 186}, {"atMs": 2883, "rttMs": 80}, {"atMs": 2961, "rttMs": 103}, {"atMs": 3066, "rttMs": 278}, {"atMs": 3285, "rttMs": 346}, {"atMs": 3748, "rttMs": 97}, {"atMs": 3845, "rttMs": 303}, {"atMs": 4130, "rttMs": 175}, {"atMs": 4297, "rttMs": 119}, {"atMs": 4408, "rttMs": 62}, {"atMs": 4470, "rttMs": 56}, {"atMs": 4509, "rttMs": 112}, {"atMs": 4614, "rttMs": 78}, {"atMs": 4677, "rttMs": 127}, {"atMs": 4797, "rttMs": 109}, {"atMs": 4898, "rttMs": 194}, {"atMs": 5079, "rttMs": 71}, {"atMs": 5148, "rttMs": 50}, {"atMs": 5199, "rttMs": 36}, {"atMs": 5237, "rttMs": 41}, {"atMs": 5277, "rttMs": 45}, {"atMs": 5322, "rttMs": 104}, {"atMs": 5422, "rttMs": 188}, {"atMs": 5606, "rttMs": 129}, {"atMs": 5735, "rttMs": 86}, {"atMs": 5820, "rttMs": 83}, {"atMs": 5901, "rttMs": 90}, {"atMs": 5973, "rttMs": 211}, {"atMs": 6174, "rttMs": 103}, {"atMs": 6275, "rttMs": 37}, {"atMs": 6312, "rttMs": 33}, {"atMs": 6346, "rttMs": 35}, {"atMs": 6382, "rttMs": 54}, {"atMs": 6590, "rttMs": 115}, {"atMs": 6696, "rttMs": 59}, {"atMs": 6756, "rttMs": 130}, {"atMs": 6867, "rttMs": 345}, {"atMs": 7179, "rttMs": 400}, {"atMs": 7571, "rttMs": 122}, {"atMs": 7693, "rttMs": 71}, {"atMs": 7765, "rttMs": 168}, {"atMs": 7919, "rttMs": 234}, {"atMs": 8140, "rttMs": 116}, {"atMs": 8252, "rttMs": 49}, {"atMs": 8300, "rttMs": 66}, {"atMs": 8365, "rttMs": 53}, {"atMs": 8418, "rttMs": 38}, {"atMs": 8456, "rttMs": 83}, {"atMs": 8537, "rttMs": 95}, {"atMs": 8631, "rttMs": 111}, {"atMs": 8739, "rttMs": 47}, {"atMs": 8780, "rttMs": 49}, {"atMs": 8830, "rttMs": 96}, {"atMs": 8925, "rttMs": 83}, {"atMs": 9007, "rttMs": 58}, {"atMs": 9064, "rttMs": 106}, {"atMs": 9151, "rttMs": 116}, {"atMs": 9223, "rttMs": 216}, {"atMs": 9420, "rttMs": 178}, {"atMs": 9579, "rttMs": 146}, {"atMs": 9715, "rttMs": 377}, {"atMs": 10326, "rttMs": 228}, {"atMs": 10522, "rttMs": 275}, {"atMs": 10790, "rttMs": 280}, {"atMs": 11033, "rttMs": 204}, {"atMs": 11206, "rttMs": 218}, {"atMs": 11390, "rttMs": 327}, {"atMs": 11689, "rttMs": 217}, {"atMs": 11901, "rttMs": 114}, {"atMs": 12016, "rttMs": 69}, {"atMs": 12086, "rttMs": 178}, {"atMs": 12252, "rttMs": 270}, {"atMs": 12498, "rttMs": 223}, {"atMs": 12706, "rttMs": 62}, {"atMs": 12769, "rttMs": 32}, {"atMs": 12801, "rttMs": 76}, {"atMs": 12873, "rttMs": 87}, {"atMs": 12960, "rttMs": 203}, {"atMs": 13149, "rttMs": 80}, {"atMs": 13228, "rttMs": 44}, {"atMs": 13273, "rttMs": 57}, {"atMs": 13330, "rttMs": 41}, {"atMs": 13373, "rttMs": 42}, {"atMs": 13415, "rttMs": 38}, {"atMs": 13454, "rttMs": 140}, {"atMs": 13583, "rttMs": 110}, {"atMs": 13693, "rttMs": 52}, {"atMs": 13827, "rttMs": 93}, {"atMs": 13921, "rttMs": 288}, {"atMs": 14189, "rttMs": 141}, {"atMs": 14325, "rttMs": 60}, {"atMs": 14385, "rttMs": 42}, {"atMs": 14427, "rttMs": 34}, {"atMs": 14462, "rttMs": 43}, {"atMs": 14505, "rttMs": 72}, {"atMs": 14556, "rttMs": 236}, {"atMs": 14775, "rttMs": 306}, {"atMs": 15066, "rttMs": 74}, {"atMs": 15139, "rttMs": 55}, {"atMs": 15195, "rttMs": 74}, {"atMs": 15269, "rttMs": 61}, {"atMs": 15331, "rttMs": 96}, {"atMs": 15415, "rttMs": 180}, {"atMs": 15564, "rttMs": 95}, {"atMs": 15659, "rttMs": 64}, {"atMs": 15723, "rttMs": 31}, {"atMs": 15756, "rttMs": 33}, {"atMs": 15789, "rttMs": 32}, {"atMs": 15822, "rttMs": 118}, {"atMs": 16030, "rttMs": 98}, {"atMs": 16116, "rttMs": 55}, {"atMs": 16172, "rttMs": 32}, {"atMs": 16205, "rttMs": 39}, {"atMs": 16244, "rttMs": 79}, {"atMs": 16304, "rttMs": 116}, {"atMs": 16408, "rttMs": 101}, {"atMs": 16500, "rttMs": 64}, {"atMs": 16564, "rttMs": 37}, {"atMs": 16603, "rttMs": 47}, {"atMs": 16651, "rttMs": 70}, {"atMs": 16938, "rttMs": 36}, {"atMs": 17033, "rttMs": 262}, {"atMs": 17437, "rttMs": 134}, {"atMs": 17567, "rttMs": 79}, {"atMs": 17646, "rttMs": 42}, {"atMs": 17755, "rttMs": 463}, {"atMs": 18200, "rttMs": 277}, {"atMs": 18622, "rttMs": 101}, {"atMs": 18719, "rttMs": 239}, {"atMs": 18931, "rttMs": 279}, {"atMs": 19782, "rttMs": 205}, {"atMs": 19979, "rttMs": 222}, {"atMs": 20177, "rttMs": 311}, {"atMs": 20729, "rttMs": 102}, {"atMs": 20828, "rttMs": 72}, {"atMs": 20899, "rttMs": 49}, {"atMs": 20949, "rttMs": 42}, {"atMs": 20992, "rttMs": 37}, {"atMs": 21033, "rttMs": 107}, {"atMs": 21260, "rttMs": 66}, {"atMs": 21370, "rttMs": 39}, {"atMs": 21433, "rttMs": 73}, {"atMs": 21503, "rttMs": 155}, {"atMs": 21822, "rttMs": 84}, {"atMs": 21905, "rttMs": 131}, {"atMs": 22022, "rttMs": 236}, {"atMs": 22202, "rttMs": 333}, {"atMs": 22741, "rttMs": 104}, {"atMs": 22834, "rttMs": 67}, {"atMs": 22900, "rttMs": 48}, {"atMs": 22950, "rttMs": 93}, {"atMs": 23038, "rttMs": 84}, {"atMs": 23203, "rttMs": 71}, {"atMs": 23400, "rttMs": 65}, {"atMs": 23465, "rttMs": 41}, {"atMs": 23504, "rttMs": 54}, {"atMs": 23591, "rttMs": 119}, {"atMs": 23701, "rttMs": 113}, {"atMs": 23861, "rttMs": 42}, {"atMs": 23904, "rttMs": 39}, {"atMs": 23945, "rttMs": 34}, {"atMs": 24467, "rttMs": 328}, {"atMs": 24785, "rttMs": 109}, {"atMs": 24891, "rttMs": 50}, {"atMs": 24982, "rttMs": 74}, {"atMs": 25053, "rttMs": 151}, {"atMs": 25190, "rttMs": 169}, {"atMs": 25339, "rttMs": 181}, {"atMs": 25619, "rttMs": 152}, {"atMs": 25763, "rttMs": 116}, {"atMs": 25870, "rttMs": 148}, {"atMs": 26014, "rttMs": 148}, {"atMs": 26257, "rttMs": 315}, {"atMs": 26769, "rttMs": 133}, {"atMs": 26896, "rttMs": 173}, {"atMs": 27052, "rttMs": 419}, {"atMs": 27443, "rttMs": 348}, {"atMs": 27945, "rttMs": 211}, {"atMs": 28118, "rttMs": 286}, {"atMs": 28397, "rttMs": 259}, {"atMs": 28644, "rttMs": 121}, {"atMs": 28942, "rttMs": 264}, {"atMs": 29196, "rttMs": 284}, {"atMs": 29453, "rttMs": 160}, {"atMs": 29608, "rttMs": 184}, {"atMs": 29785, "rttMs": 66}, {"atMs": 29842, "rttMs": 62}, {"atMs": 29905, "rttMs": 203}, {"atMs": 30097, "rttMs": 212}, {"atMs": 30294, "rttMs": 132}, {"atMs": 30425, "rttMs": 81}, {"atMs": 30600, "rttMs": 335}] \ No newline at end of file diff --git a/tests/int/bomperator-prediction.int.spec.ts b/tests/int/bomperator-prediction.int.spec.ts deleted file mode 100644 index 7f387308..00000000 --- a/tests/int/bomperator-prediction.int.spec.ts +++ /dev/null @@ -1,907 +0,0 @@ -/** - * 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(); - /** 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. Because the component now advances prediction by - // real elapsed time (1s sanity cap), pred catches up in one frame after the - // stall instead of permanently trailing the server by the capped 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, 1000); - 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 * Math.min(dtMs, 100)) / 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); - }); -}); - -describe("projectServerPosition time base", () => { - const openGrid = () => new Array(GRID_W * GRID_H).fill(0) as number[]; - - it("does not replay the age of an unacknowledged input older than the snapshot", () => { - const T = 10_000; - const projected = projectServerPosition( - openGrid(), - [], - { x: 5, y: 6 }, - "right", - "right", - [{ seq: 9, dir: "right", sentAt: T - 300 }], - 7, - false, - 4, - T, - T + 5, - ); - // 5ms of travel, not 305: rewinding `t` to T-300 made the trailing segment - // span the keepalive's whole age (2.1 cells of phantom lead at 7 cells/s). - expect(projected.pos.x).toBeCloseTo(5.035, 3); - expect(projected.pos.x).toBeLessThan(5.1); - }); - - it("still advances through inputs received after the snapshot clock", () => { - const T = 10_000; - const projected = projectServerPosition( - openGrid(), - [], - { x: 5, y: 6 }, - "right", - "right", - [{ seq: 9, dir: "right", sentAt: T - 10 }], - 7, - false, - 4, - T, - T + 40, - ); - expect(projected.pos.x).toBeCloseTo(5.28, 2); - }); -});