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.

RAG: avoid re-hashing linked-folder snapshots in start_ingestion (#9913)

Dhruva9640d8c63e5c
diff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.py
index 920c65fc9a9..fe8d35fab53 100644
--- a/studio/backend/core/rag/folder_sync.py
+++ b/studio/backend/core/rag/folder_sync.py
@@ -1442,6 +1442,7 @@ def _reconcile_folder(job_id: str) -> None:
linked_relative_path = rel,
model_name = embedding_model,
background = False,
+ content_hash = content_hash,
)
result = ingestion.get_job_status(ingestion_job)
if result is None:
diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.py
index d34cadacbd1..cfd7c2cb337 100644
--- a/studio/backend/core/rag/ingestion.py
+++ b/studio/backend/core/rag/ingestion.py
@@ -12,6 +12,7 @@ import hashlib
import logging
import os
import queue
+import re
import threading
from storage import rag_db
@@ -26,6 +27,7 @@ _workers: dict[str, threading.Thread] = {}
_jobs_lock = threading.Lock()
_EMBED_BATCH = 64 # bounds peak memory
+_SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$")
# Poll with a timeout so the generator wakes periodically to detect a gone
# client or a terminal job whose worker died without the None sentinel.
@@ -357,10 +359,17 @@ def start_ingestion(
linked_folder_id: str | None = None,
linked_relative_path: str | None = None,
background: bool = True,
+ content_hash: str | None = None,
) -> tuple[str, str]:
"""Create the document + job rows and spawn the worker, returning
``(document_id, job_id)``. A duplicate content hash in this scope returns the
- existing id with an already-completed job (no re-ingest)."""
+ existing id with an already-completed job (no re-ingest).
+
+ ``content_hash`` lets a caller that already hashed ``stored_path`` (linked-folder
+ reconciliation hashes it to detect content-identical renames) pass that digest
+ through instead of paying for a second full read of the file. Must be the lowercase
+ hex sha256 of ``stored_path``; a mismatched value would misfile the document under
+ the wrong hash, so it is trusted as given and never reverified here."""
ext = os.path.splitext(stored_path)[1].lower()
if ext not in config.UPLOAD_EXTS:
raise ValueError(f"unsupported file type: {ext}")
@@ -368,7 +377,9 @@ def start_ingestion(
# Reclaim queues for finished jobs so the registry stays bounded.
_reap_finished_jobs()
- sha = _sha256_file(stored_path)
+ if content_hash is not None and not _SHA256_HEX_RE.match(content_hash):
+ raise ValueError("content_hash must be a lowercase hex sha256 digest")
+ sha = content_hash or _sha256_file(stored_path)
conn = rag_db.get_connection()
try:
# Named before the transaction opens, because naming the embedder on a fresh
diff --git a/studio/backend/tests/test_rag_ingestion.py b/studio/backend/tests/test_rag_ingestion.py
index 268d7712265..63a5f220dce 100644
--- a/studio/backend/tests/test_rag_ingestion.py
+++ b/studio/backend/tests/test_rag_ingestion.py
@@ -195,6 +195,44 @@ def test_ingestion_dedupe_by_hash(rag_home, stub_embeddings, tmp_path):
conn.close()
+def test_start_ingestion_accepts_precomputed_content_hash(
+ rag_home, stub_embeddings, tmp_path, monkeypatch
+):
+ """A caller that already hashed the file (linked-folder sync) can pass that
+ digest through instead of paying for a second full read of it."""
+ path = _write(tmp_path, "doc.txt", "alpha bravo charlie")
+ scope = store.kb_scope("K1")
+ precomputed = ingestion._sha256_file(path)
+
+ calls = []
+ original = ingestion._sha256_file
+
+ def counting(p):
+ calls.append(p)
+ return original(p)
+
+ monkeypatch.setattr(ingestion, "_sha256_file", counting)
+ doc_id, job_id = ingestion.start_ingestion(
+ scope, "K1", None, "doc.txt", path, content_hash = precomputed
+ )
+ _drain(job_id)
+ _wait_completed(job_id)
+
+ assert calls == [] # start_ingestion never re-hashed the file
+ conn = rag_db.get_connection()
+ try:
+ assert store.get_document(conn, doc_id)["sha256"] == precomputed
+ finally:
+ conn.close()
+
+
+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")
+ with pytest.raises(ValueError):
+ ingestion.start_ingestion(scope, "K1", None, "doc.txt", path, content_hash = "not-a-sha256")
+
+
def test_manual_upload_does_not_dedupe_to_linked_folder_document(
rag_home, stub_embeddings, tmp_path
):