runner: per-game advisory lock so restarts never run a turn twice
This commit is contained in:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user