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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: pipeline linked-folder RAG ingestion (#9873)
Kenshi1f936adc9772
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.pyindex 726c3c05ba5..003de624eb6 100644--- a/studio/backend/core/rag/config.py+++ b/studio/backend/core/rag/config.py@@ -55,6 +55,8 @@ MAX_UPLOAD_BYTES = int(os.environ.get("RAG_MAX_UPLOAD_BYTES", str(200 * 1024 * 1FOLDER_SYNC_INTERVAL_S = float(os.environ.get("RAG_FOLDER_SYNC_INTERVAL_S", "30"))FOLDER_MAX_FILES = int(os.environ.get("RAG_FOLDER_MAX_FILES", "10000"))FOLDER_JOB_HISTORY_LIMIT = int(os.environ.get("RAG_FOLDER_JOB_HISTORY_LIMIT", "200"))+# Linked-folder documents ingested concurrently, clamped to 1..4.+FOLDER_INGEST_WORKERS = int(os.environ.get("RAG_FOLDER_INGEST_WORKERS", "2"))# Falls back to plain PyMuPDF text when off, when pymupdf4llm is missing, or when extraction fails.PDF_MARKDOWN = os.environ.get("RAG_PDF_MARKDOWN", "1") == "1"diff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.pyindex c761c99cf06..747c5b9f0a9 100644--- a/studio/backend/core/rag/folder_sync.py+++ b/studio/backend/core/rag/folder_sync.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Durable, sequential reconciliation for linked local RAG folders."""+"""Durable, bounded-pipeline reconciliation for linked local RAG folders."""from __future__ import annotations@@ -11,7 +11,7 @@ from core.training.account_jobs import (account_path,job_accounts,)-from utils.account_context import account_thread, run_as+from utils.account_context import account_thread, current_account, run_asimport hashlibimport jsonimport logging@@ -21,8 +21,10 @@ import statimport threadingimport timeimport uuid-from contextlib import closingimport weakref+from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait+from contextlib import closing+from dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Path, PurePosixPath@@ -67,6 +69,22 @@ class _FolderChanged(RuntimeError):pass+@dataclass+class _IngestionResult:+ document_id: str | None = None+ ingestion_job: str | None = None+ error: Exception | None = None+++@dataclass+class _PendingIngestion:+ relative_path: str+ snapshot: str+ metadata: dict+ content_hash: str+ future: Future["_IngestionResult"]++def _folder_lock(folder_id: str) -> threading.RLock:with _named_locks_lock:return _folder_locks.setdefault(account_key(folder_id), threading.RLock())@@ -1354,6 +1372,62 @@ def _failure_summary(failures: list[str]) -> str | None:return f"{len(failures)} file(s) could not be indexed ({named})"+def _ingest_folder_document(+ job_id: str,+ stop_event: threading.Event,+ folder: dict,+ relative_path: str,+ snapshot: str,+ content_hash: str,+ embedding_model: str,+ rebuild: bool,+) -> _IngestionResult:+ """Ingest one file in a pool thread; the coordinator owns all folder state."""+ # Thread-local, so copy the coordinator's lease and stop state for _check_running.+ _worker_state.job_id = job_id+ _worker_state.stop_event = stop_event+ document_id = None+ ingestion_job = None+ try:+ _check_running()+ document_id, ingestion_job = ingestion.start_ingestion(+ folder["scope"],+ folder["scope_id"] if folder["scope_type"] == "knowledge_base" else None,+ None,+ relative_path,+ snapshot,+ project_id = folder["scope_id"] if folder["scope_type"] == "project" else None,+ model_name = embedding_model,+ content_hash = content_hash,+ dedupe = False,+ linked_folder_id = folder["id"],+ linked_relative_path = relative_path,+ background = False,+ reuse_identical = not rebuild,+ )+ result = ingestion.get_job_status(ingestion_job)+ if result is None:+ raise RuntimeError("Ingestion job disappeared")+ if result["status"] != "completed":+ raise RuntimeError(result.get("error") or "Ingestion failed")+ _check_running()+ return _IngestionResult(document_id, ingestion_job)+ except Exception as exc: # noqa: BLE001 - the coordinator classifies it+ return _IngestionResult(document_id, ingestion_job, exc)+++def _cleanup_pending_ingestion(pending: _PendingIngestion, result: _IngestionResult) -> None:+ """Remove an uninstalled document, or its snapshot if admission never completed."""+ if result.document_id is not None:+ _discard_document(result.document_id)+ else:+ _remove_snapshot(pending.snapshot)+++def _folder_ingest_workers() -> int:+ return max(1, min(4, config.FOLDER_INGEST_WORKERS))++def _reconcile_folder(job_id: str) -> None:"""Run one complete reconciliation; called serially by the coordinator."""_check_running()@@ -1437,113 +1511,202 @@ def _reconcile_folder(job_id: str) -> None:added = changed_count = 0failures: list[str] = []withheld: set[str] = set()- for index, rel in enumerate(work):- snapshot = None- document_id = None- ingestion_job = None- try:- _check_running()- metadata = current[rel]- snapshot = _snapshot(folder["path"], metadata)- content_hash = _hash_file(snapshot)- _check_running()- if not rebuild and rel in changed and content_hash == known[rel].get("content_hash"):- _check_root_identity(folder["path"], scanned_identity)- _update_mapping_metadata(folder["id"], rel, metadata, content_hash)- _remove_snapshot(snapshot)- snapshot = None- _set_job(job_id, progress = (index + 1) / max(total, 1))- continue- if not rebuild and rel in new:- rename_key = (content_hash, os.path.splitext(rel)[1].lower())- rename_candidates = missing_by_content.get(rename_key)- if rename_candidates:- old_rel = rename_candidates.pop(0)- missing.discard(old_rel)- _check_root_identity(folder["path"], scanned_identity)- _rename_mapping(folder["id"], old_rel, rel)- _update_mapping_metadata(folder["id"], rel, metadata, content_hash)- _remove_snapshot(snapshot)- snapshot = None- renamed += 1- _set_job(- job_id,- renamed = renamed,- progress = (index + 1) / max(total, 1),- )- continue- document_id, ingestion_job = ingestion.start_ingestion(- folder["scope"],- folder["scope_id"] if folder["scope_type"] == "knowledge_base" else None,- None,- rel,- snapshot,- project_id = folder["scope_id"] if folder["scope_type"] == "project" else None,- dedupe = False,- linked_folder_id = folder["id"],- linked_relative_path = rel,- model_name = embedding_model,- background = False,- content_hash = content_hash,- reuse_identical = not rebuild,- )- result = ingestion.get_job_status(ingestion_job)- if result is None:- raise RuntimeError("Ingestion job disappeared")- if result["status"] != "completed":- raise RuntimeError(result.get("error") or "Ingestion failed")- _check_running()- _check_root_identity(folder["path"], scanned_identity)- _install_mapping(- folder,- rel,- metadata,- document_id,- content_hash,- )- if rel in new:- added += 1- else:- changed_count += 1- except (_SyncStopped, _LeaseLost):- if document_id:- _discard_document(document_id)- else:- _remove_snapshot(snapshot)- raise- except _FolderChanged:- if document_id:- _discard_document(document_id)- else:- _remove_snapshot(snapshot)- raise- except Exception:- failures.append(rel)- # a failed file may be a rename or copy of a vanished path, so grant one pass- withheld.update(missing - already_withheld)- logger.warning("linked-folder ingestion failed for %s", rel, exc_info = True)- if document_id:- _discard_document(document_id)- else:- _remove_snapshot(snapshot)- finally:- if ingestion_job:- try:- ingestion.delete_terminal_job(ingestion_job)- except Exception:- logger.warning(- "failed to prune linked-folder ingestion job %s",- ingestion_job,- exc_info = True,- )+ processed = 0+ stop_event = getattr(_worker_state, "stop_event", _stop)+ account = current_account()+ workers = _folder_ingest_workers()+ in_flight: dict[Future["_IngestionResult"], _PendingIngestion] = {}++ def update_progress() -> None:_set_job(job_id,added = added,changed = changed_count,failed = len(failures),- progress = (index + 1) / max(total, 1),+ renamed = renamed,+ progress = processed / max(total, 1),)+ def prune_ingestion_job(result: _IngestionResult) -> None:+ if result.ingestion_job is None:+ return+ try:+ ingestion.delete_terminal_job(result.ingestion_job)+ except Exception:+ logger.warning(+ "failed to prune linked-folder ingestion job %s",+ result.ingestion_job,+ exc_info = True,+ )++ def finish_pending(pending: _PendingIngestion) -> None:+ nonlocal added, changed_count, processed+ result = _IngestionResult()+ try:+ try:+ result = pending.future.result()+ except Exception as exc: # noqa: BLE001+ result = _IngestionResult(error = exc)++ if result.error is not None:+ if isinstance(result.error, (_SyncStopped, _LeaseLost, _FolderChanged)):+ _cleanup_pending_ingestion(pending, result)+ raise result.error+ failures.append(pending.relative_path)+ # A failed file may be a rename or copy of a vanished path, so grant one pass.+ withheld.update(missing - already_withheld)+ logger.warning(+ "linked-folder ingestion failed for %s",+ pending.relative_path,+ exc_info = (type(result.error), result.error, result.error.__traceback__),+ )+ _cleanup_pending_ingestion(pending, result)+ else:+ try:+ _check_running()+ _check_root_identity(folder["path"], scanned_identity)+ _install_mapping(+ folder,+ pending.relative_path,+ pending.metadata,+ result.document_id,+ pending.content_hash,+ )+ except (_SyncStopped, _LeaseLost, _FolderChanged):+ _cleanup_pending_ingestion(pending, result)+ raise+ except Exception as exc: # noqa: BLE001+ failures.append(pending.relative_path)+ withheld.update(missing - already_withheld)+ logger.warning(+ "linked-folder ingestion failed for %s",+ pending.relative_path,+ exc_info = (type(exc), exc, exc.__traceback__),+ )+ _cleanup_pending_ingestion(pending, result)+ else:+ if pending.relative_path in new:+ added += 1+ else:+ changed_count += 1+ finally:+ prune_ingestion_job(result)+ processed += 1+ update_progress()++ def drain_one() -> None:+ if not in_flight:+ return+ completed, _ = wait(tuple(in_flight), return_when = FIRST_COMPLETED)+ for future in completed:+ pending = in_flight.pop(future)+ finish_pending(pending)++ def abort_in_flight() -> None:+ pending_items = list(in_flight.items())+ for future, _ in pending_items:+ future.cancel()+ for future, pending in pending_items:+ in_flight.pop(future, None)+ if future.cancelled():+ result = _IngestionResult()+ else:+ try:+ result = future.result()+ except Exception as exc: # noqa: BLE001+ result = _IngestionResult(error = exc)+ try:+ _cleanup_pending_ingestion(pending, result)+ except Exception:+ logger.warning(+ "failed to clean up aborted linked-folder ingestion for %s",+ pending.relative_path,+ exc_info = True,+ )+ prune_ingestion_job(result)++ with ThreadPoolExecutor(+ max_workers = workers,+ thread_name_prefix = "rag-folder-ingest",+ ) as executor:+ try:+ for rel in work:+ if len(in_flight) >= workers:+ drain_one()+ snapshot = None+ try:+ _check_running()+ metadata = current[rel]+ snapshot = _snapshot(folder["path"], metadata)+ content_hash = _hash_file(snapshot)+ _check_running()+ if (+ not rebuild+ and rel in changed+ and content_hash == known[rel].get("content_hash")+ ):+ _check_root_identity(folder["path"], scanned_identity)+ _update_mapping_metadata(folder["id"], rel, metadata, content_hash)+ _remove_snapshot(snapshot)+ snapshot = None+ elif not rebuild and rel in new:+ rename_key = (content_hash, os.path.splitext(rel)[1].lower())+ rename_candidates = missing_by_content.get(rename_key)+ if rename_candidates:+ old_rel = rename_candidates.pop(0)+ missing.discard(old_rel)+ _check_root_identity(folder["path"], scanned_identity)+ _rename_mapping(folder["id"], old_rel, rel)+ _update_mapping_metadata(folder["id"], rel, metadata, content_hash)+ _remove_snapshot(snapshot)+ snapshot = None+ renamed += 1+ if snapshot is not None:+ # reuse_identical needs a finished donor, so a copy waits for its in-flight twin.+ while not rebuild and any(+ p.content_hash == content_hash for p in in_flight.values()+ ):+ drain_one()+ # Pool threads start as the owner account; rebind to this job's.+ future = executor.submit(+ run_as,+ account,+ _ingest_folder_document,+ job_id,+ stop_event,+ folder,+ rel,+ snapshot,+ content_hash,+ embedding_model,+ rebuild,+ )+ in_flight[future] = _PendingIngestion(+ relative_path = rel,+ snapshot = snapshot,+ metadata = metadata,+ content_hash = content_hash,+ future = future,+ )+ snapshot = None+ except (_SyncStopped, _LeaseLost, _FolderChanged):+ _remove_snapshot(snapshot)+ raise+ except Exception:+ failures.append(rel)+ withheld.update(missing - already_withheld)+ logger.warning("linked-folder ingestion failed for %s", rel, exc_info = True)+ _remove_snapshot(snapshot)+ if any(pending.relative_path == rel for pending in in_flight.values()):+ continue+ processed += 1+ update_progress()+ while in_flight:+ drain_one()+ except Exception:+ abort_in_flight()+ raise+deleted = 0for rel in sorted(missing - withheld):_check_running()diff --git a/studio/backend/tests/test_rag_folder_sync_retirement.py b/studio/backend/tests/test_rag_folder_sync_retirement.pyindex 42ab85f5c92..1521c7d8214 100644--- a/studio/backend/tests/test_rag_folder_sync_retirement.py+++ b/studio/backend/tests/test_rag_folder_sync_retirement.py@@ -162,3 +162,23 @@ def test_the_shared_worker_still_syncs_accounts_behind_a_corrupt_database(two_acstop.set()folder_sync._wake.set()worker.join(30)+++@requires_sqlite_vec+def test_pipelined_ingestion_writes_into_the_syncing_accounts_database(two_accounts):+ from core.rag import store++ folder, bob_job = _link(BOB, two_accounts[BOB.account_id], "bob")+ run_as(BOB, folder_sync.reconcile_folder, bob_job)++ def indexed():+ assert folder_sync.get_job(bob_job)["status"] == "completed"+ with rag_db.get_connection() as conn:+ row = conn.execute(+ "SELECT d.id FROM linked_folder_files f JOIN documents d ON d.id = f.document_id"+ " WHERE f.folder_id = ?",+ (folder["id"],),+ ).fetchone()+ return row is not None and bool(store.search_lexical(conn, folder["scope"], "bob", 5))++ assert run_as(BOB, indexed), "a pool thread indexed the file outside the account's database"diff --git a/studio/backend/tests/test_rag_linked_folders.py b/studio/backend/tests/test_rag_linked_folders.pyindex e32264a6fb6..859c0bceec9 100644--- a/studio/backend/tests/test_rag_linked_folders.py+++ b/studio/backend/tests/test_rag_linked_folders.py@@ -521,6 +521,124 @@ def test_reconcile_pins_one_embedding_model_for_every_file(rag_home, stub_embeddassert models == ["model/one", "model/one"]+@requires_sqlite_vec+def test_reconcile_overlaps_the_next_parse_with_embedding(rag_home, stub_embeddings, monkeypatch):+ source, folder = _folder(rag_home)+ (source / "a-first.txt").write_text("first document words", encoding = "utf-8")+ (source / "b-second.txt").write_text("second document words", encoding = "utf-8")+ monkeypatch.setattr(folder_sync.config, "FOLDER_INGEST_WORKERS", 2)++ from core.rag import embeddings++ real_parse = folder_sync.ingestion.parsers.parse+ real_encode = embeddings.encode+ second_parsed = threading.Event()+ overlap_observed = []++ def observe_parse(path):+ pages = real_parse(path)+ if any("second document" in page.text for page in pages):+ second_parsed.set()+ return pages++ def observe_encode(+ texts,+ *,+ model_name = None,+ normalize = True,+ ):+ if any("first document" in text for text in texts):+ overlap_observed.append(second_parsed.wait(5))+ return real_encode(texts, model_name = model_name, normalize = normalize)++ monkeypatch.setattr(folder_sync.ingestion.parsers, "parse", observe_parse)+ monkeypatch.setattr(embeddings, "encode", observe_encode)++ result = _run(folder["id"])++ assert result["status"] == "completed"+ assert overlap_observed == [True]+ assert (+ _row(+ "SELECT COUNT(*) AS count FROM linked_folder_files WHERE folder_id=?",+ (folder["id"],),+ )["count"]+ == 2+ )+++@requires_sqlite_vec+def test_reconcile_keeps_successful_sibling_when_parallel_ingest_fails(+ rag_home, stub_embeddings, monkeypatch+):+ source, folder = _folder(rag_home)+ (source / "a-good.txt").write_text("successful sibling words", encoding = "utf-8")+ (source / "b-fails.txt").write_text("failed sibling words", encoding = "utf-8")+ monkeypatch.setattr(folder_sync.config, "FOLDER_INGEST_WORKERS", 2)+ real_start = folder_sync.ingestion.start_ingestion++ def fail_one(*args, **kwargs):+ if args[3] == "b-fails.txt":+ raise RuntimeError("synthetic ingestion failure")+ return real_start(*args, **kwargs)++ monkeypatch.setattr(folder_sync.ingestion, "start_ingestion", fail_one)++ result = _run(folder["id"])++ assert result["status"] == "failed"+ assert result["failed"] == 1+ with _connection() as conn:+ paths = {+ row["relative_path"]+ for row in conn.execute(+ "SELECT relative_path FROM linked_folder_files WHERE folder_id=?",+ (folder["id"],),+ )+ }+ assert paths == {"a-good.txt"}+ assert store.search_lexical(conn, folder["scope"], "successful", 5)+ assert not store.search_lexical(conn, folder["scope"], "failed", 5)+++@requires_sqlite_vec+def test_reconcile_ingests_new_files_alongside_renames(rag_home, stub_embeddings, monkeypatch):+ source, folder = _folder(rag_home)+ (source / "original.txt").write_text("original searchable text", encoding = "utf-8")+ assert _run(folder["id"], rebuild = True)["status"] == "completed"+ (source / "original.txt").rename(source / "renamed.txt")+ (source / "new.txt").write_text("newly added searchable text", encoding = "utf-8")++ progress = []+ real_set_job = folder_sync._set_job++ def track_progress(job_id, **kwargs):+ if "progress" in kwargs:+ progress.append(kwargs["progress"])+ return real_set_job(job_id, **kwargs)++ monkeypatch.setattr(folder_sync, "_set_job", track_progress)+ result = _run(folder["id"])++ assert result["status"] == "completed"+ assert result["added"] == 1+ assert result["renamed"] == 1+ assert result["failed"] == 0+ assert progress and all(0 <= value <= 1 for value in progress)+ assert progress == sorted(progress)+ with _connection() as conn:+ paths = {+ row["relative_path"]+ for row in conn.execute(+ "SELECT relative_path FROM linked_folder_files WHERE folder_id=?",+ (folder["id"],),+ )+ }+ assert paths == {"new.txt", "renamed.txt"}+ assert store.search_lexical(conn, folder["scope"], "newly", 5)+ assert conn.execute("SELECT COUNT(*) FROM ingestion_jobs").fetchone()[0] == 0++@requires_sqlite_vecdef test_reconcile_retains_mapping_when_missing_file_reappears(rag_home, stub_embeddings, monkeypatch