Spaces:
Sleeping
Sleeping
Update main.py
Browse files270 unmodified lines2712722732742752762772782798 unmodified lines288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348105 unmodified lines454455456457458459460351 unmodified lines812813814815816817818270 unmodified lines# βββ Background Memory Cleanup Task βββββββββββββββββββββββββββββββββββββββββββ_RAM_CLEANUP_THRESHOLD_MB = float(os.environ.get("RAM_CLEANUP_THRESHOLD_MB", "300"))_RAM_RESTART_THRESHOLD_MB = float(os.environ.get("RAM_RESTART_THRESHOLD_MB", "1400"))_RAM_CLEANUP_INTERVAL_SEC = int(os.environ.get("RAM_CLEANUP_INTERVAL_SEC", "30"))_ENGINE_NODES_LIMIT = int(os.environ.get("ENGINE_NODES_LIMIT", "1500000"))_CLEAR_HASH_AFTER_MOVE = os.environ.get("CLEAR_HASH_AFTER_MOVE", "1").strip().lower() not in {"0", "false", "no", "off"}_RESTART_ENGINE_AFTER_MOVE = os.environ.get("RESTART_ENGINE_AFTER_MOVE", "1").strip().lower() not in {"0", "false", "no", "off"}8 unmodified linestry:process = psutil.Process(os.getpid())mem_mb = process.memory_info().rss / 1024 / 1024# Sum up all children (chess engines) memory toototal_mb = mem_mbchild_count = 0for child in process.children(recursive=True):try:total_mb += child.memory_info().rss / 1024 / 1024child_count += 1except (psutil.NoSuchProcess, psutil.AccessDenied):pass# βββ RESTART CHECK (The Last Resort) βββββββββββββββββββββββββββββif total_mb > _RAM_RESTART_THRESHOLD_MB:active_count = len(manager.active_connections)print(f"[CRITICAL] RAM at {total_mb:.1f}MB β RESTARTING SERVER (Limit: {_RAM_RESTART_THRESHOLD_MB}MB, Active: {active_count})")# Immediate exit: Hugging Face or Docker will automatically restart the process/container# This clears all leaky memory and hung engine processes at once.os._exit(0)# βββ REGULAR CLEANUP βββββββββββββββββββββββββββββββββββββββββββββif total_mb > _RAM_CLEANUP_THRESHOLD_MB:print(f"[CLEANUP] total_tree_ram={total_mb:.1f}MB (threshold {_RAM_CLEANUP_THRESHOLD_MB}MB) β purging engines & GC")# 1. Purge global engineengine = _GLOBAL_DEEPCASTLE_ENGINEif engine is not None:try:async with _ENGINE_IO_LOCK:async with _ENGINE_LOCK:_GLOBAL_DEEPCASTLE_ENGINE = Noneawait asyncio.wait_for(engine.quit(), timeout=3.0)except Exception:pass# 2. Hard purge any orphaned engine processesfor child in process.children(recursive=True):try:if "deepcastle" in child.name().lower() or "stockfish" in child.name().lower():print(f"[CLEANUP] Killing orphaned engine: {child.pid}")child.kill()except Exception:pass# 3. Release memoryforce_memory_release()after_mb = process.memory_info().rss / 1024 / 1024print(f"[CLEANUP] Finished. RAM: {total_mb:.1f}MB β {after_mb:.1f}MB")else:# Basic maintenanceforce_memory_release()if total_mb > _RAM_CLEANUP_THRESHOLD_MB * 0.7:print(f"[CLEANUP] Maintenance. RAM {total_mb:.1f}MB (OK)")except Exception as e:print(f"[CLEANUP] Task error: {e}")@asynccontextmanager105 unmodified lines"child_process_count": child_count,"vms_mb": round(mem.vms / 1024 / 1024, 2),"threshold_mb": _RAM_CLEANUP_THRESHOLD_MB,"restart_threshold_mb": _RAM_RESTART_THRESHOLD_MB,"cleanup_interval_sec": _RAM_CLEANUP_INTERVAL_SEC,"status": "high" if total_mb > _RAM_CLEANUP_THRESHOLD_MB else "ok","active_rooms": len(manager.active_connections),351 unmodified linestry:engine = await get_stockfish_engine(hash_mb=2048)board = chess.Board(request.start_fen) if request.start_fen else chess.Board()limit = chess.engine.Limit(time=request.time_per_move, nodes=_ENGINE_NODES_LIMIT)analysis_results = []ply_timeout = _analyze_ply_timeout(request.time_per_move)270 unmodified lines2712722732742752762778 unmodified lines286287288289290291292293294295296297298299300301302303304305306307308309310311312105 unmodified lines418419420421422423351 unmodified lines775776777778779780781270 unmodified lines# βββ Background Memory Cleanup Task βββββββββββββββββββββββββββββββββββββββββββ_RAM_CLEANUP_THRESHOLD_MB = float(os.environ.get("RAM_CLEANUP_THRESHOLD_MB", "300"))_RAM_CLEANUP_INTERVAL_SEC = int(os.environ.get("RAM_CLEANUP_INTERVAL_SEC", "60"))_CLEAR_HASH_AFTER_MOVE = os.environ.get("CLEAR_HASH_AFTER_MOVE", "1").strip().lower() not in {"0", "false", "no", "off"}_RESTART_ENGINE_AFTER_MOVE = os.environ.get("RESTART_ENGINE_AFTER_MOVE", "1").strip().lower() not in {"0", "false", "no", "off"}8 unmodified linestry:process = 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:try:if not engine.is_terminated():async with _ENGINE_IO_LOCK:await _clear_engine_hash(engine)except Exception:passforce_memory_release()after_mb = process.memory_info().rss / 1024 / 1024print(f"[CLEANUP] Done. RAM: {mem_mb:.1f}MB β {after_mb:.1f}MB")else:# Always nudge GC + malloc_trim even when RAM is fineforce_memory_release()print(f"[CLEANUP] RAM at {mem_mb:.1f}MB β OK")except Exception as e:print(f"[CLEANUP] Error during cleanup: {e}")@asynccontextmanager105 unmodified lines"child_process_count": child_count,"vms_mb": round(mem.vms / 1024 / 1024, 2),"threshold_mb": _RAM_CLEANUP_THRESHOLD_MB,"cleanup_interval_sec": _RAM_CLEANUP_INTERVAL_SEC,"status": "high" if total_mb > _RAM_CLEANUP_THRESHOLD_MB else "ok","active_rooms": len(manager.active_connections),351 unmodified linestry:engine = await get_stockfish_engine(hash_mb=2048)board = chess.Board(request.start_fen) if request.start_fen else chess.Board()limit = chess.engine.Limit(time=request.time_per_move)analysis_results = []ply_timeout = _analyze_ply_timeout(request.time_per_move)
main.py+12-49