fix(perf): блок ④ — тяжёлую синхронщину с event loop в поток (не морозить всех)

Синхронный 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) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-18 20:39:18 +10:00
co-authored by Claude Opus 4.8
parent 1f8f884207
commit eff51aad77
2 changed files with 39 additions and 29 deletions
+34 -27
View File
@@ -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
+5 -2
View File
@@ -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 не отправлен. Обратитесь к администратору."}