From 4a57854d1e22984868ee47a2bf95cca86087def5 Mon Sep 17 00:00:00 2001 From: ai-chess Date: Fri, 15 May 2026 00:56:34 +0300 Subject: [PATCH] fix: revive dead stockfish + backfill missing evals on startup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/ai_chess/app.py | 60 ++++++++++++++++++++++++-------- src/ai_chess/stockfish_engine.py | 7 +++- 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/src/ai_chess/app.py b/src/ai_chess/app.py index 61a47d9..2ecc17f 100644 --- a/src/ai_chess/app.py +++ b/src/ai_chess/app.py @@ -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()) diff --git a/src/ai_chess/stockfish_engine.py b/src/ai_chess/stockfish_engine.py index d481ddf..362d2f4 100644 --- a/src/ai_chess/stockfish_engine.py +++ b/src/ai_chess/stockfish_engine.py @@ -11,9 +11,14 @@ class StockfishEngine: self._proc: asyncio.subprocess.Process | None = None 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: - if self._proc is not None: + if self.is_alive(): return + # Reset any dead handle from a prior run. + self._proc = None self._proc = await asyncio.create_subprocess_exec( self.path, stdin=asyncio.subprocess.PIPE,