1
0
Fork 0

fix(minigames): stop Bomperator prediction losing time and disagreeing on ghosts

Prod telemetry (3291 snapshots, one match): gap p50 0.18 but p95 1.22,
max 4.19 cells and 43 eases. A 4-cell gap is ~0.6s of running, so these
are events, not latency noise. Tuning the correction envelope could only
change how they were presented.

- advance prediction by real elapsed time (1s sanity cap) instead of a
  100ms slice: the engine runs on wall clock, so every main-thread hitch
  over 100ms left a permanent gap that had to be eased back. The ease
  branch keeps its own 100ms slice so a catch-up frame cannot discharge
  a whole gap at once
- release held keys when the tab hides: input is level-triggered, so a
  backgrounded tab kept the technician running server-side and then
  snapped back on return
- replay optimistic ghost charges in the server estimate too; pred saw a
  charge the estimate did not, so every unconfirmed placement read as
  divergence while it was in flight
- telemetry: per-row longest frame and ghost count, frameMax/ghostRows in
  stats, so the next playtest attributes any remaining gap directly
- harness mirror: same 1s catch-up and 100ms ease slice; 12 scenarios green
This commit is contained in:
Jason Fraley 2026-10-21 01:19:38 -04:00
parent 69a3cb92fb
commit b51d4bc0d0
3 changed files with 64 additions and 9 deletions

View file

@ -72,6 +72,10 @@ interface DbgRow {
s: number;
/** remote-player >1.5-cell snaps since the previous row. */
rs: number;
/** Longest render frame since the previous row, ms. */
d: number;
/** Optimistic ghost charges alive at this record. */
gh: number;
}
function dbgRecord(
@ -82,6 +86,8 @@ function dbgRecord(
e: number,
b: number,
r: number,
d = 0,
gh = 0,
): void {
if (!st) return;
st.ring.push({
@ -93,6 +99,8 @@ function dbgRecord(
r: Math.round(r),
s: Math.round(now - st.lastAt),
rs: st.remoteSnaps - st.lastRs,
d: Math.round(d),
gh,
});
st.lastAt = now;
st.lastRs = st.remoteSnaps;
@ -498,6 +506,8 @@ export function BomperatorGame({
gapMax: r.length ? Math.max(...r.map((x) => x.g)) : 0,
snapDtP50: pct(r.map((x) => x.s), 0.5),
snapDtP95: pct(r.map((x) => x.s), 0.95),
frameMax: r.length ? Math.max(...r.map((x) => x.d)) : 0,
ghostRows: r.filter((x) => x.gh > 0).length,
rttMin: r.length ? Math.min(...r.map((x) => x.r)) : 0,
rttMax: r.length ? Math.max(...r.map((x) => x.r)) : 0,
};
@ -648,6 +658,15 @@ export function BomperatorGame({
window.addEventListener("keydown", onKeyDown, { capture: true });
window.addEventListener("keyup", onKeyUp, { capture: true });
// A hidden tab stops receiving frames but the server keeps applying the
// held direction (input is level-triggered), so switching tabs or
// minimizing left the technician running into a wall and then snapping
// back on return. Treat hiding as releasing the keys.
const onVisibility = () => {
if (document.visibilityState === "hidden") stopAll();
};
document.addEventListener("visibilitychange", onVisibility);
// Slow re-assert, only while actually holding a direction. An idle tab sends
// nothing, so it adds zero load.
const keepalive = window.setInterval(() => {
@ -658,10 +677,11 @@ export function BomperatorGame({
return () => {
window.removeEventListener("keydown", onKeyDown, { capture: true });
window.removeEventListener("keyup", onKeyUp, { capture: true });
document.removeEventListener("visibilitychange", onVisibility);
window.clearInterval(keepalive);
heldKeysRef.current = [];
};
}, [canControl, pressDir, releaseDir, sendDir, sendDrop]);
}, [canControl, pressDir, releaseDir, sendDir, sendDrop, stopAll]);
/* ---- board swipes (touch): swipe sets direction, tap stops ---- */
@ -710,12 +730,23 @@ export function BomperatorGame({
let raf = 0;
let last = performance.now();
let maxFrameMs = 0;
const step = (now: number) => {
raf = requestAnimationFrame(step);
const rawDt = now - last;
last = now;
const dt = Math.min(rawDt / 16.6667, 3);
const dtMs = Math.min(rawDt, 100);
// 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;
const ease = Math.min(1, 0.4 * dt);
@ -775,7 +806,18 @@ export function BomperatorGame({
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);
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.
@ -807,6 +849,15 @@ export function BomperatorGame({
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 });
}
let t = now - rtt / 2 - TICK_MS / 2;
let est = { x: me.x, y: me.y };
let dir = ackedDir;
@ -852,7 +903,7 @@ export function BomperatorGame({
(me.speed * (rttEnv / 2 + TICK_MS / 2 + PRED_ENVELOPE_BUDGET_MS)) / 1000,
);
if (gap > 2.5) {
const maxStep = (me.speed * 2.5 * dtMs) / 1000;
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;
@ -878,6 +929,8 @@ export function BomperatorGame({
envelope,
gap > 2.5 ? 2 : gap > envelope ? 1 : 0,
rttAvgRef.current,
maxFrameMs,
ghostBombsRef.current.length,
);
}
}
@ -910,6 +963,7 @@ export function BomperatorGame({
}
}
knownBombIdsRef.current = new Set(view.bombs.map((b) => b.id));
maxFrameMs = 0;
}
}

View file

@ -11,7 +11,7 @@ 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*(rttAvg/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)` ride untouched, anything beyond is trimmed on EVERY snapshot, 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). 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.
- **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. 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=<playwright chromium>` when Vivaldi crashes.
- Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong.

View file

@ -447,8 +447,9 @@ function runScenario(cfg: ScenarioConfig): Telemetry {
// 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.
// 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 &&
@ -457,7 +458,7 @@ function runScenario(cfg: ScenarioConfig): Telemetry {
continue;
}
if (now - lastFrameAt < FRAME_MS) continue;
const dtMs = Math.min(now - lastFrameAt, 100);
const dtMs = Math.min(now - lastFrameAt, 1000);
lastFrameAt = now;
// 5a. Snapshot delivery (Arena applies monotonically; newest wins per
@ -583,7 +584,7 @@ function runScenario(cfg: ScenarioConfig): Telemetry {
pred.x = est.x;
pred.y = est.y;
} else {
const maxStep = (me.speed * 2.5 * dtMs) / 1000;
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;