feat(2.2,2.3): блокирующий файловый IO в bridge → to_thread; таймаут+потолок на агентный Docker-запуск

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 <noreply@anthropic.com>
This commit is contained in:
anor
2026-06-10 17:34:54 +10:00
co-authored by Claude Fable 5
parent 0637426d5c
commit 846145a00a
2 changed files with 27 additions and 5 deletions
+23 -3
View File
@@ -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()
+4 -2
View File
@@ -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)