Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions backend/services/stockfish_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,14 +277,19 @@ def start(self):

def _spawn(self):
try:
self._engine = chess.engine.SimpleEngine.popen_uci(self._path, timeout=3.0)
# Cold containers can take several seconds to load Stockfish's
# embedded neural network. Keep that startup allowance separate
# from the timeout used for ordinary move requests.
self._engine = chess.engine.SimpleEngine.popen_uci(self._path, timeout=15.0)
self._engine.configure({"Threads": 1, "Hash": 32})
self._engine.ping()
self._engine.timeout = 3.0
logger.info("Stockfish engine process spawned successfully.")
except Exception as e:
if self._engine:
self._engine.close()
self._engine = None
logger.error(f"Stockfish spawn failed: {e}")
logger.error("Stockfish spawn failed (%s): %r", type(e).__name__, e)
raise

def stop(self):
Expand Down
33 changes: 33 additions & 0 deletions backend/tests/test_stockfish_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pytest
import chess
import time
import sys
from services.stockfish_service import (
StockfishService,
validate_fen,
Expand Down Expand Up @@ -45,6 +46,38 @@ def test_stockfish_service_startup_resilience():
assert sf.is_ready
sf.stop()


def test_cold_uci_engine_can_initialize_after_three_seconds(tmp_path, monkeypatch):
engine_script = tmp_path / "cold_engine.py"
engine_script.write_text('''
import sys
import time
for line in sys.stdin:
command = line.strip()
if command == "uci":
time.sleep(3.2)
print("id name Cold test engine")
print("option name Threads type spin default 1 min 1 max 128")
print("option name Hash type spin default 16 min 1 max 256")
print("uciok", flush=True)
elif command == "isready":
print("readyok", flush=True)
elif command.startswith("go"):
print("bestmove e2e4", flush=True)
elif command == "quit":
break
''', encoding="utf-8")
monkeypatch.setattr("services.stockfish_service._resolve_path",
lambda: [sys.executable, "-u", str(engine_script)])
sf = StockfishService()
try:
sf.start()
assert sf.is_ready and not sf.is_fallback
result = sf.get_best_move(chess.STARTING_FEN)
assert result["engine"] == "stockfish" and result["uci"] == "e2e4"
finally:
sf.stop()

def test_fallback_engine_eval():
fb = PythonFallbackEngine()
move = fb.get_best_move("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", depth=10, mode="win")
Expand Down
2 changes: 2 additions & 0 deletions docs/PERFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ Stockfish is kept in a persistent UCI process with one thread and a 32 MB hash t

Stockfish search uses both the selected depth and a 350 ms search budget. Weaker mode can perform an additional short candidate analysis. Process startup, UCI communication, detection, queueing, and network time are additional overhead; the search budget is not a whole-request latency guarantee.

Cold engine initialization allows up to 15 seconds to load the embedded neural network and confirm readiness. Once initialized, ordinary engine operations use a three-second timeout. This avoids permanently switching a slow-starting container to the fallback engine.

When Stockfish cannot run, the Python evaluator performs a shallower search with a 300 ms target budget and returns legal advice. Responses label this fallback and omit an Elo estimate. Its recommendations should not be treated as Stockfish strength.

## Sessions and caching
Expand Down
Loading