From eff51aad77196c28e6b4c067703639eb180932e0 Mon Sep 17 00:00:00 2001 From: anor Date: Sat, 18 Jul 2026 20:39:18 +1000 Subject: [PATCH] =?UTF-8?q?fix(perf):=20=D0=B1=D0=BB=D0=BE=D0=BA=20?= =?UTF-8?q?=E2=91=A3=20=E2=80=94=20=D1=82=D1=8F=D0=B6=D1=91=D0=BB=D1=83?= =?UTF-8?q?=D1=8E=20=D1=81=D0=B8=D0=BD=D1=85=D1=80=D0=BE=D0=BD=D1=89=D0=B8?= =?UTF-8?q?=D0=BD=D1=83=20=D1=81=20event=20loop=20=D0=B2=20=D0=BF=D0=BE?= =?UTF-8?q?=D1=82=D0=BE=D0=BA=20(=D0=BD=D0=B5=20=D0=BC=D0=BE=D1=80=D0=BE?= =?UTF-8?q?=D0=B7=D0=B8=D1=82=D1=8C=20=D0=B2=D1=81=D0=B5=D1=85)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Синхронный I/O/CPU в async-пути под нагрузкой морозил сервер у ВСЕХ (класс инцидента с сетью ФГИС, Fable audit): - audit-middleware: log_action (INSERT на КАЖДОМ запросе) → asyncio.to_thread. - регистрация: SMTP (SSL connect+login, timeout 10s) → to_thread. - GLM stream_claude: весь тяжёлый сбор контекста (_search_resources перебор 24k, _search_corpus, _search_fssc, _search_winter, RAG faiss+embed, _search_normative) → to_thread (был синхронным; в потоке уже был только _read_work_dir_files). Осталось (ниже частота, отдельно): save_message в чат-стриме, прочие db-вызовы. Co-Authored-By: Claude Opus 4.8 (1M context) --- claude_bridge_glm.py | 61 ++++++++++++++++++++++++-------------------- main.py | 7 +++-- 2 files changed, 39 insertions(+), 29 deletions(-) diff --git a/claude_bridge_glm.py b/claude_bridge_glm.py index 0687ae6..bb3a949 100644 --- a/claude_bridge_glm.py +++ b/claude_bridge_glm.py @@ -607,6 +607,29 @@ def _search_corpus(message: str) -> str: "НЕ смешивай в одной смете:\n" + "\n".join(lines)) +def _search_rag(message: str) -> str: + """Main RAG (faiss + embed_query) — синхронный, зовётся через to_thread из stream_claude.""" + try: + from smeta_railway.ai.embeddings import embed_query as _embed_q + from smeta_railway.ai.chunker import load_rag_index as _load_rag + import faiss as _faiss + + _rag_idx, _rag_chunks = _load_rag("src/smeta_railway/ai/index") + _q = _embed_q(message) + _faiss.normalize_L2(_q) + _scores, _indices = _rag_idx.search(_q, 5) + _hits = [] + for _s, _i in zip(_scores[0], _indices[0]): + if _s > 0.82: + _c = _rag_chunks[_i] + _hits.append(f"[{_c.get('source','?')}] {_c['text'][:400]}") + if _hits: + return "Найденные фрагменты нормативных документов:\n" + "\n---\n".join(_hits) + except Exception: # noqa: BLE001 — RAG опционален, сбой не должен ронять чат + pass + return "" + + async def stream_claude( message: str, username: str, @@ -635,14 +658,16 @@ async def stream_claude( "расценк", "гэсн", "фер", "норм", ] corpus_context = "" + # to_thread: тяжёлый синхронный поиск (перебор 24k ресурсов, парс корпуса) иначе + # морозит event loop на секунды — сервер замирал у всех (Fable audit #4). if any(p in message.lower() for p in gesn_patterns): - resource_context = _search_resources(message, _resources) + resource_context = await asyncio.to_thread(_search_resources, message, _resources) # Also search in full 181K GESN extra - gesn_extra = _search_gesn_extra(message) + gesn_extra = await asyncio.to_thread(_search_gesn_extra, message) if gesn_extra: resource_context = (resource_context + "\n\n" + gesn_extra) if resource_context else gesn_extra # Реальные цены из корпуса смет (для расчётов — закрывает фабрикацию) - corpus_context = _search_corpus(message) + corpus_context = await asyncio.to_thread(_search_corpus, message) # Search ФССЦ material prices fssc_context = "" @@ -650,41 +675,23 @@ async def stream_claude( "песок", "щебен", "цемент", "раствор", "труб", "кабел", "провод", "фссц", "сметн цен"] if any(p in message.lower() for p in mat_patterns): - fssc_context = _search_fssc(message, top_k=10) + fssc_context = await asyncio.to_thread(_search_fssc, message, top_k=10) # Search winter zones winter_context = "" winter_patterns = ["зимн", "зона", "удорожан", "морозн", "температур"] if any(p in message.lower() for p in winter_patterns): - winter_context = _search_winter(message) + winter_context = await asyncio.to_thread(_search_winter, message) - # Search main RAG (30K chunks from GESN PDFs, orders, etc.) - rag_context = "" - try: - from smeta_railway.ai.embeddings import embed_query as _embed_q - from smeta_railway.ai.chunker import load_rag_index as _load_rag - import faiss as _faiss - - _rag_idx, _rag_chunks = _load_rag("src/smeta_railway/ai/index") - _q = _embed_q(message) - _faiss.normalize_L2(_q) - _scores, _indices = _rag_idx.search(_q, 5) - _hits = [] - for _s, _i in zip(_scores[0], _indices[0]): - if _s > 0.82: - _c = _rag_chunks[_i] - _hits.append(f"[{_c.get('source','?')}] {_c['text'][:400]}") - if _hits: - rag_context = "Найденные фрагменты нормативных документов:\n" + "\n---\n".join(_hits) - except Exception: - pass + # Search main RAG (faiss + embed_query — тяжело; в поток, чтобы не морозить loop) + rag_context = await asyncio.to_thread(_search_rag, message) # Read files from work directory if they exist. # В отдельном потоке: openpyxl/zip синхронны и на тяжёлых xlsx морозят event loop. file_context = await asyncio.to_thread(_read_work_dir_files, work_dir) - # Search normative RAG (TG posts + PDF) - normative_context = _search_normative(message) + # Search normative RAG (TG posts + PDF) — faiss/чтение индекса тоже в поток + normative_context = await asyncio.to_thread(_search_normative, message) # Build user message with context user_content = message diff --git a/main.py b/main.py index b3abecf..1a74ff1 100644 --- a/main.py +++ b/main.py @@ -249,7 +249,9 @@ async def audit_middleware(request: Request, call_next): detail = sub ip = request.client.host if request.client else None try: - log_action(username, action, method, path, detail, ip, response.status_code) + # to_thread: синхронный INSERT на КАЖДОМ запросе иначе морозит event loop + # при WAL-локе (busy_timeout=10s) — сервер замирал бы у всех (Fable audit). + await asyncio.to_thread(log_action, username, action, method, path, detail, ip, response.status_code) except Exception: pass return response @@ -464,7 +466,8 @@ async def register(request: Request): code = result.get("code", "") if code: from email_service import send_verification_code - sent = send_verification_code(email, code) + # to_thread: SMTP (SSL connect + login, timeout 10s) иначе морозит event loop (Fable) + sent = await asyncio.to_thread(send_verification_code, email, code) if not sent: return {"message": "Аккаунт создан, но email не отправлен. Обратитесь к администратору."}