From ef5ce9f95218607c094fe8dca7a08ad095bb93db Mon Sep 17 00:00:00 2001 From: "Bingxi Zhao (Frank)" <13051345080@163.com> Date: Sun, 2 Aug 2026 13:07:32 +0800 Subject: [PATCH] fix: RAM issues --- .gitignore | 1 + Dockerfile | 15 +- README.md | 6 +- assets/README/README_AR.md | 6 +- assets/README/README_CN.md | 6 +- assets/README/README_ES.md | 6 +- assets/README/README_FR.md | 6 +- assets/README/README_HI.md | 6 +- assets/README/README_JA.md | 6 +- assets/README/README_PL.md | 6 +- assets/README/README_PT.md | 6 +- assets/README/README_RU.md | 6 +- assets/README/README_TH.md | 6 +- deeptutor/agents/__init__.py | 14 +- deeptutor/api/main.py | 18 ++ deeptutor/api/run_server.py | 18 +- deeptutor/api/utils/task_id_manager.py | 17 ++ deeptutor/api/utils/task_log_stream.py | 139 +++++++++++++- deeptutor/book/engine.py | 7 + deeptutor/core/agentic/__init__.py | 56 +++--- deeptutor/core/agentic/client.py | 112 ++++++++++- deeptutor/runtime/launcher.py | 176 +++++++++++++++++- deeptutor/runtime/memory_reclaim.py | 73 ++++++++ deeptutor/services/config/__init__.py | 2 + deeptutor/services/config/runtime_settings.py | 15 ++ deeptutor/services/llm/client.py | 13 ++ deeptutor/services/llm/error_mapping.py | 52 ++---- .../services/llm/provider_core/__init__.py | 38 +++- deeptutor/services/llm/provider_core/base.py | 18 ++ deeptutor/services/llm/provider_factory.py | 142 ++++++++++++-- .../rag/pipelines/llamaindex/storage.py | 41 +++- deeptutor/services/session/turn_runtime.py | 6 + deeptutor/utils/document_extractor.py | 86 ++++++--- deeptutor_cli/main.py | 12 +- scripts/start_web.py | 8 +- tests/api/test_task_id_manager.py | 38 ++++ tests/book/test_runtime_reclaim.py | 25 +++ tests/cli/test_chat_cli.py | 11 +- .../test_agentic_client_provider_kwargs.py | 51 +++++ tests/logging/test_task_log_stream.py | 30 +++ .../test_api_import_memory_boundary.py | 43 +++++ tests/runtime/test_launcher.py | 109 +++++++++++ tests/runtime/test_launcher_allocator_env.py | 18 ++ tests/runtime/test_memory_reclaim.py | 28 +++ tests/runtime/test_run_server_memory_mode.py | 51 +++++ tests/runtime/test_uvicorn_launch_flags.py | 66 +++++++ tests/scripts/test_start_web.py | 5 +- tests/services/llm/test_provider_pool.py | 101 ++++++++++ .../rag/test_llamaindex_index_cache_bounds.py | 40 ++++ web/eslint.config.mjs | 2 +- web/next.config.js | 6 + web/package.json | 4 +- web/scripts/dev.mjs | 69 +++++++ web/tests/dev-heap-ceiling.test.ts | 83 +++++++++ web/tsconfig.json | 4 +- 55 files changed, 1757 insertions(+), 172 deletions(-) create mode 100644 deeptutor/runtime/memory_reclaim.py create mode 100644 tests/api/test_task_id_manager.py create mode 100644 tests/book/test_runtime_reclaim.py create mode 100644 tests/runtime/test_api_import_memory_boundary.py create mode 100644 tests/runtime/test_launcher_allocator_env.py create mode 100644 tests/runtime/test_memory_reclaim.py create mode 100644 tests/runtime/test_run_server_memory_mode.py create mode 100644 tests/runtime/test_uvicorn_launch_flags.py create mode 100644 tests/services/llm/test_provider_pool.py create mode 100644 tests/services/rag/test_llamaindex_index_cache_bounds.py create mode 100644 web/scripts/dev.mjs create mode 100644 web/tests/dev-heap-ceiling.test.ts diff --git a/.gitignore b/.gitignore index 8554b2ab9..fee2b05fb 100644 --- a/.gitignore +++ b/.gitignore @@ -76,6 +76,7 @@ node_modules/ # Next.js build output .next/ web/.next/ +web/.next-deeptutor/ out/ web/out/ .vercel/ diff --git a/Dockerfile b/Dockerfile index fd9925d64..73dc72145 100644 --- a/Dockerfile +++ b/Dockerfile @@ -111,6 +111,8 @@ LABEL maintainer="DeepTutor Team" \ ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PYTHONIOENCODING=utf-8 \ + MALLOC_ARENA_MAX=2 \ + MALLOC_TRIM_THRESHOLD_=131072 \ NODE_ENV=production \ DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES=1 @@ -279,8 +281,15 @@ echo "[Backend] 🚀 Starting FastAPI backend on ${BACKEND_HOST}:${BACKEND_PORT # --ws-max-size: chat attachments travel base64 inside one WS message; derive # the frame cap from the configured attachment policy (system.json) so uploads # the policy allows are not severed by uvicorn's 16MB default. +# +# --timeout-keep-alive: the frontend proxy (web/proxy.ts) forwards over Node's +# http.globalAgent, which reaps idle sockets on a 5s timer — identical to +# uvicorn's default, so both ends raced to close the same socket and the loser's +# request died with ECONNRESET (a 500 in the UI). Stay well above the proxy's +# reaper so the client is the only side retiring idle connections. WS_MAX_SIZE=$(python -c "from deeptutor.services.config import get_ws_max_size; print(get_ws_max_size())" 2>/dev/null || echo 16777216) -exec python -m uvicorn deeptutor.api.main:app --host ${BACKEND_HOST} --port ${BACKEND_PORT} --no-access-log --ws-max-size ${WS_MAX_SIZE} +KEEP_ALIVE=$(python -c "from deeptutor.services.config import HTTP_KEEP_ALIVE_TIMEOUT; print(HTTP_KEEP_ALIVE_TIMEOUT)" 2>/dev/null || echo 300) +exec python -m uvicorn deeptutor.api.main:app --host ${BACKEND_HOST} --port ${BACKEND_PORT} --no-access-log --ws-max-size ${WS_MAX_SIZE} --timeout-keep-alive ${KEEP_ALIVE} EOF RUN sed -i 's/\r$//' /app/start-backend.sh && chmod +x /app/start-backend.sh @@ -463,7 +472,7 @@ RUN pip install --no-cache-dir \ # the production stage is reused as-is. RUN cat > /etc/supervisor/conf.d/programs.conf <<'EOF' [program:backend] -command=/bin/bash -c "exec python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port ${BACKEND_PORT:-8001} --reload --no-access-log --ws-max-size $(python -c 'from deeptutor.services.config import get_ws_max_size; print(get_ws_max_size())' 2>/dev/null || echo 16777216)" +command=/bin/bash -c "exec python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port ${BACKEND_PORT:-8001} --reload --no-access-log --ws-max-size $(python -c 'from deeptutor.services.config import get_ws_max_size; print(get_ws_max_size())' 2>/dev/null || echo 16777216) --timeout-keep-alive $(python -c 'from deeptutor.services.config import HTTP_KEEP_ALIVE_TIMEOUT; print(HTTP_KEEP_ALIVE_TIMEOUT)' 2>/dev/null || echo 300)" directory=/app user=deeptutor autostart=true @@ -475,7 +484,7 @@ stderr_logfile_maxbytes=0 environment=PYTHONPATH="/app",PYTHONUNBUFFERED="1" [program:frontend] -command=/bin/bash -c "cd /app/web && node node_modules/next/dist/bin/next dev -H 0.0.0.0 -p ${FRONTEND_PORT:-3782}" +command=/bin/bash -c "cd /app/web && node scripts/dev.mjs -H 0.0.0.0 -p ${FRONTEND_PORT:-3782}" directory=/app/web user=deeptutor autostart=true diff --git a/README.md b/README.md index 884c311c4..25c4ea346 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` Source installs run Next.js in dev mode against the local `web/` directory; everything else (config layout, ports, stop with `Ctrl+C`) matches Option 1. @@ -272,7 +272,7 @@ pip install -e ".[math-animator]" # Manim addon; requires LaTeX/ffmpeg/system ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -716,7 +716,7 @@ The repo ships a root [`SKILL.md`](SKILL.md) — a ~150-line handover doc that t | Command | Description | |:---|:---| | `deeptutor init` | Create or update `data/user/settings` for the current workspace | -| `deeptutor start [--home PATH]` | Launch backend + frontend together | +| `deeptutor start [--home PATH] [--dev]` | Launch backend + frontend together; `--dev` enables frontend HMR | | `deeptutor serve [--port PORT]` | Start only the FastAPI backend | | `deeptutor run ` | Run a single capability turn (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); add `--format json` for NDJSON output | | `deeptutor chat` | Interactive REPL with capability, tool, KB, notebook, and history controls | diff --git a/assets/README/README_AR.md b/assets/README/README_AR.md index dc369ae56..d16e3f5ed 100644 --- a/assets/README/README_AR.md +++ b/assets/README/README_AR.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` تشغّل تثبيتات المصدر Next.js في وضع التطوير مقابل دليل `web/` المحلي؛ كل شيء آخر (تخطيط التهيئة، المنافذ، الإيقاف بـ `Ctrl+C`) يطابق الخيار 1. @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # إضافة Manim؛ تتطلب LaTeX/ffmpeg ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -569,7 +569,7 @@ deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format j | الأمر | الوصف | |:---|:---| | `deeptutor init` | إنشاء أو تحديث `data/user/settings` لمساحة العمل الحالية | -| `deeptutor start [--home PATH]` | تشغيل الخلفية + الواجهة الأمامية معاً | +| `deeptutor start [--home PATH] [--dev]` | تشغيل الخلفية + الواجهة الأمامية معاً | | `deeptutor serve [--port PORT]` | تشغيل خلفية FastAPI فقط | | `deeptutor run ` | تشغيل دور قدرة واحدة (`chat` و`deep_solve` و`deep_question` و`deep_research` و`visualize` و`math_animator` و`mastery_path`)؛ أضف `--format json` لإخراج NDJSON | | `deeptutor chat` | REPL تفاعلي مع تحكمات القدرة والأداة وقاعدة المعرفة ودفتر الملاحظات والتاريخ | diff --git a/assets/README/README_CN.md b/assets/README/README_CN.md index 38455106f..276f246aa 100644 --- a/assets/README/README_CN.md +++ b/assets/README/README_CN.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` 源码安装会以开发模式运行 Next.js,指向本地 `web/` 目录;其他所有内容(配置布局、端口、`Ctrl+C` 停止)与方式一相同。 @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # Manim 插件;需要 LaTeX/ffmpeg/系统 ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -569,7 +569,7 @@ deeptutor run deep_question "就那篇调研测验我" --session "$SID" --format | 命令 | 说明 | |:---|:---| | `deeptutor init` | 为当前工作区创建或更新 `data/user/settings` | -| `deeptutor start [--home PATH]` | 同时启动后端 + 前端 | +| `deeptutor start [--home PATH] [--dev]` | 同时启动后端 + 前端;`--dev` 启用前端热更新 | | `deeptutor serve [--port PORT]` | 仅启动 FastAPI 后端 | | `deeptutor run ` | 运行单次能力对话(`chat`、`deep_solve`、`deep_question`、`deep_research`、`visualize`、`math_animator`、`mastery_path`);添加 `--format json` 可获得 NDJSON 输出 | | `deeptutor chat` | 交互式 REPL,支持能力、工具、知识库、笔记本和历史控制 | diff --git a/assets/README/README_ES.md b/assets/README/README_ES.md index 27d174672..0c31edd04 100644 --- a/assets/README/README_ES.md +++ b/assets/README/README_ES.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` Las instalaciones desde fuente ejecutan Next.js en modo de desarrollo contra el directorio `web/` local; todo lo demás (diseño de configuración, puertos, detener con `Ctrl+C`) coincide con la Opción 1. @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # complemento Manim; requiere LaTeX/ffmpeg/l ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -581,7 +581,7 @@ El repo incluye un [`SKILL.md`](../../SKILL.md) raíz — un documento de traspa | Comando | Descripción | |:---|:---| | `deeptutor init` | Crear o actualizar `data/user/settings` para el espacio de trabajo actual | -| `deeptutor start [--home PATH]` | Lanzar backend + frontend juntos | +| `deeptutor start [--home PATH] [--dev]` | Lanzar backend + frontend juntos | | `deeptutor serve [--port PORT]` | Iniciar solo el backend FastAPI | | `deeptutor run ` | Ejecutar un turno de capacidad único (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); agrega `--format json` para salida NDJSON | | `deeptutor chat` | REPL interactivo con controles de capacidad, herramienta, KB, notebook e historial | diff --git a/assets/README/README_FR.md b/assets/README/README_FR.md index 4e442a5f0..9c0e1a46e 100644 --- a/assets/README/README_FR.md +++ b/assets/README/README_FR.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` Les installations depuis les sources exécutent Next.js en mode dev contre le répertoire `web/` local ; tout le reste (structure de configuration, ports, arrêt avec `Ctrl+C`) correspond à l'Option 1. @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # addon Manim ; nécessite LaTeX/ffmpeg/libs ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -591,7 +591,7 @@ Le dépôt inclut un [`SKILL.md`](SKILL.md) racine — un document de passation | Commande | Description | |:---|:---| | `deeptutor init` | Créer ou mettre à jour `data/user/settings` pour l'espace de travail actuel | -| `deeptutor start [--home PATH]` | Lancer le backend + frontend ensemble | +| `deeptutor start [--home PATH] [--dev]` | Lancer le backend + frontend ensemble | | `deeptutor serve [--port PORT]` | Démarrer uniquement le backend FastAPI | | `deeptutor run ` | Exécuter un seul tour de capacité (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`) ; ajoutez `--format json` pour la sortie NDJSON | | `deeptutor chat` | REPL interactif avec contrôles de capacité, outil, KB, carnet et historique | diff --git a/assets/README/README_HI.md b/assets/README/README_HI.md index 342045c4d..ae47488f2 100644 --- a/assets/README/README_HI.md +++ b/assets/README/README_HI.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` Source installs local `web/` directory के विरुद्ध Next.js को dev mode में run करते हैं; बाकी सब (config layout, ports, `Ctrl+C` से stop) Option 1 से match करता है। @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # Manim addon; LaTeX/ffmpeg/system libs च ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -569,7 +569,7 @@ Repo एक root [`SKILL.md`](../../SKILL.md) ship करता है — ए | Command | विवरण | |:---|:---| | `deeptutor init` | Current workspace के लिए `data/user/settings` create या update करें | -| `deeptutor start [--home PATH]` | Backend + frontend को एक साथ launch करें | +| `deeptutor start [--home PATH] [--dev]` | Backend + frontend को एक साथ launch करें | | `deeptutor serve [--port PORT]` | केवल FastAPI backend start करें | | `deeptutor run ` | एक single capability turn run करें (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); NDJSON output के लिए `--format json` add करें | | `deeptutor chat` | capability, tool, KB, notebook, और history controls के साथ interactive REPL | diff --git a/assets/README/README_JA.md b/assets/README/README_JA.md index 476c3bc4f..6bc530df2 100644 --- a/assets/README/README_JA.md +++ b/assets/README/README_JA.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` ソースインストールはローカルの`web/`ディレクトリに対してNext.jsをdevモードで実行します。その他(設定レイアウト、ポート、`Ctrl+C`での停止)はオプション1と同じです。 @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # Maninアドオン; LaTeX/ffmpeg/システ ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -569,7 +569,7 @@ deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format j | コマンド | 説明 | |:---|:---| | `deeptutor init` | 現在のワークスペースの`data/user/settings`を作成または更新 | -| `deeptutor start [--home PATH]` | バックエンド + フロントエンドを一緒に起動 | +| `deeptutor start [--home PATH] [--dev]` | バックエンド + フロントエンドを一緒に起動 | | `deeptutor serve [--port PORT]` | FastAPIバックエンドのみ起動 | | `deeptutor run ` | 単一機能ターンを実行(`chat`、`deep_solve`、`deep_question`、`deep_research`、`visualize`、`math_animator`、`mastery_path`);`--format json`でNDJSON出力 | | `deeptutor chat` | 機能、ツール、KB、ノートブック、履歴コントロール付きインタラクティブREPL | diff --git a/assets/README/README_PL.md b/assets/README/README_PL.md index ee748a824..9b1e7d5fa 100644 --- a/assets/README/README_PL.md +++ b/assets/README/README_PL.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` Instalacje ze źródeł uruchamiają Next.js w trybie deweloperskim względem lokalnego katalogu `web/`; wszystko inne (układ konfiguracji, porty, zatrzymanie za pomocą `Ctrl+C`) odpowiada Opcji 1. @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # addon Manim; wymaga LaTeX/ffmpeg/bibliotek ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -569,7 +569,7 @@ Repozytorium zawiera główny [`SKILL.md`](../../SKILL.md) — około 150-liniow | Polecenie | Opis | |:---|:---| | `deeptutor init` | Utwórz lub zaktualizuj `data/user/settings` dla bieżącego obszaru roboczego | -| `deeptutor start [--home PATH]` | Uruchom backend + frontend razem | +| `deeptutor start [--home PATH] [--dev]` | Uruchom backend + frontend razem | | `deeptutor serve [--port PORT]` | Uruchom tylko backend FastAPI | | `deeptutor run ` | Uruchom jedną turę możliwości (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); dodaj `--format json` dla wyjścia NDJSON | | `deeptutor chat` | Interaktywny REPL z kontrolkami możliwości, narzędzia, KB, notatnika i historii | diff --git a/assets/README/README_PT.md b/assets/README/README_PT.md index d1488fb49..e1ae90292 100644 --- a/assets/README/README_PT.md +++ b/assets/README/README_PT.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` As instalações a partir de fonte executam o Next.js em modo de desenvolvimento contra o diretório `web/` local; todo o resto (layout de configuração, portas, parar com `Ctrl+C`) corresponde à Opção 1. @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # add-on Manim; requer LaTeX/ffmpeg/libs do ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -581,7 +581,7 @@ O repositório inclui um [`SKILL.md`](../../SKILL.md) raiz — um documento de t | Comando | Descrição | |:---|:---| | `deeptutor init` | Criar ou atualizar `data/user/settings` para o espaço de trabalho atual | -| `deeptutor start [--home PATH]` | Lançar backend + frontend juntos | +| `deeptutor start [--home PATH] [--dev]` | Lançar backend + frontend juntos | | `deeptutor serve [--port PORT]` | Iniciar apenas o backend FastAPI | | `deeptutor run ` | Executar um turno de capacidade único (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); adicionar `--format json` para saída NDJSON | | `deeptutor chat` | REPL interativo com controlos de capacidade, ferramenta, KB, notebook e histórico | diff --git a/assets/README/README_RU.md b/assets/README/README_RU.md index 4214125aa..ee3730e79 100644 --- a/assets/README/README_RU.md +++ b/assets/README/README_RU.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` Установки из исходного кода запускают Next.js в режиме разработки для локальной директории `web/`; всё остальное (структура конфигурации, порты, остановка с `Ctrl+C`) соответствует Варианту 1. @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # дополнение Manim; требует ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -569,7 +569,7 @@ deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format j | Команда | Описание | |:---|:---| | `deeptutor init` | Создать или обновить `data/user/settings` для текущего рабочего пространства | -| `deeptutor start [--home PATH]` | Запустить бэкенд + фронтенд вместе | +| `deeptutor start [--home PATH] [--dev]` | Запустить бэкенд + фронтенд вместе | | `deeptutor serve [--port PORT]` | Запустить только бэкенд FastAPI | | `deeptutor run ` | Запустить один ход возможности (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); добавьте `--format json` для вывода NDJSON | | `deeptutor chat` | Интерактивный REPL с управлением возможностями, инструментами, KB, блокнотами и историей | diff --git a/assets/README/README_TH.md b/assets/README/README_TH.md index 37f0337a9..4bf893b96 100644 --- a/assets/README/README_TH.md +++ b/assets/README/README_TH.md @@ -109,7 +109,7 @@ python -m pip install -e . ( cd web && npm ci --legacy-peer-deps ) deeptutor init -deeptutor start +deeptutor start --dev ``` การติดตั้งจากซอร์สจะรัน Next.js ในโหมด dev กับไดเร็กทอรี `web/` ในเครื่อง ทุกอย่างอื่น (layout ของ config, พอร์ต, หยุดด้วย `Ctrl+C`) ตรงกับตัวเลือกที่ 1 @@ -147,7 +147,7 @@ pip install -e ".[math-animator]" # Manim addon; ต้องการ LaTeX/f ```bash rm -f web/.next/dev/lock web/.next/lock -deeptutor start +deeptutor start --dev ``` @@ -569,7 +569,7 @@ repo มี root [`SKILL.md`](../../SKILL.md) — เอกสาร handover ~1 | คำสั่ง | คำอธิบาย | |:---|:---| | `deeptutor init` | สร้างหรืออัพเดต `data/user/settings` สำหรับ workspace ปัจจุบัน | -| `deeptutor start [--home PATH]` | เปิดตัว backend + frontend ด้วยกัน | +| `deeptutor start [--home PATH] [--dev]` | เปิดตัว backend + frontend ด้วยกัน | | `deeptutor serve [--port PORT]` | เริ่มเฉพาะ FastAPI backend | | `deeptutor run ` | รัน capability turn เดียว (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); เพิ่ม `--format json` สำหรับ NDJSON output | | `deeptutor chat` | Interactive REPL พร้อม capability, tool, KB, notebook และ history controls | diff --git a/deeptutor/agents/__init__.py b/deeptutor/agents/__init__.py index 0fa654638..03f348bcf 100644 --- a/deeptutor/agents/__init__.py +++ b/deeptutor/agents/__init__.py @@ -20,7 +20,17 @@ Usage: ... """ -from .base_agent import BaseAgent -from .chat import ChatAgent, SessionManager +from importlib import import_module __all__ = ["BaseAgent", "ChatAgent", "SessionManager"] + + +def __getattr__(name: str): + if name == "BaseAgent": + value = import_module(f"{__name__}.base_agent").BaseAgent + elif name in {"ChatAgent", "SessionManager"}: + value = getattr(import_module(f"{__name__}.chat"), name) + else: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + globals()[name] = value + return value diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py index e8756a68a..374f43013 100644 --- a/deeptutor/api/main.py +++ b/deeptutor/api/main.py @@ -216,6 +216,24 @@ async def lifespan(app: FastAPI): except Exception as e: logger.warning(f"Failed to close MCP connections: {e}") + # Close pooled LLM SDK clients so their keep-alive sockets and transports + # are released deterministically instead of waiting for interpreter GC. + try: + from deeptutor.services.llm.provider_factory import close_runtime_provider_pool + + await close_runtime_provider_pool() + logger.info("LLM provider pool closed") + except Exception as e: + logger.warning(f"Failed to close LLM provider pool: {e}") + + try: + from deeptutor.core.agentic.client import close_agentic_client_pool + + await close_agentic_client_pool() + logger.info("Agentic LLM client pool closed") + except Exception as e: + logger.warning(f"Failed to close agentic LLM client pool: {e}") + # Stop EventBus try: from deeptutor.events.event_bus import get_event_bus diff --git a/deeptutor/api/run_server.py b/deeptutor/api/run_server.py index 5f3476150..b316731f3 100644 --- a/deeptutor/api/run_server.py +++ b/deeptutor/api/run_server.py @@ -35,7 +35,7 @@ def main() -> None: # Get port from configuration from deeptutor.logging import configure_logging from deeptutor.runtime.mode import RunMode, set_mode - from deeptutor.services.config import get_ws_max_size + from deeptutor.services.config import HTTP_KEEP_ALIVE_TIMEOUT, get_ws_max_size from deeptutor.services.setup import get_backend_port set_mode(RunMode.SERVER) @@ -58,17 +58,25 @@ def main() -> None: # Filter out non-existent directories to avoid warnings reload_excludes = [d for d in reload_excludes if Path(d).exists()] - # Start uvicorn server with reload enabled. ws_max_size tracks the - # configured chat-attachment total so base64 uploads fit in one WS frame. + # Reload launches a supervisor plus a worker and retains file-watcher state, + # so keep it opt-in for local development. ws_max_size tracks the configured + # chat-attachment total so base64 uploads fit in one WS frame. + dev_reload = os.environ.get("DEEPTUTOR_DEV_RELOAD", "").strip().lower() in { + "1", + "true", + "yes", + "on", + } uvicorn.run( "deeptutor.api.main:app", host="0.0.0.0", port=backend_port, - reload=True, - reload_excludes=reload_excludes, + reload=dev_reload, + reload_excludes=reload_excludes if dev_reload else None, log_level="info", access_log=False, ws_max_size=get_ws_max_size(), + timeout_keep_alive=HTTP_KEEP_ALIVE_TIMEOUT, ) diff --git a/deeptutor/api/utils/task_id_manager.py b/deeptutor/api/utils/task_id_manager.py index a1ffbf70e..4e50910aa 100644 --- a/deeptutor/api/utils/task_id_manager.py +++ b/deeptutor/api/utils/task_id_manager.py @@ -14,6 +14,8 @@ logger = logging.getLogger(__name__) class TaskIDManager: """Singleton class for managing task IDs""" + _MAX_COMPLETED_TASKS = 256 + _instance: Optional["TaskIDManager"] = None _lock = threading.Lock() _task_ids: dict[str, str] = {} # task_key -> task_id @@ -39,6 +41,7 @@ class TaskIDManager: Returns: Task ID (format: {task_type}_{timestamp}_{uuid}) """ + self.cleanup_old_tasks() with self._lock: # If task already exists, return existing ID if task_key in self._task_ids: @@ -101,3 +104,17 @@ class TaskIDManager: task_key = metadata.get("task_key") if task_key: self._task_ids.pop(task_key, None) + + completed = sorted( + ( + (str(metadata.get("finished_at") or ""), task_id) + for task_id, metadata in self._task_metadata.items() + if metadata.get("status") in ["completed", "error", "cancelled"] + ) + ) + overflow = len(completed) - self._MAX_COMPLETED_TASKS + for _, task_id in completed[: max(0, overflow)]: + metadata = self._task_metadata.pop(task_id, {}) + task_key = metadata.get("task_key") + if task_key: + self._task_ids.pop(task_key, None) diff --git a/deeptutor/api/utils/task_log_stream.py b/deeptutor/api/utils/task_log_stream.py index 8517dc00f..42fd14184 100644 --- a/deeptutor/api/utils/task_log_stream.py +++ b/deeptutor/api/utils/task_log_stream.py @@ -22,13 +22,23 @@ def _format_sse(event: str, payload: dict[str, Any]) -> str: class KnowledgeTaskStreamManager: + _MAX_EVENTS_PER_TASK = 500 + _MAX_BYTES_PER_TASK = 2 * 1024 * 1024 + _MAX_RETAINED_TASKS = 32 + _MAX_TERMINAL_TOMBSTONES = 256 + _TERMINAL_TTL_SECONDS = 60 * 60 + _TOMBSTONE_TTL_SECONDS = 24 * 60 * 60 + _instance: "KnowledgeTaskStreamManager | None" = None _instance_lock = threading.Lock() def __init__(self): self._lock = threading.Lock() self._buffers: dict[str, deque[dict[str, Any]]] = {} + self._buffer_bytes: dict[str, int] = {} self._subscribers: dict[str, list[tuple[asyncio.Queue, asyncio.AbstractEventLoop]]] = {} + self._terminal_at: dict[str, float] = {} + self._terminal_tombstones: dict[str, tuple[float, dict[str, Any]]] = {} @classmethod def get_instance(cls) -> "KnowledgeTaskStreamManager": @@ -40,20 +50,35 @@ class KnowledgeTaskStreamManager: def ensure_task(self, task_id: str): with self._lock: - self._buffers.setdefault(task_id, deque(maxlen=500)) + self._prune_locked(time.monotonic()) + if task_id not in self._buffers: + restored = self._terminal_tombstones.pop(task_id, None) + self._buffers[task_id] = deque(maxlen=self._MAX_EVENTS_PER_TASK) + self._buffer_bytes[task_id] = 0 + if restored is not None: + terminal_at, event = restored + self._append_locked(task_id, event) + self._terminal_at[task_id] = terminal_at self._subscribers.setdefault(task_id, []) def emit(self, task_id: str, event: str, payload: dict[str, Any]): event_payload = {"event": event, "payload": payload} with self._lock: - self._buffers.setdefault(task_id, deque(maxlen=500)).append(event_payload) + self._buffers.setdefault(task_id, deque(maxlen=self._MAX_EVENTS_PER_TASK)) + self._buffer_bytes.setdefault(task_id, 0) + self._append_locked(task_id, event_payload) + if event in {"complete", "failed"}: + self._terminal_at[task_id] = time.monotonic() subscribers = list(self._subscribers.get(task_id, [])) + self._prune_locked(time.monotonic()) for queue, loop in subscribers: try: loop.call_soon_threadsafe(self._queue_event, queue, event_payload) except RuntimeError: continue + if event in {"complete", "failed"}: + self._schedule_memory_reclaim() def emit_process_log(self, task_id: str, event: ProcessLogEvent): payload = event.to_dict() @@ -85,7 +110,15 @@ class KnowledgeTaskStreamManager: queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=200) loop = asyncio.get_running_loop() with self._lock: - self._buffers.setdefault(task_id, deque(maxlen=500)) + self._prune_locked(time.monotonic()) + if task_id not in self._buffers: + restored = self._terminal_tombstones.pop(task_id, None) + self._buffers[task_id] = deque(maxlen=self._MAX_EVENTS_PER_TASK) + self._buffer_bytes[task_id] = 0 + if restored is not None: + terminal_at, event = restored + self._append_locked(task_id, event) + self._terminal_at[task_id] = terminal_at self._subscribers.setdefault(task_id, []).append((queue, loop)) backlog = list(self._buffers[task_id]) return queue, backlog, loop @@ -95,11 +128,109 @@ class KnowledgeTaskStreamManager: ): with self._lock: subscribers = self._subscribers.get(task_id, []) - self._subscribers[task_id] = [ + remaining = [ (subscriber_queue, subscriber_loop) for subscriber_queue, subscriber_loop in subscribers if subscriber_queue is not queue or subscriber_loop is not loop ] + if remaining: + self._subscribers[task_id] = remaining + else: + self._subscribers.pop(task_id, None) + self._prune_locked(time.monotonic()) + + @staticmethod + def _event_bytes(event: dict[str, Any]) -> int: + try: + return len(json.dumps(event, ensure_ascii=False, default=str).encode("utf-8")) + except Exception: + return 256 + + def _append_locked(self, task_id: str, event: dict[str, Any]) -> None: + buffer = self._buffers[task_id] + size = self._event_bytes(event) + while buffer and ( + len(buffer) >= self._MAX_EVENTS_PER_TASK + or self._buffer_bytes.get(task_id, 0) + size > self._MAX_BYTES_PER_TASK + ): + removed = buffer.popleft() + self._buffer_bytes[task_id] = max( + 0, self._buffer_bytes.get(task_id, 0) - self._event_bytes(removed) + ) + # Keep a single oversized terminal/error event so a subscriber always + # observes task completion. Its traceback is clipped to the hard byte + # budget rather than retaining an arbitrary multi-megabyte payload. + if size > self._MAX_BYTES_PER_TASK: + compact = { + "event": event.get("event", "process_log"), + "payload": { + "detail": str((event.get("payload") or {}).get("detail") or "")[:8192], + "truncated": True, + }, + } + event = compact + size = self._event_bytes(event) + buffer.append(event) + self._buffer_bytes[task_id] = self._buffer_bytes.get(task_id, 0) + size + + def _drop_task_locked(self, task_id: str) -> None: + buffer = self._buffers.pop(task_id, None) + terminal_at = self._terminal_at.pop(task_id, None) + if buffer and terminal_at is not None: + terminal = next( + (item for item in reversed(buffer) if item.get("event") in {"complete", "failed"}), + None, + ) + if terminal is not None: + self._terminal_tombstones[task_id] = (terminal_at, terminal) + self._buffer_bytes.pop(task_id, None) + if not self._subscribers.get(task_id): + self._subscribers.pop(task_id, None) + + def _prune_locked(self, now: float) -> None: + for task_id, terminal_at in list(self._terminal_at.items()): + if now - terminal_at >= self._TERMINAL_TTL_SECONDS and not self._subscribers.get(task_id): + self._drop_task_locked(task_id) + + overflow = len(self._buffers) - self._MAX_RETAINED_TASKS + if overflow > 0: + candidates = sorted( + ( + (terminal_at, task_id) + for task_id, terminal_at in self._terminal_at.items() + if not self._subscribers.get(task_id) + ) + ) + for _, task_id in candidates[:overflow]: + self._drop_task_locked(task_id) + + expired_tombstones = [ + task_id + for task_id, (terminal_at, _) in self._terminal_tombstones.items() + if now - terminal_at >= self._TOMBSTONE_TTL_SECONDS + ] + for task_id in expired_tombstones: + self._terminal_tombstones.pop(task_id, None) + overflow = len(self._terminal_tombstones) - self._MAX_TERMINAL_TOMBSTONES + if overflow > 0: + oldest = sorted( + self._terminal_tombstones, + key=lambda task_id: self._terminal_tombstones[task_id][0], + ) + for task_id in oldest[:overflow]: + self._terminal_tombstones.pop(task_id, None) + + def retained_task_count(self) -> int: + with self._lock: + self._prune_locked(time.monotonic()) + return len(self._buffers) + + @staticmethod + def _schedule_memory_reclaim() -> None: + """Run after the producing coroutine unwinds and releases job locals.""" + from deeptutor.runtime.memory_reclaim import schedule_memory_reclaim + + schedule_memory_reclaim() async def stream(self, task_id: str) -> AsyncGenerator[str, None]: queue, backlog, loop = self.subscribe(task_id) diff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.py index ebab3c44f..350f124b6 100644 --- a/deeptutor/book/engine.py +++ b/deeptutor/book/engine.py @@ -842,6 +842,13 @@ class BookEngine: async with runtime.lock: if runtime.queue.empty(): runtime.worker = None + runtime.stream = None + async with self._global_lock: + if self._runtimes.get(book_id) is runtime: + self._runtimes.pop(book_id, None) + from deeptutor.runtime.memory_reclaim import schedule_memory_reclaim + + schedule_memory_reclaim() return continue diff --git a/deeptutor/core/agentic/__init__.py b/deeptutor/core/agentic/__init__.py index 6a97478b2..93bbae2f2 100644 --- a/deeptutor/core/agentic/__init__.py +++ b/deeptutor/core/agentic/__init__.py @@ -19,28 +19,7 @@ in each capability's own module — the primitives expose hooks but do not bake those decisions in. """ -from deeptutor.core.agentic.client import ( - LLMClientConfig, - build_completion_kwargs, - build_openai_client, - can_use_native_tool_calling, -) -from deeptutor.core.agentic.labeled_step import LabeledStepResult, run_labeled_step -from deeptutor.core.agentic.labels import ( - LABEL_PROBE_MAX_CHARS, - LABEL_UNKNOWN, - classify_label, - find_inline_labels, - strip_label_probe_prefix, -) -from deeptutor.core.agentic.loop import LabelProtocol, LoopHost, LoopOutcome, run_agentic_loop -from deeptutor.core.agentic.tool_dispatch import ( - MAX_PARALLEL_TOOL_CALLS, - DispatchOutcome, - dispatch_tool_calls, - execute_tool_call, -) -from deeptutor.core.agentic.usage import UsageTracker +from importlib import import_module __all__ = [ "LABEL_PROBE_MAX_CHARS", @@ -64,3 +43,36 @@ __all__ = [ "run_labeled_step", "strip_label_probe_prefix", ] + + +_EXPORT_MODULES = { + "LLMClientConfig": "client", + "build_completion_kwargs": "client", + "build_openai_client": "client", + "can_use_native_tool_calling": "client", + "LabeledStepResult": "labeled_step", + "run_labeled_step": "labeled_step", + "LABEL_PROBE_MAX_CHARS": "labels", + "LABEL_UNKNOWN": "labels", + "classify_label": "labels", + "find_inline_labels": "labels", + "strip_label_probe_prefix": "labels", + "LabelProtocol": "loop", + "LoopHost": "loop", + "LoopOutcome": "loop", + "run_agentic_loop": "loop", + "MAX_PARALLEL_TOOL_CALLS": "tool_dispatch", + "DispatchOutcome": "tool_dispatch", + "dispatch_tool_calls": "tool_dispatch", + "execute_tool_call": "tool_dispatch", + "UsageTracker": "usage", +} + + +def __getattr__(name: str): + module_name = _EXPORT_MODULES.get(name) + if module_name is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + value = getattr(import_module(f"{__name__}.{module_name}"), name) + globals()[name] = value + return value diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.py index 79d6e2de8..4d352843e 100644 --- a/deeptutor/core/agentic/client.py +++ b/deeptutor/core/agentic/client.py @@ -8,9 +8,14 @@ provider gating, Azure detection, SSL bypass, or per-model token caps. from __future__ import annotations import asyncio +from collections import OrderedDict from collections.abc import Callable +import contextlib from dataclasses import dataclass +import hashlib +import inspect import json +import threading from types import SimpleNamespace from typing import Any @@ -38,6 +43,9 @@ _NATIVE_TOOL_BLOCKED_BINDINGS: frozenset[str] = frozenset( # AsyncOpenAI client pointed at a non-OpenAI wire format. github_copilot is # adapter-routed but deliberately excluded from this set. _NATIVE_TOOL_BACKENDS: frozenset[str] = frozenset({"anthropic", "openai_codex"}) +_AGENTIC_CLIENT_POOL_MAXSIZE = 2 +_agentic_client_pool: "OrderedDict[tuple[Any, ...], Any]" = OrderedDict() +_agentic_client_pool_lock = threading.RLock() @dataclass(frozen=True) @@ -53,8 +61,26 @@ class LLMClientConfig: reasoning_effort: str | None = None -def build_openai_client(config: LLMClientConfig) -> Any: - """Construct an ``AsyncOpenAI`` / ``AsyncAzureOpenAI`` client.""" +def _client_cache_key( + config: LLMClientConfig, + loop: asyncio.AbstractEventLoop, + disable_ssl_verify: bool, +) -> tuple[Any, ...]: + secret = hashlib.sha256((config.api_key or "").encode("utf-8")).hexdigest()[:16] + headers = json.dumps(config.extra_headers or {}, sort_keys=True, separators=(",", ":")) + return ( + loop, + config.binding, + config.model or "", + secret, + config.base_url or "", + config.api_version or "", + headers, + disable_ssl_verify, + ) + + +def _build_openai_client(config: LLMClientConfig, *, disable_ssl_verify: bool) -> Any: default_headers = config.extra_headers or None spec = find_by_name(config.binding) if spec: @@ -63,7 +89,7 @@ def build_openai_client(config: LLMClientConfig) -> Any: return native_adapter http_client = None - if load_system_settings()["disable_ssl_verify"]: + if disable_ssl_verify: http_client = httpx.AsyncClient(verify=False) # nosec B501 if config.binding == "azure_openai" or (config.binding == "openai" and config.api_version): return AsyncAzureOpenAI( @@ -81,6 +107,81 @@ def build_openai_client(config: LLMClientConfig) -> Any: ) +async def _close_client(client: Any) -> None: + close = getattr(client, "aclose", None) or getattr(client, "close", None) + if not callable(close): + return + result = close() + if inspect.isawaitable(result): + await result + + +def _schedule_client_close(client: Any, loop: asyncio.AbstractEventLoop) -> None: + async def _close() -> None: + with contextlib.suppress(Exception): + await _close_client(client) + + loop.create_task(_close()) + + +def build_openai_client(config: LLMClientConfig) -> Any: + """Return a bounded, event-loop-local OpenAI-compatible client. + + The chat, research and question pipelines build this handle per turn. The + handle itself owns an HTTP connection pool, so reusing it is both faster + and prevents a new allocator/socket high-water mark on every turn. + """ + disable_ssl_verify = bool(load_system_settings()["disable_ssl_verify"]) + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return _build_openai_client(config, disable_ssl_verify=disable_ssl_verify) + + key = _client_cache_key(config, loop, disable_ssl_verify) + with _agentic_client_pool_lock: + cached = _agentic_client_pool.get(key) + if cached is not None: + _agentic_client_pool.move_to_end(key) + return cached + client = _build_openai_client(config, disable_ssl_verify=disable_ssl_verify) + _agentic_client_pool[key] = client + _agentic_client_pool.move_to_end(key) + while len(_agentic_client_pool) > _AGENTIC_CLIENT_POOL_MAXSIZE: + _, evicted = _agentic_client_pool.popitem(last=False) + _schedule_client_close(evicted, loop) + return client + + +async def close_agentic_client_pool() -> None: + with _agentic_client_pool_lock: + clients = list(_agentic_client_pool.values()) + _agentic_client_pool.clear() + if clients: + await asyncio.gather(*(_close_client(client) for client in clients), return_exceptions=True) + + +def reset_agentic_client_pool() -> None: + with _agentic_client_pool_lock: + clients = list(_agentic_client_pool.values()) + _agentic_client_pool.clear() + if not clients: + return + try: + loop = asyncio.get_running_loop() + except RuntimeError: + for client in clients: + with contextlib.suppress(Exception): + asyncio.run(_close_client(client)) + return + for client in clients: + _schedule_client_close(client, loop) + + +def agentic_client_pool_size() -> int: + with _agentic_client_pool_lock: + return len(_agentic_client_pool) + + def _build_anthropic_adapter(config: LLMClientConfig, spec: Any) -> Any: from deeptutor.services.llm.provider_core import AnthropicProvider @@ -132,6 +233,11 @@ class _ProviderOpenAIAdapter: self._provider = provider self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create_completion)) + async def close(self) -> None: + close = getattr(self._provider, "aclose", None) + if callable(close): + await close() + async def _create_completion(self, **kwargs: Any) -> Any: stream = bool(kwargs.pop("stream", False)) messages = kwargs.pop("messages", []) diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.py index f34da93a5..b062e1fed 100644 --- a/deeptutor/runtime/launcher.py +++ b/deeptutor/runtime/launcher.py @@ -4,6 +4,7 @@ from __future__ import annotations import atexit from dataclasses import dataclass +import hashlib import json import os from pathlib import Path @@ -27,6 +28,22 @@ FRONTEND_READY_TIMEOUT = 120 FRONTEND_REUSE_PROBE_TIMEOUT = 2 KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM) WEB_CACHE_DIR = Path("data") / "user" / "runtime" / "web" +SOURCE_PRODUCTION_DIST_DIR = ".next-deeptutor" +SOURCE_BUILD_MARKER = ".deeptutor-build.json" +SOURCE_BUILD_EXCLUDED_DIRS = { + "node_modules", + "dist", + "playwright-report", + "test-results", + "coverage", +} + + +def _apply_single_user_allocator_env(env: dict[str, str]) -> None: + """Reduce glibc arena fragmentation without overriding operator tuning.""" + + env.setdefault("MALLOC_ARENA_MAX", "2") + env.setdefault("MALLOC_TRIM_THRESHOLD_", "131072") # Mutable holder so module-level helpers can format messages in the active # UI language without threading the labels through every function. @@ -573,12 +590,141 @@ def _ensure_web_dependencies(source: Path, npm: str) -> None: ) +def _source_production_env(*, api_base: str, auth_enabled: bool) -> dict[str, str]: + """Environment shared by the source production build and server.""" + + env = os.environ.copy() + env["DEEPTUTOR_NEXT_DIST_DIR"] = SOURCE_PRODUCTION_DIST_DIR + env["NEXT_PUBLIC_API_BASE"] = api_base + env["NEXT_PUBLIC_AUTH_ENABLED"] = "true" if auth_enabled else "false" + return env + + +def _source_build_fingerprint(source: Path, env: dict[str, str]) -> str: + """Hash source inputs and build-time public settings for build reuse.""" + + digest = hashlib.sha256() + for key in ( + "DEEPTUTOR_NEXT_DIST_DIR", + "NEXT_PUBLIC_API_BASE", + "NEXT_PUBLIC_AUTH_ENABLED", + ): + digest.update(key.encode("utf-8")) + digest.update(b"\0") + digest.update(env.get(key, "").encode("utf-8")) + digest.update(b"\0") + + version_file = PACKAGE_ROOT / "deeptutor" / "__version__.py" + candidates: list[Path] = [] + for dirpath, dirnames, filenames in os.walk(source): + dirnames[:] = sorted( + name + for name in dirnames + if name not in SOURCE_BUILD_EXCLUDED_DIRS and not name.startswith(".next") + ) + root = Path(dirpath) + candidates.extend(root / name for name in sorted(filenames)) + if version_file.is_file(): + candidates.append(version_file) + + for path in candidates: + relative = ( + path.relative_to(source).as_posix() + if path.is_relative_to(source) + else f"../deeptutor/{path.name}" + ) + digest.update(relative.encode("utf-8")) + digest.update(b"\0") + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + digest.update(b"\0") + return digest.hexdigest() + + +def _ensure_source_production_build( + source: Path, + npm: str, + *, + api_base: str, + auth_enabled: bool, +) -> None: + """Build source installs once, then reuse them until an input changes. + + Long-running ``deeptutor start`` processes must not use ``next dev``: its + compiler and HMR caches are development machinery, and a v1.5.7 deployment + grew past 14 GB before V8 aborted. A dedicated dist directory lets an + explicit ``--dev`` server keep using ``.next`` without either mode erasing + the other's output. + """ + + env = _source_production_env(api_base=api_base, auth_enabled=auth_enabled) + dist = source / SOURCE_PRODUCTION_DIST_DIR + marker = dist / SOURCE_BUILD_MARKER + payload = {"fingerprint": _source_build_fingerprint(source, env)} + if (dist / "BUILD_ID").is_file() and (dist / "standalone" / "server.js").is_file(): + try: + if json.loads(marker.read_text(encoding="utf-8")) == payload: + _prepare_source_standalone(source) + return + except Exception: + pass + + _log(f"Building the source frontend for production in {source} ...") + # Next rewrites these source-controlled files to point at whichever dist + # directory was built most recently. Preserve the developer's versions so + # a production launch neither dirties the checkout nor breaks the next + # explicit ``--dev`` typecheck. + generated_config = [source / "next-env.d.ts", source / "tsconfig.json"] + snapshots = {path: path.read_bytes() if path.is_file() else None for path in generated_config} + try: + result = subprocess.run([npm, "run", "build"], cwd=source, env=env) + finally: + for path, original in snapshots.items(): + if original is None: + path.unlink(missing_ok=True) + elif not path.is_file() or path.read_bytes() != original: + path.write_bytes(original) + if result.returncode != 0: + raise SystemExit( + f"`npm run build` failed (exit {result.returncode}). " + "Fix the error above, then retry `deeptutor start`." + ) + if not (dist / "BUILD_ID").is_file(): + raise SystemExit(f"`npm run build` completed without creating {dist / 'BUILD_ID'}.") + _prepare_source_standalone(source) + marker.write_text(json.dumps(payload, indent=2), encoding="utf-8") + + +def _prepare_source_standalone(source: Path) -> Path: + """Add static/public assets omitted from Next's standalone directory.""" + + dist = source / SOURCE_PRODUCTION_DIST_DIR + standalone = dist / "standalone" + if not (standalone / "server.js").is_file(): + raise SystemExit( + f"`npm run build` did not create the standalone server at {standalone / 'server.js'}." + ) + static = dist / "static" + if static.is_dir(): + shutil.copytree( + static, + standalone / SOURCE_PRODUCTION_DIST_DIR / "static", + dirs_exist_ok=True, + ) + public = source / "public" + if public.is_dir(): + shutil.copytree(public, standalone / "public", dirs_exist_ok=True) + return standalone + + def _resolve_frontend( home: Path, frontend_port: int, *, api_base: str, auth_enabled: bool, + dev: bool = False, ) -> FrontendRuntime: packaged = _packaged_web_dir() node = shutil.which("node") @@ -601,6 +747,21 @@ def _resolve_frontend( "npm not found. Source installs require Node.js/npm and `cd web && npm install`." ) _ensure_web_dependencies(source, npm) + if not dev: + if not node: + raise SystemExit("Node.js 20+ is required to run the source production build.") + _ensure_source_production_build( + source, + npm, + api_base=api_base, + auth_enabled=auth_enabled, + ) + standalone = source / SOURCE_PRODUCTION_DIST_DIR / "standalone" + return FrontendRuntime( + "source-production", + [node, str(standalone / "server.js")], + standalone, + ) return FrontendRuntime( "source", [npm, "run", "dev", "--", "--port", str(frontend_port)], source ) @@ -764,7 +925,7 @@ def _install_signal_handlers(request_shutdown: Callable[[str | None], None]) -> continue -def start(home: str | Path | None = None) -> None: +def start(home: str | Path | None = None, *, dev: bool = False) -> None: _relax_console_encoding() runtime_home = get_runtime_home(home) runtime_home.mkdir(parents=True, exist_ok=True) @@ -772,6 +933,7 @@ def start(home: str | Path | None = None) -> None: _reset_runtime_singletons() from deeptutor.services.config import ( + HTTP_KEEP_ALIVE_TIMEOUT, ensure_runtime_settings_files, export_runtime_settings_to_env, get_ws_max_size, @@ -803,6 +965,7 @@ def start(home: str | Path | None = None) -> None: frontend_port, api_base=api_base, auth_enabled=auth_enabled, + dev=dev, ) existing_frontend = _detect_existing_source_frontend(frontend) if existing_frontend is not None and not _http_ready( @@ -838,6 +1001,7 @@ def start(home: str | Path | None = None) -> None: frontend_port, api_base=api_base, auth_enabled=auth_enabled, + dev=dev, ) frontend_url = ( @@ -873,6 +1037,9 @@ def start(home: str | Path | None = None) -> None: common_env["DEEPTUTOR_AUTH_ENABLED"] = "true" if auth_enabled else "false" common_env["PYTHONUNBUFFERED"] = "1" common_env["PYTHONIOENCODING"] = "utf-8:replace" + _apply_single_user_allocator_env(common_env) + if frontend.kind == "source-production": + common_env["DEEPTUTOR_NEXT_DIST_DIR"] = SOURCE_PRODUCTION_DIST_DIR backend_cmd = [ sys.executable, @@ -896,6 +1063,13 @@ def start(home: str | Path | None = None) -> None: # the attachment limits therefore takes a restart to fully apply. "--ws-max-size", str(get_ws_max_size()), + # Outlast the frontend proxy's idle socket pool. web/proxy.ts forwards + # over Node's http.globalAgent, which reaps idle sockets on its own 5s + # timer — the same value as uvicorn's default, so both ends raced to + # close the same socket and a FIN landing on a reuse surfaced as + # ECONNRESET ("Failed to proxy ... socket hang up" -> 500). + "--timeout-keep-alive", + str(HTTP_KEEP_ALIVE_TIMEOUT), ] processes: list[ManagedProcess] = [] diff --git a/deeptutor/runtime/memory_reclaim.py b/deeptutor/runtime/memory_reclaim.py new file mode 100644 index 000000000..e1f72f771 --- /dev/null +++ b/deeptutor/runtime/memory_reclaim.py @@ -0,0 +1,73 @@ +"""Best-effort memory reclamation after infrequent, allocation-heavy jobs.""" + +from __future__ import annotations + +import asyncio +import gc +import logging +import sys +import threading +from typing import Any + +logger = logging.getLogger(__name__) +_reclaim_tasks: dict[asyncio.AbstractEventLoop, asyncio.Task[tuple[int, bool]]] = {} +_reclaim_tasks_lock = threading.Lock() + + +def release_unused_memory() -> tuple[int, bool]: + """Collect cycles and ask glibc to return free heap pages on Linux. + + Python normally keeps freed arenas for reuse, which is fast but makes RSS + look permanently pinned after document parsing or index construction. + ``malloc_trim`` is glibc-specific, so every other platform simply gets the + portable cycle collection step. + """ + collected = gc.collect() + trimmed = False + if not sys.platform.startswith("linux"): + return collected, trimmed + + try: + import ctypes + + libc = ctypes.CDLL(None) + malloc_trim = getattr(libc, "malloc_trim", None) + if malloc_trim is not None: + malloc_trim.argtypes = [ctypes.c_size_t] + malloc_trim.restype = ctypes.c_int + trimmed = bool(malloc_trim(0)) + except Exception: + logger.debug("malloc_trim unavailable", exc_info=True) + return collected, trimmed + + +def schedule_memory_reclaim() -> asyncio.Task[tuple[int, bool]] | None: + """Coalesce reclamation after the current coroutine releases its locals.""" + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return None + + with _reclaim_tasks_lock: + pending = _reclaim_tasks.get(loop) + if pending is not None and not pending.done(): + return pending + + async def _reclaim() -> tuple[int, bool]: + await asyncio.sleep(0) + return await asyncio.to_thread(release_unused_memory) + + task = loop.create_task(_reclaim()) + with _reclaim_tasks_lock: + _reclaim_tasks[loop] = task + + def _forget(completed: asyncio.Task[Any]) -> None: + with _reclaim_tasks_lock: + if _reclaim_tasks.get(loop) is completed: + _reclaim_tasks.pop(loop, None) + + task.add_done_callback(_forget) + return task + + +__all__ = ["release_unused_memory", "schedule_memory_reclaim"] diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.py index c0bf832de..b2167c6c3 100644 --- a/deeptutor/services/config/__init__.py +++ b/deeptutor/services/config/__init__.py @@ -20,6 +20,7 @@ from .loader import ( ) from .model_catalog import ModelCatalogService, get_model_catalog_service from .runtime_settings import ( + HTTP_KEEP_ALIVE_TIMEOUT, ChatAttachmentLimits, RuntimeSettingsService, ensure_runtime_settings_files, @@ -71,6 +72,7 @@ __all__ = [ "ConfigTestRunner", "TestRun", "get_config_test_runner", + "HTTP_KEEP_ALIVE_TIMEOUT", "ChatAttachmentLimits", "RuntimeSettingsService", "ensure_runtime_settings_files", diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py index 88e5723cd..7d28470e0 100644 --- a/deeptutor/services/config/runtime_settings.py +++ b/deeptutor/services/config/runtime_settings.py @@ -1010,6 +1010,21 @@ def get_ws_max_size() -> int: return compute_ws_max_size(get_chat_attachment_limits().max_total_bytes) +# Idle keep-alive window for backend HTTP connections — wire into every uvicorn +# launch. The browser never reaches the backend directly: `web/proxy.ts` rewrites +# `/api/*` and Next.js forwards over Node's `http.globalAgent`, which pools idle +# sockets and reaps them on its own 5s `timeout`. uvicorn's `timeout_keep_alive` +# also defaults to 5s, so both ends armed an identical idle timer on the same +# socket and raced to close it: when the server's FIN landed on a socket the pool +# was simultaneously handing to a new request, the request died with `ECONNRESET` +# and the proxy turned it into a 500 ("Failed to proxy ... socket hang up" -> +# "Failed to load sessions" in the UI). Any value comfortably above the proxy's +# 5s reaper leaves the client as the only side that closes an idle connection, +# which is the safe direction — a pool retiring its own socket removes it before +# any request can be assigned to it, so the collision cannot happen at all. +HTTP_KEEP_ALIVE_TIMEOUT = 300 + + def load_auth_settings() -> dict[str, Any]: return get_runtime_settings_service().load_auth() diff --git a/deeptutor/services/llm/client.py b/deeptutor/services/llm/client.py index a22920a1f..6192a1d29 100644 --- a/deeptutor/services/llm/client.py +++ b/deeptutor/services/llm/client.py @@ -237,3 +237,16 @@ def reset_llm_client() -> None: """Reset the singleton LLM client.""" global _client _client = None + # The services-layer factory owns the actual SDK connection pools. Keep a + # settings reload authoritative by retiring clients built from the old + # credentials/base URL as well as this legacy facade. + from .provider_factory import reset_runtime_provider_pool + + reset_runtime_provider_pool() + try: + from deeptutor.core.agentic.client import reset_agentic_client_pool + + reset_agentic_client_pool() + except ImportError: + # CLI-only/lightweight imports may never have loaded the agentic stack. + pass diff --git a/deeptutor/services/llm/error_mapping.py b/deeptutor/services/llm/error_mapping.py index 9936baada..0e8d2b5cc 100644 --- a/deeptutor/services/llm/error_mapping.py +++ b/deeptutor/services/llm/error_mapping.py @@ -17,15 +17,6 @@ from .exceptions import ( ProviderContextWindowError, ) -try: - import openai - - _HAS_OPENAI = True -except ImportError: # pragma: no cover - openai = None # type: ignore - _HAS_OPENAI = False - - logger = logging.getLogger(__name__) @@ -50,7 +41,25 @@ def _message_contains(*needles: str) -> ErrorClassifier: return _classifier +def _class_named(*names: str) -> ErrorClassifier: + """Match optional SDK exceptions without importing the SDK at startup.""" + expected = set(names) + + def _classifier(exc: Exception) -> bool: + return any(cls.__name__ in expected for cls in type(exc).__mro__) + + return _classifier + + _GLOBAL_RULES: list[MappingRule] = [ + MappingRule( + classifier=_class_named("AuthenticationError", "AuthenticationStatusError"), + factory=lambda exc, provider: LLMAuthenticationError(str(exc), provider=provider), + ), + MappingRule( + classifier=_class_named("RateLimitError"), + factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider), + ), MappingRule( classifier=_message_contains("rate limit", "429", "quota"), factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider), @@ -61,31 +70,6 @@ _GLOBAL_RULES: list[MappingRule] = [ ), ] -if _HAS_OPENAI and openai is not None: - _GLOBAL_RULES[:0] = [ - MappingRule( - classifier=_instance_of(openai.AuthenticationError), - factory=lambda exc, provider: LLMAuthenticationError(str(exc), provider=provider), - ), - MappingRule( - classifier=_instance_of(openai.RateLimitError), - factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider), - ), - ] - -# Attempt to load Anthropic and Google rules if SDKs are present -try: - import anthropic - - _GLOBAL_RULES.append( - MappingRule( - classifier=_instance_of(anthropic.RateLimitError), - factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider), - ) - ) -except ImportError: - pass - def map_error(exc: Exception, provider: str | None = None) -> LLMError: """Map provider-specific errors to unified internal exceptions.""" diff --git a/deeptutor/services/llm/provider_core/__init__.py b/deeptutor/services/llm/provider_core/__init__.py index 344e99f74..767c376c1 100644 --- a/deeptutor/services/llm/provider_core/__init__.py +++ b/deeptutor/services/llm/provider_core/__init__.py @@ -1,11 +1,18 @@ -"""Services-layer provider runtime used by both llm.factory and TutorBot.""" +"""Services-layer provider runtime with lazy SDK-backed implementations.""" + +from __future__ import annotations + +from importlib import import_module +from typing import TYPE_CHECKING -from .anthropic_provider import AnthropicProvider -from .azure_openai_provider import AzureOpenAIProvider from .base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest -from .github_copilot_provider import GitHubCopilotProvider -from .openai_codex_provider import OpenAICodexProvider -from .openai_compat_provider import OpenAICompatProvider + +if TYPE_CHECKING: + from .anthropic_provider import AnthropicProvider + from .azure_openai_provider import AzureOpenAIProvider + from .github_copilot_provider import GitHubCopilotProvider + from .openai_codex_provider import OpenAICodexProvider + from .openai_compat_provider import OpenAICompatProvider __all__ = [ "AnthropicProvider", @@ -18,3 +25,22 @@ __all__ = [ "OpenAICompatProvider", "ToolCallRequest", ] + + +_LAZY_TYPES = { + "AnthropicProvider": ("anthropic_provider", "AnthropicProvider"), + "AzureOpenAIProvider": ("azure_openai_provider", "AzureOpenAIProvider"), + "GitHubCopilotProvider": ("github_copilot_provider", "GitHubCopilotProvider"), + "OpenAICodexProvider": ("openai_codex_provider", "OpenAICodexProvider"), + "OpenAICompatProvider": ("openai_compat_provider", "OpenAICompatProvider"), +} + + +def __getattr__(name: str): + target = _LAZY_TYPES.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + module_name, class_name = target + value = getattr(import_module(f"{__name__}.{module_name}"), class_name) + globals()[name] = value + return value diff --git a/deeptutor/services/llm/provider_core/base.py b/deeptutor/services/llm/provider_core/base.py index d7b7363db..656bf6278 100644 --- a/deeptutor/services/llm/provider_core/base.py +++ b/deeptutor/services/llm/provider_core/base.py @@ -6,6 +6,7 @@ from abc import ABC, abstractmethod import asyncio from collections.abc import Awaitable, Callable, Sequence from dataclasses import dataclass, field +import inspect import json from typing import Any @@ -118,6 +119,23 @@ class LLMProvider(ABC): self.api_base = api_base self.generation: GenerationSettings = GenerationSettings() + async def aclose(self) -> None: + """Release an SDK/HTTP client owned by this provider. + + Provider implementations intentionally expose a common lifecycle even + though the underlying SDKs use either ``close`` or ``aclose``. Most + providers own no client and therefore make this a cheap no-op. + """ + client = getattr(self, "_client", None) + if client is None: + return + close = getattr(client, "aclose", None) or getattr(client, "close", None) + if not callable(close): + return + result = close() + if inspect.isawaitable(result): + await result + @staticmethod def _sanitize_empty_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: """Replace empty text content that causes provider 400 errors.""" diff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.py index 54de97dff..485693c9d 100644 --- a/deeptutor/services/llm/provider_factory.py +++ b/deeptutor/services/llm/provider_factory.py @@ -2,31 +2,67 @@ from __future__ import annotations +import asyncio +from collections import OrderedDict +import contextlib +import hashlib +import json +import threading +from typing import Any + from deeptutor.services.llm.config import LLMConfig, get_llm_config -from deeptutor.services.llm.provider_core import ( - AnthropicProvider, - AzureOpenAIProvider, - GenerationSettings, - GitHubCopilotProvider, - LLMProvider, - OpenAICodexProvider, - OpenAICompatProvider, -) +from deeptutor.services.llm.provider_core.base import GenerationSettings, LLMProvider from deeptutor.services.provider_registry import find_by_name +_PROVIDER_POOL_MAXSIZE = 2 +_provider_pool: "OrderedDict[tuple[Any, ...], LLMProvider]" = OrderedDict() +_provider_pool_lock = threading.RLock() -def get_runtime_provider(config: LLMConfig | None = None) -> LLMProvider: - """Build the authoritative services-layer provider for the supplied config.""" - llm_config = config or get_llm_config() + +def _secret_fingerprint(value: str | None) -> str: + if not value: + return "" + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:16] + + +def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> tuple[Any, ...]: + headers = json.dumps(config.extra_headers or {}, sort_keys=True, separators=(",", ":")) + return ( + loop, + config.provider_name or config.binding, + config.provider_mode, + config.model, + _secret_fingerprint(config.api_key), + config.effective_url or config.base_url or "", + config.api_version or "", + headers, + config.temperature, + config.max_tokens, + config.reasoning_effort, + ) + + +def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider: + """Construct one provider, importing only the selected backend SDK.""" provider_name = llm_config.provider_name or llm_config.binding spec = find_by_name(provider_name) backend = spec.backend if spec else "openai_compat" if backend == "openai_codex": + from deeptutor.services.llm.provider_core.openai_codex_provider import ( + OpenAICodexProvider, + ) + provider: LLMProvider = OpenAICodexProvider(default_model=llm_config.model) elif backend == "github_copilot": + from deeptutor.services.llm.provider_core.github_copilot_provider import ( + GitHubCopilotProvider, + ) + provider = GitHubCopilotProvider(default_model=llm_config.model) elif backend == "azure_openai": + from deeptutor.services.llm.provider_core.azure_openai_provider import AzureOpenAIProvider + provider = AzureOpenAIProvider( api_key=llm_config.api_key or "", api_base=llm_config.effective_url or llm_config.base_url or "", @@ -34,6 +70,8 @@ def get_runtime_provider(config: LLMConfig | None = None) -> LLMProvider: extra_headers=llm_config.extra_headers or None, ) elif backend == "anthropic": + from deeptutor.services.llm.provider_core.anthropic_provider import AnthropicProvider + provider = AnthropicProvider( api_key=llm_config.api_key or None, api_base=llm_config.effective_url or llm_config.base_url or None, @@ -42,6 +80,8 @@ def get_runtime_provider(config: LLMConfig | None = None) -> LLMProvider: supports_prompt_caching=bool(spec and spec.supports_prompt_caching), ) else: + from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider + provider = OpenAICompatProvider( api_key=llm_config.api_key or None, api_base=llm_config.effective_url or llm_config.base_url or None, @@ -57,3 +97,81 @@ def get_runtime_provider(config: LLMConfig | None = None) -> LLMProvider: reasoning_effort=llm_config.reasoning_effort, ) return provider + + +def _schedule_close(provider: LLMProvider, loop: asyncio.AbstractEventLoop) -> None: + async def _close() -> None: + with contextlib.suppress(Exception): + await provider.aclose() + + loop.create_task(_close()) + + +def get_runtime_provider(config: LLMConfig | None = None) -> LLMProvider: + """Return a small event-loop-local pool entry for the supplied config. + + A provider owns an SDK HTTP connection pool. Recreating it for every token + request steadily raises the process high-water mark and forfeits keep-alive. + Calls made outside an event loop remain uncached for cross-loop safety. + """ + llm_config = config or get_llm_config() + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return _build_runtime_provider(llm_config) + + key = _provider_cache_key(llm_config, loop) + with _provider_pool_lock: + cached = _provider_pool.get(key) + if cached is not None: + _provider_pool.move_to_end(key) + return cached + + provider = _build_runtime_provider(llm_config) + _provider_pool[key] = provider + _provider_pool.move_to_end(key) + while len(_provider_pool) > _PROVIDER_POOL_MAXSIZE: + _, evicted = _provider_pool.popitem(last=False) + _schedule_close(evicted, loop) + return provider + + +async def close_runtime_provider_pool() -> None: + """Close every pooled SDK client during shutdown or config reload.""" + with _provider_pool_lock: + providers = list(_provider_pool.values()) + _provider_pool.clear() + if providers: + await asyncio.gather(*(provider.aclose() for provider in providers), return_exceptions=True) + + +def reset_runtime_provider_pool() -> None: + """Clear the pool from synchronous cache-invalidation call sites.""" + with _provider_pool_lock: + providers = list(_provider_pool.values()) + _provider_pool.clear() + if not providers: + return + try: + loop = asyncio.get_running_loop() + except RuntimeError: + for provider in providers: + with contextlib.suppress(Exception): + asyncio.run(provider.aclose()) + return + for provider in providers: + _schedule_close(provider, loop) + + +def runtime_provider_pool_size() -> int: + """Expose the bounded size for diagnostics and regression tests.""" + with _provider_pool_lock: + return len(_provider_pool) + + +__all__ = [ + "close_runtime_provider_pool", + "get_runtime_provider", + "reset_runtime_provider_pool", + "runtime_provider_pool_size", +] diff --git a/deeptutor/services/rag/pipelines/llamaindex/storage.py b/deeptutor/services/rag/pipelines/llamaindex/storage.py index 3d48758bc..8be8b8648 100644 --- a/deeptutor/services/rag/pipelines/llamaindex/storage.py +++ b/deeptutor/services/rag/pipelines/llamaindex/storage.py @@ -8,6 +8,7 @@ import json from pathlib import Path import shutil import threading +import time from typing import Any from deeptutor.services.embedding.validation import validate_embedding_batch @@ -200,9 +201,26 @@ def validate_storage_embeddings(storage_dir: Path) -> None: # re-validate the (potentially large) persisted store. Entries are keyed by a # freshness token derived from the store files' mtimes, so a re-index or # incremental insert naturally invalidates the stale entry. -_INDEX_CACHE: "OrderedDict[tuple[str, tuple[int, ...]], Any]" = OrderedDict() +@dataclass +class _CachedIndex: + index: Any + last_used: float + + +_INDEX_CACHE: "OrderedDict[tuple[str, tuple[int, ...]], _CachedIndex]" = OrderedDict() _INDEX_CACHE_LOCK = threading.Lock() -_INDEX_CACHE_MAXSIZE = 8 +_INDEX_CACHE_MAXSIZE = 2 +_INDEX_CACHE_IDLE_SECONDS = 10 * 60 + + +def _prune_index_cache_locked(now: float) -> None: + stale = [ + key + for key, entry in _INDEX_CACHE.items() + if now - entry.last_used >= _INDEX_CACHE_IDLE_SECONDS + ] + for key in stale: + _INDEX_CACHE.pop(key, None) def _freshness_token(storage_dir: Path) -> tuple[int, ...]: @@ -224,11 +242,14 @@ def _load_validated_index(storage_dir: Path) -> Any: def _cached_index(storage_dir: Path) -> Any: key = (str(storage_dir.resolve()), _freshness_token(storage_dir)) + now = time.monotonic() with _INDEX_CACHE_LOCK: - cached = _INDEX_CACHE.get(key) - if cached is not None: + _prune_index_cache_locked(now) + entry = _INDEX_CACHE.get(key) + if entry is not None: + entry.last_used = now _INDEX_CACHE.move_to_end(key) - return cached + return entry.index # Load outside the lock so a slow first load of one KB does not block other # KBs' queries. A concurrent duplicate load is harmless (idempotent). @@ -237,7 +258,7 @@ def _cached_index(storage_dir: Path) -> Any: # Drop any superseded entry for the same storage dir (older token). for stale in [existing for existing in _INDEX_CACHE if existing[0] == key[0]]: _INDEX_CACHE.pop(stale, None) - _INDEX_CACHE[key] = index + _INDEX_CACHE[key] = _CachedIndex(index=index, last_used=time.monotonic()) _INDEX_CACHE.move_to_end(key) while len(_INDEX_CACHE) > _INDEX_CACHE_MAXSIZE: _INDEX_CACHE.popitem(last=False) @@ -250,6 +271,14 @@ def clear_index_cache() -> None: _INDEX_CACHE.clear() +def prune_index_cache() -> int: + """Drop indexes idle past the single-user warm window.""" + with _INDEX_CACHE_LOCK: + before = len(_INDEX_CACHE) + _prune_index_cache_locked(time.monotonic()) + return before - len(_INDEX_CACHE) + + def retrieve_nodes(storage_dir: Path, query: str, *, top_k: int = 5) -> list[Any]: index = _cached_index(Path(storage_dir)) retriever = retrievers.build_retriever(index, Path(storage_dir), top_k=top_k) diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py index 34159f18e..8d069c8ee 100644 --- a/deeptutor/services/session/turn_runtime.py +++ b/deeptutor/services/session/turn_runtime.py @@ -1819,6 +1819,12 @@ class TurnRuntimeManager: with contextlib.suppress(asyncio.QueueFull): subscriber.queue.put_nowait(None) self._executions.pop(turn_id, None) + # A turn may have parsed large attachments or built substantial + # temporary prompts/results. Reclaim after this coroutine returns, + # outside the user-visible streaming path. + from deeptutor.runtime.memory_reclaim import schedule_memory_reclaim + + schedule_memory_reclaim() async def _publish_live_event( self, diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py index 4aa25537c..17e362e9b 100644 --- a/deeptutor/utils/document_extractor.py +++ b/deeptutor/utils/document_extractor.py @@ -31,36 +31,19 @@ from defusedxml.common import DefusedXmlException from deeptutor.services.rag.file_routing import FileTypeRouter -try: - import fitz # pymupdf -except ImportError: # pragma: no cover - fitz = None # type: ignore[assignment] - -try: - from pypdf import PdfReader - from pypdf.errors import FileNotDecryptedError as _PypdfNotDecryptedError -except ImportError: # pragma: no cover - PdfReader = None # type: ignore[assignment] - _PypdfNotDecryptedError = Exception # type: ignore[assignment,misc] - -try: - from docx import Document as DocxDocument -except ImportError: # pragma: no cover - DocxDocument = None # type: ignore[assignment] - -try: - from openpyxl import load_workbook -except ImportError: # pragma: no cover - load_workbook = None # type: ignore[assignment] - -try: - from pptx import Presentation as PptxPresentation -except ImportError: # pragma: no cover - PptxPresentation = None # type: ignore[assignment] - - logger = logging.getLogger(__name__) +# Optional parser libraries are resolved on first use. The public-ish module +# names remain overrideable because downstream deployments and tests use +# ``None`` to force the pure-OOXML fallback. +_NOT_LOADED = object() +fitz: Any = _NOT_LOADED +PdfReader: Any = _NOT_LOADED +_PypdfNotDecryptedError: Any = _NOT_LOADED +DocxDocument: Any = _NOT_LOADED +load_workbook: Any = _NOT_LOADED +PptxPresentation: Any = _NOT_LOADED + _OFFICE_EXTENSIONS: frozenset[str] = frozenset(FileTypeRouter.PARSER_EXTENSIONS) # Text-like formats are sourced from the KB file router so chat and KB stay @@ -231,6 +214,15 @@ def extract_text_from_path( def _extract_pdf(data: bytes, filename: str) -> str: + global fitz, PdfReader, _PypdfNotDecryptedError + if fitz is _NOT_LOADED: + try: + import fitz as fitz_module # pymupdf + + fitz = fitz_module + except ImportError: # pragma: no cover + fitz = None + if fitz is not None: try: with fitz.open(stream=data, filetype="pdf") as doc: @@ -247,6 +239,17 @@ def _extract_pdf(data: bytes, filename: str) -> str: except Exception as exc: logger.warning("pymupdf failed on %s: %s — falling back to pypdf", filename, exc) + if PdfReader is _NOT_LOADED: + try: + from pypdf import PdfReader as reader_type + from pypdf.errors import FileNotDecryptedError + + PdfReader = reader_type + _PypdfNotDecryptedError = FileNotDecryptedError + except ImportError: # pragma: no cover + PdfReader = None + _PypdfNotDecryptedError = Exception + if PdfReader is None: raise CorruptDocumentError( f"{filename}: no PDF reader available (install pymupdf or pypdf)", @@ -276,6 +279,15 @@ def _extract_pdf(data: bytes, filename: str) -> str: def _extract_docx(data: bytes, filename: str) -> str: + global DocxDocument + if DocxDocument is _NOT_LOADED: + try: + from docx import Document as document_type + + DocxDocument = document_type + except ImportError: # pragma: no cover + DocxDocument = None + primary_error: Exception | None = None primary_text = "" if DocxDocument is not None: @@ -306,6 +318,15 @@ def _extract_docx(data: bytes, filename: str) -> str: def _extract_xlsx(data: bytes, filename: str) -> str: + global load_workbook + if load_workbook is _NOT_LOADED: + try: + from openpyxl import load_workbook as workbook_loader + + load_workbook = workbook_loader + except ImportError: # pragma: no cover + load_workbook = None + if load_workbook is None: return _extract_xlsx_ooxml(data, filename) try: @@ -335,6 +356,15 @@ def _extract_xlsx(data: bytes, filename: str) -> str: def _extract_pptx(data: bytes, filename: str) -> str: + global PptxPresentation + if PptxPresentation is _NOT_LOADED: + try: + from pptx import Presentation as presentation_type + + PptxPresentation = presentation_type + except ImportError: # pragma: no cover + PptxPresentation = None + if PptxPresentation is None: return _extract_pptx_ooxml(data, filename) try: diff --git a/deeptutor_cli/main.py b/deeptutor_cli/main.py index 2c881ef85..d722f1422 100644 --- a/deeptutor_cli/main.py +++ b/deeptutor_cli/main.py @@ -117,11 +117,16 @@ def run_capability( @app.command() def start( home: Path | None = typer.Option(None, "--home", help="Runtime workspace root."), + dev: bool = typer.Option( + False, + "--dev", + help="Use the Next.js development server for frontend work.", + ), ) -> None: - """Launch backend + frontend together. Press Ctrl+C to stop.""" + """Launch backend + frontend together. Source installs default to production.""" from deeptutor.runtime.launcher import start as start_web - start_web(home=home) + start_web(home=home, dev=dev) @app.command() @@ -155,7 +160,7 @@ def serve( ) raise typer.Exit(code=1) - from deeptutor.services.config import get_ws_max_size + from deeptutor.services.config import HTTP_KEEP_ALIVE_TIMEOUT, get_ws_max_size # ws_max_size tracks the configured chat-attachment total so base64 # uploads fit in one WS frame (uvicorn defaults to 16MB). @@ -166,6 +171,7 @@ def serve( reload=reload, reload_excludes=["web/*", "data/*"] if reload else None, ws_max_size=get_ws_max_size(), + timeout_keep_alive=HTTP_KEEP_ALIVE_TIMEOUT, ) diff --git a/scripts/start_web.py b/scripts/start_web.py index bfb811bf5..ea44451bd 100644 --- a/scripts/start_web.py +++ b/scripts/start_web.py @@ -22,11 +22,17 @@ def build_parser() -> argparse.ArgumentParser: default=None, help="Runtime workspace root. Defaults to the current directory.", ) + parser.add_argument( + "--dev", + action="store_true", + help="Use the Next.js development server for frontend work.", + ) return parser def main(argv: list[str] | None = None) -> None: - start(home=build_parser().parse_args(argv).home) + args = build_parser().parse_args(argv) + start(home=args.home, dev=args.dev) if __name__ == "__main__": diff --git a/tests/api/test_task_id_manager.py b/tests/api/test_task_id_manager.py new file mode 100644 index 000000000..53c9e6a90 --- /dev/null +++ b/tests/api/test_task_id_manager.py @@ -0,0 +1,38 @@ +from datetime import datetime, timedelta + +from deeptutor.api.utils.task_id_manager import TaskIDManager + + +def _manager() -> TaskIDManager: + manager = TaskIDManager() + manager._task_ids = {} + manager._task_metadata = {} + return manager + + +def test_generate_prunes_expired_completed_tasks() -> None: + manager = _manager() + old_id = manager.generate_task_id("kb", "old") + manager.update_task_status(old_id, "completed") + manager._task_metadata[old_id]["finished_at"] = ( + datetime.now() - timedelta(hours=25) + ).isoformat() + + manager.generate_task_id("kb", "new") + + assert old_id not in manager._task_metadata + assert "old" not in manager._task_ids + + +def test_completed_task_metadata_has_hard_count_bound() -> None: + manager = _manager() + manager._MAX_COMPLETED_TASKS = 3 + + for index in range(8): + task_id = manager.generate_task_id("kb", f"task-{index}") + manager.update_task_status(task_id, "completed") + + manager.cleanup_old_tasks() + + assert len(manager._task_metadata) == 3 + assert len(manager._task_ids) == 3 diff --git a/tests/book/test_runtime_reclaim.py b/tests/book/test_runtime_reclaim.py new file mode 100644 index 000000000..a6b9428e1 --- /dev/null +++ b/tests/book/test_runtime_reclaim.py @@ -0,0 +1,25 @@ +import asyncio + +import pytest + +from deeptutor.book import engine as engine_module +from deeptutor.book.engine import BookEngine, _BookRuntime + + +@pytest.mark.asyncio +async def test_idle_background_runtime_is_released(monkeypatch) -> None: + engine = BookEngine.__new__(BookEngine) + engine._global_lock = asyncio.Lock() + runtime = _BookRuntime() + engine._runtimes = {"book-1": runtime} + + async def _timeout(*args, **kwargs): + raise asyncio.TimeoutError + + monkeypatch.setattr(engine_module.asyncio, "wait_for", _timeout) + + await engine._worker_loop("book-1") + + assert "book-1" not in engine._runtimes + assert runtime.worker is None + assert runtime.stream is None diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.py index e9ec68864..f341eecba 100644 --- a/tests/cli/test_chat_cli.py +++ b/tests/cli/test_chat_cli.py @@ -226,12 +226,17 @@ def test_session_list_command_uses_shared_store(monkeypatch) -> None: def test_start_command_delegates_to_runtime_launcher(monkeypatch) -> None: calls: list[object] = [] - def _fake_start(home=None): # noqa: ANN001 - calls.append(home) + def _fake_start(home=None, *, dev=False): # noqa: ANN001 + calls.append((home, dev)) monkeypatch.setattr("deeptutor.runtime.launcher.start", _fake_start) result = runner.invoke(app, ["start"]) assert result.exit_code == 0, result.output - assert calls == [None] + assert calls == [(None, False)] + + result = runner.invoke(app, ["start", "--dev"]) + + assert result.exit_code == 0, result.output + assert calls[-1] == (None, True) diff --git a/tests/core/test_agentic_client_provider_kwargs.py b/tests/core/test_agentic_client_provider_kwargs.py index 9ab1feecc..b0b11fdc1 100644 --- a/tests/core/test_agentic_client_provider_kwargs.py +++ b/tests/core/test_agentic_client_provider_kwargs.py @@ -2,6 +2,7 @@ from __future__ import annotations import pytest +from deeptutor.core.agentic import client as agentic_client from deeptutor.core.agentic.client import ( _NATIVE_ADAPTER_BUILDERS, _NATIVE_TOOL_BACKENDS, @@ -320,3 +321,53 @@ async def test_anthropic_adapter_emits_final_tool_call_delta() -> None: assert tool_delta.function.name == "read_file" assert '"SOUL.md"' in tool_delta.function.arguments assert chunks[-1].choices[0].finish_reason == "tool_calls" + + +@pytest.mark.asyncio +async def test_agentic_client_pool_reuses_and_bounds_clients(monkeypatch) -> None: + await agentic_client.close_agentic_client_pool() + built = [] + + class FakeClient: + def __init__(self) -> None: + self.closed = 0 + + async def close(self) -> None: + self.closed += 1 + + def _build(config, *, disable_ssl_verify): + client = FakeClient() + built.append(client) + return client + + monkeypatch.setattr(agentic_client, "_build_openai_client", _build) + monkeypatch.setattr( + agentic_client, "load_system_settings", lambda: {"disable_ssl_verify": False} + ) + base = LLMClientConfig( + binding="openai", + model="model-0", + api_key="secret", + base_url="https://example.test/v1", + ) + + first = build_openai_client(base) + assert build_openai_client(base) is first + for index in range(1, agentic_client._AGENTIC_CLIENT_POOL_MAXSIZE + 1): + build_openai_client( + LLMClientConfig( + binding="openai", + model=f"model-{index}", + api_key="secret", + base_url="https://example.test/v1", + ) + ) + + import asyncio + + await asyncio.sleep(0) + assert agentic_client.agentic_client_pool_size() == ( + agentic_client._AGENTIC_CLIENT_POOL_MAXSIZE + ) + assert built[0].closed == 1 + await agentic_client.close_agentic_client_pool() diff --git a/tests/logging/test_task_log_stream.py b/tests/logging/test_task_log_stream.py index 30b876148..5770ba97e 100644 --- a/tests/logging/test_task_log_stream.py +++ b/tests/logging/test_task_log_stream.py @@ -95,3 +95,33 @@ def test_capture_task_logs_forwards_graphrag_propagating_logger_once(): and event["payload"]["context"]["task_id"] == "task-graphrag" ] assert len(matches) == 1 + + +def test_completed_task_buffers_are_bounded_and_restore_terminal_event(): + manager = KnowledgeTaskStreamManager() + manager._MAX_RETAINED_TASKS = 3 + + for index in range(8): + task_id = f"task-{index}" + manager.ensure_task(task_id) + manager.emit_log(task_id, "x" * 100) + manager.emit_complete(task_id) + + assert manager.retained_task_count() == 3 + assert len(manager._terminal_tombstones) == 5 + + manager.ensure_task("task-0") + restored = list(manager._buffers["task-0"]) + assert restored[-1]["event"] == "complete" + + +def test_task_buffer_has_approximate_byte_ceiling(): + manager = KnowledgeTaskStreamManager() + manager._MAX_BYTES_PER_TASK = 2_000 + manager.ensure_task("large-task") + + for _ in range(20): + manager.emit_log("large-task", "x" * 500) + + assert manager._buffer_bytes["large-task"] <= manager._MAX_BYTES_PER_TASK + assert len(manager._buffers["large-task"]) < 20 diff --git a/tests/runtime/test_api_import_memory_boundary.py b/tests/runtime/test_api_import_memory_boundary.py new file mode 100644 index 000000000..9068bcce8 --- /dev/null +++ b/tests/runtime/test_api_import_memory_boundary.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import json +from pathlib import Path +import subprocess +import sys + + +def test_api_import_keeps_optional_heavy_dependencies_cold() -> None: + repo_root = Path(__file__).resolve().parents[2] + probe = """ +import json +import sys + +import deeptutor.api.main # noqa: F401 + +heavy_roots = { + "anthropic", + "docx", + "fitz", + "graphrag", + "llama_index", + "matplotlib", + "networkx", + "numpy", + "openpyxl", + "pandas", + "pptx", + "pypdf", +} +loaded = sorted(name for name in heavy_roots if name in sys.modules) +print(json.dumps(loaded)) +""" + + result = subprocess.run( + [sys.executable, "-c", probe], + cwd=repo_root, + capture_output=True, + check=True, + text=True, + ) + + assert json.loads(result.stdout) == [] diff --git a/tests/runtime/test_launcher.py b/tests/runtime/test_launcher.py index 16f7d5343..910228eae 100644 --- a/tests/runtime/test_launcher.py +++ b/tests/runtime/test_launcher.py @@ -292,3 +292,112 @@ def test_ensure_web_dependencies_surfaces_a_failed_install( launcher._ensure_web_dependencies(source, "npm") assert "npm ci" in str(excinfo.value) + + +def test_source_frontend_defaults_to_cached_production_build( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = tmp_path / "web" + (source / "node_modules").mkdir(parents=True) + builds: list[tuple[Path, str, str, bool]] = [] + + monkeypatch.setattr(launcher, "_packaged_web_dir", lambda: None) + monkeypatch.setattr(launcher, "_source_web_dir", lambda _home: source) + monkeypatch.setattr(launcher.shutil, "which", lambda name: f"/bin/{name}") + monkeypatch.setattr( + launcher, + "_ensure_source_production_build", + lambda path, npm, *, api_base, auth_enabled: builds.append( + (path, npm, api_base, auth_enabled) + ), + ) + + runtime = launcher._resolve_frontend( + tmp_path, + 3782, + api_base="http://localhost:8001", + auth_enabled=True, + ) + + assert runtime.kind == "source-production" + standalone = source / launcher.SOURCE_PRODUCTION_DIST_DIR / "standalone" + assert runtime.command == ["/bin/node", str(standalone / "server.js")] + assert runtime.cwd == standalone + assert builds == [(source, "/bin/npm", "http://localhost:8001", True)] + + +def test_source_frontend_dev_mode_is_explicit_and_skips_production_build( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = tmp_path / "web" + (source / "node_modules").mkdir(parents=True) + + monkeypatch.setattr(launcher, "_packaged_web_dir", lambda: None) + monkeypatch.setattr(launcher, "_source_web_dir", lambda _home: source) + monkeypatch.setattr(launcher.shutil, "which", lambda name: f"/bin/{name}") + monkeypatch.setattr( + launcher, + "_ensure_source_production_build", + lambda *_args, **_kwargs: (_ for _ in ()).throw( + AssertionError("--dev must not build the production frontend") + ), + ) + + runtime = launcher._resolve_frontend( + tmp_path, + 3782, + api_base="http://localhost:8001", + auth_enabled=False, + dev=True, + ) + + assert runtime.kind == "source" + assert runtime.command == ["/bin/npm", "run", "dev", "--", "--port", "3782"] + + +def test_source_production_build_is_reused_until_an_input_changes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = tmp_path / "web" + source.mkdir() + (source / "package.json").write_text('{"scripts":{"build":"next build"}}', encoding="utf-8") + next_env = source / "next-env.d.ts" + next_env.write_text("// developer dist types\n", encoding="utf-8") + app = source / "app" + app.mkdir() + page = app / "page.tsx" + page.write_text("export default function Page() { return null; }", encoding="utf-8") + calls: list[tuple[list[str], Path, str]] = [] + + def _run(command, cwd, env, **_kwargs): + calls.append((list(command), Path(cwd), env["DEEPTUTOR_NEXT_DIST_DIR"])) + next_env.write_text("// production dist types\n", encoding="utf-8") + dist = source / launcher.SOURCE_PRODUCTION_DIST_DIR + (dist / "standalone").mkdir(parents=True, exist_ok=True) + (dist / "BUILD_ID").write_text(f"build-{len(calls)}", encoding="utf-8") + (dist / "standalone" / "server.js").write_text("", encoding="utf-8") + return _CompletedProcess(0) + + monkeypatch.setattr(launcher.subprocess, "run", _run) + + for _ in range(2): + launcher._ensure_source_production_build( + source, + "npm", + api_base="http://localhost:8001", + auth_enabled=False, + ) + + page.write_text("export default function Page() { return
; }", encoding="utf-8") + launcher._ensure_source_production_build( + source, + "npm", + api_base="http://localhost:8001", + auth_enabled=False, + ) + + assert calls == [ + (["npm", "run", "build"], source, launcher.SOURCE_PRODUCTION_DIST_DIR), + (["npm", "run", "build"], source, launcher.SOURCE_PRODUCTION_DIST_DIR), + ] + assert next_env.read_text(encoding="utf-8") == "// developer dist types\n" diff --git a/tests/runtime/test_launcher_allocator_env.py b/tests/runtime/test_launcher_allocator_env.py new file mode 100644 index 000000000..ad5f3b3ef --- /dev/null +++ b/tests/runtime/test_launcher_allocator_env.py @@ -0,0 +1,18 @@ +from deeptutor.runtime.launcher import _apply_single_user_allocator_env + + +def test_single_user_allocator_defaults_reduce_fragmentation() -> None: + env: dict[str, str] = {} + + _apply_single_user_allocator_env(env) + + assert env["MALLOC_ARENA_MAX"] == "2" + assert env["MALLOC_TRIM_THRESHOLD_"] == "131072" + + +def test_single_user_allocator_preserves_operator_overrides() -> None: + env = {"MALLOC_ARENA_MAX": "4", "MALLOC_TRIM_THRESHOLD_": "262144"} + + _apply_single_user_allocator_env(env) + + assert env == {"MALLOC_ARENA_MAX": "4", "MALLOC_TRIM_THRESHOLD_": "262144"} diff --git a/tests/runtime/test_memory_reclaim.py b/tests/runtime/test_memory_reclaim.py new file mode 100644 index 000000000..5627f94c4 --- /dev/null +++ b/tests/runtime/test_memory_reclaim.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +import asyncio + +import pytest + +from deeptutor.runtime import memory_reclaim + + +@pytest.mark.asyncio +async def test_scheduled_reclaims_are_coalesced(monkeypatch: pytest.MonkeyPatch) -> None: + calls = 0 + + def _release() -> tuple[int, bool]: + nonlocal calls + calls += 1 + return 3, True + + monkeypatch.setattr(memory_reclaim, "release_unused_memory", _release) + + first = memory_reclaim.schedule_memory_reclaim() + second = memory_reclaim.schedule_memory_reclaim() + + assert first is second + assert first is not None + assert await first == (3, True) + await asyncio.sleep(0) + assert calls == 1 diff --git a/tests/runtime/test_run_server_memory_mode.py b/tests/runtime/test_run_server_memory_mode.py new file mode 100644 index 000000000..3cfa8bb4f --- /dev/null +++ b/tests/runtime/test_run_server_memory_mode.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest + +from deeptutor.api import run_server + + +@pytest.fixture +def uvicorn_kwargs(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict[str, Any]: + captured: dict[str, Any] = {} + + monkeypatch.setattr(run_server, "get_runtime_home", lambda: tmp_path) + monkeypatch.setattr(run_server.os, "chdir", lambda _path: None) + monkeypatch.setattr(run_server.uvicorn, "run", lambda *args, **kwargs: captured.update(kwargs)) + + from deeptutor import logging as deeptutor_logging + from deeptutor.runtime import mode + from deeptutor.services import setup + + monkeypatch.setattr(deeptutor_logging, "configure_logging", lambda: None) + monkeypatch.setattr(mode, "set_mode", lambda _mode: None) + monkeypatch.setattr(setup, "get_backend_port", lambda _root: 8001) + return captured + + +def test_run_server_disables_reload_by_default( + monkeypatch: pytest.MonkeyPatch, uvicorn_kwargs: dict[str, Any] +) -> None: + monkeypatch.delenv("DEEPTUTOR_DEV_RELOAD", raising=False) + + run_server.main() + + assert uvicorn_kwargs["reload"] is False + assert uvicorn_kwargs["reload_excludes"] is None + + +def test_run_server_reload_remains_available_for_development( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + uvicorn_kwargs: dict[str, Any], +) -> None: + monkeypatch.setenv("DEEPTUTOR_DEV_RELOAD", "true") + (tmp_path / "data").mkdir() + + run_server.main() + + assert uvicorn_kwargs["reload"] is True + assert str(tmp_path / "data") in uvicorn_kwargs["reload_excludes"] diff --git a/tests/runtime/test_uvicorn_launch_flags.py b/tests/runtime/test_uvicorn_launch_flags.py new file mode 100644 index 000000000..3105dc4ce --- /dev/null +++ b/tests/runtime/test_uvicorn_launch_flags.py @@ -0,0 +1,66 @@ +"""Guards that every uvicorn launch point wires the shared serving flags. + +The browser never reaches the backend directly: ``web/proxy.ts`` rewrites +``/api/*`` and Next.js forwards over Node's ``http.globalAgent``, which reaps +idle pooled sockets on its own 5s timer. uvicorn's ``timeout_keep_alive`` +defaults to the same 5s, so both ends armed an identical idle timer on the same +socket and raced to close it; a FIN landing on a socket the pool was handing to +a new request killed it with ``ECONNRESET``, which the proxy turned into a 500 +("Failed to proxy ... socket hang up" -> "Failed to load sessions" in the UI). +``--timeout-keep-alive`` fixes it, and ``--ws-max-size`` has the same shape: +correct only if *every* launch point passes it, and DeepTutor has five (two +Dockerfile stages, the ``deeptutor start`` launcher, the CLI, run_server). A +launch point that forgets one reintroduces the bug for whoever starts the +backend that way, which no per-module test would catch. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +_REPO = Path(__file__).resolve().parents[2] + +# (path, marker anchoring the uvicorn invocation, flag spellings for this style) +_PYTHON_FLAGS = ("ws_max_size", "timeout_keep_alive") +_CLI_FLAGS = ("--ws-max-size", "--timeout-keep-alive") +_LAUNCH_POINTS = [ + ("deeptutor/runtime/launcher.py", '"uvicorn",', _CLI_FLAGS), + ("deeptutor/api/run_server.py", "uvicorn.run(", _PYTHON_FLAGS), + ("deeptutor_cli/main.py", "uvicorn.run(", _PYTHON_FLAGS), +] + + +@pytest.mark.parametrize(("relpath", "marker", "flags"), _LAUNCH_POINTS) +def test_python_launch_point_wires_serving_flags( + relpath: str, marker: str, flags: tuple[str, ...] +) -> None: + source = (_REPO / relpath).read_text(encoding="utf-8") + assert marker in source, f"{relpath} no longer launches uvicorn as expected" + for flag in flags: + assert flag in source, f"{relpath} launches uvicorn without {flag}" + + +def test_dockerfile_launch_points_wire_serving_flags() -> None: + """Both container stages (production entrypoint + dev supervisord).""" + lines = [ + line + for line in (_REPO / "Dockerfile").read_text(encoding="utf-8").splitlines() + if "-m uvicorn deeptutor.api.main:app" in line + ] + assert len(lines) == 2, f"expected 2 Dockerfile uvicorn launches, found {len(lines)}" + for line in lines: + for flag in _CLI_FLAGS: + assert flag in line, f"Dockerfile launches uvicorn without {flag}: {line.strip()[:80]}" + + +def test_keep_alive_outlasts_the_proxy_socket_reaper() -> None: + """Must stay clear of the 5s idle timer on Node's ``http.globalAgent``. + + Matching it is what caused the collision, so a value anywhere near 5s puts + the two timers back in contention. + """ + from deeptutor.services.config import HTTP_KEEP_ALIVE_TIMEOUT + + assert HTTP_KEEP_ALIVE_TIMEOUT >= 60, "too close to the proxy's 5s socket reaper" diff --git a/tests/scripts/test_start_web.py b/tests/scripts/test_start_web.py index e1848c282..d600c9dd8 100644 --- a/tests/scripts/test_start_web.py +++ b/tests/scripts/test_start_web.py @@ -16,9 +16,10 @@ def _load_module(): def test_start_web_parser_supports_home(tmp_path: Path) -> None: start_web = _load_module() - args = start_web.build_parser().parse_args(["--home", str(tmp_path)]) + args = start_web.build_parser().parse_args(["--home", str(tmp_path), "--dev"]) assert args.home == tmp_path + assert args.dev is True def test_start_web_delegates_to_runtime_launcher(tmp_path: Path) -> None: @@ -26,4 +27,4 @@ def test_start_web_delegates_to_runtime_launcher(tmp_path: Path) -> None: with mock.patch.object(start_web, "start") as start: start_web.main(["--home", str(tmp_path)]) - start.assert_called_once_with(home=tmp_path) + start.assert_called_once_with(home=tmp_path, dev=False) diff --git a/tests/services/llm/test_provider_pool.py b/tests/services/llm/test_provider_pool.py new file mode 100644 index 000000000..6464abc90 --- /dev/null +++ b/tests/services/llm/test_provider_pool.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from typing import Any + +import pytest +import pytest_asyncio + +from deeptutor.services.llm import provider_factory +from deeptutor.services.llm.config import LLMConfig + + +class _FakeProvider: + def __init__(self) -> None: + self.generation: Any = None + self.closed = 0 + + async def aclose(self) -> None: + self.closed += 1 + + +def _config(**overrides: Any) -> LLMConfig: + values = { + "model": "test-model", + "api_key": "secret", + "base_url": "https://api.example.test/v1", + "effective_url": "https://api.example.test/v1", + "binding": "openai", + "provider_name": "openai", + "provider_mode": "standard", + "extra_headers": {}, + } + values.update(overrides) + return LLMConfig(**values) + + +@pytest_asyncio.fixture(autouse=True) +async def _empty_pool(): + await provider_factory.close_runtime_provider_pool() + yield + await provider_factory.close_runtime_provider_pool() + + +@pytest.mark.asyncio +async def test_runtime_provider_reuses_identical_config(monkeypatch) -> None: + built: list[_FakeProvider] = [] + + def _build(_config: LLMConfig) -> _FakeProvider: + provider = _FakeProvider() + built.append(provider) + return provider + + monkeypatch.setattr(provider_factory, "_build_runtime_provider", _build) + + first = provider_factory.get_runtime_provider(_config()) + second = provider_factory.get_runtime_provider(_config()) + + assert first is second + assert len(built) == 1 + assert provider_factory.runtime_provider_pool_size() == 1 + + +@pytest.mark.asyncio +async def test_runtime_provider_pool_is_bounded_and_closes_evictions(monkeypatch) -> None: + built: list[_FakeProvider] = [] + + def _build(_config: LLMConfig) -> _FakeProvider: + provider = _FakeProvider() + built.append(provider) + return provider + + monkeypatch.setattr(provider_factory, "_build_runtime_provider", _build) + + for index in range(provider_factory._PROVIDER_POOL_MAXSIZE + 1): + provider_factory.get_runtime_provider(_config(model=f"model-{index}")) + + # Eviction closes asynchronously on the owning server loop. + import asyncio + + await asyncio.sleep(0) + assert provider_factory.runtime_provider_pool_size() == provider_factory._PROVIDER_POOL_MAXSIZE + assert built[0].closed == 1 + + +@pytest.mark.asyncio +async def test_reset_closes_all_cached_providers(monkeypatch) -> None: + built: list[_FakeProvider] = [] + + def _build(_config: LLMConfig) -> _FakeProvider: + provider = _FakeProvider() + built.append(provider) + return provider + + monkeypatch.setattr(provider_factory, "_build_runtime_provider", _build) + provider_factory.get_runtime_provider(_config()) + + provider_factory.reset_runtime_provider_pool() + import asyncio + + await asyncio.sleep(0) + assert provider_factory.runtime_provider_pool_size() == 0 + assert built[0].closed == 1 diff --git a/tests/services/rag/test_llamaindex_index_cache_bounds.py b/tests/services/rag/test_llamaindex_index_cache_bounds.py new file mode 100644 index 000000000..aff782720 --- /dev/null +++ b/tests/services/rag/test_llamaindex_index_cache_bounds.py @@ -0,0 +1,40 @@ +from pathlib import Path + +import pytest + +from deeptutor.services.rag.pipelines.llamaindex import storage + + +@pytest.fixture(autouse=True) +def _clear_cache(): + storage.clear_index_cache() + yield + storage.clear_index_cache() + + +def test_loaded_index_cache_uses_small_lru(monkeypatch, tmp_path: Path) -> None: + monkeypatch.setattr(storage, "_load_validated_index", lambda path: object()) + paths = [tmp_path / f"kb-{index}" for index in range(4)] + for path in paths: + path.mkdir() + storage._cached_index(path) + + assert len(storage._INDEX_CACHE) == storage._INDEX_CACHE_MAXSIZE + retained_paths = {key[0] for key in storage._INDEX_CACHE} + assert str(paths[-1].resolve()) in retained_paths + assert str(paths[-2].resolve()) in retained_paths + + +def test_loaded_index_cache_expires_after_idle_ttl(monkeypatch, tmp_path: Path) -> None: + now = [100.0] + monkeypatch.setattr(storage.time, "monotonic", lambda: now[0]) + monkeypatch.setattr(storage, "_INDEX_CACHE_IDLE_SECONDS", 10) + monkeypatch.setattr(storage, "_load_validated_index", lambda path: object()) + path = tmp_path / "kb" + path.mkdir() + storage._cached_index(path) + + now[0] = 111.0 + + assert storage.prune_index_cache() == 1 + assert not storage._INDEX_CACHE diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs index 698b6d25a..219dd5436 100644 --- a/web/eslint.config.mjs +++ b/web/eslint.config.mjs @@ -14,7 +14,7 @@ const config = [ }, }, { - ignores: ["node_modules/**", ".next/**", "out/**"], + ignores: ["node_modules/**", ".next/**", ".next-deeptutor/**", "dist/**", "out/**"], }, ]; diff --git a/web/next.config.js b/web/next.config.js index 3ce125ab2..44ed21c5e 100644 --- a/web/next.config.js +++ b/web/next.config.js @@ -91,6 +91,12 @@ const APP_VERSION = (() => { })(); const nextConfig = { + // Keep the production build used by `deeptutor start` separate from the + // `.next` development cache used by the explicit `deeptutor start --dev`. + // Without separate directories either command can invalidate the other + // process while it is running. + distDir: process.env.DEEPTUTOR_NEXT_DIST_DIR || ".next", + // Expose the build-time version to the browser so the sidebar badge // can compare it against GitHub's latest release. env: { diff --git a/web/package.json b/web/package.json index 9c88744a0..6c388b34f 100644 --- a/web/package.json +++ b/web/package.json @@ -3,8 +3,8 @@ "version": "1.0.0", "private": true, "scripts": { - "dev": "node --max-old-space-size=4096 ./node_modules/next/dist/bin/next dev", - "dev:turbo": "node --max-old-space-size=6144 ./node_modules/next/dist/bin/next dev --turbopack", + "dev": "node ./scripts/dev.mjs", + "dev:turbo": "node ./scripts/dev.mjs --turbopack", "build": "next build", "start": "next start", "lint": "eslint .", diff --git a/web/scripts/dev.mjs b/web/scripts/dev.mjs new file mode 100644 index 000000000..e6eca28f5 --- /dev/null +++ b/web/scripts/dev.mjs @@ -0,0 +1,69 @@ +#!/usr/bin/env node +/** + * Dev-server entrypoint that pins the V8 heap ceiling of the process that + * actually holds the memory. + * + * `next dev` does not render in the process you launch — it spawns a separate + * render worker, and V8 flags in argv are not inherited by child processes. So + * the long-standing `node --max-old-space-size=4096 .../next dev` never reached + * the worker: Next reads the ceiling from NODE_OPTIONS + * (`getMaxOldSpaceSize()`), finds nothing, and substitutes 50% of total RAM + * with no upper bound (`next dev` CLI, guarded by NEXT_DISABLE_MEM_OVERRIDE). + * On a 24GB machine that is a 12GB heap, which V8 will genuinely try to fill: + * an hour-long session died in `Ineffective mark-compacts near heap limit` + * after spending 63 seconds inside a single mark-compact, with the machine + * swapping long before that. + * + * Setting the ceiling here fixes both halves — the worker inherits NODE_OPTIONS, + * and Next stops overriding it. Keep Next's 50% rule so small machines are not + * handed a heap larger than their RAM, but cap it: past a few GB the extra + * headroom buys a slower death, not a working dev server. An explicit + * NODE_OPTIONS ceiling from the developer always wins. + */ + +import { spawn } from "node:child_process"; +import { readFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const HEAP_CEILING_MB = 4096; +const WEB_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), ".."); +const NEXT_BIN = path.join(WEB_DIR, "node_modules", "next", "dist", "bin", "next"); + +/** Memory this process may actually use, in MB — cgroup limit included so the + * container dev stage sizes to its own budget rather than the host's RAM. */ +function memoryBudgetMB() { + let bytes = os.totalmem(); + try { + const limit = Number(readFileSync("/sys/fs/cgroup/memory.max", "utf8").trim()); + if (Number.isFinite(limit) && limit > 0) bytes = Math.min(bytes, limit); + } catch { + // No cgroup v2 limit (macOS, Windows, unconstrained container). + } + return Math.floor(bytes / 1024 / 1024); +} + +const inherited = process.env.NODE_OPTIONS ?? ""; +const nodeOptions = /--max[-_]old[-_]space[-_]size/.test(inherited) + ? inherited + : `${inherited} --max-old-space-size=${Math.min( + HEAP_CEILING_MB, + Math.floor(memoryBudgetMB() * 0.5), + )}`.trim(); + +const child = spawn(process.execPath, [NEXT_BIN, "dev", ...process.argv.slice(2)], { + cwd: WEB_DIR, + stdio: "inherit", + env: { ...process.env, NODE_OPTIONS: nodeOptions }, +}); + +// Let Next own the terminal: forward the signals it already handles (lock file +// cleanup, worker teardown) instead of dying first and orphaning the worker. +for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) { + process.on(signal, () => child.kill(signal)); +} +child.on("exit", (code, signal) => { + if (signal) process.kill(process.pid, signal); + else process.exit(code ?? 0); +}); diff --git a/web/tests/dev-heap-ceiling.test.ts b/web/tests/dev-heap-ceiling.test.ts new file mode 100644 index 000000000..2d0796cf1 --- /dev/null +++ b/web/tests/dev-heap-ceiling.test.ts @@ -0,0 +1,83 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import path from "node:path"; + +/** + * `next dev` renders in a worker it spawns itself, and V8 flags in argv are not + * inherited by child processes — so a `node --max-old-space-size=N .../next dev` + * script silently does nothing for the process that holds the memory, and Next + * substitutes 50% of total RAM (12GB on a 24GB machine) instead. That shipped + * for a while and ended in `Ineffective mark-compacts near heap limit`. + * scripts/dev.mjs is the fix: the ceiling goes through NODE_OPTIONS, which the + * worker inherits and Next honors. Every dev launch point must route through it + * or the override quietly comes back. + */ + +// The node-test harness runs from web/ (see scripts/run-node-tests.mjs). +const webRoot = process.cwd(); +const repoRoot = path.resolve(webRoot, ".."); + +const read = (...parts: string[]) => + readFileSync(path.join(...parts), "utf8"); + +test("npm dev scripts route through the heap-ceiling wrapper", () => { + const scripts = JSON.parse(read(webRoot, "package.json")).scripts as Record< + string, + string + >; + for (const name of ["dev", "dev:turbo"]) { + const script = scripts[name]; + assert.ok(script, `package.json is missing the ${name} script`); + assert.match( + script, + /scripts\/dev\.mjs/, + `${name} must launch via scripts/dev.mjs, got: ${script}`, + ); + assert.doesNotMatch( + script, + /--max-old-space-size/, + `${name} passes the heap flag in argv, where the render worker never sees it`, + ); + } +}); + +test("the container dev stage routes through the wrapper too", () => { + // Command lines only — prose mentions of `next dev` are not launch points. + const devFrontend = read(repoRoot, "Dockerfile") + .split("\n") + .filter((line) => !line.trimStart().startsWith("#")) + .filter( + (line) => line.includes("bin/next dev") || line.includes("scripts/dev.mjs"), + ); + assert.ok(devFrontend.length > 0, "no dev frontend command found in Dockerfile"); + for (const line of devFrontend) { + assert.match( + line, + /scripts\/dev\.mjs/, + `Dockerfile dev frontend bypasses the wrapper: ${line.trim()}`, + ); + } +}); + +test("the wrapper caps the ceiling and respects an explicit NODE_OPTIONS", () => { + const source = read(webRoot, "scripts", "dev.mjs"); + // A ceiling only helps if it is a ceiling: Next's own 50%-of-RAM rule is what + // produced the 12GB heap, so the wrapper must clamp rather than mirror it. + assert.match(source, /Math\.min\(/, "wrapper must clamp the computed size"); + assert.match( + source, + /NODE_OPTIONS/, + "the ceiling has to travel via NODE_OPTIONS to reach the worker", + ); + assert.match( + source, + /max\[-_\]old\[-_\]space\[-_\]size/, + "wrapper must detect an inherited ceiling instead of appending a second one", + ); + assert.match( + source, + /HEAP_CEILING_MB\s*=\s*4096/, + "the fallback ceiling must preserve the original 4GB dev-server budget", + ); +}); diff --git a/web/tsconfig.json b/web/tsconfig.json index 60c6b1dec..4d5663091 100644 --- a/web/tsconfig.json +++ b/web/tsconfig.json @@ -22,7 +22,9 @@ "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", - ".next/dev/types/**/*.ts" + ".next/dev/types/**/*.ts", + ".next-deeptutor/types/**/*.ts", + ".next-deeptutor/dev/types/**/*.ts" ], "exclude": ["node_modules"] }