diff --git a/apps/server/src/games/runner.ts b/apps/server/src/games/runner.ts index 5d0d6c9..55fd255 100644 --- a/apps/server/src/games/runner.ts +++ b/apps/server/src/games/runner.ts @@ -8,7 +8,7 @@ import { type ToolCallLog, type TranscriptItem, } from "@aichess/core"; -import { db, schema } from "../db/client.ts"; +import { db, schema, sqlClient } from "../db/client.ts"; import { bus, gameChannel } from "../bus.ts"; import { boss, Q, type EvalJob, type TurnJob } from "../jobs.ts"; import { config } from "../config.ts"; @@ -61,7 +61,31 @@ function asAgentPlayer(p: PlayerRow): AgentPlayer { // ------------------------------------------------------------------ turn job +/** + * One agent per game at a time, across processes and restarts: a session-level advisory lock on a + * reserved connection. If the holder dies its connection drops and the lock is released, so the + * pg-boss retry (heartbeat) can take over; a duplicate job while the holder is alive just exits. + */ async function handleTurn(data: TurnJob, retryCount: number) { + const conn = await sqlClient.reserve(); + const key = `turn:${data.gameId}`; + try { + const [row] = await conn`select pg_try_advisory_lock(hashtext(${key})) as ok`; + if (!row?.ok) { + log("turn", `${data.gameId}#${data.ply}: another worker holds the game — skipping duplicate`); + return; + } + try { + await runTurnLocked(data, retryCount); + } finally { + await conn`select pg_advisory_unlock(hashtext(${key}))`.catch(() => {}); + } + } finally { + conn.release(); + } +} + +async function runTurnLocked(data: TurnJob, retryCount: number) { const g = await loadGame(data.gameId); if (!g || g.game.status !== "running" || g.game.ply !== data.ply - 1) return; // stale const side = sideOfPly(data.ply);