DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(knowledge): keep batch uploads off the event loop (#777)
Bingxi Zhao (Frank)f342281f33d5
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex b9b218cf0..2fa90f600 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -458,6 +458,34 @@ def _save_uploaded_files(return uploaded_files, uploaded_file_paths+async def _save_uploaded_files_off_loop(+ files: list[UploadFile],+ target_dir: Path,+ allowed_extensions: set[str] | None = None,+ kb_name: str | None = None,+ rel_paths: list[str] | None = None,+) -> tuple[list[str], list[str]]:+ """:func:`_save_uploaded_files` on a worker thread.++ That function blocks end to end — a chunked write of every uploaded byte,+ zip extraction for archive members, and (when PocketBase is enabled) one+ synchronous HTTP upload per file. Called inline from an ``async def``+ route it held the event loop for the whole batch, so every other request+ — chat WebSockets included — stalled until the upload finished (#777).++ Safe to hand to a thread: it only touches ``UploadFile.file``, the plain+ ``SpooledTemporaryFile`` underneath, never the async ``UploadFile`` API.+ """+ return await asyncio.to_thread(+ _save_uploaded_files,+ files,+ target_dir,+ allowed_extensions=allowed_extensions,+ kb_name=kb_name,+ rel_paths=rel_paths,+ )++def _get_upload_file_size(file: UploadFile) -> int | None:"""Best-effort byte size detection without consuming the uploaded stream."""try:@@ -853,7 +881,14 @@ async def run_upload_processing_task(rag_provider=rag_provider,)- staged_files = adder.add_documents(uploaded_file_paths, allow_duplicates=False)+ # Staging blocks: a full-content hash per file, plus a copy for+ # anything not already under raw/. A BackgroundTasks entry declared+ # ``async def`` is awaited ON the event loop — starlette only routes+ # *sync* callables to its threadpool — so doing this inline stalled+ # every other request for the length of the batch (#777).+ staged_files = await asyncio.to_thread(+ adder.add_documents, uploaded_file_paths, allow_duplicates=False+ )_task_log(task_id, f"Staged {len(staged_files)} new file(s)")if not staged_files:@@ -2195,7 +2230,7 @@ async def upload_files(# archive itself is never indexed (``safe_extract_zip`` skips ``.zip``).upload_extensions = allowed_extensions | {".zip"}_validate_upload_batch(files, allowed_extensions=upload_extensions, rel_paths=rel_paths)- uploaded_files, uploaded_file_paths = _save_uploaded_files(+ uploaded_files, uploaded_file_paths = await _save_uploaded_files_off_loop(files, raw_dir, allowed_extensions=upload_extensions, rel_paths=rel_paths)task_id = _build_unique_task_id("kb_upload", kb_name)@@ -2302,7 +2337,7 @@ async def create_knowledge_base(logger.warning(f"KB {name} not found in config, registering manually")initializer._register_to_config()- uploaded_files, _ = _save_uploaded_files(+ uploaded_files, _ = await _save_uploaded_files_off_loop(files, initializer.raw_dir, allowed_extensions=allowed_extensions, rel_paths=rel_paths)diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.pyindex 0f6d652a8..abb8e2eb8 100644--- a/deeptutor/knowledge/add_documents.py+++ b/deeptutor/knowledge/add_documents.py@@ -280,7 +280,11 @@ class DocumentAdder:success = await rag_service.add_documents(self.kb_name, [str(doc_file)])if success:processed_files.append(doc_file)- self._record_successful_hash(doc_file)+ # Re-hashes the whole file, so it stays off the event loop:+ # this runs inside a FastAPI BackgroundTasks entry, which is+ # awaited on the loop and would otherwise stall unrelated+ # requests once per indexed file (#777).+ await asyncio.to_thread(self._record_successful_hash, doc_file)logger.info(f"Processed: {doc_file.name}")else:error = "Provider returned failure without details."diff --git a/tests/api/test_upload_off_event_loop.py b/tests/api/test_upload_off_event_loop.pynew file mode 100644index 000000000..127e4c767--- /dev/null+++ b/tests/api/test_upload_off_event_loop.py@@ -0,0 +1,127 @@+"""The upload path must never hold the event loop (issue #777).++Batch-uploading files stalled every other request — chat WebSockets included+— for the whole duration of the batch. Two distinct causes, both pinned here:++* ``_save_uploaded_files`` is blocking end to end (a chunked write of every+ uploaded byte, zip extraction, plus a synchronous HTTP upload per file when+ PocketBase is on) and was called inline from an ``async def`` route.+* the follow-up work runs in a FastAPI ``BackgroundTasks`` entry declared+ ``async def``, which starlette awaits ON the event loop — only *sync*+ callables get routed to its threadpool — so the staging hash/copy and the+ per-file re-hash blocked there too.++Each test asserts the work happens on a worker thread, and one asserts the+loop keeps serving unrelated work while an upload is being written.+"""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+import threading+from typing import Any++import pytest++from deeptutor.api.routers import knowledge as knowledge_router+from deeptutor.knowledge.add_documents import DocumentAdder+++def test_saving_uploads_runs_on_a_worker_thread(monkeypatch, tmp_path: Path) -> None:+ recorded: dict[str, int] = {}++ def _fake_save(+ files: list[Any],+ target_dir: Path,+ **_kwargs: Any,+ ) -> tuple[list[str], list[str]]:+ recorded["thread"] = threading.get_ident()+ return (["a.pdf"], [str(target_dir / "a.pdf")])++ monkeypatch.setattr(knowledge_router, "_save_uploaded_files", _fake_save)++ uploaded, paths = asyncio.run(+ knowledge_router._save_uploaded_files_off_loop([], tmp_path, rel_paths=None)+ )++ assert (uploaded, paths) == (["a.pdf"], [str(tmp_path / "a.pdf")])+ assert recorded["thread"] != threading.get_ident()+++async def test_event_loop_keeps_serving_while_an_upload_is_written(+ monkeypatch, tmp_path: Path+) -> None:+ """The regression itself: unrelated work must progress mid-write."""+ started = threading.Event()+ release = threading.Event()++ def _blocking_save(*_args: Any, **_kwargs: Any) -> tuple[list[str], list[str]]:+ started.set()+ release.wait(timeout=5)+ return ([], [])++ monkeypatch.setattr(knowledge_router, "_save_uploaded_files", _blocking_save)++ ticks = 0++ async def _other_request_traffic() -> None:+ nonlocal ticks+ while True:+ ticks += 1+ await asyncio.sleep(0.005)++ heartbeat = asyncio.create_task(_other_request_traffic())+ save = asyncio.create_task(knowledge_router._save_uploaded_files_off_loop([], tmp_path))+ try:+ await asyncio.to_thread(started.wait, 5)+ ticks_at_start = ticks+ await asyncio.sleep(0.05)+ assert ticks > ticks_at_start, "the event loop stalled while the upload was written"+ finally:+ release.set()+ heartbeat.cancel()+ await save+++def test_recording_an_indexed_file_hash_runs_on_a_worker_thread(+ monkeypatch, tmp_path: Path+) -> None:+ """Re-hashes the whole file, once per indexed document."""+ kb_dir = tmp_path / "kb"+ raw_dir = kb_dir / "raw"+ raw_dir.mkdir(parents=True)+ version_dir = kb_dir / "version-1"+ version_dir.mkdir()+ (version_dir / "docstore.json").write_text("{}", encoding="utf-8")+ (version_dir / "index_store.json").write_text("{}", encoding="utf-8")+ (version_dir / "meta.json").write_text(+ json.dumps({"provider": "llamaindex", "signature": "llamaindex", "version": "version-1"}),+ encoding="utf-8",+ )+ doc = raw_dir / "ok.txt"+ doc.write_text("hello", encoding="utf-8")++ class _OkRagService:+ def __init__(self, *_args: Any, **_kwargs: Any) -> None:+ pass++ async def add_documents(self, *_args: Any, **_kwargs: Any) -> bool:+ return True++ monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _OkRagService)++ adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path))+ recorded: dict[str, int] = {}++ def _spy(file_path: Path) -> None:+ recorded["thread"] = threading.get_ident()++ monkeypatch.setattr(adder, "_record_successful_hash", _spy)++ result = asyncio.run(adder.process_new_documents([doc]))++ assert result.processed_files == [doc]+ assert recorded["thread"] != threading.get_ident()