Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: run document uploads off the event loop (#10552)

Nilayf452d415edce
diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.py
index 330ff3001be..aac6ec0658a 100644
--- a/studio/backend/routes/rag.py
+++ b/studio/backend/routes/rag.py
@@ -110,8 +110,12 @@ def _sanitize_filename(name: str) -> str:
return stem[: 200 - len(ext)] + ext
-def _persist_upload_stream(source, filename: str, *, empty_detail: str) -> tuple[str, str]:
- """Copy a validated document stream into the managed uploads root."""
+def _persist_upload_stream(source, filename: str, *, empty_detail: str) -> tuple[str, str, str]:
+ """Copy a validated document stream into the managed uploads root.
+
+ Returns ``(stored_path, filename, content_hash)``; the digest spares ingestion a
+ second full read of the file.
+ """
ext = os.path.splitext(filename)[1].lower()
if ext not in config.UPLOAD_EXTS:
raise HTTPException(
@@ -122,6 +126,7 @@ def _persist_upload_stream(source, filename: str, *, empty_detail: str) -> tuple
stored_path = str(uploads / f"{uuid.uuid4().hex}{ext}")
size = 0
cap = config.MAX_UPLOAD_BYTES
+ digest = hashlib.sha256()
try:
with open(stored_path, "wb") as out:
while True:
@@ -132,6 +137,7 @@ def _persist_upload_stream(source, filename: str, *, empty_detail: str) -> tuple
if cap and size > cap:
break
out.write(block)
+ digest.update(block)
except OSError:
_remove_stored_upload(stored_path)
raise
@@ -144,11 +150,11 @@ def _persist_upload_stream(source, filename: str, *, empty_detail: str) -> tuple
if size == 0:
_remove_stored_upload(stored_path)
raise HTTPException(status_code = 400, detail = empty_detail)
- return stored_path, filename
+ return stored_path, filename, digest.hexdigest()
-def _save_upload(file: UploadFile) -> tuple[str, str]:
- """Persist a browser upload; returns (stored_path, filename)."""
+def _save_upload(file: UploadFile) -> tuple[str, str, str]:
+ """Persist a browser upload; returns (stored_path, filename, content_hash)."""
filename = _sanitize_filename(file.filename or "document")
return _persist_upload_stream(
file.file,
@@ -157,8 +163,8 @@ def _save_upload(file: UploadFile) -> tuple[str, str]:
)
-def _save_native_path_upload(lease: str) -> tuple[str, str]:
- """Persist a desktop drop; returns (stored_path, filename).
+def _save_native_path_upload(lease: str) -> tuple[str, str, str]:
+ """Persist a desktop drop; returns (stored_path, filename, content_hash).
The webview never gets to name a path directly: Rust signs the path it saw and we
re-verify + re-stat that grant here before reading a byte.
@@ -190,7 +196,7 @@ def _save_native_path_upload(lease: str) -> tuple[str, str]:
def _resolve_document_upload(
file: UploadFile | None, native_path_lease: str | None
-) -> tuple[str, str]:
+) -> tuple[str, str, str]:
if native_path_lease:
return _save_native_path_upload(native_path_lease)
if file is None:
@@ -476,8 +482,10 @@ def _raise_if_scope_retired(scope: str, detail: str = "Knowledge base is being d
raise HTTPException(status_code = 409, detail = detail)
+# The three upload routes stay sync so FastAPI runs them in the threadpool; their
+# copy + start_ingestion work would stall every other request on the event loop.
@router.post("/knowledge-bases/{kb_id}/documents")
-async def upload_kb_document(
+def upload_kb_document(
kb_id: str,
file: UploadFile | None = File(None),
native_path_lease: str | None = Form(None, alias = "nativePathLease"),
@@ -494,14 +502,21 @@ async def upload_kb_document(
conn.close()
scope = store.kb_scope(kb_id)
_raise_if_scope_retired(scope)
- stored_path, filename = _resolve_document_upload(file, native_path_lease)
+ stored_path, filename, content_hash = _resolve_document_upload(file, native_path_lease)
try:
with folder_sync.scope_lock(scope):
_require_scope_owner("knowledge_base", kb_id)
_raise_if_scope_retired(scope)
with _rag_unavailable_as_503(stored_path):
document_id, job_id = ingestion.start_ingestion(
- scope, kb_id, None, filename, stored_path, ocr = ocr, caption = caption
+ scope,
+ kb_id,
+ None,
+ filename,
+ stored_path,
+ ocr = ocr,
+ caption = caption,
+ content_hash = content_hash,
)
except Exception:
_remove_stored_upload(stored_path)
@@ -531,8 +546,9 @@ def link_kb_folder(
return _create_linked_folder("knowledge_base", kb_id, payload)
+# Stays sync for the reason above upload_kb_document.
@router.post("/threads/{thread_id}/documents")
-async def upload_thread_document(
+def upload_thread_document(
thread_id: str,
file: UploadFile | None = File(None),
native_path_lease: str | None = Form(None, alias = "nativePathLease"),
@@ -541,7 +557,7 @@ async def upload_thread_document(
subject: str = Depends(get_current_subject),
) -> dict:
_require_rag()
- stored_path, filename = _resolve_document_upload(file, native_path_lease)
+ stored_path, filename, content_hash = _resolve_document_upload(file, native_path_lease)
with _rag_unavailable_as_503(stored_path):
document_id, job_id = ingestion.start_ingestion(
store.thread_scope(thread_id),
@@ -551,6 +567,7 @@ async def upload_thread_document(
stored_path,
ocr = ocr,
caption = caption,
+ content_hash = content_hash,
)
return {"documentId": document_id, "jobId": job_id, "filename": filename}
@@ -580,8 +597,9 @@ def _discard_document(document_id: str) -> None:
_remove_stored_upload(document.get("stored_path"))
+# Stays sync for the reason above upload_kb_document.
@router.post("/projects/{project_id}/documents")
-async def upload_project_document(
+def upload_project_document(
project_id: str,
file: UploadFile | None = File(None),
native_path_lease: str | None = Form(None, alias = "nativePathLease"),
@@ -596,7 +614,7 @@ async def upload_project_document(
raise HTTPException(status_code = 404, detail = "Project not found")
scope = store.project_scope(project_id)
_raise_if_scope_retired(scope, "Project is being deleted")
- stored_path, filename = _resolve_document_upload(file, native_path_lease)
+ stored_path, filename, content_hash = _resolve_document_upload(file, native_path_lease)
try:
with folder_sync.scope_lock(scope):
_require_scope_owner("project", project_id)
@@ -611,6 +629,7 @@ async def upload_project_document(
project_id = project_id,
ocr = ocr,
caption = caption,
+ content_hash = content_hash,
)
except Exception:
_remove_stored_upload(stored_path)
diff --git a/studio/backend/tests/test_rag_ingestion.py b/studio/backend/tests/test_rag_ingestion.py
index e6af381e64e..e9815185619 100644
--- a/studio/backend/tests/test_rag_ingestion.py
+++ b/studio/backend/tests/test_rag_ingestion.py
@@ -230,6 +230,74 @@ def test_start_ingestion_accepts_precomputed_content_hash(
conn.close()
[email protected]("owner", ["knowledge_base", "thread", "project"])
+def test_upload_routes_hand_ingestion_the_digest_from_the_copy(
+ rag_home, stub_embeddings, monkeypatch, owner
+):
+ """Every upload route already reads the whole file to copy it into the uploads root,
+ so it hashes as it writes and start_ingestion is spared a second full read."""
+ import hashlib
+ import io
+
+ from routes import rag as rag_routes
+ from storage import studio_db
+
+ # Over one 1 MiB read block, so a digest built from a single block would not match.
+ payload = b"alpha bravo charlie delta\n" * 44_000
+
+ class _Up:
+ filename = "notes.txt"
+ file = io.BytesIO(payload)
+
+ rehashed = []
+ original = ingestion._sha256_file
+
+ def counting(path):
+ rehashed.append(path)
+ return original(path)
+
+ opened = []
+ builtin_open = open
+
+ def recording_open(path, *args, **kwargs):
+ opened.append((str(path), args[0] if args else kwargs.get("mode", "r")))
+ return builtin_open(path, *args, **kwargs)
+
+ monkeypatch.setattr(ingestion, "_sha256_file", counting)
+ # A module global shadows the builtin, so only routes/rag.py's own opens are recorded.
+ monkeypatch.setattr(rag_routes, "open", recording_open, raising = False)
+
+ # Every Form/File parameter by name: called directly, the unpassed ones keep their
+ # FastAPI sentinel default, and a truthy sentinel would send this down the drop path.
+ call = dict(file = _Up(), native_path_lease = None, ocr = None, caption = None, subject = "test")
+ if owner == "knowledge_base":
+ conn = rag_db.get_connection()
+ try:
+ kb_id = store.create_kb(conn, name = "Digest")
+ finally:
+ conn.close()
+ result = rag_routes.upload_kb_document(kb_id, **call)
+ elif owner == "thread":
+ result = rag_routes.upload_thread_document("T1", **call)
+ else:
+ monkeypatch.setattr(studio_db, "get_chat_project", lambda value: {"id": value})
+ result = rag_routes.upload_project_document("P1", **call)
+
+ _drain(result["jobId"])
+ _wait_completed(result["jobId"])
+
+ conn = rag_db.get_connection()
+ try:
+ assert store.get_document(conn, result["documentId"])["sha256"] == (
+ hashlib.sha256(payload).hexdigest()
+ )
+ finally:
+ conn.close()
+ assert rehashed == [] # start_ingestion took the digest instead of reading the file again
+ # The copy is the only pass over the stored file; hashing it apart would open it twice.
+ assert [mode for path, mode in opened if path.endswith(".txt")] == ["wb"]
+
+
def test_start_ingestion_rejects_malformed_content_hash(rag_home, stub_embeddings, tmp_path):
path = _write(tmp_path, "doc.txt", "alpha bravo charlie")
scope = store.kb_scope("K1")
diff --git a/studio/backend/tests/test_rag_linked_folders.py b/studio/backend/tests/test_rag_linked_folders.py
index de81a27d5de..faba00fad10 100644
--- a/studio/backend/tests/test_rag_linked_folders.py
+++ b/studio/backend/tests/test_rag_linked_folders.py
@@ -12,6 +12,7 @@ import sqlite3
import threading
import time
from contextlib import closing, contextmanager
+from functools import partial
from pathlib import Path
from types import SimpleNamespace
@@ -1817,7 +1818,7 @@ def test_project_upload_cleans_saved_file_when_scope_retires_after_save(rag_home
nonlocal retired
saved_path.write_text("saved", encoding = "utf-8")
retired = True
- return str(saved_path), "race.txt"
+ return str(saved_path), "race.txt", "0" * 64
monkeypatch.setattr(rag_routes.rag_db, "rag_available", lambda: True)
monkeypatch.setattr(studio_db, "get_chat_project", lambda value: {"id": value})
@@ -1834,7 +1835,7 @@ def test_project_upload_cleans_saved_file_when_scope_retires_after_save(rag_home
)
with pytest.raises(Exception) as exc_info:
- asyncio.run(rag_routes.upload_project_document(project_id, subject = "test"))
+ rag_routes.upload_project_document(project_id, subject = "test")
assert getattr(exc_info.value, "status_code", None) == 409
assert not saved_path.exists()
@@ -1855,7 +1856,7 @@ def test_upload_rechecks_owner_after_saving_file(rag_home, monkeypatch, scope_ty
nonlocal owner_exists
saved_path.write_text("saved", encoding = "utf-8")
owner_exists = False
- return str(saved_path), saved_path.name
+ return str(saved_path), saved_path.name, "0" * 64
monkeypatch.setattr(rag_routes.rag_db, "rag_available", lambda: True)
monkeypatch.setattr(rag_routes.folder_sync, "scope_retired", lambda scope: False)
@@ -1871,17 +1872,17 @@ def test_upload_rechecks_owner_after_saving_file(rag_home, monkeypatch, scope_ty
"get_kb",
lambda conn, value: {"id": value} if owner_exists else None,
)
- upload = rag_routes.upload_kb_document(owner_id, subject = "test")
+ upload = partial(rag_routes.upload_kb_document, owner_id, subject = "test")
else:
monkeypatch.setattr(
studio_db,
"get_chat_project",
lambda value: {"id": value} if owner_exists else None,
)
- upload = rag_routes.upload_project_document(owner_id, subject = "test")
+ upload = partial(rag_routes.upload_project_document, owner_id, subject = "test")
with pytest.raises(Exception) as exc_info:
- asyncio.run(upload)
+ upload()
assert getattr(exc_info.value, "status_code", None) == 404
assert not saved_path.exists()
@@ -2115,7 +2116,7 @@ def test_kb_upload_rejects_retired_scope_before_saving(rag_home, monkeypatch):
)
with pytest.raises(Exception) as exc_info:
- asyncio.run(rag_routes.upload_kb_document("knowledge", subject = "test"))
+ rag_routes.upload_kb_document("knowledge", subject = "test")
assert getattr(exc_info.value, "status_code", None) == 409
diff --git a/studio/backend/tests/test_rag_native_drop_upload.py b/studio/backend/tests/test_rag_native_drop_upload.py
index bd46b8998f8..a909f9a381d 100644
--- a/studio/backend/tests/test_rag_native_drop_upload.py
+++ b/studio/backend/tests/test_rag_native_drop_upload.py
@@ -84,9 +84,10 @@ def _doc(
def test_signed_drop_is_copied_into_the_uploads_root(rag_home, tmp_path):
source = _doc(tmp_path)
- stored_path, filename = _save_native_path_upload(_sign(source))
+ stored_path, filename, content_hash = _save_native_path_upload(_sign(source))
assert filename == "notes.txt"
+ assert content_hash == hashlib.sha256(source.read_bytes()).hexdigest()
# Copied, not referenced: ingestion must not read from wherever the user dragged from.
assert os.path.realpath(stored_path) != os.path.realpath(source)
with open(stored_path, encoding = "utf-8") as handle:
diff --git a/studio/backend/tests/test_rag_upload_event_loop.py b/studio/backend/tests/test_rag_upload_event_loop.py
new file mode 100644
index 00000000000..afaeb109001
--- /dev/null
+++ b/studio/backend/tests/test_rag_upload_event_loop.py
@@ -0,0 +1,159 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A document upload must not occupy the event loop while it runs.
+
+The upload routes copy the file and call start_ingestion inline, and start_ingestion
+re-hashes the file and probes nvidia-smi through embedding_identity. Run on the event
+loop that is seconds of dead backend: a streaming reply stops mid-token and every other
+request queues behind the attachment. These tests count the trivial concurrent requests
+answered while an upload is in flight, so they fail whenever the blocking work moves back
+onto the loop, regardless of how the routes are spelled.
+"""
+
+import asyncio
+import time
+
+import httpx
+import pytest
+
+from core.rag import ingestion, store
+from storage import rag_db
+from .test_rag_native_drop_upload import SECRET, _sign
+
+BLOCK_SECONDS = 0.6
+PAYLOAD = b"alpha bravo charlie delta\n" * 320_000
+POLL_INTERVAL = 0.005
+# Blocked, the poller gets exactly two turns: one before the handler takes the loop and one
+# after it hands it back. Free, it gets around a hundred. A count separates those by
+# construction rather than by wall clock, so this file can stay in the -n 4 parallel run
+# that test_scan_loras_off_event_loop, whose tick floor is loose for the same reason, is
+# kept out of. The floor is 10x the blocked count and a fifth of the free one.
+SERVED_FLOOR = 20
+
+
+def blocking_ingestion(monkeypatch):
+ """start_ingestion stands in for the real re-hash + nvidia-smi probe."""
+
+ def slow_start_ingestion(*args, **kwargs):
+ time.sleep(BLOCK_SECONDS)
+ return "doc-1", "job-1"
+
+ monkeypatch.setattr(ingestion, "start_ingestion", slow_start_ingestion)
+
+
+def lease_secret(monkeypatch):
+ import base64
+
+ import utils.native_path_leases as leases
+
+ monkeypatch.setenv(
+ leases.LEASE_SECRET_ENV,
+ base64.urlsafe_b64encode(SECRET).decode("ascii").rstrip("="),
+ )
+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None, raising = False)
+ yield
+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None, raising = False)
+
+
+def _app():
+ from fastapi import FastAPI
+
+ from auth.authentication import get_current_subject
+ from routes import rag as rag_routes
+
+ app = FastAPI()
+ app.include_router(rag_routes.router, prefix = "/api/rag")
+ app.dependency_overrides[get_current_subject] = lambda: "tester"
+
+ @app.get("/ping")
+ async def ping() -> dict:
+ return {"ok": True}
+
+ return app
+
+
+async def _upload_then_ping(path: str, **post_kwargs) -> tuple[httpx.Response, int, float]:
+ """POST the upload while a trivial request is polled, counting the ones it answers."""
+ latencies: list[float] = []
+ done = asyncio.Event()
+
+ async def poll_ping(client: httpx.AsyncClient) -> None:
+ while not done.is_set():
+ started = time.perf_counter()
+ await asyncio.sleep(POLL_INTERVAL)
+ ping = await client.get("/ping", timeout = 30.0)
+ assert ping.status_code == 200
+ latencies.append(time.perf_counter() - started - POLL_INTERVAL)
+
+ transport = httpx.ASGITransport(app = _app())
+ async with httpx.AsyncClient(transport = transport, base_url = "http://test") as client:
+ poller = asyncio.ensure_future(poll_ping(client))
+ try:
+ response = await client.post(path, timeout = 30.0, **post_kwargs)
+ finally:
+ done.set()
+ await poller
+ return response, len(latencies), max(latencies, default = 0.0)
+
+
+def _kb_id() -> str:
+ conn = rag_db.get_connection()
+ try:
+ return store.create_kb(conn, name = "Latency")
+ finally:
+ conn.close()
+
+
+def _files() -> dict:
+ return {"file": ("notes.txt", PAYLOAD, "text/plain")}
+
+
+def _assert_loop_stayed_free(
+ response,
+ served: int,
+ worst: float,
+ what: str = "upload",
+) -> None:
+ assert response.status_code == 200
+ assert served >= SERVED_FLOOR, (
+ f"only {served} of the polled requests completed during the {what}; "
+ f"the worst waited {worst * 1000:.0f} ms"
+ )
+
+
+def test_kb_upload_leaves_the_event_loop_free(rag_home, blocking_ingestion):
+ response, served, worst = asyncio.run(
+ _upload_then_ping(f"/api/rag/knowledge-bases/{_kb_id()}/documents", files = _files())
+ )
+ _assert_loop_stayed_free(response, served, worst, "upload")
+
+
+def test_thread_upload_leaves_the_event_loop_free(rag_home, blocking_ingestion):
+ response, served, worst = asyncio.run(
+ _upload_then_ping("/api/rag/threads/T1/documents", files = _files())
+ )
+ _assert_loop_stayed_free(response, served, worst, "upload")
+
+
+def test_project_upload_leaves_the_event_loop_free(rag_home, blocking_ingestion, monkeypatch):
+ from storage import studio_db
+
+ monkeypatch.setattr(studio_db, "get_chat_project", lambda project_id: {"id": project_id})
+ response, served, worst = asyncio.run(
+ _upload_then_ping("/api/rag/projects/P1/documents", files = _files())
+ )
+ _assert_loop_stayed_free(response, served, worst, "upload")
+
+
+def test_native_drop_leaves_the_event_loop_free(
+ rag_home, blocking_ingestion, lease_secret, tmp_path
+):
+ dropped = tmp_path / "dropped.txt"
+ dropped.write_bytes(PAYLOAD)
+ response, served, worst = asyncio.run(
+ _upload_then_ping("/api/rag/threads/T1/documents", data = {"nativePathLease": _sign(dropped)})
+ )
+ _assert_loop_stayed_free(response, served, worst, "drop")
diff --git a/studio/backend/tests/test_rag_upload_formats.py b/studio/backend/tests/test_rag_upload_formats.py
index 040b9f4c8cf..9fb0bb7de3c 100644
--- a/studio/backend/tests/test_rag_upload_formats.py
+++ b/studio/backend/tests/test_rag_upload_formats.py
@@ -5,6 +5,7 @@
import base64
import codecs
+import hashlib
from pathlib import Path
import pytest
@@ -84,8 +85,9 @@ def test_formats_finish_and_remain_searchable(
):
assert set(EXTENSIONS) == config.UPLOAD_EXTS
source = write_document(tmp_path / f"report{extension}", large = True)
- stored, filename = persist_document(source, transport)
+ stored, filename, content_hash = persist_document(source, transport)
assert Path(stored).read_bytes() == source.read_bytes()
+ assert content_hash == hashlib.sha256(source.read_bytes()).hexdigest()
vision_calls = []
monkeypatch.setattr(captioner, "vision_endpoint", lambda: ("http://local", "local"))
monkeypatch.setattr(captioner, "_caption_one", lambda *args: vision_calls.append("caption"))
@@ -110,7 +112,8 @@ def test_formats_finish_and_remain_searchable(
assert not store.search_lexical(conn, scope, "hiddenscriptmarker", 5)
finally:
conn.close()
- duplicate_path, filename = persist_document(source, transport)
+ duplicate_path, filename, duplicate_hash = persist_document(source, transport)
+ assert duplicate_hash == content_hash
duplicate_id, duplicate_job = ingestion.start_ingestion(
scope, None, "formats", filename, duplicate_path, background = False
)