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:
+23
-3
@@ -28,6 +28,12 @@ _sessions: dict[tuple[str, str], str] = {}
|
|||||||
# Concurrency limit
|
# Concurrency limit
|
||||||
_semaphore = asyncio.Semaphore(3)
|
_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):
|
def _preprocess_xlsx(work_dir: Path):
|
||||||
"""Convert xlsx files that openpyxl can't read into CSV + readable xlsx.
|
"""Convert xlsx files that openpyxl can't read into CSV + readable xlsx.
|
||||||
@@ -165,8 +171,9 @@ async def stream_claude(
|
|||||||
f"{message}"
|
f"{message}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Pre-process xlsx files that openpyxl can't read → CSV
|
# Pre-process xlsx files that openpyxl can't read → CSV.
|
||||||
_preprocess_xlsx(work_dir)
|
# В отдельном потоке: парсинг xlsx синхронный и блокирует event loop.
|
||||||
|
await asyncio.to_thread(_preprocess_xlsx, work_dir)
|
||||||
|
|
||||||
instructions = APP_DIR / "claude_project_instructions.md"
|
instructions = APP_DIR / "claude_project_instructions.md"
|
||||||
|
|
||||||
@@ -275,9 +282,22 @@ async def stream_claude(
|
|||||||
limit=10 * 1024 * 1024,
|
limit=10 * 1024 * 1024,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
_loop = asyncio.get_running_loop()
|
||||||
|
_deadline = _loop.time() + AGENT_TOTAL_DEADLINE
|
||||||
try:
|
try:
|
||||||
while True:
|
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:
|
if not raw_line:
|
||||||
break
|
break
|
||||||
line = raw_line.decode().strip()
|
line = raw_line.decode().strip()
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ resources.json for code lookups, GLM-5 API for generation.
|
|||||||
No Docker, no subprocess — pure Python, fast.
|
No Docker, no subprocess — pure Python, fast.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
@@ -441,8 +442,9 @@ async def stream_claude(
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Read files from work directory if they exist
|
# Read files from work directory if they exist.
|
||||||
file_context = _read_work_dir_files(work_dir)
|
# В отдельном потоке: openpyxl/zip синхронны и на тяжёлых xlsx морозят event loop.
|
||||||
|
file_context = await asyncio.to_thread(_read_work_dir_files, work_dir)
|
||||||
|
|
||||||
# Search normative RAG (TG posts + PDF)
|
# Search normative RAG (TG posts + PDF)
|
||||||
normative_context = _search_normative(message)
|
normative_context = _search_normative(message)
|
||||||
|
|||||||
Reference in New Issue
Block a user