From 846145a00afc3f1216a2afdc392b592ddf15e13d Mon Sep 17 00:00:00 2001 From: anor Date: Wed, 10 Jun 2026 17:34:54 +1000 Subject: [PATCH] =?UTF-8?q?feat(2.2,2.3):=20=D0=B1=D0=BB=D0=BE=D0=BA=D0=B8?= =?UTF-8?q?=D1=80=D1=83=D1=8E=D1=89=D0=B8=D0=B9=20=D1=84=D0=B0=D0=B9=D0=BB?= =?UTF-8?q?=D0=BE=D0=B2=D1=8B=D0=B9=20IO=20=D0=B2=20bridge=20=E2=86=92=20t?= =?UTF-8?q?o=5Fthread;=20=D1=82=D0=B0=D0=B9=D0=BC=D0=B0=D1=83=D1=82+=D0=BF?= =?UTF-8?q?=D0=BE=D1=82=D0=BE=D0=BB=D0=BE=D0=BA=20=D0=BD=D0=B0=20=D0=B0?= =?UTF-8?q?=D0=B3=D0=B5=D0=BD=D1=82=D0=BD=D1=8B=D0=B9=20Docker-=D0=B7?= =?UTF-8?q?=D0=B0=D0=BF=D1=83=D1=81=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 2.2: openpyxl/zip чтение (glm _read_work_dir_files, claude _preprocess_xlsx) больше не морозит event loop. 2.3: asyncio.wait_for вокруг readline (silence=180с) + общий дедлайн 600с — зависший контейнер не даёт вечный спиннер и освобождает слот семафора. Co-Authored-By: Claude Fable 5 --- claude_bridge.py | 26 +++++++++++++++++++++++--- claude_bridge_glm.py | 6 ++++-- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/claude_bridge.py b/claude_bridge.py index eee15c2..e8ea0e0 100644 --- a/claude_bridge.py +++ b/claude_bridge.py @@ -28,6 +28,12 @@ _sessions: dict[tuple[str, str], str] = {} # Concurrency limit _semaphore = asyncio.Semaphore(3) +# Таймауты агентного запуска: без них зависший Docker-контейнер держит слот +# семафора и даёт пользователю вечный спиннер. SILENCE — макс. пауза без вывода +# (Docker-спинап и tool-паузы укладываются), DEADLINE — общий потолок на запрос. +AGENT_READ_SILENCE = int(os.environ.get("AGENT_READ_SILENCE", "180")) +AGENT_TOTAL_DEADLINE = int(os.environ.get("AGENT_TOTAL_DEADLINE", "600")) + def _preprocess_xlsx(work_dir: Path): """Convert xlsx files that openpyxl can't read into CSV + readable xlsx. @@ -165,8 +171,9 @@ async def stream_claude( f"{message}" ) - # Pre-process xlsx files that openpyxl can't read → CSV - _preprocess_xlsx(work_dir) + # Pre-process xlsx files that openpyxl can't read → CSV. + # В отдельном потоке: парсинг xlsx синхронный и блокирует event loop. + await asyncio.to_thread(_preprocess_xlsx, work_dir) instructions = APP_DIR / "claude_project_instructions.md" @@ -275,9 +282,22 @@ async def stream_claude( limit=10 * 1024 * 1024, ) + _loop = asyncio.get_running_loop() + _deadline = _loop.time() + AGENT_TOTAL_DEADLINE try: while True: - raw_line = await proc.stdout.readline() + if _loop.time() > _deadline: + yield f"event: text\ndata: {json.dumps({'text': '\n\n⏱ Превышен лимит времени агента — задача прервана. Упростите запрос или повторите.'}, ensure_ascii=False)}\n\n" + yield f"event: done\ndata: {json.dumps({'result': ''}, ensure_ascii=False)}\n\n" + break + try: + raw_line = await asyncio.wait_for( + proc.stdout.readline(), timeout=AGENT_READ_SILENCE + ) + except asyncio.TimeoutError: + yield f"event: text\ndata: {json.dumps({'text': '\n\n⏱ Агент не отвечает (таймаут). Задача прервана.'}, ensure_ascii=False)}\n\n" + yield f"event: done\ndata: {json.dumps({'result': ''}, ensure_ascii=False)}\n\n" + break if not raw_line: break line = raw_line.decode().strip() diff --git a/claude_bridge_glm.py b/claude_bridge_glm.py index 80109a2..c8d3b92 100644 --- a/claude_bridge_glm.py +++ b/claude_bridge_glm.py @@ -5,6 +5,7 @@ resources.json for code lookups, GLM-5 API for generation. No Docker, no subprocess — pure Python, fast. """ +import asyncio import json import os import re @@ -441,8 +442,9 @@ async def stream_claude( except Exception: pass - # Read files from work directory if they exist - file_context = _read_work_dir_files(work_dir) + # 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)