Spaces:
Sleeping
Sleeping
Update main.py
Browse files121 unmodified lines122123124125126127128129130131125126127133 unmodified lines2612622632712722732742752762772642652662672687 unmodified lines276277278291292293294295296297298279280281282161 unmodified lines44444544646646746846947047144744844945045145247847948048148248348448548648748848949049149245345445545645745845946046146246346446549349446646746819 unmodified lines48848949052052152252352449149249310 unmodified lines50450550654154250750850951051154854955055155255351251351451551651756056156256356456556656756856957057157257357451851952052152252352452552652752852953057557653153253340 unmodified lines574575576623624577578579149 unmodified lines72973073178078178278378478578678778878973273373426 unmodified lines761762763822823824764826827828829830831832833834765766767120 unmodified lines888889890961962963891892893121 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 up
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", "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 = 5_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 lines process = psutil.Process(os.getpid()) mem_mb = process.memory_info().rss / 1024 / 1024
# PANIC CASE: Over 18GB - total server reset if 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 CLEANUP elif mem_mb > _RAM_CLEANUP_THRESHOLD_MB: if 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_ENGINE if 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_REQUESTS if _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 += 1 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)
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, ) 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 lines
del result del 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 lines except 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_REQUESTS if _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 += 1 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)
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, ) 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 lines except 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_REVIEWS if _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 += 1 try: engine = await get_stockfish_engine() board = chess.Board(request.start_fen) if request.start_fen else chess.Board()26 unmodified lines player_moves_count = 0 current_score, _ = get_normalized_score(infos_before[0])
process = psutil.Process() mem_start = process.memory_info().rss / 1024 / 1024 for i, san_move in enumerate(request.moves): # Check individual session growth (4GB limit) mem_now = process.memory_info().rss / 1024 / 1024 if (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 / 1024
is_white_turn = board.turn == chess.WHITE is_player_turn = is_white_turn if player_is_white else not is_white_turn
120 unmodified lines except Exception as e: print(f"Analysis Error: {e}") raise HTTPException(status_code=500, detail=str(e)) finally: _PENDING_ENGINE_REQUESTS -= 1 _PENDING_GAME_REVIEWS -= 1
if __name__ == "__main__":main.py+29-102