Spaces:
Sleeping
Sleeping
Update main.py
Browse files121 unmodified lines122123124125126127128129130131132133134133 unmodified lines2682692702712722732742752762772782792807 unmodified lines288289290291292293294295296297298299300301161 unmodified lines46346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649719 unmodified lines51751851952052152252352452552652710 unmodified lines53853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857940 unmodified lines620621622623624625626627149 unmodified lines77777877978078178278378478578678778878979079179226 unmodified lines819820821822823824825826827828829830831832833834835836837120 unmodified lines958959960961962963964965966121 unmodified lines_ENGINE_LOCK = asyncio.Lock()_ENGINE_IO_LOCK = asyncio.Lock()# Global state for monitoring_PENDING_ENGINE_REQUESTS = 0_MAX_PENDING_ENGINE_REQUESTS = 10 # Drop requests if queue is too long to prevent OOM_MAX_PENDING_GAME_REVIEWS = 2 # Max concurrent full game reviews (heavy RAM)_PENDING_GAME_REVIEWS = 0_LOCK_TIMEOUT_SEC = 20.0 # Max wait time in queue before giving updef _engine_hash_mb() -> int:try:133 unmodified lines# βββ Background Memory Cleanup Task βββββββββββββββββββββββββββββββββββββββββββ_RAM_CLEANUP_THRESHOLD_MB = float(os.environ.get("RAM_CLEANUP_THRESHOLD_MB", "1024"))# Global System Limit: 18GB (All analysis sessions freed)_RAM_PANIC_THRESHOLD_MB = 18000.0# Individual Session Limit: 4GB_RAM_SESSION_LIMIT_MB = 4000.0# How often to run the cleanup in seconds (5s)_RAM_CLEANUP_INTERVAL_SEC = 5async def memory_cleanup_task():"""7 unmodified linesprocess = psutil.Process(os.getpid())mem_mb = process.memory_info().rss / 1024 / 1024# PANIC CASE: Over 18GB - total server resetif mem_mb > _RAM_PANIC_THRESHOLD_MB:print(f"[PANIC] RAM at {mem_mb:.1f}MB! Exceeded 18GB System limit. Resetting everything...")await shutdown_engine_async()force_memory_release()# NORMAL CLEANUPelif mem_mb > _RAM_CLEANUP_THRESHOLD_MB:print(f"[CLEANUP] RAM at {mem_mb:.1f}MB (threshold {_RAM_CLEANUP_THRESHOLD_MB}MB) β clearing engine hash")engine = _GLOBAL_DEEPCASTLE_ENGINEif engine is not None:161 unmodified lines# βββ Bot Move (/move) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/move", response_model=MoveResponse)async def get_move(request: MoveRequest):global _PENDING_ENGINE_REQUESTSif _PENDING_ENGINE_REQUESTS > _MAX_PENDING_ENGINE_REQUESTS:force_memory_release()raise HTTPException(status_code=429, detail="Server busy β too many analysis requests.")_PENDING_ENGINE_REQUESTS += 1try:engine = await get_deepcastle_engine()board = chess.Board(request.fen)limit = chess.engine.Limit(time=request.time, depth=request.depth)tsec = _search_timeout_sec(request.time, request.depth)try:async with asyncio.timeout(_LOCK_TIMEOUT_SEC):async with _ENGINE_IO_LOCK:result = await _engine_call(engine,engine.play(board, limit, info=chess.engine.INFO_ALL),tsec,)info = dict(result.info)if not info:info = await _engine_call(engine,engine.analyse(board, limit, info=chess.engine.INFO_ALL),tsec,)except asyncio.TimeoutError:raise HTTPException(status_code=503, detail="Server overloaded β lock wait timeout.")score_cp, mate_in = get_normalized_score(info)depth, nodes, nps = normalize_search_stats(info)19 unmodified linesdel resultdel info# Match Shield: Force cleanup and hash clear after every move to prevent "Idle Growth"async with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)force_memory_release()return MoveResponse(bestmove=best_move,10 unmodified linesexcept Exception as e:print(f"Error: {e}")raise HTTPException(status_code=500, detail=str(e))finally:_PENDING_ENGINE_REQUESTS -= 1# βββ Hint Move (/analysis-move) βββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analysis-move", response_model=MoveResponse)async def get_analysis_move(request: MoveRequest):global _PENDING_ENGINE_REQUESTSif _PENDING_ENGINE_REQUESTS > _MAX_PENDING_ENGINE_REQUESTS:force_memory_release()raise HTTPException(status_code=429, detail="Server busy β too many analysis requests.")_PENDING_ENGINE_REQUESTS += 1try:engine = await get_stockfish_engine()board = chess.Board(request.fen)limit = chess.engine.Limit(time=request.time, depth=request.depth)tsec = _search_timeout_sec(request.time, request.depth)try:async with asyncio.timeout(_LOCK_TIMEOUT_SEC):async with _ENGINE_IO_LOCK:result = await _engine_call(engine,engine.play(board, limit, info=chess.engine.INFO_ALL),tsec,)info = dict(result.info)if not info:info = await _engine_call(engine,engine.analyse(board, limit, info=chess.engine.INFO_ALL),tsec,)except asyncio.TimeoutError:raise HTTPException(status_code=503, detail="Server overloaded β lock wait timeout.")score_cp, mate_in = get_normalized_score(info)depth, nodes, nps = normalize_search_stats(info)40 unmodified linesexcept Exception as e:print(f"Analysis move error: {e}")raise HTTPException(status_code=500, detail=str(e))finally:_PENDING_ENGINE_REQUESTS -= 1# βββ Openings DB βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ149 unmodified lines# βββ Game Analysis (/analyze-game) ββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analyze-game", response_model=AnalyzeResponse)async def analyze_game(request: AnalyzeRequest):global _PENDING_ENGINE_REQUESTS, _PENDING_GAME_REVIEWSif _PENDING_GAME_REVIEWS >= _MAX_PENDING_GAME_REVIEWS:raise HTTPException(status_code=429, detail="Analysis queue full. Only 2 games can be reviewed at once.")if _PENDING_ENGINE_REQUESTS >= _MAX_PENDING_ENGINE_REQUESTS:raise HTTPException(status_code=429, detail="Server busy β too many moving parts.")_PENDING_ENGINE_REQUESTS += 1_PENDING_GAME_REVIEWS += 1try:engine = await get_stockfish_engine()board = chess.Board(request.start_fen) if request.start_fen else chess.Board()26 unmodified linesplayer_moves_count = 0current_score, _ = get_normalized_score(infos_before[0])process = psutil.Process()mem_start = process.memory_info().rss / 1024 / 1024for i, san_move in enumerate(request.moves):# Check individual session growth (4GB limit)mem_now = process.memory_info().rss / 1024 / 1024if (mem_now - mem_start) > _RAM_SESSION_LIMIT_MB:print(f"[ANALYSIS-RESET] Individual session exceeds 4GB growth. Clearing RAM mid-analysis.")async with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)force_memory_release()mem_start = process.memory_info().rss / 1024 / 1024is_white_turn = board.turn == chess.WHITEis_player_turn = is_white_turn if player_is_white else not is_white_turn120 unmodified linesexcept Exception as e:print(f"Analysis Error: {e}")raise HTTPException(status_code=500, detail=str(e))finally:_PENDING_ENGINE_REQUESTS -= 1_PENDING_GAME_REVIEWS -= 1if __name__ == "__main__":121 unmodified lines122123124125126127133 unmodified lines2612622632642652662672687 unmodified lines276277278279280281282161 unmodified lines44444544644744844945045145245345445545645745845946046146246346446546646746819 unmodified lines48848949049149249310 unmodified lines50450550650750850951051151251351451551651751851952052152252352452552652752852953053153253340 unmodified lines574575576577578579149 unmodified lines72973073173273373426 unmodified lines761762763764765766767120 unmodified lines888889890891892893121 unmodified lines_ENGINE_LOCK = asyncio.Lock()_ENGINE_IO_LOCK = asyncio.Lock()def _engine_hash_mb() -> int:try:133 unmodified lines# βββ Background Memory Cleanup Task βββββββββββββββββββββββββββββββββββββββββββ_RAM_CLEANUP_THRESHOLD_MB = float(os.environ.get("RAM_CLEANUP_THRESHOLD_MB", "400"))_RAM_CLEANUP_INTERVAL_SEC = int(os.environ.get("RAM_CLEANUP_INTERVAL_SEC", "300"))async def memory_cleanup_task():"""7 unmodified linesprocess = psutil.Process(os.getpid())mem_mb = process.memory_info().rss / 1024 / 1024if mem_mb > _RAM_CLEANUP_THRESHOLD_MB:print(f"[CLEANUP] RAM at {mem_mb:.1f}MB (threshold {_RAM_CLEANUP_THRESHOLD_MB}MB) β clearing engine hash")engine = _GLOBAL_DEEPCASTLE_ENGINEif engine is not None:161 unmodified lines# βββ Bot Move (/move) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/move", response_model=MoveResponse)async def get_move(request: MoveRequest):try:engine = await get_deepcastle_engine()board = chess.Board(request.fen)limit = chess.engine.Limit(time=request.time, depth=request.depth)tsec = _search_timeout_sec(request.time, request.depth)async with _ENGINE_IO_LOCK:result = await _engine_call(engine,engine.play(board, limit, info=chess.engine.INFO_ALL),tsec,)info = dict(result.info)if not info:info = await _engine_call(engine,engine.analyse(board, limit, info=chess.engine.INFO_ALL),tsec,)score_cp, mate_in = get_normalized_score(info)depth, nodes, nps = normalize_search_stats(info)19 unmodified linesdel resultdel inforeturn MoveResponse(bestmove=best_move,10 unmodified linesexcept Exception as e:print(f"Error: {e}")raise HTTPException(status_code=500, detail=str(e))# βββ Hint Move (/analysis-move) βββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analysis-move", response_model=MoveResponse)async def get_analysis_move(request: MoveRequest):try:engine = await get_stockfish_engine()board = chess.Board(request.fen)limit = chess.engine.Limit(time=request.time, depth=request.depth)tsec = _search_timeout_sec(request.time, request.depth)async with _ENGINE_IO_LOCK:result = await _engine_call(engine,engine.play(board, limit, info=chess.engine.INFO_ALL),tsec,)info = dict(result.info)if not info:info = await _engine_call(engine,engine.analyse(board, limit, info=chess.engine.INFO_ALL),tsec,)score_cp, mate_in = get_normalized_score(info)depth, nodes, nps = normalize_search_stats(info)40 unmodified linesexcept Exception as e:print(f"Analysis move error: {e}")raise HTTPException(status_code=500, detail=str(e))# βββ Openings DB βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ149 unmodified lines# βββ Game Analysis (/analyze-game) ββββββββββββββββββββββββββββββββββββββββββββ@app.post("/analyze-game", response_model=AnalyzeResponse)async def analyze_game(request: AnalyzeRequest):try:engine = await get_stockfish_engine()board = chess.Board(request.start_fen) if request.start_fen else chess.Board()26 unmodified linesplayer_moves_count = 0current_score, _ = get_normalized_score(infos_before[0])for i, san_move in enumerate(request.moves):is_white_turn = board.turn == chess.WHITEis_player_turn = is_white_turn if player_is_white else not is_white_turn120 unmodified linesexcept Exception as e:print(f"Analysis Error: {e}")raise HTTPException(status_code=500, detail=str(e))if __name__ == "__main__":
main.py+29-102