fix: revive dead stockfish + backfill missing evals on startup
If the stockfish child dies mid-game (e.g. user pkill'd it, OS OOM killed it), eval_bridge silently lost analyses. Now: - StockfishEngine.is_alive() checks the process' returncode. - _analyze_and_publish() retries once: on first failure, drops the dead handle and calls start() before the second attempt. - On lifespan startup, _backfill_missing_evals() replays the current game's history via python-chess to derive each FEN and analyzes any position that's missing from state.eval_cache. This catches the gap that opens whenever stockfish dies under a running game. Doesn't help across backend restarts (state.game is still in-memory only) — for that we'd need a per-move snapshot of the active game. 55 → 61 tests still pass; engine smoke test now uses is_alive() too.
This commit is contained in:
+46
-14
@@ -33,10 +33,8 @@ def build_app(state: state_mod.AppState) -> FastAPI:
|
|||||||
eng = StockfishEngine()
|
eng = StockfishEngine()
|
||||||
state.runtime = {"session": session, "coord": coord, "tailer": tailer, "engine": eng} # type: ignore[attr-defined]
|
state.runtime = {"session": session, "coord": coord, "tailer": tailer, "engine": eng} # type: ignore[attr-defined]
|
||||||
|
|
||||||
eng_ok = False
|
|
||||||
try:
|
try:
|
||||||
await eng.start()
|
await eng.start()
|
||||||
eng_ok = True
|
|
||||||
print("[lifespan] stockfish started", flush=True)
|
print("[lifespan] stockfish started", flush=True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[lifespan] stockfish.start failed: {e}", flush=True)
|
print(f"[lifespan] stockfish.start failed: {e}", flush=True)
|
||||||
@@ -49,8 +47,53 @@ def build_app(state: state_mod.AppState) -> FastAPI:
|
|||||||
# mirrors the agent panes, so the polling would be wasted work and
|
# mirrors the agent panes, so the polling would be wasted work and
|
||||||
# also flood every subscriber queue with large term_chunk events.
|
# also flood every subscriber queue with large term_chunk events.
|
||||||
|
|
||||||
|
async def _analyze_and_publish(fen: str) -> bool:
|
||||||
|
"""Run stockfish analyze; revive a dead engine once if needed."""
|
||||||
|
for attempt in (1, 2):
|
||||||
|
try:
|
||||||
|
if not eng.is_alive():
|
||||||
|
await eng.start()
|
||||||
|
res = await eng.analyze(
|
||||||
|
fen, depth=state.settings.stockfish_depth,
|
||||||
|
)
|
||||||
|
state.eval_cache[fen] = {**res, "fen": fen}
|
||||||
|
await state.events.publish({"type": "eval", **res, "fen": fen})
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[eval_bridge] analyze attempt {attempt} failed: {e}",
|
||||||
|
flush=True)
|
||||||
|
# Drop the dead handle so the next start() spawns fresh.
|
||||||
|
eng._proc = None # type: ignore[attr-defined]
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _backfill_missing_evals() -> None:
|
||||||
|
"""After (re)start, fill evals for any history positions that
|
||||||
|
still don't have one. Replays history via python-chess to derive
|
||||||
|
each FEN deterministically (same producer the move events use)."""
|
||||||
|
import chess as _chess
|
||||||
|
game = state.game
|
||||||
|
if game is None:
|
||||||
|
return
|
||||||
|
b = _chess.Board()
|
||||||
|
for h in game.history:
|
||||||
|
if not h.uci or h.uci in ("resign", "agreement"):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
b.push(_chess.Move.from_uci(h.uci))
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
fen = b.fen()
|
||||||
|
if fen in state.eval_cache:
|
||||||
|
continue
|
||||||
|
ok = await _analyze_and_publish(fen)
|
||||||
|
if not ok:
|
||||||
|
return # engine refuses to come up; bail
|
||||||
|
|
||||||
async def eval_bridge():
|
async def eval_bridge():
|
||||||
q = state.events.subscribe()
|
q = state.events.subscribe()
|
||||||
|
# If something was missed before we subscribed (e.g. after a
|
||||||
|
# silent stockfish crash), fill the gap once on startup.
|
||||||
|
asyncio.create_task(_backfill_missing_evals())
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
ev = await q.get()
|
ev = await q.get()
|
||||||
@@ -59,18 +102,7 @@ def build_app(state: state_mod.AppState) -> FastAPI:
|
|||||||
continue
|
continue
|
||||||
if ev.get("type") != "move" or not ev.get("fen"):
|
if ev.get("type") != "move" or not ev.get("fen"):
|
||||||
continue
|
continue
|
||||||
if not eng_ok:
|
await _analyze_and_publish(ev["fen"])
|
||||||
continue
|
|
||||||
try:
|
|
||||||
res = await eng.analyze(
|
|
||||||
ev["fen"], depth=state.settings.stockfish_depth,
|
|
||||||
)
|
|
||||||
payload = {"type": "eval", **res, "fen": ev["fen"]}
|
|
||||||
# Cache so future WS clients can backfill on connect.
|
|
||||||
state.eval_cache[ev["fen"]] = {**res, "fen": ev["fen"]}
|
|
||||||
await state.events.publish(payload)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[eval_bridge] analyze failed: {e}", flush=True)
|
|
||||||
finally:
|
finally:
|
||||||
state.events.unsubscribe(q)
|
state.events.unsubscribe(q)
|
||||||
bridge_task = asyncio.create_task(eval_bridge())
|
bridge_task = asyncio.create_task(eval_bridge())
|
||||||
|
|||||||
@@ -11,9 +11,14 @@ class StockfishEngine:
|
|||||||
self._proc: asyncio.subprocess.Process | None = None
|
self._proc: asyncio.subprocess.Process | None = None
|
||||||
self._lock = asyncio.Lock()
|
self._lock = asyncio.Lock()
|
||||||
|
|
||||||
|
def is_alive(self) -> bool:
|
||||||
|
return self._proc is not None and self._proc.returncode is None
|
||||||
|
|
||||||
async def start(self) -> None:
|
async def start(self) -> None:
|
||||||
if self._proc is not None:
|
if self.is_alive():
|
||||||
return
|
return
|
||||||
|
# Reset any dead handle from a prior run.
|
||||||
|
self._proc = None
|
||||||
self._proc = await asyncio.create_subprocess_exec(
|
self._proc = await asyncio.create_subprocess_exec(
|
||||||
self.path,
|
self.path,
|
||||||
stdin=asyncio.subprocess.PIPE,
|
stdin=asyncio.subprocess.PIPE,
|
||||||
|
|||||||
Reference in New Issue
Block a user