From 0fd9f95a1f72829717d2debc21934a5f48797e08 Mon Sep 17 00:00:00 2001 From: anor Date: Sat, 18 Jul 2026 19:01:49 +1000 Subject: [PATCH] =?UTF-8?q?perf(search):=20=D0=BA=D1=8D=D1=88=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D0=BD=D0=BE=D0=B9=20=D0=B1=D0=B0=D0=B7=D1=8B=20?= =?UTF-8?q?=D0=93=D0=AD=D0=A1=D0=9D=20(181K)=20=D0=BF=D0=BE=20mtime=20?= =?UTF-8?q?=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20re-parse=20=D0=BD=D0=B0?= =?UTF-8?q?=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _search_gesn_extra на КАЖДЫЙ запрос заново json.loads-ил все gesn_*.json (181K норм) — секунды блокировки event loop на каждое сметное слово (Fable audit). Вынесен предпарсенный индекс _gesn_extra_index() с инвалидацией по (mtime_ns,size) набора файлов; диск читается только после pull-обновления базы. Поиск/вывод байт-в-байт прежние (имя в оригинальном регистре сохранено). Битый файл больше не роняет весь поиск. Финальная проверка — test_search_engine на dev (нужен pymorphy2). Co-Authored-By: Claude Opus 4.8 (1M context) --- search_engine.py | 61 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/search_engine.py b/search_engine.py index c504bce..8f9f83a 100644 --- a/search_engine.py +++ b/search_engine.py @@ -118,34 +118,61 @@ def _search_fssc(query: str, top_k: int = 5) -> str: # === ГЭСН extra (181K norms) === -def _search_gesn_extra(query: str, top_k: int = 5) -> str: - """Search in full 181K GESN norms (gesn_extra JSON files).""" +_gesn_extra_cache: list[tuple[str, str, str, str]] = [] # (code, name, name_lower, unit) +_gesn_extra_sig: tuple = () # (имя, mtime_ns, size)* — инвалидация + + +def _gesn_extra_index() -> list[tuple[str, str, str, str]]: + """Предпарсенный индекс полной базы ГЭСН с кэшем по mtime/size файлов. + + Раньше _search_gesn_extra на КАЖДЫЙ запрос заново json.loads-ил все gesn_*.json + (181K норм, секунды блокировки event loop на сообщение — Fable audit). Теперь + диск читается только когда набор файлов изменился (напр. после pull-обновления).""" + global _gesn_extra_cache, _gesn_extra_sig gesn_dir = SMETA_DIR / "data" / "gesn_extra" if not gesn_dir.exists(): - return "" - - query_lower = query.lower() - terms = [_normalize(t) for t in query_lower.split() if len(t) > 2] - results = [] - - for f in gesn_dir.glob("gesn_*.json"): - data = json.loads(f.read_text(encoding="utf-8")) + return [] + files = sorted(gesn_dir.glob("gesn_*.json")) + sig = tuple((f.name, f.stat().st_mtime_ns, f.stat().st_size) for f in files) + if sig == _gesn_extra_sig and _gesn_extra_cache: + return _gesn_extra_cache + index: list[tuple[str, str, str, str]] = [] + for f in files: + try: + data = json.loads(f.read_text(encoding="utf-8")) + except Exception: # noqa: BLE001 — битый файл не должен ронять весь поиск + continue for code, info in data.items(): if not isinstance(info, dict) or "error" in info: continue - name = info.get("name", "").lower() - score = sum(1 for t in terms if t in name) - if score >= 2 or (score == 1 and len(terms) == 1): - results.append((score, code, info)) + name = info.get("name", "") + index.append((code, name, name.lower(), info.get("unit", ""))) + _gesn_extra_cache = index + _gesn_extra_sig = sig + return index + + +def _search_gesn_extra(query: str, top_k: int = 5) -> str: + """Search in full 181K GESN norms (gesn_extra JSON files).""" + index = _gesn_extra_index() + if not index: + return "" + + terms = [_normalize(t) for t in query.lower().split() if len(t) > 2] + if not terms: + return "" + results = [] + for code, name, name_lower, unit in index: + score = sum(1 for t in terms if t in name_lower) + if score >= 2 or (score == 1 and len(terms) == 1): + results.append((score, code, name, unit)) results.sort(reverse=True, key=lambda x: x[0]) if not results: return "" lines = ["Расценки из полной базы ГЭСН (181 000+ норм):"] - for score, code, info in results[:top_k]: - name = info.get("name", "") - unit = info.get("unit", "") + for score, code, name, unit in results[:top_k]: lines.append(f"- ГЭСН {code}: {name} [{unit}]") return "\n".join(lines)