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:
ai-chess
2026-05-15 00:56:34 +03:00
parent 21dd169dfa
commit 4a57854d1e
2 changed files with 52 additions and 15 deletions
+46 -14
View File
@@ -33,10 +33,8 @@ def build_app(state: state_mod.AppState) -> FastAPI:
eng = StockfishEngine()
state.runtime = {"session": session, "coord": coord, "tailer": tailer, "engine": eng} # type: ignore[attr-defined]
eng_ok = False
try:
await eng.start()
eng_ok = True
print("[lifespan] stockfish started", flush=True)
except Exception as e:
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
# 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():
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:
while True:
ev = await q.get()
@@ -59,18 +102,7 @@ def build_app(state: state_mod.AppState) -> FastAPI:
continue
if ev.get("type") != "move" or not ev.get("fen"):
continue
if not eng_ok:
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)
await _analyze_and_publish(ev["fen"])
finally:
state.events.unsubscribe(q)
bridge_task = asyncio.create_task(eval_bridge())